WDPayCashierLogic.php 13 KB

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