AgentPaymentOrderTest.php 13 KB

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