WDPayCashierLogic.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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\WDPay;
  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 WDPayCashierLogic implements CashierInterFace
  17. {
  18. const AGENT = 100; // WDPay代付渠道值,需要根据实际配置修改
  19. protected $agent = 100;
  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. // 使用WDPay服务类进行签名(WDPayOut配置)
  26. $service = new WDPay();
  27. $payConfigService = new PayConfig();
  28. $config = $payConfigService->getConfig('WDPayOut');
  29. $service->config = $config;
  30. $service->key = $config['key'] ?? '';
  31. // WDPay支付方式映射
  32. $wayCode = [
  33. 1 => 'cashapp', // CashApp
  34. 2 => 'paypal' // PayPal
  35. ];
  36. // 根据PixType选择账号
  37. // PixType: 1=CashApp, 2=PayPal
  38. $account = '';
  39. if ($PixType == 1) {
  40. $account = '$'.$PixNum; // CashApp标签,如: $abcd1234
  41. } elseif ($PixType == 2) {
  42. $account = $email; // PayPal邮箱,如: 1111@gmail.com
  43. }
  44. // 构建提现请求参数(按WDPay官方文档 /charging/create-pay-out)
  45. $params = [
  46. "country" => "US", // 国家,默认US
  47. "currency" => "USD", // 货币,默认USD
  48. "wayCode" => $wayCode[$PixType] ?? 'cashapp', // cashapp或paypal
  49. "account" => $account, // CashApp标签或PayPal邮箱
  50. "username" => $accountName ?: $email, // 用户名称,没有则用email
  51. "amount" => number_format($amount / 100, 2, '.', ''), // 价格,保留2位小数(元)
  52. "platform" => Util::getDeviceType(), // 设备:android/ios,默认ios
  53. "ip" => Util::getClientIp(), // 用户真实IP
  54. "customer" => $config['customer'], // 商户简称
  55. "customerNo" => $config['customerNo'], // 商户编号
  56. "customerOrderNo" => $OrderId, // 商户自定义订单号
  57. "timestamp" => (string)round(microtime(true) * 1000), // 13位时间戳(毫秒)
  58. "callback" => $config['cashNotify'] ?? '', // 回调地址
  59. "signType" => "MD5", // 传MD5
  60. ];
  61. // 使用WDPay的签名方法
  62. $signedParams = $service->sign($params);
  63. $url = $config['apiUrl'] ?? ''; // /charging/create-pay-out
  64. Util::WriteLog('WDPay_payout', 'WDPay提现请求: ' . $url . ' | 参数: ' . json_encode($signedParams));
  65. try {
  66. // 使用独立的 curlPost 方法发送请求
  67. $result = $this->curlPost($url, $signedParams);
  68. } catch (\Exception $exception) {
  69. Util::WriteLog('WDPay_payout_error', '提现请求异常:' . $exception->getMessage());
  70. return 'fail';
  71. }
  72. Util::WriteLog('WDPay_payout', 'WDPay提现结果: ' . ($result ?? "no result"));
  73. try {
  74. $data = \GuzzleHttp\json_decode($result, true);
  75. } catch (\Exception $e) {
  76. Util::WriteLog("WDPay_payout_error", ['解析失败', $result, $e->getMessage()]);
  77. return 'fail';
  78. }
  79. // WDPay官方返回格式:{"code": 200, "data": {...}, "message": "success"}
  80. if (isset($data['code']) && $data['code'] == 200) {
  81. Util::WriteLog('WDPay_payout', "提现订单创建成功: {$OrderId}");
  82. return $data;
  83. } else {
  84. // 提现失败处理
  85. Util::WriteLog('WDPay_payout_error', "提现失败: {$OrderId} | " . json_encode($data));
  86. if ($query->State == 5) {
  87. // 同步失败,发送邮件给玩家,退还金币
  88. $msg = $data['message'] ?? 'Transfer failed';
  89. $WithDraw = $query->WithDraw + $query->ServiceFee;
  90. $bonus = '30000,' . $WithDraw;
  91. PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
  92. $withdraw_data = [
  93. 'State' => 6,
  94. 'agent' => $this->agent,
  95. 'finishDate' => now(),
  96. 'remark' => json_encode($data)
  97. ];
  98. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  99. ->where('OrderId', $query->OrderId)
  100. ->update($withdraw_data);
  101. $RecordData = ['after_state' => 6, 'update_at' => now()];
  102. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
  103. ->where('type', 1)
  104. ->where('RecordID', $RecordID)
  105. ->update($RecordData);
  106. }
  107. return 'fail';
  108. }
  109. }
  110. public function notify($post)
  111. {
  112. if (!is_array($post)) $post = \GuzzleHttp\json_decode($post, true);
  113. Util::WriteLog('WDPay', 'WDPay 提现回调:' . json_encode($post));
  114. try {
  115. // 判断订单是否存在(WDPay使用customerOrderNo作为商户订单号)
  116. $OrderId = $post['customerOrderNo'] ?? '';
  117. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $OrderId)->first();
  118. if (!$query) {
  119. Util::WriteLog('WDPay_payout','提现订单不存在: ' . $OrderId);
  120. return '{"msg":"success","code":200}';
  121. }
  122. if ($query->State != 5 && $query->State != 7) {
  123. Util::WriteLog('WDPay_payout', $OrderId . '_提现订单状态已完成');
  124. return '{"msg":"success","code":200}';
  125. }
  126. $agentID = DB::connection('write')->table('agent.dbo.admin_configs')
  127. ->where('config_value', self::AGENT)
  128. ->where('type', 'cash')
  129. ->select('id')
  130. ->first()->id ?? '';
  131. $now = now();
  132. $notify_data = [
  133. 'state' => 1,
  134. 'finish_at' => $now,
  135. 'casOrdNo' => $post['orderNo'] ?? '', // WDPay交易号
  136. 'extra' => \GuzzleHttp\json_encode($post),
  137. 'created_at' => $now,
  138. 'updated_at' => $now,
  139. 'order_sn' => $OrderId,
  140. 'amount' => $query->WithDraw,
  141. ];
  142. // 判断订单状态(WDPay提现状态:PAID=成功, REJECTED=失败)
  143. $orderStatus = 0;
  144. if (isset($post['status'])) {
  145. $status = strtoupper($post['status']);
  146. if ($status == 'PAID') {
  147. $orderStatus = 1; // 提现成功
  148. } elseif ($status == 'REJECTED') {
  149. $orderStatus = 2; // 提现失败
  150. }
  151. }
  152. if (!$orderStatus) {
  153. Util::WriteLog('WDPay_payout', 'WDPay提现处理中:' . $OrderId . ', 状态: ' . ($post['status'] ?? 'unknown'));
  154. return '{"msg":"success","code":200}';
  155. }
  156. Util::WriteLog('WDPay_payout', 'WDPay提现回调:' . $OrderId . ', 状态: ' . ($post['status'] ?? '') . ', 处理结果: ' . $orderStatus);
  157. $UserID = $query->UserID;
  158. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  159. switch ($orderStatus) {
  160. case 1: // 提现成功
  161. Util::WriteLog('WDPay', 'WDPay提现成功');
  162. $withdraw_data = [
  163. 'State' => 2,
  164. 'agent' => $agentID,
  165. 'finishDate' => $now
  166. ];
  167. // 增加提现记录
  168. $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->first();
  169. if ($first) {
  170. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->increment('TakeMoney', $TakeMoney);
  171. } else {
  172. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  173. try {
  174. PrivateMail::praiseSendMail($UserID);
  175. } catch (\Exception $e) {
  176. // 忽略邮件发送失败
  177. }
  178. }
  179. // 免审的时候,修改免审状态
  180. $withdrawal_position_log = DB::connection('write')->table('agent.dbo.withdrawal_position_log')->where('order_sn', $OrderId)->first();
  181. if ($withdrawal_position_log) {
  182. 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')]);
  183. }
  184. try {
  185. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  186. } catch (\Exception $exception) {
  187. Util::WriteLog('StoredProcedure', $exception);
  188. }
  189. $ServiceFee = $query->ServiceFee;
  190. // 增加用户提现值
  191. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  192. // 数据统计后台 -- 提现记录添加
  193. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney);
  194. $redis = Redis::connection();
  195. $redis->incr('draw_' . date('Ymd') . $UserID);
  196. break;
  197. case 2: // 提现失败
  198. $msg = 'Encomenda rejeitada pelo banco';
  199. $bonus = '30000,' . $TakeMoney;
  200. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  201. Util::WriteLog('WDPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  202. $withdraw_data = ['State' => 6, 'agent' => $agentID, 'remark' => @$post['transMsg'] ?: ''];
  203. $notify_data = ['state' => 2];
  204. break;
  205. }
  206. $RecordData = [
  207. 'before_state' => $query->State,
  208. 'after_state' => $withdraw_data['State'] ?? 0,
  209. 'RecordID' => $query->RecordID,
  210. 'update_at' => date('Y-m-d H:i:s')
  211. ];
  212. // 添加用户提现操作记录
  213. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
  214. // DB::connection('write')->table('QPAccountsDB.dbo.withdraw_notify')->updateOrInsert(['order_sn' => $OrderId], $notify_data);
  215. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $query->OrderId)->update($withdraw_data);
  216. if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
  217. // 单控标签
  218. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  219. }
  220. Util::WriteLog('WDPay_payout', "提现回调处理完成: {$OrderId}");
  221. return '{"msg":"success","code":200}';
  222. } catch (\Exception $exception) {
  223. Util::WriteLog('WDPay_payout_error', 'WDPay提现回调处理失败:' . $exception->getMessage() . "\n" . $exception->getTraceAsString());
  224. return '{"msg":"error","code":500}';
  225. }
  226. }
  227. /**
  228. * POST请求方法 - application/x-www-form-urlencoded(WDPay协议)
  229. */
  230. private function curlPost($url, $payload)
  231. {
  232. $timeout = 20;
  233. // WDPay使用 application/x-www-form-urlencoded 格式
  234. $data = http_build_query($payload);
  235. $headers = [
  236. 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
  237. ];
  238. $ch = curl_init();
  239. curl_setopt($ch, CURLOPT_URL, $url);
  240. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  241. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  242. curl_setopt($ch, CURLOPT_POST, 1);
  243. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  244. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  245. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  246. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  247. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  248. $result = curl_exec($ch);
  249. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  250. if (curl_errno($ch)) {
  251. $error = curl_error($ch);
  252. Util::WriteLog('WDPay_error', 'CURL Error: ' . $error);
  253. curl_close($ch);
  254. return false;
  255. }
  256. if ($httpCode != 200) {
  257. Util::WriteLog('WDPay_error', 'HTTP Code: ' . $httpCode . " | Response: " . $result);
  258. }
  259. curl_close($ch);
  260. return $result;
  261. }
  262. }