WiwiPayCashierLogic.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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\WiwiPay;
  9. use App\Services\PayConfig;
  10. use App\Services\PayUtils;
  11. use App\Services\StoredProcedure;
  12. use App\Util;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. class WiwiPayCashierLogic implements CashierInterFace
  17. {
  18. const AGENT = 99; // 需要根据实际情况修改
  19. protected $agent = 99;
  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('WiwiPayOut');
  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. // 直接使用 PayUtils 签名(使用 WiwiPayOut 的 key)
  54. $apiKey = $config['key'];
  55. $signedParams = PayUtils::sign($params, $apiKey);
  56. $url = $config['apiUrl'];
  57. Log::info('WiwiPay 提现参数:', $signedParams);
  58. try {
  59. // 使用独立的 curlPost 方法发送请求
  60. $result = $this->curlPost($url, $signedParams);
  61. } catch (\Exception $exception) {
  62. Log::info('WiwiPay 提现请求异常:', [$exception->getMessage()]);
  63. return 'fail';
  64. }
  65. Log::info('WiwiPay 提现结果:', [$result ?? "no result"]);
  66. try {
  67. $data = \GuzzleHttp\json_decode($result, true);
  68. } catch (\Exception $e) {
  69. Util::WriteLog("WiwiPay_error", [$result, $e->getMessage(), $e->getTraceAsString()]);
  70. return 'fail';
  71. }
  72. if (isset($data['code']) && $data['code'] == 0) {
  73. return $data;
  74. } else {
  75. if ($query->State == 5) {
  76. // 同步失败,发送邮件给玩家,退还金币
  77. $msg = 'Liquidation failure';
  78. $WithDraw = $query->WithDraw + $query->ServiceFee;
  79. $bonus = '30000,' . $WithDraw;
  80. PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
  81. $withdraw_data = ['State' => 6, 'agent' => 1039, 'finishDate' => now(),'remark' => json_encode($data)];
  82. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $query->OrderId)->update($withdraw_data);
  83. $RecordData = ['after_state' => 6, 'update_at' => now()];
  84. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->where('type', 1)->where('RecordID', $RecordID)->update($RecordData);
  85. }
  86. return 'fail';
  87. }
  88. }
  89. public function notify($post)
  90. {
  91. if (!is_array($post)) $post = \GuzzleHttp\json_decode($post, true);
  92. Util::WriteLog('WiwiPay', 'WiwiPay 提现回调:' . json_encode($post));
  93. try {
  94. // 判断订单是否存在
  95. $OrderId = $post['mchOrderNo'] ?? '';
  96. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $OrderId)->first();
  97. if (!$query) {
  98. Util::WriteLog('WiwiPay','订单不存在');
  99. return '{"success":true,"message":"Accepted"}';
  100. }
  101. if ($query->State != 5 && $query->State != 7) {
  102. Util::WriteLog('WiwiPay',$OrderId.'_订单状态已完成');
  103. return 'SUCCESS';
  104. }
  105. $agentID = DB::connection('write')->table('agent.dbo.admin_configs')
  106. ->where('config_value', self::AGENT)
  107. ->where('type', 'cash')
  108. ->select('id')
  109. ->first()->id ?? '';
  110. $now = now();
  111. $notify_data = [
  112. 'state' => 1,
  113. 'finish_at' => $now,
  114. 'casOrdNo' => $post['mchOrderNo'] ?? '',
  115. 'extra' => \GuzzleHttp\json_encode($post),
  116. 'created_at' => $now,
  117. 'updated_at' => $now,
  118. 'order_sn' => $OrderId,
  119. 'amount' => $query->WithDraw,
  120. ];
  121. //state
  122. //0-订单生成
  123. //1-支付中
  124. //2-支付成功
  125. //3-支付失败
  126. //4-已撤销
  127. //5-已退款
  128. //6-订单关闭
  129. // 判断订单状态
  130. $orderStatus = 0;
  131. if (isset($post['state'])) {
  132. // state: 2=成功, 3=失败
  133. if ($post['state'] == 2) {
  134. $orderStatus = 1; // 成功
  135. } elseif ($post['state'] == 3) {
  136. $orderStatus = 2; // 失败
  137. }
  138. }
  139. if (!$orderStatus) {
  140. Util::WriteLog('WiwiPay', 'WiwiPay 提现处理中:' . $OrderId);
  141. return 'success';
  142. }
  143. Util::WriteLog('WiwiPay', 'WiwiPay 提现结果:' . $OrderId . '_' . $orderStatus);
  144. $UserID = $query->UserID;
  145. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  146. switch ($orderStatus) {
  147. case 1: // 提现成功
  148. Util::WriteLog('WiwiPay', 'WiwiPay提现成功');
  149. $withdraw_data = [
  150. 'State' => 2,
  151. 'agent' => $agentID,
  152. 'finishDate' => $now
  153. ];
  154. $payConfigService = new PayConfig();
  155. $config = $payConfigService->getConfig('WiwiPayOut');
  156. $payRates = @$config['pay_rate'];
  157. if(is_array($payRates)){
  158. $payMethod = $query->PixType??1;
  159. $payRate = $payRates[$payMethod] ?? $payRates[1];
  160. $withdraw_data['withdraw_fee'] = intval(($query->WithDraw * ($payRate[0] ?? 15))/100)+($payRate[1]??0.3)*NumConfig::NUM_VALUE;
  161. }
  162. // 增加提现记录
  163. $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->first();
  164. if ($first) {
  165. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->increment('TakeMoney', $TakeMoney);
  166. } else {
  167. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  168. try {
  169. PrivateMail::praiseSendMail($UserID);
  170. } catch (\Exception $e) {
  171. // 忽略邮件发送失败
  172. }
  173. }
  174. // 免审的时候,修改免审状态
  175. $withdrawal_position_log = DB::connection('write')->table('agent.dbo.withdrawal_position_log')->where('order_sn', $OrderId)->first();
  176. if ($withdrawal_position_log) {
  177. 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')]);
  178. }
  179. try {
  180. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  181. } catch (\Exception $exception) {
  182. Util::WriteLog('StoredProcedure', $exception);
  183. }
  184. $ServiceFee = $query->ServiceFee;
  185. // 增加用户提现值
  186. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  187. // 数据统计后台 -- 提现记录添加
  188. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, $withdraw_data['withdraw_fee'] ?? 0, $ServiceFee);
  189. $redis = Redis::connection();
  190. $redis->incr('draw_' . date('Ymd') . $UserID);
  191. PrivateMail::successMail($UserID, $OrderId, $TakeMoney);
  192. break;
  193. case 2: // 提现失败
  194. $msg = 'Encomenda rejeitada pelo banco';
  195. $bonus = '30000,' . $TakeMoney;
  196. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  197. Util::WriteLog('WiwiPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  198. $withdraw_data = ['State' => 6, 'agent' => $agentID, 'remark' => @$post['errMsg'] ?: ''];
  199. $notify_data = ['state' => 2];
  200. break;
  201. }
  202. $RecordData = [
  203. 'before_state' => $query->State,
  204. 'after_state' => $withdraw_data['State'] ?? 0,
  205. 'RecordID' => $query->RecordID,
  206. 'update_at' => date('Y-m-d H:i:s')
  207. ];
  208. // 添加用户提现操作记录
  209. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
  210. // DB::connection('write')->table('QPAccountsDB.dbo.withdraw_notify')->updateOrInsert(['order_sn' => $OrderId], $notify_data);
  211. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $query->OrderId)->update($withdraw_data);
  212. if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
  213. // 单控标签
  214. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  215. }
  216. return 'success';
  217. } catch (\Exception $exception) {
  218. Util::WriteLog('WiwiPay', 'WiwiPay异步业务逻辑处理失败:' . $exception->getMessage());
  219. return '{"success":false,"message":"商户自定义出错信息"}';
  220. }
  221. }
  222. /**
  223. * POST请求方法(复用 WiwiPay 的实现)
  224. */
  225. private function curlPost($url, $payload)
  226. {
  227. $timeout = 20;
  228. $data = json_encode($payload, JSON_UNESCAPED_UNICODE);
  229. $headers = [
  230. 'Content-Type: application/json',
  231. ];
  232. $ch = curl_init();
  233. curl_setopt($ch, CURLOPT_URL, $url);
  234. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  235. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  236. curl_setopt($ch, CURLOPT_POST, 1);
  237. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  238. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  239. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  240. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  241. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  242. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  243. $result = curl_exec($ch);
  244. if (curl_errno($ch)) {
  245. $error = curl_error($ch);
  246. Util::WriteLog('WiwiPay_error', 'CURL Error: ' . $error);
  247. curl_close($ch);
  248. return false;
  249. }
  250. if (strstr($result, 'code') || $httpCode != 200) {
  251. // 可选:记录错误日志
  252. }
  253. curl_close($ch);
  254. return $result;
  255. }
  256. }