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/tests/PaytaroPaymentServiceTest.php

695 lines
29 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
$System_Config = ['baseUrl' => 'https://panel.example.com'];
use App\Services\Payment\PaytaroConfig;
use App\Services\Payment\PaytaroCredentialCipher;
use App\Services\Payment\PaytaroClient;
use App\Services\Payment\PaytaroPaymentService;
use App\Services\Payment\PaytaroProtocol;
use App\Services\Payment\PaytaroSigner;
use App\Services\Payment\PaymentOrderCreationException;
use App\Models\Code;
use App\Models\User;
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;
$documentedMapiCallback = [
'pid' => 'A1B2C3D4E5F',
'money' => '10.00',
'out_trade_no' => 'ORDER20260826001',
'trade_no' => '20260826120000123456',
'trade_status' => 'TRADE_SUCCESS',
'type' => 'alipay',
];
if (PaytaroSigner::sign($documentedMapiCallback, 'test_secret_123') !== '766c87ac10fbcd6c89da0cd2e086f8e7') {
fwrite(STDERR, 'Paytaro documented MAPI signature vector mismatch.' . PHP_EOL);
exit(1);
}
$documentedLegacyMgateCallback = [
'app_id' => 'A1B2C3D4E5F',
'out_trade_no' => 'ORDER20260826001',
'total_amount' => '1000',
'trade_no' => '20260826120000123456',
];
$legacyMgateSignature = md5(PaytaroSigner::legacyMgateCanonical($documentedLegacyMgateCallback) . 'test_secret_123');
if ($legacyMgateSignature !== 'ae3dd668b274d9563cd841c2e07393e7') {
fwrite(STDERR, 'Paytaro legacy MGate transition signature vector mismatch.' . PHP_EOL);
exit(1);
}
$legacyTransitionCallback = [
'app_id' => 'A1B2C3D4E5F',
'out_trade_no' => 'PT20260815120000A1B2C3D4E5F60708',
'total_amount' => '10000',
'trade_no' => '202608151234567890',
];
$legacyTransitionCallback['sign'] = md5(PaytaroSigner::legacyMgateCanonical($legacyTransitionCallback) . 'merchant-secret');
$legacyNotification = PaytaroProtocol::notification($legacyTransitionCallback, [
'paytaro_app_id' => 'A1B2C3D4E5F',
PaytaroConfig::SECRET_KEY => 'merchant-secret',
], '/^PT\d{14}[A-F0-9]{16}$/');
if (($legacyNotification['order_no'] ?? '') !== 'PT20260815120000A1B2C3D4E5F60708'
|| ($legacyNotification['amount_cents'] ?? '') !== '10000') {
fwrite(STDERR, 'Paytaro legacy MGate transition callback failed.' . PHP_EOL);
exit(1);
}
$fixed = [
'pid' => 'A1B2C3D4E5F',
'type' => '12345678-1234-1234-1234-123456789abc',
'out_trade_no' => 'PT20260815120000A1B2C3D4E5F60708',
'notify_url' => 'https://panel.example.com/paytaro/callback',
'return_url' => 'https://panel.example.com/paytaro/return',
'name' => 'Account balance recharge',
'money' => '100.00',
'sign_type' => 'MD5',
];
$signed = $fixed;
$signed['sign'] = PaytaroSigner::sign($signed, 'merchant-secret');
if (!PaytaroSigner::verify($signed, 'merchant-secret')) {
fwrite(STDERR, 'Valid Paytaro signature was rejected.' . PHP_EOL);
exit(1);
}
$signed['money'] = '100.01';
if (PaytaroSigner::verify($signed, 'merchant-secret')) {
fwrite(STDERR, 'Modified Paytaro payload passed signature verification.' . PHP_EOL);
exit(1);
}
$history = [];
$mock = new MockHandler([
new Response(200, ['Content-Type' => 'application/json'], json_encode([
'code' => 1,
'msg' => 'success',
'trade_no' => '20260826120000123456',
'payurl' => 'https://openapi.alipay.com/gateway.do?method=alipay.trade.wap.pay&app_id=2026000000000000',
])),
new Response(200, ['Content-Type' => 'application/json'], json_encode([
'code' => 1,
'msg' => 'success',
'trade_no' => '20260826120000123457',
'payurl' => 'https://mclient.alipay.com/cashier/mobilepay.htm?token=example',
])),
new Response(200, ['Content-Type' => 'application/json'], json_encode([
'code' => 1,
'msg' => 'success',
'trade_no' => '20260826120000123458',
'payurl' => 'https://qr.alipay.com/upx06709emtdfisjmz3h8557',
])),
new Response(200, ['Content-Type' => 'application/json'], json_encode([
'code' => 1,
'msg' => 'success',
'trade_no' => '20260826120000123459',
'payurl' => 'http://payment.example.com/insecure',
])),
]);
$handler = HandlerStack::create($mock);
$handler->push(Middleware::history($history));
$httpClient = new Client(['handler' => $handler, 'http_errors' => false]);
$gateway = (new PaytaroClient([
'paytaro_gateway_url' => PaytaroConfig::MAPI_GATEWAY_URL,
'paytaro_request_timeout_seconds' => 15,
PaytaroConfig::SECRET_KEY => 'merchant-secret',
], $httpClient))->createOrder($fixed);
$sent = [];
parse_str((string) $history[0]['request']->getBody(), $sent);
if ((string) $history[0]['request']->getUri() !== PaytaroConfig::MAPI_GATEWAY_URL
|| ($sent['pid'] ?? '') !== 'A1B2C3D4E5F'
|| ($sent['type'] ?? '') !== '12345678-1234-1234-1234-123456789abc'
|| ($sent['money'] ?? '') !== '100.00'
|| ($sent['sign_type'] ?? '') !== 'MD5'
|| !PaytaroSigner::verify($sent, 'merchant-secret')
|| isset($sent['app_id'])
|| isset($sent['total_amount'])
|| ($gateway['gateway_trade_no'] ?? '') !== '20260826120000123456'
|| ($gateway['payment_value'] ?? '') !== 'https://openapi.alipay.com/gateway.do?method=alipay.trade.wap.pay&app_id=2026000000000000') {
fwrite(STDERR, 'Paytaro MAPI request or response mapping failed.' . PHP_EOL);
exit(1);
}
$mobileGateway = (new PaytaroClient([
'paytaro_gateway_url' => PaytaroConfig::MAPI_GATEWAY_URL,
'paytaro_request_timeout_seconds' => 15,
PaytaroConfig::SECRET_KEY => 'merchant-secret',
], $httpClient))->createOrder($fixed);
if (($mobileGateway['payment_value'] ?? '') !== 'https://mclient.alipay.com/cashier/mobilepay.htm?token=example') {
fwrite(STDERR, 'Paytaro MAPI mobile payment URL was rejected.' . PHP_EOL);
exit(1);
}
$qrGateway = (new PaytaroClient([
'paytaro_gateway_url' => PaytaroConfig::MAPI_GATEWAY_URL,
'paytaro_request_timeout_seconds' => 15,
PaytaroConfig::SECRET_KEY => 'merchant-secret',
], $httpClient))->createOrder($fixed);
if (($qrGateway['payment_value'] ?? '') !== 'https://qr.alipay.com/upx06709emtdfisjmz3h8557') {
fwrite(STDERR, 'Paytaro MAPI QR payment URL was rejected.' . PHP_EOL);
exit(1);
}
try {
(new PaytaroClient([
'paytaro_gateway_url' => PaytaroConfig::MAPI_GATEWAY_URL,
'paytaro_request_timeout_seconds' => 15,
PaytaroConfig::SECRET_KEY => 'merchant-secret',
], $httpClient))->createOrder($fixed);
fwrite(STDERR, 'Paytaro accepted a non-HTTPS payment URL.' . PHP_EOL);
exit(1);
} catch (RuntimeException $exception) {
// Expected: payment links returned to the browser must use HTTPS.
}
$adminActor = new class {
public function isAdmin() { return true; }
};
$userActor = new class {
public function isAdmin() { return false; }
};
if (PaytaroConfig::canUserAccess($adminActor, ['paytaro_enabled' => true, 'paytaro_test_mode' => true]) !== true
|| PaytaroConfig::canUserAccess($userActor, ['paytaro_enabled' => true, 'paytaro_test_mode' => true]) !== false
|| PaytaroConfig::canUserAccess($userActor, ['paytaro_enabled' => true, 'paytaro_test_mode' => false]) !== true) {
fwrite(STDERR, 'Paytaro test mode access policy failed.' . PHP_EOL);
exit(1);
}
$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) {
$table->increments('id');
$table->string('name')->nullable();
$table->text('value')->nullable();
});
$schema->create('user', function (Blueprint $table) {
$table->increments('id');
$table->decimal('money', 12, 2)->default(0);
$table->integer('enable')->default(1);
$table->integer('ref_by')->default(0);
$table->dateTime('reg_date');
$table->decimal('aff_rate', 8, 2)->default(0);
$table->decimal('aff_money', 12, 2)->default(0);
});
$schema->create('paylist', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('userid');
$table->decimal('total', 12, 2);
$table->integer('status')->default(0);
$table->string('tradeno');
$table->integer('datetime')->default(0);
});
$schema->create('code', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('code');
$table->integer('type');
$table->decimal('number', 12, 2);
$table->integer('isused');
$table->integer('userid');
$table->dateTime('usedatetime');
});
$schema->create('payback', function (Blueprint $table) {
$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('paytaro_orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('order_no')->unique();
$table->string('gateway_trade_no')->nullable()->unique();
$table->integer('paylist_id')->unique();
$table->integer('user_id');
$table->decimal('amount', 12, 2);
$table->string('payment_kind')->default('');
$table->text('payment_value')->nullable();
$table->string('status')->default('creating');
$table->string('error_message')->default('');
$table->integer('paid_at')->default(0);
$table->integer('created_at')->default(0);
$table->integer('updated_at')->default(0);
});
$schema->create('paytaro_callback_events', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('event_key')->unique();
$table->string('order_no');
$table->string('gateway_trade_no');
$table->string('trade_status');
$table->text('payload');
$table->integer('received_at');
$table->integer('processed_at');
});
$schema->create('cloud_orders', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('plan_id');
$table->decimal('amount', 12, 2);
$table->string('status');
});
$schema->create('cloud_invoices', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('purpose')->default('renewal');
$table->integer('order_id')->nullable();
$table->integer('user_id');
$table->integer('plan_id')->nullable();
$table->integer('due_at')->default(0);
$table->decimal('amount', 12, 2)->default(0);
$table->string('status')->default('open');
});
$schema->create('cloud_invoice_payments', function (Blueprint $table) {
$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')->default('creating');
$table->integer('created_at');
$table->integer('updated_at');
$table->unique(['provider', 'provider_order_no']);
$table->unique(['user_id', 'idempotency_key']);
});
$schema->create('cloud_jobs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('operation_id')->unique();
$table->string('request_idempotency_key');
$table->string('request_fingerprint');
$table->integer('parent_job_id')->nullable();
$table->integer('order_id')->nullable();
$table->integer('invoice_id')->nullable();
$table->integer('instance_id')->nullable();
$table->integer('snapshot_id')->nullable();
$table->integer('user_id');
$table->integer('host_id')->nullable();
$table->string('kind');
$table->string('execution_mode');
$table->string('phase');
$table->string('outcome')->nullable();
$table->string('status');
$table->text('sealed_payload');
$table->integer('attempts')->default(0);
$table->integer('dispatch_attempts')->default(0);
$table->integer('dispatch_deadline_at');
$table->integer('dispatch_started_at')->nullable();
$table->integer('agent_accepted_at')->nullable();
$table->integer('receipt_deadline_at')->nullable();
$table->integer('terminal_at')->nullable();
$table->boolean('effect_may_have_applied')->nullable();
$table->boolean('safe_to_resubmit')->nullable();
$table->string('effect_resolution');
$table->integer('effect_resolved_at')->nullable();
$table->integer('effect_resolved_by')->nullable();
$table->text('effect_resolution_reason')->default('');
$table->boolean('finalization_incident')->default(false);
$table->string('finalization_error_code')->nullable();
$table->string('completion_event_id')->nullable();
$table->integer('read_at')->nullable();
$table->integer('dispatched_at')->nullable();
$table->string('lease_token')->nullable();
$table->integer('lease_until')->default(0);
$table->integer('available_at');
$table->string('error_code')->nullable();
$table->text('result_json')->nullable();
$table->integer('created_at');
$table->integer('updated_at');
$table->unique(['user_id', 'request_idempotency_key']);
});
Capsule::table('configurations')->insert([
'name' => 'paytaro_gateway_url',
'value' => 'https://legacy-paytaro.example.com/v1/gateway/pay',
]);
if (PaytaroConfig::values()['paytaro_gateway_url'] !== PaytaroConfig::MAPI_GATEWAY_URL) {
fwrite(STDERR, 'Paytaro did not ignore the legacy gateway configuration.' . PHP_EOL);
exit(1);
}
putenv('PAYTARO_CREDENTIAL_KEY=' . str_repeat('5', 64));
$_ENV['PAYTARO_CREDENTIAL_KEY'] = str_repeat('5', 64);
$secret = 'merchant-secret';
Capsule::table('configurations')->insert([
['name' => 'paytaro_enabled', 'value' => 'true'],
['name' => 'paytaro_test_mode', 'value' => 'false'],
['name' => 'paytaro_app_id', 'value' => 'A1B2C3D4E5F'],
['name' => 'paytaro_method_uuid', 'value' => '12345678-1234-1234-1234-123456789abc'],
['name' => 'paytaro_app_key', 'value' => PaytaroCredentialCipher::encrypt($secret)],
]);
Capsule::table('user')->insert([
['id' => 1, 'money' => 0, 'ref_by' => 2, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 0, 'aff_money' => 0],
['id' => 2, 'money' => 0, 'ref_by' => 0, 'reg_date' => date('Y-m-d H:i:s'), 'aff_rate' => 10, 'aff_money' => 0],
]);
Capsule::table('cloud_orders')->insert([
['id' => 1998, 'user_id' => 1, 'plan_id' => 1,
'amount' => '42.00', 'status' => 'awaiting_payment'],
['id' => 1997, 'user_id' => 1, 'plan_id' => 1,
'amount' => '43.00', 'status' => 'awaiting_payment'],
]);
Capsule::table('cloud_invoices')->insert([
['id' => 998, 'purpose' => 'provision', 'order_id' => 1998,
'user_id' => 1, 'plan_id' => 1, 'due_at' => time() + 1800,
'amount' => '42.00', 'status' => 'open'],
['id' => 997, 'purpose' => 'provision', 'order_id' => 1997,
'user_id' => 1, 'plan_id' => 1, 'due_at' => time() + 1800,
'amount' => '43.00', 'status' => 'open'],
]);
$invoiceCreateGateway = new class {
public function createOrder(array $payload)
{
return [
'gateway_trade_no' => '202609270000000011',
'payment_kind' => 'payurl',
'payment_value' => 'https://pay.example.com/invoice/paytaro',
];
}
};
$invoiceCreateService = new class($invoiceCreateGateway) extends PaytaroPaymentService {
private $fakeGateway;
public function __construct($fakeGateway) { $this->fakeGateway = $fakeGateway; }
protected function gatewayClient(array $settings) { return $this->fakeGateway; }
};
$createdInvoiceOrder = $invoiceCreateService->createOrder(
User::find(1), '42.00', '192.0.2.30', 'test', 'https://panel.example.com',
['invoice_id' => 998, 'idempotency_key' => 'paytaro-invoice-create-01', 'provider' => 'paytaro']
);
$createdAttempt = Capsule::table('cloud_invoice_payments')
->where('provider_order_no', (string) $createdInvoiceOrder->order_no)->first();
if ($createdAttempt === null
|| (string) $createdAttempt->status !== 'creating'
|| (string) $createdAttempt->provider !== 'paytaro'
|| !Capsule::table('paylist')->where('tradeno', (string) $createdInvoiceOrder->order_no)->exists()) {
fwrite(STDERR, 'Paytaro invoice attempt was not recorded with the local order.' . PHP_EOL);
exit(1);
}
$invoiceFailGateway = new class {
public function createOrder(array $payload)
{
throw PaymentOrderCreationException::notDispatched(
'simulated Paytaro pre-dispatch rejection'
);
}
};
$invoiceFailService = new class($invoiceFailGateway) extends PaytaroPaymentService {
private $fakeGateway;
public function __construct($fakeGateway) { $this->fakeGateway = $fakeGateway; }
protected function gatewayClient(array $settings) { return $this->fakeGateway; }
};
try {
$invoiceFailService->createOrder(
User::find(1), '43.00', '192.0.2.31', 'test', 'https://panel.example.com',
['invoice_id' => 997, 'idempotency_key' => 'paytaro-invoice-failed-01', 'provider' => 'paytaro']
);
fwrite(STDERR, 'Paytaro invoice gateway failure unexpectedly succeeded.' . PHP_EOL);
exit(1);
} catch (RuntimeException $exception) {
// The provider proved that no order was created. This terminal local
// classification permits an explicit new request but never auto-retries.
}
$failedAttempt = Capsule::table('cloud_invoice_payments')
->where('idempotency_key', 'paytaro-invoice-failed-01')->first();
if ($failedAttempt === null
|| (string) $failedAttempt->status !== 'not_created'
|| Capsule::table('paytaro_orders')->where('order_no', $failedAttempt->provider_order_no)
->where('status', 'not_created')->count() !== 1) {
fwrite(STDERR, 'Paytaro failed invoice attempt was not synchronized.' . PHP_EOL);
exit(1);
}
$orderNo = 'PT20260815120000A1B2C3D4E5F60708';
$paylistId = Capsule::table('paylist')->insertGetId([
'userid' => 1,
'total' => 100,
'status' => 0,
'tradeno' => $orderNo,
'datetime' => time(),
]);
Capsule::table('paytaro_orders')->insert([
'order_no' => $orderNo,
'gateway_trade_no' => null,
'paylist_id' => $paylistId,
'user_id' => 1,
'amount' => 100,
'payment_kind' => 'payurl',
'payment_value' => 'https://pay.example.com/order/1',
// Simulate an ambiguous gateway-create timeout: a later signed callback
// must still recover the user's money.
'status' => 'creation_unknown',
]);
$callback = [
'pid' => 'A1B2C3D4E5F',
'type' => 'alipay',
'out_trade_no' => $orderNo,
'money' => '100.00',
'trade_no' => '202608151234567890',
'trade_status' => 'TRADE_SUCCESS',
'sign_type' => 'MD5',
];
$callback['sign'] = PaytaroSigner::sign($callback, $secret);
$service = new PaytaroPaymentService();
$first = $service->processCallback($callback);
$second = $service->processCallback($callback);
$displayCode = (string) Capsule::table('code')->where('type', PaytaroPaymentService::LEDGER_TYPE)->value('code');
if (!$first['credited'] || $first['duplicate'] || $second['credited'] || !$second['duplicate']
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== 100.0
|| (float) Capsule::table('user')->where('id', 2)->value('aff_money') !== 10.0
|| Capsule::table('code')->where('type', PaytaroPaymentService::LEDGER_TYPE)->count() !== 1
|| Capsule::table('payback')->count() !== 1
|| preg_match('/^[A-F0-9]{8}$/', $displayCode) !== 1
|| $displayCode === $orderNo
|| Capsule::table('paytaro_callback_events')->count() !== 1
|| Capsule::table('paytaro_orders')->where('status', 'paid')->count() !== 1) {
fwrite(STDERR, 'Paytaro callback idempotency, credit, or referral check failed.' . PHP_EOL);
exit(1);
}
$wrongAmount = $callback;
$wrongAmount['money'] = '100.01';
$wrongAmount['sign'] = PaytaroSigner::sign($wrongAmount, $secret);
try {
$service->processCallback($wrongAmount);
fwrite(STDERR, 'Paytaro callback accepted a mismatched amount.' . PHP_EOL);
exit(1);
} catch (RuntimeException $exception) {
// Expected: a signed callback must still match the local order amount.
}
$wrongApp = $callback;
$wrongApp['pid'] = 'F5E4D3C2B1A';
$wrongApp['sign'] = PaytaroSigner::sign($wrongApp, $secret);
try {
$service->processCallback($wrongApp);
fwrite(STDERR, 'Paytaro callback accepted another App ID.' . PHP_EOL);
exit(1);
} catch (RuntimeException $exception) {
// Expected: a callback must belong to the configured merchant App ID.
}
$invoiceOrderNo = 'PT20260927120000B1B2C3D4E5F60708';
$invoicePaylistId = Capsule::table('paylist')->insertGetId([
'userid' => 1,
'total' => 25,
'status' => 0,
'tradeno' => $invoiceOrderNo,
'datetime' => time(),
]);
Capsule::table('paytaro_orders')->insert([
'order_no' => $invoiceOrderNo,
'gateway_trade_no' => null,
'paylist_id' => $invoicePaylistId,
'user_id' => 1,
'amount' => 25,
'payment_kind' => 'payurl',
'payment_value' => 'https://pay.example.com/order/invoice',
'status' => 'creation_unknown',
]);
Capsule::table('cloud_invoice_payments')->insert([
'invoice_id' => 999,
'user_id' => 1,
'provider' => 'paytaro',
'provider_order_no' => $invoiceOrderNo,
'idempotency_key' => 'paytaro-invoice-callback-01',
'amount' => 25,
'status' => 'creation_unknown',
'created_at' => time(),
'updated_at' => time(),
]);
$paymentJobNow = time();
Capsule::table('cloud_jobs')->insert([
'operation_id' => str_repeat('1', 32),
'request_idempotency_key' => 'paytaro-invoice-callback-01',
'request_fingerprint' => str_repeat('a', 64),
'invoice_id' => 999,
'user_id' => 1,
'host_id' => null,
'kind' => 'payment_create',
'execution_mode' => 'local',
'phase' => 'terminal',
'outcome' => 'failed',
'status' => 'failed',
'sealed_payload' => '',
'attempts' => 1,
'dispatch_attempts' => 1,
'dispatch_deadline_at' => $paymentJobNow - 120,
'dispatch_started_at' => $paymentJobNow - 90,
'receipt_deadline_at' => $paymentJobNow - 30,
'terminal_at' => $paymentJobNow - 1,
'effect_may_have_applied' => true,
'safe_to_resubmit' => false,
'effect_resolution' => 'unknown',
'effect_resolution_reason' => '',
'finalization_incident' => false,
'lease_until' => 0,
'available_at' => $paymentJobNow - 120,
'error_code' => 'payment_creation_unknown',
'result_json' => json_encode(['cause_code' => 'payment_creation_unknown']),
'created_at' => $paymentJobNow - 120,
'updated_at' => $paymentJobNow - 1,
]);
$providerOrderCountBeforeInvoiceCallback = Capsule::table('paytaro_orders')->count();
$invoiceCallback = [
'pid' => 'A1B2C3D4E5F',
'type' => 'alipay',
'out_trade_no' => $invoiceOrderNo,
'money' => '25.00',
'trade_no' => '202609271234567891',
'trade_status' => 'TRADE_SUCCESS',
'sign_type' => 'MD5',
];
$invoiceCallback['sign'] = PaytaroSigner::sign($invoiceCallback, $secret);
$invoiceResult = $service->processCallback($invoiceCallback);
$resolvedPaymentJob = Capsule::table('cloud_jobs')
->where('request_idempotency_key', 'paytaro-invoice-callback-01')->first();
if (!$invoiceResult['credited']
|| (string) Capsule::table('cloud_invoice_payments')
->where('provider_order_no', $invoiceOrderNo)->value('status') !== 'credited_balance'
|| (string) Capsule::table('paytaro_orders')->where('order_no', $invoiceOrderNo)
->value('status') !== 'paid'
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== 125.0
|| $resolvedPaymentJob === null
|| (string) $resolvedPaymentJob->phase !== 'terminal'
|| (string) $resolvedPaymentJob->outcome !== 'failed'
|| (string) $resolvedPaymentJob->status !== 'failed'
|| (string) $resolvedPaymentJob->effect_resolution !== 'applied'
|| (int) $resolvedPaymentJob->effect_resolved_at < $paymentJobNow
|| $resolvedPaymentJob->effect_resolved_by !== null
|| (string) $resolvedPaymentJob->effect_resolution_reason
!== '经签名支付回调确认原订单已由渠道接受'
|| (int) $resolvedPaymentJob->finalization_incident !== 0
|| Capsule::table('cloud_jobs')->count() !== 1
|| Capsule::table('paytaro_orders')->count()
!== $providerOrderCountBeforeInvoiceCallback) {
fwrite(STDERR, 'Paytaro invoice callback did not invoke invoice settlement.' . PHP_EOL);
exit(1);
}
$smartyDirectory = sys_get_temp_dir() . '/sspanel-paytaro-smarty';
if (!is_dir($smartyDirectory) && !mkdir($smartyDirectory, 0700, true) && !is_dir($smartyDirectory)) {
fwrite(STDERR, 'Could not create the Paytaro Smarty test directory.' . PHP_EOL);
exit(1);
}
$smarty = new Smarty();
$smarty->setTemplateDir(dirname(__DIR__) . '/resources/views/venix');
$smarty->setCompileDir($smartyDirectory);
$smarty->setCacheDir($smartyDirectory);
$smarty->force_compile = true;
$adminUser = (object) [
'isLogin' => true,
'gravatar' => '',
'user_name' => 'Admin',
'email' => 'admin@example.com',
];
$smarty->assign([
'config' => ['appName' => 'Test Panel'],
'cdn' => '',
'user' => $adminUser,
'paytaro_config' => [
'paytaro_enabled' => false,
'paytaro_test_mode' => true,
'paytaro_gateway_url' => '',
'paytaro_gateway_url_configured' => true,
'paytaro_callback_base_url' => '',
'paytaro_callback_base_url_configured' => true,
'paytaro_app_id' => '',
'paytaro_app_id_configured' => true,
'paytaro_method_uuid' => '',
'paytaro_method_uuid_configured' => true,
'paytaro_secret_configured' => false,
'paytaro_min_amount' => '1.00',
'paytaro_max_amount' => '10000.00',
'paytaro_request_timeout_seconds' => 15,
],
'paytaro_orders' => null,
'paytaro_summary' => ['total' => 0, 'pending' => 0, 'paid' => 0, 'paid_amount' => '0.00'],
'paytaro_table_error' => '',
'paytaro_filters' => ['keyword' => '', 'status' => ''],
]);
$adminHtml = $smarty->fetch('admin/paytaro/index.tpl');
$adminControllerSource = file_get_contents(dirname(__DIR__) . '/app/Controllers/Admin/PaytaroController.php');
if (strpos($adminHtml, 'action="/admin/paytaro/config"') === false
|| strpos($adminHtml, 'PAYTARO_CREDENTIAL_KEY') === false
|| strpos($adminHtml, 'Paytaro MAPI') === false
|| strpos($adminHtml, 'name="paytaro_method_uuid"') === false
|| strpos($adminHtml, 'href="/admin/paytaro"') === false
|| $adminControllerSource === false
|| strpos($adminControllerSource, "getParam('page', 1)") === false
|| strpos($adminControllerSource, "paginate(30, ['*'], 'page', \$page)") === false
|| strpos($adminHtml, '隐藏 Venix 充值页支付宝按钮') !== false) {
fwrite(STDERR, 'Paytaro admin template rendering failed.' . PHP_EOL);
exit(1);
}
$rechargeTemplate = file_get_contents(dirname(__DIR__) . '/resources/views/venix/user/paytaro.tpl');
$userLayoutScripts = file_get_contents(dirname(__DIR__) . '/resources/views/venix/user/layout_scripts.tpl');
$rechargeScript = file_get_contents(dirname(__DIR__) . '/public/theme/venix/js/recharge.js');
$previousTimezone = date_default_timezone_get();
date_default_timezone_set('Asia/Shanghai');
$historyRecord = new Code();
$historyRecord->setRawAttributes(['usedatetime' => '2026-11-02 16:00:00']);
$historyEpoch = $historyRecord->used_at_timestamp;
date_default_timezone_set($previousTimezone);
if ($rechargeTemplate === false
|| $userLayoutScripts === false
|| $rechargeScript === false
|| strpos($rechargeTemplate, 'src="/theme/venix/js/recharge.js?') === false
|| strpos($rechargeScript, 'definition.type === "paytaro" && isPaytaroMobileDevice()') === false
|| strpos($rechargeScript, 'alipays://platformapi/startapp?appId=20000067') === false
|| strpos($rechargeScript, 'url.searchParams.get("method") === "alipay.trade.wap.pay"') === false
|| strpos($rechargeScript, 'host === "mclient.alipay.com"') === false
|| strpos($rechargeScript, 'function isPaytaroMobileDevice()') === false
|| strpos($rechargeScript, 'navigator.userAgentData.mobile') === false
|| strpos($rechargeScript, 'topWindow().location.assign(mobileUrl)') === false
|| strpos($rechargeScript, 'function renderPaymentQr(') === false
|| strpos($rechargeScript, 'content.length > 1200 ? levels.L : levels.M') === false
|| strpos($rechargeTemplate, 'data-recharge-time') === false
|| strpos($rechargeTemplate, 'data-timestamp="{$code->used_at_timestamp|escape:') === false
|| strpos($rechargeScript, 'function renderBrowserTimes()') === false
|| strpos($rechargeScript,
'window.VenixUserCopy.date(date.getTime(), { hour12: false })') === false
|| $historyEpoch !== 1793606400
|| strpos($userLayoutScripts, 'src="{$cdn}/theme/venix/js/qrcode.min.js?v={$vu_asset_version}"') === false) {
fwrite(STDERR, 'Paytaro mobile redirect policy failed.' . PHP_EOL);
exit(1);
}
$userControllerSource = file_get_contents(dirname(__DIR__) . '/app/Controllers/PaytaroController.php');
if ($userControllerSource === false
|| strpos($userControllerSource, "->whereNotExists(function (\$query)") === false
|| strpos($userControllerSource, "withRedirect('/user/cloud/invoices', 302)") === false) {
fwrite(STDERR, 'Paytaro invoice orders are not isolated from recharge status and return handling.' . PHP_EOL);
exit(1);
}
echo 'Paytaro MAPI signing, invoice bridge, callback, idempotency, credit, and referral checks passed.' . PHP_EOL;