You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Payment/PaytaroClient.php

130 lines
4.6 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services\Payment;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
class PaytaroClient
{
private $settings;
private $client;
public function __construct(array $settings, ?Client $client = null)
{
$this->settings = $settings;
if ($client !== null) {
$this->client = $client;
return;
}
$timeout = max(3, min(60, (int) $settings['paytaro_request_timeout_seconds']));
$this->client = new Client([
'timeout' => $timeout,
'connect_timeout' => min(10, $timeout),
'verify' => true,
'http_errors' => false,
'allow_redirects' => false,
]);
}
public function createOrder(array $payload)
{
$payload['sign_type'] = 'MD5';
$payload['sign'] = PaytaroSigner::sign($payload, $this->settings[PaytaroConfig::SECRET_KEY]);
try {
$response = $this->client->post(
(string) $this->settings['paytaro_gateway_url'], [
'headers' => ['Accept' => 'application/json'],
'form_params' => $payload,
]
);
} catch (ConnectException $exception) {
$errno = (int) ($exception->getHandlerContext()['errno'] ?? 0);
if (in_array($errno, [6, 7], true)) {
throw PaymentOrderCreationException::notDispatched(
'Paytaro 连接失败,订单没有发送到网关'
);
}
throw PaymentOrderCreationException::unknown(
'Paytaro 创建订单响应未确认'
);
} catch (\Throwable $exception) {
throw PaymentOrderCreationException::unknown(
'Paytaro 创建订单响应未确认'
);
}
$data = $this->decode($response->getStatusCode(), (string) $response->getBody());
$paymentValue = trim((string) ($data['payurl'] ?? ''));
if (!$this->safePaymentUrl($paymentValue)) {
throw PaymentOrderCreationException::unknown(
'Paytaro 成功响应缺少安全有效的支付链接'
);
}
$tradeNo = trim((string) ($data['trade_no'] ?? ''));
if (!preg_match('/^[A-Za-z0-9_.:-]{1,80}$/', $tradeNo)) {
throw PaymentOrderCreationException::unknown(
'Paytaro 成功响应缺少有效的平台订单号'
);
}
return [
'gateway_trade_no' => $tradeNo,
'payment_kind' => 'payurl',
'payment_value' => $paymentValue,
];
}
public function testConnection()
{
$response = $this->client->request('OPTIONS', (string) $this->settings['paytaro_gateway_url'], [
'headers' => ['Accept' => 'application/json'],
]);
$status = (int) $response->getStatusCode();
if ($status <= 0 || $status >= 500) {
throw new \RuntimeException('Paytaro 网关返回 HTTP ' . $status);
}
return $status;
}
private function decode($httpStatus, $body)
{
if (strlen($body) > 65536) {
throw PaymentOrderCreationException::unknown(
'Paytaro 创建订单响应过大'
);
}
$data = json_decode($body, true);
if ((int) $httpStatus !== 200 || !is_array($data)) {
throw PaymentOrderCreationException::unknown(
'Paytaro 返回了无效响应(HTTP ' . (int) $httpStatus . ')'
);
}
if ((int) ($data['code'] ?? 0) !== 1) {
$message = mb_substr(trim(strip_tags((string) ($data['msg'] ?? ''))), 0, 300);
throw PaymentOrderCreationException::rejected(
$message !== '' ? 'Paytaro:' . $message
: 'Paytaro 拒绝创建订单'
);
}
if (!array_key_exists('payurl', $data)) {
throw PaymentOrderCreationException::unknown(
'Paytaro 成功响应缺少支付链接'
);
}
return $data;
}
private function safePaymentUrl($value)
{
if ($value === '' || strlen($value) > 8192 || preg_match('/[\x00-\x20\x7F]/', $value) === 1) {
return false;
}
$parts = parse_url($value);
return is_array($parts)
&& strtolower((string) ($parts['scheme'] ?? '')) === 'https'
&& trim((string) ($parts['host'] ?? '')) !== ''
&& empty($parts['user'])
&& empty($parts['pass'])
&& filter_var((string) $parts['host'], FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) !== false;
}
}