WDPayCashierLogic.php 15 KB

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