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

276 lines
11 KiB
PHP

<?php
require dirname(__DIR__) . '/vendor/autoload.php';
$System_Config = ['baseUrl' => 'https://panel.example.com'];
use App\Models\Code;
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('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');
});
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],
]);
$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',
]);
$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(1, 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);
}
echo 'Yipay signing, credit, referral and full-refund checks passed.' . PHP_EOL;