SfPayCashierLogic.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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\SfPay;
  9. use App\Services\PayConfig;
  10. use App\Services\StoredProcedure;
  11. use App\Services\WithdrawalPayoutMonitor;
  12. use App\Util;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Log;
  15. use Illuminate\Support\Facades\Redis;
  16. class SfPayCashierLogic implements CashierInterFace
  17. {
  18. const AGENT = 108; // SfPay代付渠道值(对应 admin_configs config_value)
  19. protected $agent = 108;
  20. /**
  21. * 支付方式位掩码 → SfPay payProduct 映射(代付)
  22. * 1=cashapp, 2=paypal
  23. */
  24. protected $payoutProductMap = [
  25. 1 => 'USA202', // cashapp
  26. 2 => 'USA203', // paypal
  27. ];
  28. /**
  29. * PixType → 代付方式映射
  30. */
  31. protected $bankTypeMap = [
  32. 1 => 'USA202', // cashapp
  33. 2 => 'USA203', // paypal
  34. ];
  35. /**
  36. * 提交代付申请
  37. */
  38. public function payment($RecordID, $amount, $accountName, $phone, $email, $OrderId, $PixNum, $PixType, $IFSCNumber, $BranchBank, $BankNO)
  39. {
  40. // 查询订单
  41. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $RecordID)->first();
  42. if (!$query) return 'fail';
  43. $payConfigService = new PayConfig();
  44. $config = $payConfigService->getConfig('SfPay');
  45. $service = new SfPay();
  46. // 确定代付产品
  47. $payProduct = $this->payoutProductMap[$PixType] ?? 'USA202';
  48. // 构建收款账号
  49. if ($PixType == 1) {
  50. // CashApp: cashtag,需 $ 前缀
  51. $account = ($PixNum && strpos($PixNum, '$') !== 0) ? '$' . $PixNum : $PixNum;
  52. } elseif ($PixType == 2) {
  53. // PayPal: 邮箱
  54. $account = $email ?: $PixNum;
  55. } else {
  56. $account = $PixNum ?: $email;
  57. }
  58. // 构建代付请求参数
  59. $params = [
  60. 'merchantOrderNo' => $OrderId,
  61. 'amount' => (float)number_format($amount / NumConfig::NUM_VALUE, 2, '.', ''),
  62. 'beneficiaryAccount' => $account,
  63. 'beneficiaryName' => $accountName ?: 'user',
  64. 'countryId' => 'USA',
  65. 'payProduct' => $payProduct,
  66. 'notifyUrl' => $config['cash_notify_url'] ?? '',
  67. 'beneficiaryEmail' => $email ?: '',
  68. 'beneficiaryPhoneNo' => $phone ?: '',
  69. ];
  70. Log::info('SfPay 提现参数:', $params);
  71. $url = $service->apiUrl . '/gateway/payout/init';
  72. try {
  73. $result = $service->curlPost($url, $params);
  74. } catch (\Exception $exception) {
  75. Log::info('SfPay 提现请求异常:', [$exception->getMessage()]);
  76. Util::WriteLog('SfPay_error', 'SfPay 提现请求异常:' . $exception->getMessage());
  77. return 'fail';
  78. }
  79. Log::info('SfPay 提现结果:', [$result ?? 'no result']);
  80. try {
  81. $data = \GuzzleHttp\json_decode($result, true);
  82. } catch (\Exception $e) {
  83. Util::WriteLog("SfPay_error", [$result, $e->getMessage()]);
  84. return 'fail';
  85. }
  86. // SfPay 代付成功响应: code=0
  87. if (isset($data['code']) && $data['code'] === 0) {
  88. return $data;
  89. }
  90. // 同步失败处理:回复玩家金币,标记订单失败
  91. WithdrawalPayoutMonitor::handleFailedCallback(self::AGENT, $data, $OrderId);
  92. if ($query->State == 5) {
  93. $msg = 'Liquidation failure';
  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' => 1080,
  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. * 代付异步回调处理
  116. *
  117. * SfPay代付回调格式(POST JSON,不加密):
  118. * {
  119. * "data": {
  120. * "amount": "30.00",
  121. * "orderNo": "...",
  122. * "message": "...",
  123. * "type": "payout",
  124. * "merchantOrderNo": "...",
  125. * "processedTime": "...",
  126. * "processAmount": "0.00",
  127. * "status": "SUCCESS"
  128. * },
  129. * "signature_n": "..."
  130. * }
  131. */
  132. public function notify($post)
  133. {
  134. if (!is_array($post)) {
  135. $post = \GuzzleHttp\json_decode($post, true);
  136. }
  137. Util::WriteLog('SfPay', 'SfPay 提现回调:' . json_encode($post));
  138. try {
  139. $callbackData = $post['data'] ?? [];
  140. $signatureN = $post['signature_n'] ?? '';
  141. if (empty($callbackData) || empty($signatureN)) {
  142. Util::WriteLog('SfPay', '提现回调数据不完整');
  143. return 'SUCCESS';
  144. }
  145. // 验签
  146. $service = new SfPay();
  147. if (!$service->verifySign($callbackData, $signatureN)) {
  148. Util::WriteLog('SfPay', '提现回调签名验证失败');
  149. return 'SUCCESS';
  150. }
  151. // 判断订单是否存在
  152. $OrderId = $callbackData['merchantOrderNo'] ?? '';
  153. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  154. ->where('OrderId', $OrderId)
  155. ->first();
  156. if (!$query) {
  157. Util::WriteLog('SfPay', '提现订单不存在: ' . $OrderId);
  158. return 'SUCCESS';
  159. }
  160. // 订单已完成处理
  161. if ($query->State != 5 && $query->State != 7) {
  162. Util::WriteLog('SfPay', $OrderId . '_订单状态已完成');
  163. return 'SUCCESS';
  164. }
  165. $agentID = DB::connection('write')->table('agent.dbo.admin_configs')
  166. ->where('config_value', self::AGENT)
  167. ->where('type', 'cash')
  168. ->select('id')
  169. ->first()->id ?? '';
  170. $now = now();
  171. $notify_data = [
  172. 'state' => 1,
  173. 'finish_at' => $now,
  174. 'casOrdNo' => $callbackData['orderNo'] ?? '',
  175. 'extra' => \GuzzleHttp\json_encode($post),
  176. 'created_at' => $now,
  177. 'updated_at' => $now,
  178. 'order_sn' => $OrderId,
  179. 'amount' => $query->WithDraw,
  180. ];
  181. // 判断回调结果: SUCCESS=成功, FAILURE=失败
  182. $status = $callbackData['status'] ?? '';
  183. $orderStatus = 0;
  184. if ($status === 'SUCCESS') {
  185. $orderStatus = 1; // 成功
  186. } elseif ($status === 'FAILURE' || $status === 'REVERSED') {
  187. $orderStatus = 2; // 失败
  188. }
  189. if (!$orderStatus) {
  190. Util::WriteLog('SfPay', 'SfPay 提现处理中:' . $OrderId);
  191. return 'SUCCESS';
  192. }
  193. Util::WriteLog('SfPay', 'SfPay 提现结果:' . $OrderId . '_' . $orderStatus);
  194. $UserID = $query->UserID;
  195. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  196. $withdraw_data = [];
  197. switch ($orderStatus) {
  198. case 1: // 提现成功
  199. Util::WriteLog('SfPay', 'SfPay提现成功');
  200. $withdraw_data = [
  201. 'State' => 2,
  202. 'agent' => $agentID,
  203. 'finishDate' => $now
  204. ];
  205. // 增加提现记录
  206. $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  207. ->where('UserID', $UserID)->first();
  208. if ($first) {
  209. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  210. ->where('UserID', $UserID)
  211. ->increment('TakeMoney', $TakeMoney);
  212. } else {
  213. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  214. ->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  215. try {
  216. PrivateMail::praiseSendMail($UserID);
  217. } catch (\Exception $e) {
  218. // 忽略邮件发送失败
  219. }
  220. }
  221. // 免审的时候,修改免审状态
  222. $withdrawal_position_log = DB::connection('write')
  223. ->table('agent.dbo.withdrawal_position_log')
  224. ->where('order_sn', $OrderId)
  225. ->first();
  226. if ($withdrawal_position_log) {
  227. DB::connection('write')->table('agent.dbo.withdrawal_position_log')
  228. ->where('order_sn', $OrderId)
  229. ->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
  230. }
  231. try {
  232. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  233. } catch (\Exception $exception) {
  234. Util::WriteLog('StoredProcedure', $exception);
  235. }
  236. $ServiceFee = $query->ServiceFee;
  237. // 增加用户提现值
  238. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  239. // 数据统计后台 -- 提现记录添加
  240. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, 0, $ServiceFee);
  241. $redis = Redis::connection();
  242. $redis->incr('draw_' . date('Ymd') . $UserID);
  243. PrivateMail::successMail($UserID, $OrderId, $TakeMoney);
  244. break;
  245. case 2: // 提现失败
  246. $msg = 'Encomenda rejeitada pelo banco';
  247. $bonus = '30000,' . $TakeMoney;
  248. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  249. Util::WriteLog('SfPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  250. $withdraw_data = [
  251. 'State' => 6,
  252. 'agent' => $agentID,
  253. 'remark' => $callbackData['message'] ?? ''
  254. ];
  255. WithdrawalPayoutMonitor::handleFailedCallback(self::AGENT, $callbackData, $OrderId);
  256. $notify_data['state'] = 2;
  257. break;
  258. }
  259. $RecordData = [
  260. 'before_state' => $query->State,
  261. 'after_state' => $withdraw_data['State'] ?? 0,
  262. 'RecordID' => $query->RecordID,
  263. 'update_at' => date('Y-m-d H:i:s')
  264. ];
  265. // 添加用户提现操作记录
  266. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
  267. ->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
  268. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  269. ->where('OrderId', $query->OrderId)
  270. ->update($withdraw_data);
  271. if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
  272. // 单控标签
  273. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  274. }
  275. return 'SUCCESS';
  276. } catch (\Exception $exception) {
  277. Util::WriteLog('SfPay', 'SfPay异步业务逻辑处理失败:' . $exception->getMessage());
  278. return 'SUCCESS';
  279. }
  280. }
  281. }