SfPayCashierLogic.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. if ($query->State == 5) {
  92. $msg = 'Liquidation failure';
  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' => 1080,
  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. * 代付异步回调处理
  115. *
  116. * SfPay代付回调格式(POST JSON,不加密):
  117. * {
  118. * "data": {
  119. * "amount": "30.00",
  120. * "orderNo": "...",
  121. * "message": "...",
  122. * "type": "payout",
  123. * "merchantOrderNo": "...",
  124. * "processedTime": "...",
  125. * "processAmount": "0.00",
  126. * "status": "SUCCESS"
  127. * },
  128. * "signature_n": "..."
  129. * }
  130. */
  131. public function notify($post)
  132. {
  133. if (!is_array($post)) {
  134. $post = \GuzzleHttp\json_decode($post, true);
  135. }
  136. Util::WriteLog('SfPay', 'SfPay 提现回调:' . json_encode($post));
  137. try {
  138. $callbackData = $post['data'] ?? [];
  139. $signatureN = $post['signature_n'] ?? '';
  140. if (empty($callbackData) || empty($signatureN)) {
  141. Util::WriteLog('SfPay', '提现回调数据不完整');
  142. return 'SUCCESS';
  143. }
  144. // 验签
  145. $service = new SfPay();
  146. if (!$service->verifySign($callbackData, $signatureN)) {
  147. Util::WriteLog('SfPay', '提现回调签名验证失败');
  148. return 'SUCCESS';
  149. }
  150. // 判断订单是否存在
  151. $OrderId = $callbackData['merchantOrderNo'] ?? '';
  152. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  153. ->where('OrderId', $OrderId)
  154. ->first();
  155. if (!$query) {
  156. Util::WriteLog('SfPay', '提现订单不存在: ' . $OrderId);
  157. return 'SUCCESS';
  158. }
  159. // 订单已完成处理
  160. if ($query->State != 5 && $query->State != 7) {
  161. Util::WriteLog('SfPay', $OrderId . '_订单状态已完成');
  162. return 'SUCCESS';
  163. }
  164. $agentID = DB::connection('write')->table('agent.dbo.admin_configs')
  165. ->where('config_value', self::AGENT)
  166. ->where('type', 'cash')
  167. ->select('id')
  168. ->first()->id ?? '';
  169. $now = now();
  170. $notify_data = [
  171. 'state' => 1,
  172. 'finish_at' => $now,
  173. 'casOrdNo' => $callbackData['orderNo'] ?? '',
  174. 'extra' => \GuzzleHttp\json_encode($post),
  175. 'created_at' => $now,
  176. 'updated_at' => $now,
  177. 'order_sn' => $OrderId,
  178. 'amount' => $query->WithDraw,
  179. ];
  180. // 判断回调结果: SUCCESS=成功, FAILURE=失败
  181. $status = $callbackData['status'] ?? '';
  182. $orderStatus = 0;
  183. if ($status === 'SUCCESS') {
  184. $orderStatus = 1; // 成功
  185. } elseif ($status === 'FAILURE' || $status === 'REVERSED') {
  186. $orderStatus = 2; // 失败
  187. }
  188. if (!$orderStatus) {
  189. Util::WriteLog('SfPay', 'SfPay 提现处理中:' . $OrderId);
  190. return 'SUCCESS';
  191. }
  192. Util::WriteLog('SfPay', 'SfPay 提现结果:' . $OrderId . '_' . $orderStatus);
  193. $UserID = $query->UserID;
  194. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  195. $withdraw_data = [];
  196. switch ($orderStatus) {
  197. case 1: // 提现成功
  198. Util::WriteLog('SfPay', 'SfPay提现成功');
  199. $withdraw_data = [
  200. 'State' => 2,
  201. 'agent' => $agentID,
  202. 'finishDate' => $now
  203. ];
  204. // 增加提现记录
  205. $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  206. ->where('UserID', $UserID)->first();
  207. if ($first) {
  208. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  209. ->where('UserID', $UserID)
  210. ->increment('TakeMoney', $TakeMoney);
  211. } else {
  212. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  213. ->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  214. try {
  215. PrivateMail::praiseSendMail($UserID);
  216. } catch (\Exception $e) {
  217. // 忽略邮件发送失败
  218. }
  219. }
  220. // 免审的时候,修改免审状态
  221. $withdrawal_position_log = DB::connection('write')
  222. ->table('agent.dbo.withdrawal_position_log')
  223. ->where('order_sn', $OrderId)
  224. ->first();
  225. if ($withdrawal_position_log) {
  226. DB::connection('write')->table('agent.dbo.withdrawal_position_log')
  227. ->where('order_sn', $OrderId)
  228. ->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
  229. }
  230. try {
  231. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  232. } catch (\Exception $exception) {
  233. Util::WriteLog('StoredProcedure', $exception);
  234. }
  235. $ServiceFee = $query->ServiceFee;
  236. // 增加用户提现值
  237. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  238. // 数据统计后台 -- 提现记录添加
  239. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, 0, $ServiceFee);
  240. $redis = Redis::connection();
  241. $redis->incr('draw_' . date('Ymd') . $UserID);
  242. PrivateMail::successMail($UserID, $OrderId, $TakeMoney);
  243. break;
  244. case 2: // 提现失败
  245. $msg = 'Encomenda rejeitada pelo banco';
  246. $bonus = '30000,' . $TakeMoney;
  247. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  248. Util::WriteLog('SfPayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  249. $withdraw_data = [
  250. 'State' => 6,
  251. 'agent' => $agentID,
  252. 'remark' => $callbackData['message'] ?? ''
  253. ];
  254. WithdrawalPayoutMonitor::handleFailedCallback(self::AGENT, $callbackData, $OrderId);
  255. $notify_data['state'] = 2;
  256. break;
  257. }
  258. $RecordData = [
  259. 'before_state' => $query->State,
  260. 'after_state' => $withdraw_data['State'] ?? 0,
  261. 'RecordID' => $query->RecordID,
  262. 'update_at' => date('Y-m-d H:i:s')
  263. ];
  264. // 添加用户提现操作记录
  265. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
  266. ->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
  267. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  268. ->where('OrderId', $query->OrderId)
  269. ->update($withdraw_data);
  270. if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
  271. // 单控标签
  272. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  273. }
  274. return 'SUCCESS';
  275. } catch (\Exception $exception) {
  276. Util::WriteLog('SfPay', 'SfPay异步业务逻辑处理失败:' . $exception->getMessage());
  277. return 'SUCCESS';
  278. }
  279. }
  280. }