WDPayCashierLogic.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. if ($query->State == 5) {
  91. // 同步失败,发送邮件给玩家,退还金币
  92. $msg = $data['message'] ?? 'Transfer failed';
  93. $WithDraw = $query->WithDraw + $query->ServiceFee;
  94. $bonus = '30000,' . $WithDraw;
  95. PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
  96. $withdraw_data = [
  97. 'State' => 6,
  98. 'agent' => 1040,
  99. 'finishDate' => now(),
  100. 'remark' => json_encode($data)
  101. ];
  102. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  103. ->where('OrderId', $query->OrderId)
  104. ->update($withdraw_data);
  105. $RecordData = ['after_state' => 6, 'update_at' => now()];
  106. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
  107. ->where('type', 1)
  108. ->where('RecordID', $RecordID)
  109. ->update($RecordData);
  110. }
  111. return 'fail';
  112. }
  113. }
  114. public function notify($post)
  115. {
  116. if (!is_array($post)) $post = \GuzzleHttp\json_decode($post, true);
  117. Util::WriteLog('WDPay', 'WDPay 提现回调:' . json_encode($post));
  118. try {
  119. // 判断订单是否存在(WDPay使用customerOrderNo作为商户订单号)
  120. $OrderId = $post['customerOrderNo'] ?? '';
  121. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $OrderId)->first();
  122. if (!$query) {
  123. Util::WriteLog('WDPay_payout','提现订单不存在: ' . $OrderId);
  124. return '{"msg":"success","code":200}';
  125. }
  126. if ($query->State != 5 && $query->State != 7) {
  127. Util::WriteLog('WDPay_payout', $OrderId . '_提现订单状态已完成');
  128. return '{"msg":"success","code":200}';
  129. }
  130. $agentID = DB::connection('write')->table('agent.dbo.admin_configs')
  131. ->where('config_value', self::AGENT)
  132. ->where('type', 'cash')
  133. ->select('id')
  134. ->first()->id ?? '';
  135. $now = now();
  136. $notify_data = [
  137. 'state' => 1,
  138. 'finish_at' => $now,
  139. 'casOrdNo' => $post['orderNo'] ?? '', // WDPay交易号
  140. 'extra' => \GuzzleHttp\json_encode($post),
  141. 'created_at' => $now,
  142. 'updated_at' => $now,
  143. 'order_sn' => $OrderId,
  144. 'amount' => $query->WithDraw,
  145. ];
  146. // 判断订单状态(WDPay提现状态:PAID=成功, REJECTED=失败)
  147. $orderStatus = 0;
  148. if (isset($post['status'])) {
  149. $status = strtoupper($post['status']);
  150. if ($status == 'PAID') {
  151. $orderStatus = 1; // 提现成功
  152. } elseif ($status == 'REJECTED') {
  153. $orderStatus = 2; // 提现失败
  154. }
  155. }
  156. if (!$orderStatus) {
  157. Util::WriteLog('WDPay_payout', 'WDPay提现处理中:' . $OrderId . ', 状态: ' . ($post['status'] ?? 'unknown'));
  158. return '{"msg":"success","code":200}';
  159. }
  160. Util::WriteLog('WDPay_payout', 'WDPay提现回调:' . $OrderId . ', 状态: ' . ($post['status'] ?? '') . ', 处理结果: ' . $orderStatus);
  161. $UserID = $query->UserID;
  162. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  163. switch ($orderStatus) {
  164. case 1: // 提现成功
  165. Util::WriteLog('WDPay', 'WDPay提现成功');
  166. $withdraw_data = [
  167. 'State' => 2,
  168. 'agent' => $agentID,
  169. 'finishDate' => $now
  170. ];
  171. $payConfigService = new PayConfig();
  172. $config = $payConfigService->getConfig('WDPayOut');
  173. $payRates = @$config['pay_rate'];
  174. if(is_array($payRates)){
  175. $payMethod = $query->PixType??1;
  176. $payRate = $payRates[$payMethod] ?? $payRates[1];
  177. $withdraw_data['withdraw_fee'] = intval(($query->WithDraw * ($payRate[0] ?? 15))/100)+($payRate[1]??0.3)*NumConfig::NUM_VALUE;
  178. }
  179. // 增加提现记录
  180. $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->first();
  181. if ($first) {
  182. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->where('UserID', $UserID)->increment('TakeMoney', $TakeMoney);
  183. } else {
  184. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  185. try {
  186. PrivateMail::praiseSendMail($UserID);
  187. } catch (\Exception $e) {
  188. // 忽略邮件发送失败
  189. }
  190. }
  191. // 免审的时候,修改免审状态
  192. $withdrawal_position_log = DB::connection('write')->table('agent.dbo.withdrawal_position_log')->where('order_sn', $OrderId)->first();
  193. if ($withdrawal_position_log) {
  194. 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')]);
  195. }
  196. try {
  197. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  198. } catch (\Exception $exception) {
  199. Util::WriteLog('StoredProcedure', $exception);
  200. }
  201. $ServiceFee = $query->ServiceFee;
  202. // 增加用户提现值
  203. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  204. // 数据统计后台 -- 提现记录添加
  205. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, $withdraw_data['withdraw_fee'] ?? 0, $ServiceFee);
  206. $redis = Redis::connection();
  207. $redis->incr('draw_' . date('Ymd') . $UserID);
  208. PrivateMail::successMail($UserID, $OrderId, $TakeMoney);
  209. break;
  210. case 2: // 提现失败
  211. $msg = 'Encomenda rejeitada pelo banco';
  212. $bonus = '30000,' . $TakeMoney;
  213. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  214. Util::WriteLog('WDPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  215. $withdraw_data = ['State' => 6, 'agent' => $agentID, 'remark' => @$post['transMsg'] ?: ''];
  216. WithdrawalPayoutMonitor::handleFailedCallback(self::AGENT, $post, $OrderId);
  217. $notify_data = ['state' => 2];
  218. break;
  219. }
  220. $RecordData = [
  221. 'before_state' => $query->State,
  222. 'after_state' => $withdraw_data['State'] ?? 0,
  223. 'RecordID' => $query->RecordID,
  224. 'update_at' => date('Y-m-d H:i:s')
  225. ];
  226. // 添加用户提现操作记录
  227. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
  228. // DB::connection('write')->table('QPAccountsDB.dbo.withdraw_notify')->updateOrInsert(['order_sn' => $OrderId], $notify_data);
  229. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $query->OrderId)->update($withdraw_data);
  230. if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
  231. // 单控标签
  232. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  233. }
  234. Util::WriteLog('WDPay_payout', "提现回调处理完成: {$OrderId}");
  235. return '{"msg":"success","code":200}';
  236. } catch (\Exception $exception) {
  237. Util::WriteLog('WDPay_payout_error', 'WDPay提现回调处理失败:' . $exception->getMessage() . "\n" . $exception->getTraceAsString());
  238. return '{"msg":"error","code":500}';
  239. }
  240. }
  241. /**
  242. * POST请求方法 - application/x-www-form-urlencoded(WDPay协议)
  243. */
  244. private function curlPost($url, $payload)
  245. {
  246. $timeout = 20;
  247. // WDPay使用 application/x-www-form-urlencoded 格式
  248. $data = http_build_query($payload);
  249. // ✅ 加上真实 User-Agent
  250. $userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
  251. . 'AppleWebKit/537.36 (KHTML, like Gecko) '
  252. . 'Chrome/120.0.0.0 Safari/537.36';
  253. $headers = [
  254. 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
  255. 'User-Agent: ' . $userAgent,
  256. ];
  257. $ch = curl_init();
  258. curl_setopt($ch, CURLOPT_URL, $url);
  259. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  260. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  261. curl_setopt($ch, CURLOPT_POST, 1);
  262. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  263. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  264. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  265. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  266. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  267. // ✅ 再保险:显式设置 CURLOPT_USERAGENT(防代理/转发丢失)
  268. curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
  269. $result = curl_exec($ch);
  270. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  271. if (curl_errno($ch)) {
  272. $error = curl_error($ch);
  273. Util::WriteLog('WDPay_error', 'CURL Error: ' . $error);
  274. curl_close($ch);
  275. return false;
  276. }
  277. if ($httpCode != 200) {
  278. Util::WriteLog('WDPay_error', 'HTTP Code: ' . $httpCode . " | Response: " . $result);
  279. }
  280. curl_close($ch);
  281. return $result;
  282. }
  283. }