SafePayLogic.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. <?php
  2. namespace App\Http\logic\api;
  3. use App\dao\Pay\AccountPayInfo;
  4. use App\dao\Pay\PayController;
  5. use App\Http\helper\CreateOrder;
  6. use App\Http\helper\NumConfig;
  7. use App\Jobs\Order;
  8. use App\Services\SafePay;
  9. use App\Services\CreateLog;
  10. use App\Services\OrderServices;
  11. use App\Services\PayConfig;
  12. use App\Util;
  13. use Illuminate\Support\Facades\DB;
  14. class SafePayLogic extends BaseApiLogic
  15. {
  16. public $result;
  17. /**
  18. * 支付方式到 pay_code 的映射
  19. * 1=cashapp, 2=paypal, 4=applepay, 8=googlepay
  20. */
  21. protected $payCodeMap = [
  22. 1 => '1301', // 美国 CashApp
  23. 2 => '1305', // 美国 PayPal
  24. 4 => '1302', // 美国 ApplePay
  25. 8 => '1303', // 美国 GooglePay
  26. 16 => '1304', // 美国 BTC
  27. ];
  28. /**
  29. * 代收下单
  30. */
  31. public function pay_order($userId, $pay_amount, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType, $pay_method = '')
  32. {
  33. $dao = new AccountPayInfo();
  34. [$userPhone, $userName, $userEmail] = $dao->payInfo($userId);
  35. // 礼包类型验证
  36. $PayVerify = new PayController();
  37. $pay_amount = $PayVerify->verify($userId, $GiftsID, $pay_amount);
  38. if ($PayVerify->verify($userId, $GiftsID, $pay_amount) === false) {
  39. $this->error = $PayVerify->getError();
  40. return false;
  41. }
  42. if ($pay_amount < 0) {
  43. $this->error = 'Payment error_4';
  44. return false;
  45. }
  46. $service = new SafePay();
  47. $config = $service->config;
  48. $order_sn = CreateOrder::order_sn($userId);
  49. // 生成订单信息
  50. $logic = new OrderLogic();
  51. $amount = (int) round($pay_amount * NumConfig::NUM_VALUE);
  52. $logic->orderCreate($order_sn, $amount, 'SafePay', $userId, $pay_method, $GiftsID, $AdId, $eventType);
  53. // 确定 pay_code
  54. $payCode = $this->payCodeMap[$pay_method] ?? ($config['pay_code'] ?? '1301');
  55. // 构建支付请求参数
  56. $params = [
  57. 'mer_no' => $service->merNo,
  58. 'order_no' => $order_sn,
  59. 'amount' => (string)$pay_amount,
  60. 'name' => $userName ?: 'user',
  61. 'email' => $userEmail ?: ($userId . '@unknown.com'),
  62. 'phone' => $userPhone ?: '0000000000',
  63. 'currency' => $config['currency'] ?? 'USD',
  64. 'pay_code' => $payCode,
  65. 'notify_url' => $config['notify_url'] ?? '',
  66. 'extra' => json_encode([
  67. 'clientIP' => $buyIP,
  68. 'firstName' => $userName ?: '',
  69. 'lastName' => '',
  70. ]),
  71. ];
  72. // RSA签名
  73. $signedParams = $service->sign($params);
  74. // 生成用户请求信息日志
  75. $request_extra = \GuzzleHttp\json_encode($signedParams);
  76. CreateLog::pay_request($userPhone, $request_extra, $order_sn, $userEmail, $userId, $userName);
  77. $url = $service->apiUrl . '/open/api/order/in';
  78. $result = $service->curlPost($url, $signedParams);
  79. $rresult = compact('result', 'signedParams', 'url');
  80. Util::WriteLog('SafePay', 'SafePay支付请求' . $url . " | " . $request_extra);
  81. Util::WriteLog('SafePay', 'SafePay支付结果' . json_encode($rresult));
  82. try {
  83. $data = \GuzzleHttp\json_decode($result, true);
  84. } catch (\Exception $e) {
  85. Util::WriteLog("SafePay_error", [$result, $e->getMessage(), $e->getTraceAsString()]);
  86. $this->error = 'Payment processing error';
  87. return false;
  88. }
  89. return $data;
  90. }
  91. /**
  92. * 代收异步回调处理
  93. */
  94. public function notify($post)
  95. {
  96. $order_no = $post['order_no'] ?? '';
  97. // 查询订单信息
  98. $order = DB::connection('write')->table('agent.dbo.order')
  99. ->where('order_sn', $order_no)
  100. ->first();
  101. if (!$order) {
  102. Util::WriteLog('SafePay', '订单不存在: ' . $order_no);
  103. return 'ok';
  104. }
  105. // 已处理过则直接返回
  106. if (!empty($order->pay_at) || !empty($order->finished_at)) {
  107. return 'ok';
  108. }
  109. $status = $post['status'] ?? '';
  110. $body = [
  111. 'payment_sn' => $post['ref_no'] ?? '',
  112. 'updated_at' => date('Y-m-d H:i:s'),
  113. ];
  114. // status: success=交易成功, 其他=失败/待处理
  115. if ($status !== 'success') {
  116. // 非成功状态(如 pending/waiting),不处理,等待后续通知
  117. Util::WriteLog('SafePay', "支付未完成订单: {$order_no}, status: {$status}");
  118. return 'ok';
  119. }
  120. // 支付成功
  121. $GiftsID = $order->GiftsID ?: '';
  122. $userID = $order->user_id ?: '';
  123. $AdId = $order->AdId ?: '';
  124. $eventType = $order->eventType ?: '';
  125. $orderAmount = (float)($post['order_reality_amount'] ?? $post['order_amount'] ?? 0);
  126. $payAmt = $orderAmount;
  127. $body['pay_status'] = 1;
  128. $body['pay_at'] = date('Y-m-d H:i:s');
  129. $body['finished_at'] = date('Y-m-d H:i:s');
  130. $body['amount'] = (int) round($payAmt * NumConfig::NUM_VALUE);
  131. $config = (new PayConfig())->getConfig('SafePay');
  132. // 根据支付方式计算代收手续费: 费率% * 金额 + 固定$
  133. // pay_rate 格式: [1=>[10,0.3], 2=>[13,0.3], 4=>[11,0.3], 8=>[12,0.3]]
  134. $payRates = $config['pay_rate'] ?? null;
  135. if (is_array($payRates)) {
  136. $payMethod = $order->order_title ?? 1;
  137. $payRate = $payRates[$payMethod] ?? ($payRates[1] ?? [10, 0.3]);
  138. $feePercent = $payRate[0] ?? 10;
  139. $feeFixed = $payRate[1] ?? 0.3;
  140. $body['payment_fee'] = intval(($body['amount'] * $feePercent) / 100)
  141. + (int)($feeFixed * NumConfig::NUM_VALUE);
  142. }
  143. try {
  144. $service = new OrderServices();
  145. if (intval($order->amount) != $body['amount']) {
  146. $body['GiftsID'] = 0;
  147. $body['amount'] = (int) round($payAmt * NumConfig::NUM_VALUE);
  148. $Recharge = $payAmt;
  149. $give = 0;
  150. $favorable_price = $Recharge + $give;
  151. $czReason = 1;
  152. $cjReason = 45;
  153. } else {
  154. [$give, $favorable_price, $Recharge, $czReason, $cjReason] = $service->getPayInfo(
  155. $GiftsID, $userID, $payAmt
  156. );
  157. }
  158. // 增加充值记录
  159. [$Score] = $service->addRecord(
  160. $userID, $payAmt, $favorable_price, $order_no, $GiftsID,
  161. $Recharge, $czReason, $give, $cjReason, $AdId, $eventType,
  162. $body['payment_fee'] ?? 0
  163. );
  164. // 异步处理后续任务
  165. Order::dispatch([$userID, $payAmt, $Score, $favorable_price, $GiftsID, $order_no]);
  166. } catch (\Exception $exception) {
  167. Util::WriteLog("SafePay_error", $exception->getMessage());
  168. }
  169. // 更新订单状态
  170. $order_up = DB::connection('write')->table('agent.dbo.order')
  171. ->where('order_sn', $order_no)
  172. ->update($body);
  173. if (!$order_up) {
  174. Util::WriteLog('SafePay', '订单更新失败: ' . $order_no);
  175. return 'ok';
  176. }
  177. Util::WriteLog("SafePay", 'success: ' . $order_no);
  178. return 'ok';
  179. }
  180. }