AgentPaymentOrderTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. <?php
  2. namespace Tests\Integration;
  3. use App\Models\Agent\Agent;
  4. use App\Models\Agent\AgentEquityOrder;
  5. use App\Models\Agent\AgentPaymentOrder;
  6. use App\Models\Agent\AgentSetting;
  7. use App\Models\PaymentOrder;
  8. use App\Models\RechargeChannel;
  9. use App\Services\Agent\AgentEquityService;
  10. use App\Services\Agent\AgentPaymentService;
  11. use App\Services\Agent\AgentWalletService;
  12. use App\Services\Payment\JdPayService;
  13. use App\Services\PaymentOrderService;
  14. use GuzzleHttp\Handler\MockHandler;
  15. use GuzzleHttp\HandlerStack;
  16. use GuzzleHttp\Middleware;
  17. use GuzzleHttp\Psr7\Response;
  18. use Illuminate\Database\Schema\Blueprint;
  19. use Illuminate\Support\Facades\DB;
  20. use Illuminate\Support\Facades\Schema;
  21. use PHPUnit\Framework\TestCase;
  22. use Tests\Support\AgentTestEnvironment;
  23. /** 代理人民币充值:总后台配置的通道、三方回调入账到代理钱包、人工充值流程。 */
  24. class AgentPaymentOrderTest extends TestCase
  25. {
  26. use AgentTestEnvironment;
  27. private AgentPaymentService $payments;
  28. private function payments(): void
  29. {
  30. Schema::create('recharge_channel', function (Blueprint $t) {
  31. $t->id(); $t->integer('from'); $t->integer('data_type'); $t->string('key');
  32. $t->string('name'); $t->string('type'); $t->decimal('rate', 8, 4);
  33. $t->decimal('min')->nullable(); $t->decimal('max')->nullable(); $t->string('fixed')->nullable();
  34. $t->integer('status'); $t->integer('sort'); $t->timestamps();
  35. });
  36. Schema::create('recharge_channel_group', function (Blueprint $t) {
  37. $t->id(); $t->string('name'); $t->text('recharge_type')->nullable();
  38. $t->text('withdraw_type')->nullable(); $t->text('activity_type')->nullable(); $t->timestamps();
  39. });
  40. $fixture = require dirname(__DIR__) . '/fixtures/payment_provider_channels.php';
  41. DB::table('recharge_channel')->insert($fixture['channels']);
  42. DB::table('recharge_channel_group')->insert($fixture['groups']);
  43. foreach (['2026_09_08_160000_add_payment_provider_status_and_channel_soft_deletes.php',
  44. '2026_09_08_170000_add_soft_deletes_to_recharge_channel_groups.php',
  45. '2026_10_28_150000_add_recharge_channel_logo.php', '2026_10_28_160000_create_recharge_method_logos.php',
  46. '2026_11_08_120000_create_agent_payment_orders.php'] as $file) {
  47. (require dirname(__DIR__, 2) . '/database/migrations/' . $file)->up();
  48. }
  49. config(['app.url' => 'https://api.example.test', 'app.jd_pay_mch_id' => 'JD-MCH', 'app.jd_pay_key' => 'jd-secret']);
  50. $wallets = new AgentWalletService();
  51. $this->payments = new AgentPaymentService($wallets, new AgentEquityService($wallets));
  52. }
  53. /** 直接写库:其他测试类可能已缓存 agent_settings 的旧列清单,fill() 会丢掉新列。 */
  54. private function useGroup(int $groupId): void
  55. {
  56. AgentSetting::current();
  57. DB::table('agent_settings')->where('id', 1)->update(['recharge_channel_group_id' => $groupId]);
  58. }
  59. private function onlineOrder(Agent $agent, string $amount = '100.00'): AgentPaymentOrder
  60. {
  61. return AgentPaymentOrder::query()->create([
  62. 'agent_id' => $agent->id, 'type' => PaymentOrderService::TYPE_PAY, 'member_id' => AgentPaymentService::payerId($agent),
  63. 'order_no' => PaymentOrderService::createOrderNo('agjd1_', AgentPaymentService::payerId($agent)),
  64. 'amount' => $amount, 'channel' => JdPayService::CHANNEL, 'bank_name' => 'JD钱包',
  65. 'status' => PaymentOrderService::STATUS_PROCESS,
  66. ]);
  67. }
  68. private function jdCallback(AgentPaymentOrder $order, string $status = JdPayService::PAY_STATUS_SUCCESS): array
  69. {
  70. $amount = JdPayService::amount($order->amount);
  71. $params = ['userCode' => 'JD-MCH', 'orderCode' => $order->order_no, 'amount' => $amount, 'status' => $status];
  72. $params['sign'] = JdPayService::signature([$order->order_no, $amount, 'JD-MCH', $status], 'jd-secret');
  73. return $params;
  74. }
  75. public function test_channels_follow_the_configured_group_and_provider_whitelists(): void
  76. {
  77. $this->payments();
  78. $this->useGroup(2);
  79. $types = array_column($this->payments->channels(), 'value');
  80. $this->assertEqualsCanonicalizing(['usdt', 'rgcz', 'JDpay', 'NOpay12', 'NOpay13', 'ZIMUpay'], $types);
  81. config(['app.jd_pay_recharge_user_ids' => '1001,1002']);
  82. $this->assertNotContains('JDpay', array_column($this->payments->channels(), 'value'), 'member-only whitelist hides the channel from agents');
  83. DB::table('payment_providers')->where('code', 'no')->update(['status' => 0]);
  84. $this->assertNotContains('NOpay12', array_column($this->payments->channels(), 'value'));
  85. }
  86. public function test_online_order_rejects_channels_outside_the_group_or_disabled_providers(): void
  87. {
  88. $this->payments();
  89. $this->useGroup(2);
  90. $agent = $this->agent();
  91. foreach (['wxsm' => '不支持此充值方式', 'rgcz' => '该通道请使用对应的充值接口'] as $type => $message) {
  92. try { $this->payments->createOnline($agent, '100', $type); $this->fail($type); }
  93. catch (\Exception $e) { $this->assertSame($message, $e->getMessage()); }
  94. }
  95. DB::table('payment_providers')->where('code', 'zimu')->update(['status' => 0]);
  96. $this->expectExceptionMessage('支付公司已禁用');
  97. $this->payments->createOnline($agent, '100', 'ZIMUpay');
  98. }
  99. public function test_provider_callback_credits_the_agent_once_and_counts_as_margin(): void
  100. {
  101. $this->payments();
  102. $agent = $this->agent();
  103. $order = $this->onlineOrder($agent, '100.00');
  104. $this->assertSame($order->id, PaymentOrderService::findPayOrder($order->order_no)->id);
  105. $this->assertInstanceOf(AgentPaymentOrder::class, PaymentOrderService::findPayOrder($order->order_no));
  106. $this->assertTrue(PaymentOrderService::receivePay($this->jdCallback($order)));
  107. $this->assertTrue(PaymentOrderService::receivePay($this->jdCallback($order)), 'replayed callback is acknowledged');
  108. $agent = $agent->fresh();
  109. $this->assertSame('100.0000', $agent->balance);
  110. $this->assertSame('100.0000', $agent->margin_amount, 'joint agent recharges are margin');
  111. $this->assertSame(PaymentOrderService::STATUS_SUCCESS, $order->fresh()->status);
  112. $this->assertSame(1, DB::table('agent_balance_logs')->where('agent_id', $agent->id)->where('type', 'recharge')->count());
  113. $this->assertSame(0, DB::table('payment_orders')->count(), 'agent orders never land in member payment_orders');
  114. $this->assertSame(0, DB::table('wallets')->count());
  115. }
  116. public function test_bad_signature_and_failed_payment_do_not_credit(): void
  117. {
  118. $this->payments();
  119. $agent = $this->agent();
  120. $order = $this->onlineOrder($agent);
  121. $forged = $this->jdCallback($order);
  122. $forged['sign'] = 'X';
  123. $this->assertFalse(PaymentOrderService::receivePay($forged));
  124. $this->assertTrue(PaymentOrderService::receivePay($this->jdCallback($order, JdPayService::PAY_STATUS_FAIL)));
  125. $this->assertSame(PaymentOrderService::STATUS_FAIL, $order->fresh()->status);
  126. $this->assertTrue(PaymentOrderService::receivePay($this->jdCallback($order)), 'late success after failure is ignored');
  127. $this->assertSame('0.0000', $agent->fresh()->balance);
  128. }
  129. public function test_paid_online_recharge_opens_a_pending_equity_order(): void
  130. {
  131. $this->payments();
  132. AgentSetting::current()->update(['equity_enabled' => 1, 'equity_price_per_percent' => 1000,
  133. 'equity_min_percent' => 0.1, 'equity_max_percent' => 1]);
  134. $agent = $this->agent(Agent::TYPE_EQUITY);
  135. $equity = (new AgentEquityService(new AgentWalletService()))->order($agent, '0.1');
  136. $this->assertSame(AgentEquityOrder::STATUS_PENDING, $equity->status);
  137. PaymentOrderService::receivePay($this->jdCallback($this->onlineOrder($agent, '100.00')));
  138. $this->assertSame(AgentEquityOrder::STATUS_COMPLETED, $equity->fresh()->status);
  139. $this->assertSame('0.1000', $agent->fresh()->equity_percent);
  140. $this->assertSame('0.0000', $agent->fresh()->balance);
  141. }
  142. public function test_manual_recharge_needs_pay_data_proof_and_audit(): void
  143. {
  144. $this->payments();
  145. $this->useGroup(2);
  146. $agent = $this->agent();
  147. $order = $this->payments->createManual($agent, '500', 1);
  148. $this->assertStringStartsWith('agrgcz_', $order->order_no);
  149. try { $this->payments->submitImage($agent, $order->id, 'https://example.test/a.png'); $this->fail('proof before pay data'); }
  150. catch (\RuntimeException $e) { $this->assertSame('待处理中,请稍后', $e->getMessage()); }
  151. $this->assertSame(1, $this->payments->setPayData([$order->id], 1, '工商银行 6222… 张三'));
  152. try { $this->payments->manualAudit($order->id, 2, '', 1); $this->fail('audit before proof'); }
  153. catch (\RuntimeException $e) { $this->assertSame('代理未提交充值凭证', $e->getMessage()); }
  154. $this->payments->submitImage($agent, $order->id, 'https://example.test/a.png');
  155. $this->payments->manualAudit($order->id, 2, 'ok', 1);
  156. $this->assertSame('500.0000', $agent->fresh()->balance);
  157. $this->assertSame(PaymentOrderService::STATUS_SUCCESS, $order->fresh()->status);
  158. $this->expectExceptionMessage('订单已完成,不可驳回');
  159. $this->payments->manualAudit($order->id, 3, 'late', 1);
  160. }
  161. public function test_manual_recharge_requires_rgcz_in_the_agent_group(): void
  162. {
  163. $this->payments();
  164. $this->expectExceptionMessage('不支持此充值方式');
  165. $this->payments->createManual($this->agent(), '500', 1); // group 1 has no rgcz
  166. }
  167. /** 模拟 JD 下单返回,返回记录到的请求。 */
  168. private function fakeJd(array $response): \ArrayObject
  169. {
  170. $history = new \ArrayObject();
  171. $stack = HandlerStack::create(new MockHandler([new Response(200, [], json_encode($response))]));
  172. $stack->push(Middleware::history($history));
  173. JdPayService::$handler = $stack;
  174. config(['app.jd_pay_gateway' => 'https://jd.example.test/pay']);
  175. return $history;
  176. }
  177. protected function tearDown(): void
  178. {
  179. JdPayService::$handler = null;
  180. parent::tearDown();
  181. }
  182. public function test_online_order_is_created_in_agent_table_and_hides_raw_provider_response(): void
  183. {
  184. $this->payments();
  185. $this->useGroup(2);
  186. $agent = $this->agent();
  187. $history = $this->fakeJd(['code' => 200, 'data' => ['orderNo' => 'JD-PAY-1', 'url' => '']]);
  188. $result = $this->payments->createOnline($agent, '100.50', 'JDpay');
  189. $order = $result['order'];
  190. $this->assertStringStartsWith('agjd1_', $order->order_no);
  191. parse_str((string) $history[0]['request']->getBody(), $sent);
  192. $this->assertSame($order->order_no, $sent['orderCode']);
  193. $this->assertSame('100.50', $sent['amount']);
  194. $this->assertSame(PaymentOrderService::STATUS_PROCESS, $order->status);
  195. $this->assertSame('JD-PAY-1', $order->pay_no);
  196. $this->assertArrayNotHasKey('pay_data', $order->toArray(), 'raw provider response is not returned to the agent');
  197. $this->assertArrayNotHasKey('pay_data', $this->payments->paginate([], $agent)['list'][0]->toArray());
  198. $this->assertNotEmpty($this->payments->paginate([])['list'][0]->toArray()['pay_data'], 'admin still sees it');
  199. $this->assertSame(0, DB::table('payment_orders')->count());
  200. $this->assertTrue(PaymentOrderService::receivePay($this->jdCallback($order)));
  201. $this->assertSame('100.5000', $agent->fresh()->balance);
  202. }
  203. public function test_member_online_order_still_lands_in_payment_orders(): void
  204. {
  205. $this->payments();
  206. Schema::drop('payment_orders');
  207. Schema::create('payment_orders', function (Blueprint $t) {
  208. $t->id(); $t->tinyInteger('type'); $t->string('order_no')->unique(); $t->string('member_id');
  209. $t->decimal('amount', 18, 2); $t->decimal('fee', 18, 4)->default(0); $t->string('channel')->nullable();
  210. $t->string('bank_name')->nullable(); $t->integer('payment_type')->nullable(); $t->tinyInteger('status')->default(0);
  211. $t->string('state')->default('0'); $t->string('callback_url')->nullable(); $t->text('callback_data')->nullable();
  212. $t->string('pay_no')->nullable(); $t->text('pay_url')->nullable(); $t->text('pay_data')->nullable();
  213. $t->string('image')->nullable(); $t->tinyInteger('is_send')->default(0); $t->string('remark')->nullable();
  214. $t->text('recharge_bonus_snapshot')->nullable(); $t->timestamps();
  215. });
  216. $this->fakeJd(['code' => 200, 'data' => ['orderNo' => 'JD-PAY-2', 'url' => '']]);
  217. $result = PaymentOrderService::createPayOrder(PaymentOrder::class, 'M1001', 100, 'JDpay', 2,
  218. RechargeChannel::checkRechargeChannel('JDpay', 2));
  219. $this->assertSame(0, $result['code']);
  220. $this->assertStringStartsWith('jd1_', $result['order_no']);
  221. $found = PaymentOrderService::findPayOrder($result['order_no']);
  222. $this->assertSame(PaymentOrder::class, get_class($found));
  223. $this->assertSame('M1001', $found->member_id);
  224. $this->assertSame(0, DB::table('agent_payment_orders')->count());
  225. // 前缀约定被打破(会员订单号以 ag 开头)时回退到另一张表,不丢回调
  226. DB::table('payment_orders')->where('id', $found->id)->update(['order_no' => 'ag-member-1']);
  227. $this->assertSame($found->id, PaymentOrderService::findPayOrder('ag-member-1')->id);
  228. $this->assertInstanceOf(PaymentOrder::class, PaymentOrderService::findPayOrder('ag-member-1'));
  229. $this->assertNotInstanceOf(AgentPaymentOrder::class, PaymentOrderService::findPayOrder('ag-member-1'));
  230. }
  231. public function test_manual_recharge_respects_channel_limits_and_can_be_cancelled_to_free_a_slot(): void
  232. {
  233. $this->payments();
  234. $this->useGroup(2);
  235. $agent = $this->agent();
  236. try { $this->payments->createManual($agent, '5', 1); $this->fail('below rgcz min'); }
  237. catch (\RuntimeException $e) { $this->assertStringContainsString('10-500000', $e->getMessage()); }
  238. $orders = [];
  239. for ($i = 0; $i < 5; $i++) $orders[] = $this->payments->createManual($agent, '100', 1);
  240. $this->payments->setPayData([$orders[0]->id], 1, '收款信息');
  241. try { $this->payments->createManual($agent, '100', 1); $this->fail('open limit'); }
  242. catch (\RuntimeException $e) { $this->assertSame('未完成的人工充值过多,请等待处理', $e->getMessage()); }
  243. $cancelled = $this->payments->cancelManual($agent, $orders[0]->id); // 待提交凭证可撤回
  244. $this->assertSame(PaymentOrderService::STATUS_CANCEL, $cancelled->status);
  245. $this->payments->createManual($agent, '100', 1);
  246. $this->payments->setPayData([$orders[1]->id], 1, '收款信息');
  247. $this->payments->submitImage($agent, $orders[1]->id, 'https://example.test/a.png');
  248. $this->expectExceptionMessage('当前状态不可撤回');
  249. $this->payments->cancelManual($agent, $orders[1]->id);
  250. }
  251. }