AiNewPayCashierLogic.php 11 KB

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