|
|
<?php
|
|
|
|
|
|
namespace App\Services\Payment;
|
|
|
|
|
|
use GuzzleHttp\Client;
|
|
|
use GuzzleHttp\Exception\ConnectException;
|
|
|
|
|
|
/** Minimal server-side Stripe API client for hosted Checkout Sessions. */
|
|
|
class StripeClient
|
|
|
{
|
|
|
private array $settings;
|
|
|
private Client $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['stripe_request_timeout_seconds'] ?? 15)));
|
|
|
$this->client = new Client([
|
|
|
'base_uri' => StripeConfig::API_BASE_URL . '/',
|
|
|
'timeout' => $timeout,
|
|
|
'connect_timeout' => min(10, $timeout),
|
|
|
'verify' => true,
|
|
|
'http_errors' => false,
|
|
|
'allow_redirects' => false,
|
|
|
]);
|
|
|
}
|
|
|
|
|
|
public function createCheckoutSession(array $payload,
|
|
|
string $idempotencyKey): array
|
|
|
{
|
|
|
if (preg_match('/^[A-Za-z0-9_.-]{8,128}$/D', $idempotencyKey) !== 1) {
|
|
|
throw new \InvalidArgumentException('Stripe 幂等键格式无效');
|
|
|
}
|
|
|
try {
|
|
|
$response = $this->client->post('checkout/sessions', [
|
|
|
'headers' => $this->headers([
|
|
|
'Accept' => 'application/json',
|
|
|
'Idempotency-Key' => $idempotencyKey,
|
|
|
]),
|
|
|
'form_params' => $payload,
|
|
|
]);
|
|
|
} catch (ConnectException $exception) {
|
|
|
$errno = (int) ($exception->getHandlerContext()['errno'] ?? 0);
|
|
|
if (in_array($errno, [6, 7], true)) {
|
|
|
throw PaymentOrderCreationException::notDispatched(
|
|
|
'Stripe 连接失败,订单没有发送到网关'
|
|
|
);
|
|
|
}
|
|
|
throw PaymentOrderCreationException::unknown(
|
|
|
'Stripe Checkout 创建结果未确认'
|
|
|
);
|
|
|
} catch (\Throwable $exception) {
|
|
|
throw PaymentOrderCreationException::unknown(
|
|
|
'Stripe Checkout 创建结果未确认'
|
|
|
);
|
|
|
}
|
|
|
$status = (int) $response->getStatusCode();
|
|
|
$body = (string) $response->getBody();
|
|
|
if ($status >= 400 && $status < 500) {
|
|
|
throw PaymentOrderCreationException::rejected(
|
|
|
$this->stripeError($body, 'Stripe 拒绝创建 Checkout 订单')
|
|
|
);
|
|
|
}
|
|
|
if ($status !== 200) {
|
|
|
throw PaymentOrderCreationException::unknown(
|
|
|
'Stripe Checkout 创建结果未确认(HTTP ' . $status . ')'
|
|
|
);
|
|
|
}
|
|
|
$data = $this->json($body, 'Stripe Checkout 返回了无效响应');
|
|
|
$sessionId = trim((string) ($data['id'] ?? ''));
|
|
|
$url = trim((string) ($data['url'] ?? ''));
|
|
|
$method = trim((string) ($payload['payment_method_types'][0] ?? ''));
|
|
|
$responseMethods = is_array($data['payment_method_types'] ?? null)
|
|
|
? $data['payment_method_types'] : [];
|
|
|
if (!preg_match('/^cs_(?:test|live)_[A-Za-z0-9]+$/D', $sessionId)
|
|
|
|| !$this->checkoutUrl($url)
|
|
|
|| (string) ($data['mode'] ?? '') !== 'payment'
|
|
|
|| (string) ($data['status'] ?? '') !== 'open'
|
|
|
|| !in_array($method, $responseMethods, true)) {
|
|
|
throw PaymentOrderCreationException::unknown(
|
|
|
'Stripe Checkout 成功响应缺少有效的会话信息'
|
|
|
);
|
|
|
}
|
|
|
return [
|
|
|
'checkout_session_id' => $sessionId,
|
|
|
'checkout_url' => $url,
|
|
|
];
|
|
|
}
|
|
|
|
|
|
public function retrieveAccount(): array
|
|
|
{
|
|
|
try {
|
|
|
$response = $this->client->get('account', [
|
|
|
'headers' => $this->headers(['Accept' => 'application/json']),
|
|
|
]);
|
|
|
} catch (\Throwable $exception) {
|
|
|
throw new \RuntimeException('Stripe API 连接失败');
|
|
|
}
|
|
|
$status = (int) $response->getStatusCode();
|
|
|
$body = (string) $response->getBody();
|
|
|
if ($status !== 200) {
|
|
|
throw new \RuntimeException(
|
|
|
$this->stripeError($body, 'Stripe API 返回 HTTP ' . $status)
|
|
|
);
|
|
|
}
|
|
|
$data = $this->json($body, 'Stripe 账户响应无效');
|
|
|
if (!preg_match('/^acct_[A-Za-z0-9]+$/D',
|
|
|
(string) ($data['id'] ?? ''))) {
|
|
|
throw new \RuntimeException('Stripe 账户响应缺少有效账户 ID');
|
|
|
}
|
|
|
return [
|
|
|
'id' => (string) $data['id'],
|
|
|
'country' => strtoupper(trim((string) ($data['country'] ?? ''))),
|
|
|
'default_currency' => strtolower(trim(
|
|
|
(string) ($data['default_currency'] ?? '')
|
|
|
)),
|
|
|
'charges_enabled' => (bool) ($data['charges_enabled'] ?? false),
|
|
|
];
|
|
|
}
|
|
|
|
|
|
private function headers(array $extra): array
|
|
|
{
|
|
|
return array_merge([
|
|
|
'Authorization' => 'Bearer '
|
|
|
. $this->settings[StripeConfig::API_SECRET_KEY],
|
|
|
], $extra);
|
|
|
}
|
|
|
|
|
|
private function json(string $body, string $error): array
|
|
|
{
|
|
|
if ($body === '' || strlen($body) > 1048576) {
|
|
|
throw new \RuntimeException($error);
|
|
|
}
|
|
|
$data = json_decode($body, true);
|
|
|
if (!is_array($data)) {
|
|
|
throw new \RuntimeException($error);
|
|
|
}
|
|
|
return $data;
|
|
|
}
|
|
|
|
|
|
private function stripeError(string $body, string $fallback): string
|
|
|
{
|
|
|
if (strlen($body) > 1048576) {
|
|
|
return $fallback;
|
|
|
}
|
|
|
$data = json_decode($body, true);
|
|
|
$message = is_array($data)
|
|
|
? trim(strip_tags((string) ($data['error']['message'] ?? ''))) : '';
|
|
|
return $message === '' ? $fallback
|
|
|
: 'Stripe:' . mb_substr($message, 0, 300);
|
|
|
}
|
|
|
|
|
|
private function checkoutUrl(string $value): bool
|
|
|
{
|
|
|
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'
|
|
|
&& strtolower((string) ($parts['host'] ?? ''))
|
|
|
=== 'checkout.stripe.com'
|
|
|
&& empty($parts['user']) && empty($parts['pass']);
|
|
|
}
|
|
|
}
|