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/StripeWebhookSignature.php

48 lines
1.7 KiB
PHP

<?php
namespace App\Services\Payment;
/** Stripe-Signature verification over the exact, unparsed request body. */
final class StripeWebhookSignature
{
public static function verify(string $rawBody, string $header,
string $secret, int $now = 0, int $tolerance = 300): array
{
if ($rawBody === '' || strlen($rawBody) > 1048576) {
throw new \RuntimeException('Stripe Webhook 请求体为空或过大');
}
$timestamp = 0;
$signatures = [];
foreach (explode(',', $header) as $part) {
$pair = explode('=', trim($part), 2);
if (count($pair) !== 2) {
continue;
}
if ($pair[0] === 't' && ctype_digit($pair[1])) {
$timestamp = (int) $pair[1];
} elseif ($pair[0] === 'v1'
&& preg_match('/^[a-f0-9]{64}$/i', $pair[1])) {
$signatures[] = strtolower($pair[1]);
}
}
$now = $now > 0 ? $now : time();
if ($timestamp < 1 || $signatures === []
|| abs($now - $timestamp) > max(1, $tolerance)) {
throw new \RuntimeException('Stripe Webhook 签名时间无效');
}
$expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
$valid = false;
foreach ($signatures as $signature) {
$valid = hash_equals($expected, $signature) || $valid;
}
if (!$valid) {
throw new \RuntimeException('Stripe Webhook 签名无效');
}
$event = json_decode($rawBody, true);
if (!is_array($event) || !is_array($event['data']['object'] ?? null)) {
throw new \RuntimeException('Stripe Webhook 事件格式无效');
}
return $event;
}
}