AiNewPayCashierLogic.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php
  2. namespace App\Http\logic\api;
  3. use App\dao\Estatisticas\RechargeWithDraw;
  4. use App\Http\helper\NumConfig;
  5. use App\Inter\CashierInterFace;
  6. use App\Models\PrivateMail;
  7. use App\Models\RecordUserDataStatistics;
  8. use App\Services\PayConfig;
  9. use App\Services\PayUtils;
  10. use App\Services\StoredProcedure;
  11. use App\Util;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Log;
  14. use Illuminate\Support\Facades\Redis;
  15. class AiNewPayCashierLogic implements CashierInterFace
  16. {
  17. const AGENT = 105; // AiNewPay代付渠道值
  18. protected $agent = 105;
  19. public function payment($RecordID, $amount, $accountName, $phone, $email, $OrderId, $PixNum, $PixType, $IFSCNumber, $BranchBank, $BankNO)
  20. {
  21. // 查询订单号
  22. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $RecordID)->first();
  23. if (!$query) return 'fail'; // 订单不存在
  24. $payConfigService = new PayConfig();
  25. $config = $payConfigService->getConfig('AiNewPayOut');
  26. $wayCode = [
  27. 1 => 'ecashapp',
  28. 2 => 'paypal'
  29. ];
  30. $wayParam = [];
  31. if ($PixNum && strpos($PixNum, '$') !== 0) {
  32. $PixNum = '$' . $PixNum;
  33. }
  34. if($PixType == 1){
  35. $wayParam = ["cashtag" => $PixNum];
  36. }
  37. if($PixType == 2){
  38. $wayParam = ["email" => $email];
  39. }
  40. // 构建提现请求参数
  41. $params = [
  42. "mchNo" => $config['mchNo'] ?? '',
  43. "mchOrderNo" => $OrderId,
  44. "amount" => intval($amount),
  45. "currency" => $config['currency'] ?? "usd",
  46. "wayCode" => $wayCode[$PixType],
  47. "notifyUrl" => $config['cashNotify'],
  48. "wayParam" => $wayParam,
  49. "timestamp" => round(microtime(true) * 1000),
  50. "signType" => $config['signType'] ?? "MD5"
  51. ];
  52. // 使用 AiNewPayOut 的 key 签名
  53. $apiKey = $config['key'];
  54. $signedParams = PayUtils::sign($params, $apiKey);
  55. $url = $config['apiUrl'];
  56. Log::info('AiNewPay 提现参数:', $signedParams);
  57. try {
  58. $result = $this->curlPost($url, $signedParams);
  59. } catch (\Exception $exception) {
  60. Log::info('AiNewPay 提现请求异常:', [$exception->getMessage()]);
  61. return 'fail';
  62. }
  63. Log::info('AiNewPay 提现结果:', [$result ?? "no result"]);
  64. try {
  65. $data = \GuzzleHttp\json_decode($result, true);
  66. } catch (\Exception $e) {
  67. Util::WriteLog("AiNewPay_error", [$result, $e->getMessage(), $e->getTraceAsString()]);
  68. return 'fail';
  69. }
  70. if (isset($data['code']) && $data['code'] == 0) {
  71. return $data;
  72. } else {
  73. if ($query->State == 5) {
  74. $msg = 'Liquidation failure';
  75. $WithDraw = $query->WithDraw + $query->ServiceFee;
  76. $bonus = '30000,' . $WithDraw;
  77. PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
  78. $withdraw_data = ['State' => 6, 'agent' => 1045, 'finishDate' => now(),'remark' => json_encode($data)];
  79. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $query->OrderId)->update($withdraw_data);
  80. $RecordData = ['after_state' => 6, 'update_at' => now()];
  81. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->where('type', 1)->where('RecordID', $RecordID)->update($RecordData);
  82. }
  83. return 'fail';
  84. }
  85. }
  86. public function notify($post)
  87. {
  88. if (!is_array($post)) $post = \GuzzleHttp\json_decode($post, true);
  89. Util::WriteLog('AiNewPay', 'AiNewPay 提现回调:' . json_encode($post));
  90. try {
  91. $OrderId = $post['mchOrderNo'] ?? '';
  92. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $OrderId)->first();
  93. if (!$query) {
  94. Util::WriteLog('AiNewPay','订单不存在');
  95. return '{"success":true,"message":"Accepted"}';
  96. }
  97. if ($query->State != 5 && $query->State != 7) {
  98. Util::WriteLog('AiNewPay',$OrderId.'_订单状态已完成');
  99. return 'SUCCESS';
  100. }
  101. $agentID = DB::connection('write')->table('agent.dbo.admin_configs')
  102. ->where('config_value', self::AGENT)
  103. ->where('type', 'cash')
  104. ->select('id')
  105. ->first()->id ?? '';
  106. $now = now();
  107. $notify_data = [
  108. 'state' => 1,
  109. 'finish_at' => $now,
  110. 'casOrdNo' => $post['mchOrderNo'] ?? '',
  111. 'extra' => \GuzzleHttp\json_encode($post),
  112. 'created_at' => $now,
  113. 'updated_at' => $now,
  114. 'order_sn' => $OrderId,
  115. 'amount' => $query->WithDraw,
  116. ];
  117. $orderStatus = 0;
  118. if (isset($post['state'])) {
  119. if ($post['state'] == 2) {
  120. $orderStatus = 1; // 成功
  121. } elseif ($post['state'] == 3) {
  122. $orderStatus = 2; // 失败
  123. }
  124. }
  125. if (!$orderStatus) {
  126. Util::WriteLog('AiNewPay', 'AiNewPay 提现处理中:' . $OrderId);
  127. return 'success';
  128. }
  129. Util::WriteLog('AiNewPay', 'AiNewPay 提现结果:' . $OrderId . '_' . $orderStatus);
  130. $UserID = $query->UserID;
  131. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  132. switch ($orderStatus) {
  133. case 1: // 提现成功
  134. Util::WriteLog('AiNewPay', 'AiNewPay提现成功');
  135. $withdraw_data = [
  136. 'State' => 2,
  137. 'agent' => $agentID,
  138. 'finishDate' => $now
  139. ];
  140. $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->first();
  141. if ($first) {
  142. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->increment('TakeMoney', $TakeMoney);
  143. } else {
  144. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  145. try {
  146. PrivateMail::praiseSendMail($UserID);
  147. } catch (\Exception $e) {
  148. }
  149. }
  150. $withdrawal_position_log = DB::connection('write')->table('agent.dbo.withdrawal_position_log')->where('order_sn', $OrderId)->first();
  151. if ($withdrawal_position_log) {
  152. DB::connection('write')->table('agent.dbo.withdrawal_position_log')->where('order_sn', $OrderId)->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
  153. }
  154. try {
  155. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  156. } catch (\Exception $exception) {
  157. Util::WriteLog('StoredProcedure', $exception);
  158. }
  159. $ServiceFee = $query->ServiceFee;
  160. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  161. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney);
  162. $redis = Redis::connection();
  163. $redis->incr('draw_' . date('Ymd') . $UserID);
  164. break;
  165. case 2: // 提现失败
  166. $msg = 'Encomenda rejeitada pelo banco';
  167. $bonus = '30000,' . $TakeMoney;
  168. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  169. Util::WriteLog('AiNewPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  170. $withdraw_data = ['State' => 6, 'agent' => $agentID, 'remark' => @$post['errMsg'] ?: ''];
  171. $notify_data = ['state' => 2];
  172. break;
  173. }
  174. $RecordData = [
  175. 'before_state' => $query->State,
  176. 'after_state' => $withdraw_data['State'] ?? 0,
  177. 'RecordID' => $query->RecordID,
  178. 'update_at' => date('Y-m-d H:i:s')
  179. ];
  180. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
  181. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $query->OrderId)->update($withdraw_data);
  182. if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
  183. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  184. }
  185. return 'success';
  186. } catch (\Exception $exception) {
  187. Util::WriteLog('AiNewPay', 'AiNewPay异步业务逻辑处理失败:' . $exception->getMessage());
  188. return '{"success":false,"message":"商户自定义出错信息"}';
  189. }
  190. }
  191. /**
  192. * POST请求方法
  193. */
  194. private function curlPost($url, $payload)
  195. {
  196. $timeout = 20;
  197. $data = json_encode($payload, JSON_UNESCAPED_UNICODE);
  198. $headers = [
  199. 'Content-Type: application/json',
  200. ];
  201. $ch = curl_init();
  202. curl_setopt($ch, CURLOPT_URL, $url);
  203. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  204. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  205. curl_setopt($ch, CURLOPT_POST, 1);
  206. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  207. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  208. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  209. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  210. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  211. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  212. $result = curl_exec($ch);
  213. if (curl_errno($ch)) {
  214. $error = curl_error($ch);
  215. Util::WriteLog('AiNewPay_error', 'CURL Error: ' . $error);
  216. curl_close($ch);
  217. return false;
  218. }
  219. curl_close($ch);
  220. return $result;
  221. }
  222. }