AiNewPayCashierLogic.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. if ($query->State == 5) {
  75. $msg = 'Liquidation failure';
  76. $WithDraw = $query->WithDraw + $query->ServiceFee;
  77. $bonus = '30000,' . $WithDraw;
  78. PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
  79. $withdraw_data = ['State' => 6, 'agent' => 1045, 'finishDate' => now(),'remark' => json_encode($data)];
  80. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $query->OrderId)->update($withdraw_data);
  81. $RecordData = ['after_state' => 6, 'update_at' => now()];
  82. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->where('type', 1)->where('RecordID', $RecordID)->update($RecordData);
  83. }
  84. return 'fail';
  85. }
  86. }
  87. public function notify($post)
  88. {
  89. if (!is_array($post)) $post = \GuzzleHttp\json_decode($post, true);
  90. Util::WriteLog('AiNewPay', 'AiNewPay 提现回调:' . json_encode($post));
  91. try {
  92. $OrderId = $post['mchOrderNo'] ?? '';
  93. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $OrderId)->first();
  94. if (!$query) {
  95. Util::WriteLog('AiNewPay','订单不存在');
  96. return '{"success":true,"message":"Accepted"}';
  97. }
  98. if ($query->State != 5 && $query->State != 7) {
  99. Util::WriteLog('AiNewPay',$OrderId.'_订单状态已完成');
  100. return 'SUCCESS';
  101. }
  102. $agentID = DB::connection('write')->table('agent.dbo.admin_configs')
  103. ->where('config_value', self::AGENT)
  104. ->where('type', 'cash')
  105. ->select('id')
  106. ->first()->id ?? '';
  107. $now = now();
  108. $notify_data = [
  109. 'state' => 1,
  110. 'finish_at' => $now,
  111. 'casOrdNo' => $post['mchOrderNo'] ?? '',
  112. 'extra' => \GuzzleHttp\json_encode($post),
  113. 'created_at' => $now,
  114. 'updated_at' => $now,
  115. 'order_sn' => $OrderId,
  116. 'amount' => $query->WithDraw,
  117. ];
  118. $orderStatus = 0;
  119. if (isset($post['state'])) {
  120. if ($post['state'] == 2) {
  121. $orderStatus = 1; // 成功
  122. } elseif ($post['state'] == 3) {
  123. $orderStatus = 2; // 失败
  124. }
  125. }
  126. if (!$orderStatus) {
  127. Util::WriteLog('AiNewPay', 'AiNewPay 提现处理中:' . $OrderId);
  128. return 'success';
  129. }
  130. Util::WriteLog('AiNewPay', 'AiNewPay 提现结果:' . $OrderId . '_' . $orderStatus);
  131. $UserID = $query->UserID;
  132. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  133. switch ($orderStatus) {
  134. case 1: // 提现成功
  135. Util::WriteLog('AiNewPay', 'AiNewPay提现成功');
  136. $withdraw_data = [
  137. 'State' => 2,
  138. 'agent' => $agentID,
  139. 'finishDate' => $now
  140. ];
  141. $payConfigService = new PayConfig();
  142. $config = $payConfigService->getConfig('AiNewPayOut');
  143. $payRates = $config['pay_rate'];
  144. if(is_array($payRates)){
  145. $payMethod = $query->PixType??1;
  146. $payRate = $payRates[$payMethod] ?? $payRates[1];
  147. $withdraw_data['withdraw_fee'] = intval(($query->WithDraw * ($payRate[0] ?? 15))/100)+($payRate[1]??0.3)*NumConfig::NUM_VALUE;
  148. }
  149. $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->first();
  150. if ($first) {
  151. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->increment('TakeMoney', $TakeMoney);
  152. } else {
  153. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  154. try {
  155. PrivateMail::praiseSendMail($UserID);
  156. } catch (\Exception $e) {
  157. }
  158. }
  159. $withdrawal_position_log = DB::connection('write')->table('agent.dbo.withdrawal_position_log')->where('order_sn', $OrderId)->first();
  160. if ($withdrawal_position_log) {
  161. 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')]);
  162. }
  163. try {
  164. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  165. } catch (\Exception $exception) {
  166. Util::WriteLog('StoredProcedure', $exception);
  167. }
  168. $ServiceFee = $query->ServiceFee;
  169. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  170. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, $withdraw_data['withdraw_fee'] ?? 0, $ServiceFee);
  171. $redis = Redis::connection();
  172. $redis->incr('draw_' . date('Ymd') . $UserID);
  173. PrivateMail::successMail($UserID, $OrderId, $TakeMoney);
  174. break;
  175. case 2: // 提现失败
  176. $msg = 'Encomenda rejeitada pelo banco';
  177. $bonus = '30000,' . $TakeMoney;
  178. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  179. Util::WriteLog('AiNewPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  180. $withdraw_data = ['State' => 6, 'agent' => $agentID, 'remark' => @$post['errMsg'] ?: ''];
  181. WithdrawalPayoutMonitor::handleFailedCallback(self::AGENT, $post, $OrderId);
  182. $notify_data = ['state' => 2];
  183. break;
  184. }
  185. $RecordData = [
  186. 'before_state' => $query->State,
  187. 'after_state' => $withdraw_data['State'] ?? 0,
  188. 'RecordID' => $query->RecordID,
  189. 'update_at' => date('Y-m-d H:i:s')
  190. ];
  191. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
  192. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $query->OrderId)->update($withdraw_data);
  193. if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
  194. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  195. }
  196. return 'success';
  197. } catch (\Exception $exception) {
  198. Util::WriteLog('AiNewPay', 'AiNewPay异步业务逻辑处理失败:' . $exception->getMessage());
  199. return '{"success":false,"message":"商户自定义出错信息"}';
  200. }
  201. }
  202. /**
  203. * POST请求方法
  204. */
  205. private function curlPost($url, $payload)
  206. {
  207. $timeout = 20;
  208. $data = json_encode($payload, JSON_UNESCAPED_UNICODE);
  209. $headers = [
  210. 'Content-Type: application/json',
  211. ];
  212. $ch = curl_init();
  213. curl_setopt($ch, CURLOPT_URL, $url);
  214. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  215. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  216. curl_setopt($ch, CURLOPT_POST, 1);
  217. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  218. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  219. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  220. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  221. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  222. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  223. $result = curl_exec($ch);
  224. if (curl_errno($ch)) {
  225. $error = curl_error($ch);
  226. Util::WriteLog('AiNewPay_error', 'CURL Error: ' . $error);
  227. curl_close($ch);
  228. return false;
  229. }
  230. curl_close($ch);
  231. return $result;
  232. }
  233. }