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

460 lines
18 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
$System_Config = ['baseUrl' => 'https://panel.example.com'];
use App\Models\Code;
use App\Models\User;
use App\Services\Payment\YipayConfig;
use App\Services\Payment\YipayCredentialCipher;
use App\Services\Payment\YipayPaymentService;
use App\Services\Payment\YipaySigner;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$fixed = [
'pid' => '1001',
'type' => 'alipay',
'out_trade_no' => 'YP20260815120000A1B2C3D4E5F60708',
'notify_url' => 'https://panel.example.com/yipay/callback',
'name' => '账户余额充值',
'money' => '100.00',
'clientip' => '192.0.2.1',
'device' => 'pc',
];
if (YipaySigner::sign($fixed, 'merchant-secret') !== 'd896bf549b0e5afbb862b292ee9f0906') {
fwrite(STDERR, 'Yipay MD5 fixed vector mismatch.' . PHP_EOL);
exit(1);
}
$signed = $fixed;
$signed['sign_type'] = 'MD5';
$signed['sign'] = YipaySigner::sign($signed, 'merchant-secret');
if (!YipaySigner::verify($signed, 'merchant-secret')) {
fwrite(STDERR, 'Valid Yipay signature was rejected.' . PHP_EOL);
exit(1);
}
$signed['money'] = '100.01';
if (YipaySigner::verify($signed, 'merchant-secret')) {
fwrite(STDERR, 'Modified Yipay payload passed signature verification.' . PHP_EOL);
exit(1);
}
$adminActor = new class {
public function isAdmin() { return true; }
};
$userActor = new class {
public function isAdmin() { return false; }
};
if (YipayConfig::canUserAccess($adminActor, ['yipay_enabled' => true, 'yipay_test_mode' => true]) !== true
|| YipayConfig::canUserAccess($userActor, ['yipay_enabled' => true, 'yipay_test_mode' => true]) !== false
|| YipayConfig::canUserAccess($userActor, ['yipay_enabled' => true, 'yipay_test_mode' => false]) !== true) {
fwrite(STDERR, 'Yipay 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('restrict_balance_purchase')->default(0);
$table->integer('restrict_recharge')->default(0);
$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('yipay_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->string('payment_type');
$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('yipay_callback_events', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('event_key')->unique();
$table->string('order_no');
$table->string('gateway_trade_no');
$table->string('payment_type');
$table->string('trade_status');
$table->text('payload');
$table->integer('received_at');
$table->integer('processed_at');
});
$schema->create('yipay_refunds', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('order_no')->unique();
$table->string('gateway_trade_no')->unique();
$table->decimal('amount', 12, 2);
$table->string('status');
$table->string('gateway_message')->default('');
$table->integer('admin_user_id');
$table->decimal('referral_reversal_amount', 12, 2)->default(0);
$table->integer('requested_at');
$table->integer('completed_at');
$table->integer('updated_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']);
});
putenv('YIPAY_CREDENTIAL_KEY=' . str_repeat('2', 64));
$_ENV['YIPAY_CREDENTIAL_KEY'] = str_repeat('2', 64);
$secret = 'merchant-secret';
Capsule::table('configurations')->insert([
['name' => 'yipay_enabled', 'value' => 'true'],
['name' => 'yipay_test_mode', 'value' => 'false'],
['name' => 'yipay_pid', 'value' => '1001'],
['name' => 'yipay_secret_key', 'value' => YipayCredentialCipher::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 [
'trade_no' => '202609270000000001',
'payurl' => 'https://pay.example.com/invoice/yipay',
];
}
};
$invoiceCreateService = new class($invoiceCreateGateway) extends YipayPaymentService {
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', 'alipay', '192.0.2.20', 'test', 'https://panel.example.com',
['invoice_id' => 998, 'idempotency_key' => 'yipay-invoice-create-0001', 'provider' => 'yipay_alipay']
);
$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 !== 'yipay_alipay'
|| (int) $createdAttempt->user_id !== 1
|| !Capsule::table('paylist')->where('tradeno', (string) $createdInvoiceOrder->order_no)->exists()) {
fwrite(STDERR, 'Yipay invoice attempt was not recorded with the local order.' . PHP_EOL);
exit(1);
}
$invoiceFailGateway = new class {
public function createOrder(array $payload)
{
throw new RuntimeException('simulated Yipay gateway failure');
}
};
$invoiceFailService = new class($invoiceFailGateway) extends YipayPaymentService {
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', 'alipay', '192.0.2.21', 'test', 'https://panel.example.com',
['invoice_id' => 997, 'idempotency_key' => 'yipay-invoice-failed-0001', 'provider' => 'yipay_alipay']
);
fwrite(STDERR, 'Yipay invoice gateway failure unexpectedly succeeded.' . PHP_EOL);
exit(1);
} catch (RuntimeException $exception) {
// Expected: both the provider order and invoice attempt must become failed.
}
$failedAttempt = Capsule::table('cloud_invoice_payments')
->where('idempotency_key', 'yipay-invoice-failed-0001')->first();
if ($failedAttempt === null
|| (string) $failedAttempt->status !== 'failed'
|| Capsule::table('yipay_orders')->where('order_no', $failedAttempt->provider_order_no)
->where('status', 'failed')->count() !== 1) {
fwrite(STDERR, 'Yipay failed invoice attempt was not synchronized.' . PHP_EOL);
exit(1);
}
$orderNo = 'YP20260815120000A1B2C3D4E5F60708';
$paylistId = Capsule::table('paylist')->insertGetId([
'userid' => 1,
'total' => 100,
'status' => 0,
'tradeno' => $orderNo,
'datetime' => time(),
]);
Capsule::table('yipay_orders')->insert([
'order_no' => $orderNo,
'gateway_trade_no' => '202608151234567890',
'paylist_id' => $paylistId,
'user_id' => 1,
'payment_type' => 'alipay',
'amount' => 100,
'payment_kind' => 'payurl',
'payment_value' => 'https://pay.example.com/order/1',
'status' => 'pending',
]);
$refundRecordId = (int) Capsule::table('yipay_orders')->where('order_no', $orderNo)->value('id');
$callback = [
'pid' => '1001',
'trade_no' => '202608151234567890',
'out_trade_no' => $orderNo,
'type' => 'alipay',
'name' => '账户余额充值',
'money' => '100.00',
'trade_status' => 'TRADE_SUCCESS',
'param' => '',
'sign_type' => 'MD5',
];
$callback['sign'] = YipaySigner::sign($callback, $secret);
$service = new YipayPaymentService();
$first = $service->processCallback($callback);
$second = $service->processCallback($callback);
$displayCode = (string) Capsule::table('code')->where('type', YipayPaymentService::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', YipayPaymentService::LEDGER_TYPE)->count() !== 1
|| Capsule::table('payback')->count() !== 1
|| preg_match('/^[A-F0-9]{8}$/', $displayCode) !== 1
|| $displayCode === $orderNo
|| Capsule::table('yipay_callback_events')->count() !== 1
|| Capsule::table('yipay_orders')->where('status', 'paid')->count() !== 1) {
fwrite(STDERR, 'Yipay callback idempotency, credit or referral check failed.' . PHP_EOL);
exit(1);
}
$legacyLedger = new Code();
$legacyLedger->code = $orderNo;
$legacyLedger->type = YipayPaymentService::LEDGER_TYPE;
$expectedLegacyDisplayCode = strtoupper(substr(hash('sha256', 'recharge-display:' . $orderNo), 0, 8));
if (preg_match('/^[A-F0-9]{8}$/', (string) $legacyLedger->display_code) !== 1
|| (string) $legacyLedger->display_code === $orderNo
|| (string) $legacyLedger->display_code !== $expectedLegacyDisplayCode) {
fwrite(STDERR, 'Legacy Yipay recharge code masking failed.' . PHP_EOL);
exit(1);
}
$wrongAmount = $callback;
$wrongAmount['money'] = '100.01';
$wrongAmount['sign'] = YipaySigner::sign($wrongAmount, $secret);
try {
$service->processCallback($wrongAmount);
fwrite(STDERR, 'Yipay callback accepted a mismatched amount.' . PHP_EOL);
exit(1);
} catch (RuntimeException $exception) {
// Expected: signed callbacks must still match the local order amount.
}
// Simulate a package purchase consuming the entire recharge before refunding.
Capsule::table('user')->where('id', 1)->update(['money' => 0]);
$refundGateway = new class {
public $calls = 0;
public function refund($tradeNo, $orderNo, $amount)
{
$this->calls++;
if ($tradeNo !== '202608151234567890' || $orderNo !== 'YP20260815120000A1B2C3D4E5F60708' || $amount !== '100.00') {
throw new RuntimeException('Unexpected refund payload.');
}
return ['code' => 1, 'msg' => '退款成功'];
}
};
$refundService = new class($refundGateway) extends YipayPaymentService {
private $fakeGateway;
public function __construct($fakeGateway) { $this->fakeGateway = $fakeGateway; }
protected function gatewayClient(array $settings) { return $this->fakeGateway; }
};
$refund = $refundService->refundById($refundRecordId, 99);
if ($refund['amount'] !== '100.00'
|| $refundGateway->calls !== 1
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== -100.0
|| (float) Capsule::table('user')->where('id', 2)->value('aff_money') !== 0.0
|| (int) Capsule::table('paylist')->where('id', $paylistId)->value('status') !== 2
|| Capsule::table('code')->where('type', -2)->count() !== 1
|| (float) Capsule::table('payback')->sum('ref_get') !== 0.0
|| Capsule::table('yipay_refunds')->where('status', 'success')->count() !== 1
|| Capsule::table('yipay_orders')->where('status', 'refunded')->count() !== 1) {
fwrite(STDERR, 'Yipay refund or local balance reversal check failed.' . PHP_EOL);
exit(1);
}
try {
$refundService->refund($orderNo, 99);
fwrite(STDERR, 'Yipay duplicate refund was accepted.' . PHP_EOL);
exit(1);
} catch (RuntimeException $exception) {
// Expected: a refunded order must not call the gateway again.
}
if ($refundGateway->calls !== 1) {
fwrite(STDERR, 'Yipay duplicate refund reached the gateway.' . PHP_EOL);
exit(1);
}
$afterRefundCallback = $service->processCallback($callback);
if (!$afterRefundCallback['duplicate']
|| $afterRefundCallback['credited']
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== -100.0
|| Capsule::table('yipay_orders')->where('status', 'refunded')->count() !== 1) {
fwrite(STDERR, 'Yipay refunded order was credited by a repeated callback.' . PHP_EOL);
exit(1);
}
$invoiceOrderNo = 'YP20260927120000B1B2C3D4E5F60708';
$invoicePaylistId = Capsule::table('paylist')->insertGetId([
'userid' => 1,
'total' => 25,
'status' => 0,
'tradeno' => $invoiceOrderNo,
'datetime' => time(),
]);
Capsule::table('yipay_orders')->insert([
'order_no' => $invoiceOrderNo,
'gateway_trade_no' => '202609271234567890',
'paylist_id' => $invoicePaylistId,
'user_id' => 1,
'payment_type' => 'alipay',
'amount' => 25,
'payment_kind' => 'payurl',
'payment_value' => 'https://pay.example.com/order/invoice',
'status' => 'pending',
]);
Capsule::table('cloud_invoice_payments')->insert([
'invoice_id' => 999,
'user_id' => 1,
'provider' => 'yipay_alipay',
'provider_order_no' => $invoiceOrderNo,
'idempotency_key' => 'yipay-invoice-callback-0001',
'amount' => 25,
'status' => 'pending',
'created_at' => time(),
'updated_at' => time(),
]);
$invoiceCallback = [
'pid' => '1001',
'trade_no' => '202609271234567890',
'out_trade_no' => $invoiceOrderNo,
'type' => 'alipay',
'name' => '云服务器续费账单',
'money' => '25.00',
'trade_status' => 'TRADE_SUCCESS',
'param' => '',
'sign_type' => 'MD5',
];
$invoiceCallback['sign'] = YipaySigner::sign($invoiceCallback, $secret);
$invoiceResult = $service->processCallback($invoiceCallback);
if (!$invoiceResult['credited']
|| (string) Capsule::table('cloud_invoice_payments')
->where('provider_order_no', $invoiceOrderNo)->value('status') !== 'credited_balance'
|| (float) Capsule::table('user')->where('id', 1)->value('money') !== -75.0) {
fwrite(STDERR, 'Yipay invoice callback did not invoke invoice settlement.' . PHP_EOL);
exit(1);
}
try {
$refundService->refund($invoiceOrderNo, 99);
fwrite(STDERR, 'Yipay accepted an automatic refund for an invoice payment.' . PHP_EOL);
exit(1);
} catch (RuntimeException $exception) {
if (strpos($exception->getMessage(), '账单支付不支持自动退款') === false) {
throw $exception;
}
}
if ($refundGateway->calls !== 1
|| Capsule::table('yipay_orders')->where('order_no', $invoiceOrderNo)->value('status') !== 'paid'
|| Capsule::table('yipay_refunds')->where('order_no', $invoiceOrderNo)->exists()) {
fwrite(STDERR, 'Yipay invoice refund rejection reached the gateway or mutated the order.' . PHP_EOL);
exit(1);
}
$controllerSource = file_get_contents(dirname(__DIR__) . '/app/Controllers/YipayController.php');
if ($controllerSource === false
|| strpos($controllerSource, "->whereNotExists(function (\$query)") === false
|| strpos($controllerSource, "withRedirect('/user/cloud#invoices', 302)") === false) {
fwrite(STDERR, 'Yipay invoice orders are not isolated from recharge status and return handling.' . PHP_EOL);
exit(1);
}
echo 'Yipay signing, invoice bridge, credit, referral and refund checks passed.' . PHP_EOL;