'https://panel.example.com']; use App\Models\User; use App\Services\Payment\StripeClient; use App\Services\Payment\StripeConfig; use App\Services\Payment\StripeCredentialCipher; use App\Services\Payment\StripePaymentService; use App\Services\Payment\StripeWebhookSignature; use GuzzleHttp\Client; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use GuzzleHttp\Psr7\Response; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; function failStripePaymentTest(string $message): void { fwrite(STDERR, $message . PHP_EOL); exit(1); } function stripeSignature(string $body, string $secret, int $timestamp): string { return 't=' . $timestamp . ',v1=' . hash_hmac( 'sha256', $timestamp . '.' . $body, $secret ); } $signatureSecret = 'whsec_1234567890'; $signedBody = json_encode([ 'id' => 'evt_signature', 'type' => 'checkout.session.completed', 'data' => ['object' => ['object' => 'checkout.session']], ], JSON_UNESCAPED_SLASHES); $signedAt = time(); $verified = StripeWebhookSignature::verify($signedBody, stripeSignature($signedBody, $signatureSecret, $signedAt), $signatureSecret, $signedAt); if (($verified['id'] ?? '') !== 'evt_signature') { failStripePaymentTest('Valid Stripe signature was rejected.'); } try { StripeWebhookSignature::verify($signedBody . ' ', stripeSignature($signedBody, $signatureSecret, $signedAt), $signatureSecret, $signedAt); failStripePaymentTest('Tampered Stripe body passed signature verification.'); } catch (RuntimeException $exception) { // Expected. } try { StripeWebhookSignature::verify($signedBody, stripeSignature($signedBody, $signatureSecret, $signedAt - 301), $signatureSecret, $signedAt); failStripePaymentTest('Stale Stripe signature passed verification.'); } catch (RuntimeException $exception) { // Expected. } $history = []; $mock = new MockHandler([ new Response(200, ['Content-Type' => 'application/json'], json_encode([ 'id' => 'cs_test_1234567890', 'object' => 'checkout.session', 'mode' => 'payment', 'status' => 'open', 'payment_method_types' => ['card'], 'url' => 'https://checkout.stripe.com/c/pay/cs_test_1234567890', ])), new Response(200, ['Content-Type' => 'application/json'], json_encode([ 'id' => 'acct_1234567890', 'country' => 'US', 'default_currency' => 'usd', 'charges_enabled' => true, ])), ]); $stack = HandlerStack::create($mock); $stack->push(Middleware::history($history)); $http = new Client(['handler' => $stack, 'http_errors' => false]); $client = new StripeClient([ StripeConfig::API_SECRET_KEY => 'sk_test_1234567890', 'stripe_request_timeout_seconds' => 15, ], $http); $session = $client->createCheckoutSession([ 'mode' => 'payment', 'payment_method_types' => ['card'], 'line_items' => [['quantity' => 1, 'price_data' => [ 'currency' => 'usd', 'unit_amount' => 1234, 'product_data' => ['name' => 'Account balance recharge'], ]]], ], 'ST20261030120000A1B2C3D4E5F60708'); $requestBody = []; parse_str((string) $history[0]['request']->getBody(), $requestBody); if (($session['checkout_session_id'] ?? '') !== 'cs_test_1234567890' || ($requestBody['payment_method_types'][0] ?? '') !== 'card' || (int) ($requestBody['line_items'][0]['price_data']['unit_amount'] ?? 0) !== 1234 || $history[0]['request']->getHeaderLine('Idempotency-Key') !== 'ST20261030120000A1B2C3D4E5F60708' || $history[0]['request']->getHeaderLine('Authorization') !== 'Bearer sk_test_1234567890') { failStripePaymentTest('Stripe Checkout request mapping failed.'); } $account = $client->retrieveAccount(); if (($account['id'] ?? '') !== 'acct_1234567890' || ($account['country'] ?? '') !== 'US') { failStripePaymentTest('Stripe account response mapping failed.'); } $capsule = new Capsule(); $capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default'); $capsule->setAsGlobal(); $capsule->bootEloquent(); $schema = $capsule->getConnection('default')->getSchemaBuilder(); $schema->create('configurations', function (Blueprint $table): void { $table->increments('id'); $table->string('name')->nullable(); $table->text('value')->nullable(); }); $schema->create('user', function (Blueprint $table): void { $table->increments('id'); $table->string('email')->default(''); $table->decimal('money', 12, 2)->default(0); $table->integer('enable')->default(1); $table->integer('is_admin')->default(0); $table->integer('ref_by')->default(0); $table->dateTime('reg_date')->nullable(); $table->decimal('aff_rate', 8, 2)->default(0); $table->decimal('aff_money', 12, 2)->default(0); }); $schema->create('paylist', function (Blueprint $table): void { $table->bigIncrements('id'); $table->integer('userid'); $table->decimal('total', 12, 2); $table->integer('status')->default(0); $table->string('tradeno')->unique(); $table->integer('datetime')->default(0); }); $schema->create('code', function (Blueprint $table): void { $table->bigIncrements('id'); $table->string('code')->unique(); $table->integer('type'); $table->decimal('number', 12, 2); $table->integer('isused'); $table->integer('userid'); $table->dateTime('usedatetime'); }); $schema->create('payback', function (Blueprint $table): void { $table->bigIncrements('id'); $table->decimal('total', 12, 2); $table->integer('userid'); $table->integer('ref_by'); $table->decimal('ref_get', 12, 2); $table->integer('datetime'); }); $schema->create('stripe_orders', function (Blueprint $table): void { $table->bigIncrements('id'); $table->string('order_no')->unique(); $table->string('checkout_session_id')->nullable()->unique(); $table->string('payment_intent_id')->nullable()->unique(); $table->integer('paylist_id')->unique(); $table->integer('user_id'); $table->string('payment_method'); $table->decimal('amount', 12, 2); $table->string('currency')->default('usd'); $table->integer('livemode')->default(0); $table->text('checkout_url')->nullable(); $table->string('status')->default('creating'); $table->string('error_message')->default(''); $table->integer('paid_at')->default(0); $table->integer('created_at'); $table->integer('updated_at'); }); $schema->create('stripe_webhook_events', function (Blueprint $table): void { $table->bigIncrements('id'); $table->string('event_id')->unique(); $table->string('event_type'); $table->string('object_id'); $table->string('order_no'); $table->integer('livemode')->default(0); $table->text('payload'); $table->integer('received_at'); $table->integer('processed_at')->default(0); }); $schema->create('cloud_invoice_payments', function (Blueprint $table): void { $table->bigIncrements('id'); $table->integer('invoice_id'); $table->integer('user_id'); $table->string('provider'); $table->string('provider_order_no'); $table->string('idempotency_key'); $table->decimal('amount', 12, 2); $table->string('status'); $table->integer('created_at'); $table->integer('updated_at'); }); $schema->create('cloud_invoices', function (Blueprint $table): void { $table->bigIncrements('id'); $table->integer('user_id'); $table->decimal('amount', 12, 2); $table->string('status')->default('open'); }); $schema->create('cloud_jobs', function (Blueprint $table): void { $table->bigIncrements('id'); $table->string('kind'); $table->string('execution_mode'); $table->integer('invoice_id')->nullable(); $table->integer('user_id'); $table->string('request_idempotency_key'); $table->string('phase'); $table->string('outcome')->nullable(); $table->integer('effect_may_have_applied')->nullable(); $table->string('effect_resolution'); $table->integer('effect_resolved_at')->nullable(); $table->integer('effect_resolved_by')->nullable(); $table->text('effect_resolution_reason')->nullable(); $table->integer('updated_at'); }); putenv('STRIPE_CREDENTIAL_KEY=' . str_repeat('7', 64)); $_ENV['STRIPE_CREDENTIAL_KEY'] = str_repeat('7', 64); $apiSecret = 'sk_live_1234567890'; $webhookSecret = 'whsec_1234567890'; Capsule::table('configurations')->insert([ ['name' => 'stripe_enabled', 'value' => 'true'], ['name' => 'stripe_test_mode', 'value' => 'false'], ['name' => 'stripe_card_enabled', 'value' => 'true'], ['name' => 'stripe_alipay_enabled', 'value' => 'true'], ['name' => 'stripe_callback_base_url', 'value' => 'https://panel.example.com'], ['name' => 'stripe_min_amount', 'value' => '0.50'], ['name' => 'stripe_max_amount', 'value' => '10000.00'], ['name' => 'stripe_request_timeout_seconds', 'value' => '15'], ['name' => StripeConfig::API_SECRET_KEY, 'value' => StripeCredentialCipher::encrypt($apiSecret)], ['name' => StripeConfig::WEBHOOK_SECRET_KEY, 'value' => StripeCredentialCipher::encrypt($webhookSecret)], ]); $user = new User(); $user->email = 'stripe@example.com'; $user->money = 0; $user->enable = 1; $user->is_admin = 0; $user->ref_by = 0; $user->reg_date = date('Y-m-d H:i:s'); $user->aff_rate = 0; $user->aff_money = 0; $user->save(); class FakeStripeClient extends StripeClient { private static int $number = 0; public function __construct() {} public function createCheckoutSession(array $payload, string $idempotencyKey): array { self::$number++; return [ 'checkout_session_id' => 'cs_live_FAKE' . self::$number, 'checkout_url' => 'https://checkout.stripe.com/c/pay/cs_live_FAKE' . self::$number, ]; } } class TestStripePaymentService extends StripePaymentService { protected function gatewayClient(array $settings): StripeClient { return new FakeStripeClient(); } } $service = new TestStripePaymentService(); $order = $service->createOrder($user, '12.34', 'card', '127.0.0.1', 'test-agent', 'https://panel.example.com'); if ((string) $order->status !== 'pending' || (string) $order->checkout_session_id !== 'cs_live_FAKE1' || Capsule::table('paylist')->count() !== 1) { failStripePaymentTest('Stripe local order creation failed.'); } $successEvent = [ 'id' => 'evt_success123456', 'object' => 'event', 'type' => 'checkout.session.completed', 'livemode' => true, 'data' => ['object' => [ 'id' => (string) $order->checkout_session_id, 'object' => 'checkout.session', 'mode' => 'payment', 'amount_total' => 1234, 'currency' => 'usd', 'payment_status' => 'paid', 'status' => 'complete', 'payment_method_types' => ['card'], 'client_reference_id' => (string) $order->order_no, 'payment_intent' => 'pi_FAKE123456', 'metadata' => ['virt_order_no' => (string) $order->order_no], ]], ]; $successBody = json_encode($successEvent, JSON_UNESCAPED_SLASHES); $successHeader = stripeSignature($successBody, $webhookSecret, time()); $settled = $service->processWebhook($successBody, $successHeader); $duplicate = $service->processWebhook($successBody, $successHeader); if (!$settled['credited'] || !$duplicate['duplicate'] || (string) User::find($user->id)->money !== '12.34' || Capsule::table('code')->where('type', 10007)->count() !== 1 || Capsule::table('stripe_webhook_events')->count() !== 1 || Capsule::table('stripe_orders')->where('status', 'paid')->count() !== 1) { failStripePaymentTest('Stripe signed Webhook did not settle exactly once.'); } $expiring = $service->createOrder($user, '2.00', 'alipay', '127.0.0.1', 'test-agent', 'https://panel.example.com'); Capsule::table('cloud_invoice_payments')->insert([ 'invoice_id' => 998, 'user_id' => (int) $user->id, 'provider' => 'stripe_alipay', 'provider_order_no' => (string) $expiring->order_no, 'idempotency_key' => 'stripe-invoice-expired-0001', 'amount' => '2.00', 'status' => 'pending', 'created_at' => time(), 'updated_at' => time(), ]); $expiredJobAt = time(); Capsule::table('cloud_jobs')->insert([ 'kind' => 'payment_create', 'execution_mode' => 'local', 'invoice_id' => 998, 'user_id' => (int) $user->id, 'request_idempotency_key' => 'stripe-invoice-expired-0001', 'phase' => 'terminal', 'outcome' => 'failed', 'effect_may_have_applied' => 1, 'effect_resolution' => 'unknown', 'effect_resolved_at' => null, 'effect_resolved_by' => null, 'effect_resolution_reason' => '', 'updated_at' => $expiredJobAt, ]); $expiredEvent = [ 'id' => 'evt_expired123456', 'object' => 'event', 'type' => 'checkout.session.expired', 'livemode' => true, 'data' => ['object' => [ 'id' => (string) $expiring->checkout_session_id, 'object' => 'checkout.session', 'mode' => 'payment', 'amount_total' => 200, 'currency' => 'usd', 'payment_status' => 'unpaid', 'status' => 'expired', 'payment_method_types' => ['alipay'], 'client_reference_id' => (string) $expiring->order_no, 'payment_intent' => null, 'metadata' => ['virt_order_no' => (string) $expiring->order_no], ]], ]; $expiredBody = json_encode($expiredEvent, JSON_UNESCAPED_SLASHES); $service->processWebhook($expiredBody, stripeSignature($expiredBody, $webhookSecret, time())); if ((string) Capsule::table('stripe_orders') ->where('id', $expiring->id)->value('status') !== 'expired' || (string) Capsule::table('cloud_invoice_payments') ->where('provider_order_no', $expiring->order_no) ->value('status') !== 'expired' || (string) Capsule::table('cloud_jobs') ->where('request_idempotency_key', 'stripe-invoice-expired-0001') ->value('effect_resolution') !== 'applied' || (string) Capsule::table('cloud_jobs') ->where('request_idempotency_key', 'stripe-invoice-expired-0001') ->value('effect_resolution_reason') !== '渠道终态证明原支付订单已创建') { failStripePaymentTest( 'Stripe expired session did not release payment and unknown creation locks.' ); } $invoiceOrder = $service->createOrder($user, '3.00', 'card', '127.0.0.1', 'test-agent', 'https://panel.example.com'); Capsule::table('cloud_invoice_payments')->insert([ 'invoice_id' => 999, 'user_id' => (int) $user->id, 'provider' => 'stripe_card', 'provider_order_no' => (string) $invoiceOrder->order_no, 'idempotency_key' => 'stripe-invoice-callback-0001', 'amount' => '3.00', 'status' => 'pending', 'created_at' => time(), 'updated_at' => time(), ]); $invoiceEvent = [ 'id' => 'evt_invoice123456', 'object' => 'event', 'type' => 'checkout.session.completed', 'livemode' => true, 'data' => ['object' => [ 'id' => (string) $invoiceOrder->checkout_session_id, 'object' => 'checkout.session', 'mode' => 'payment', 'amount_total' => 300, 'currency' => 'usd', 'payment_status' => 'paid', 'status' => 'complete', 'payment_method_types' => ['card'], 'client_reference_id' => (string) $invoiceOrder->order_no, 'payment_intent' => 'pi_INVOICE123456', 'metadata' => ['virt_order_no' => (string) $invoiceOrder->order_no], ]], ]; $invoiceBody = json_encode($invoiceEvent, JSON_UNESCAPED_SLASHES); $service->processWebhook($invoiceBody, stripeSignature($invoiceBody, $webhookSecret, time())); if ((string) Capsule::table('cloud_invoice_payments') ->where('provider_order_no', $invoiceOrder->order_no) ->value('status') !== 'credited_balance' || (string) User::find($user->id)->money !== '15.34' || Capsule::table('code')->where('type', 10007)->count() !== 2) { failStripePaymentTest( 'Stripe excess payment was not retained exactly once in account balance.' ); } $actor = new class { public function isAdmin() { return false; } }; if (StripeConfig::visibleMethods($actor) !== ['card', 'alipay']) { failStripePaymentTest('Stripe live-mode method visibility failed.'); } $smartyDirectory = sys_get_temp_dir() . '/sspanel-stripe-smarty'; if (!is_dir($smartyDirectory) && !mkdir($smartyDirectory, 0700, true) && !is_dir($smartyDirectory)) { failStripePaymentTest('Could not create the Stripe Smarty test directory.'); } $smarty = new Smarty(); $smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix'); $smarty->setCompileDir($smartyDirectory); $smarty->setCacheDir($smartyDirectory); $smarty->force_compile = true; $smarty->assign([ 'config' => ['appName' => 'Test Panel'], 'cdn' => '', 'user' => (object) ['isLogin' => true, 'gravatar' => '', 'user_name' => 'Admin', 'email' => 'admin@example.com'], 'stripe_config' => [ 'stripe_enabled' => false, 'stripe_test_mode' => true, 'stripe_card_enabled' => true, 'stripe_alipay_enabled' => false, 'stripe_callback_base_url' => '', 'stripe_callback_base_url_configured' => true, 'stripe_secret_configured' => true, 'stripe_webhook_secret_configured' => true, 'stripe_min_amount' => '1.00', 'stripe_max_amount' => '10000.00', 'stripe_request_timeout_seconds' => 15, ], 'stripe_webhook_url' => 'https://panel.example.com/stripe/webhook', 'stripe_orders' => null, 'stripe_summary' => ['total' => 0, 'pending' => 0, 'paid' => 0, 'paid_amount' => '0.00'], 'stripe_table_error' => '', 'stripe_filters' => ['keyword' => '', 'status' => '', 'method' => ''], ]); $adminHtml = $smarty->fetch('admin/stripe/index.tpl'); if (strpos($adminHtml, 'action="/admin/stripe/config"') === false || strpos($adminHtml, 'STRIPE_CREDENTIAL_KEY') === false || strpos($adminHtml, 'name="stripe_card_enabled"') === false || strpos($adminHtml, 'name="stripe_alipay_enabled"') === false || strpos($adminHtml, 'checkout.session.async_payment_succeeded') === false || strpos($adminHtml, 'sk_live_1234567890') !== false || strpos($adminHtml, 'whsec_1234567890') !== false) { failStripePaymentTest('Stripe admin template rendering failed.'); } echo 'Stripe Checkout payment, signature and idempotent settlement checks passed.' . PHP_EOL;