SafePayCashierLogic.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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\SafePay;
  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 SafePayCashierLogic implements CashierInterFace
  17. {
  18. const AGENT = 106; // SafePay代付渠道值
  19. protected $agent = 106;
  20. /**
  21. * 提交代付申请
  22. */
  23. public function payment($RecordID, $amount, $accountName, $phone, $email, $OrderId, $PixNum, $PixType, $IFSCNumber, $BranchBank, $BankNO)
  24. {
  25. // 查询订单号
  26. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')->where('RecordID', $RecordID)->first();
  27. if (!$query) return 'fail'; // 订单不存在
  28. $payConfigService = new PayConfig();
  29. $config = $payConfigService->getConfig('SafePayOut');
  30. // PixType → bank_type/bank_code 映射(沿用现有系统的PixType约定)
  31. $bankTypeMap = [
  32. 1 => 'CASHAPP',
  33. 2 => 'PayPal',
  34. ];
  35. $bankType = $bankTypeMap[$PixType] ?? 'CASHAPP';
  36. // 构建收款账号
  37. // CashApp: cashtag,需 $ 前缀
  38. if ($PixType == 1) {
  39. $account = ($PixNum && strpos($PixNum, '$') !== 0) ? '$' . $PixNum : $PixNum;
  40. } elseif ($PixType == 2) {
  41. // PayPal: 使用邮箱作为账号
  42. $account = $email;
  43. } else {
  44. $account = $PixNum ?: $email;
  45. }
  46. // 构建代付请求参数
  47. $params = [
  48. 'mer_no' => $config['mer_no'] ?? '',
  49. 'order_no' => $OrderId,
  50. 'amount' => number_format($amount / NumConfig::NUM_VALUE, 2, '.', ''),
  51. 'currency' => $config['currency'] ?? 'USD',
  52. 'bank_code' => $bankType,
  53. 'bank_type' => $bankType,
  54. 'name' => $accountName ?: 'user'.$query->UserID,
  55. 'account' => $account,
  56. 'email' => $email ?: '',
  57. 'phone' => $phone ?: '0000000000',
  58. 'notify_url' => $config['notify_url'] ?? '',
  59. 'extra' => json_encode([
  60. 'userId' => (string)($query->UserID ?? ''),
  61. 'firstName' => $accountName ?: 'user'.$query->UserID,
  62. ]),
  63. ];
  64. // RSA签名
  65. $service = new SafePay();
  66. $signedParams = $service->sign($params);
  67. $url = ($config['apiUrl'] ?? 'https://api.safepay.wang') . '/open/api/order/out';
  68. Log::info('SafePay 提现参数:', $signedParams);
  69. try {
  70. $result = $service->curlPost($url, $signedParams);
  71. } catch (\Exception $exception) {
  72. Log::info('SafePay 提现请求异常:', [$exception->getMessage()]);
  73. Util::WriteLog('SafePay_error', 'SafePay 提现请求异常:' . $exception->getMessage());
  74. return 'fail';
  75. }
  76. Log::info('SafePay 提现结果:', [$result ?? "no result"]);
  77. try {
  78. $data = \GuzzleHttp\json_decode($result, true);
  79. } catch (\Exception $e) {
  80. Util::WriteLog("SafePay_error", [$result, $e->getMessage(), $e->getTraceAsString()]);
  81. return 'fail';
  82. }
  83. // SafePay 代付成功响应: code=200, data.sys_no 是系统流水号
  84. if (isset($data['code']) && $data['code'] == 200) {
  85. return $data;
  86. }
  87. // 同步失败处理:回复玩家金币,标记订单失败
  88. WithdrawalPayoutMonitor::handleFailedCallback(self::AGENT, $data, $OrderId);
  89. if ($query->State == 5) {
  90. $msg = 'Liquidation failure';
  91. $WithDraw = $query->WithDraw + $query->ServiceFee;
  92. $bonus = '30000,' . $WithDraw;
  93. PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
  94. $withdraw_data = [
  95. 'State' => 6,
  96. 'agent' => 1060,
  97. 'finishDate' => now(),
  98. 'remark' => json_encode($data)
  99. ];
  100. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  101. ->where('OrderId', $query->OrderId)
  102. ->update($withdraw_data);
  103. $RecordData = ['after_state' => 6, 'update_at' => now()];
  104. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
  105. ->where('type', 1)
  106. ->where('RecordID', $RecordID)
  107. ->update($RecordData);
  108. }
  109. return 'fail';
  110. }
  111. /**
  112. * 代付异步回调处理
  113. *
  114. * SafePay 代付回调格式(POST JSON):
  115. * {
  116. * "mer_no": 600000,
  117. * "order_no": "xxx",
  118. * "order_amount": "10.00",
  119. * "order_reality_amount": "10.00",
  120. * "currency": "USD",
  121. * "result": "success", // success=成功, fail=失败
  122. * "sys_no": "212073",
  123. * "sign": "xxx"
  124. * }
  125. */
  126. public function notify($post)
  127. {
  128. if (!is_array($post)) $post = \GuzzleHttp\json_decode($post, true);
  129. Util::WriteLog('SafePay', 'SafePay 提现回调:' . json_encode($post));
  130. try {
  131. // 判断订单是否存在
  132. $OrderId = $post['order_no'] ?? '';
  133. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  134. ->where('OrderId', $OrderId)
  135. ->first();
  136. if (!$query) {
  137. Util::WriteLog('SafePay', '提现订单不存在: ' . $OrderId);
  138. return 'SUCCESS';
  139. }
  140. // 订单已完成处理
  141. if ($query->State != 5 && $query->State != 7) {
  142. Util::WriteLog('SafePay', $OrderId . '_订单状态已完成');
  143. return 'SUCCESS';
  144. }
  145. $agentID = DB::connection('write')->table('agent.dbo.admin_configs')
  146. ->where('config_value', self::AGENT)
  147. ->where('type', 'cash')
  148. ->select('id')
  149. ->first()->id ?? '';
  150. $now = now();
  151. $notify_data = [
  152. 'state' => 1,
  153. 'finish_at' => $now,
  154. 'casOrdNo' => $post['sys_no'] ?? '',
  155. 'extra' => \GuzzleHttp\json_encode($post),
  156. 'created_at' => $now,
  157. 'updated_at' => $now,
  158. 'order_sn' => $OrderId,
  159. 'amount' => $query->WithDraw,
  160. ];
  161. // 判断回调结果: result=success=成功, result=fail=失败
  162. $result = $post['result'] ?? '';
  163. $orderStatus = 0;
  164. if ($result === 'success') {
  165. $orderStatus = 1; // 成功
  166. } elseif ($result === 'fail') {
  167. $orderStatus = 2; // 失败
  168. }
  169. if (!$orderStatus) {
  170. Util::WriteLog('SafePay', 'SafePay 提现处理中:' . $OrderId);
  171. return 'SUCCESS';
  172. }
  173. Util::WriteLog('SafePay', 'SafePay 提现结果:' . $OrderId . '_' . $orderStatus);
  174. $UserID = $query->UserID;
  175. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  176. $withdraw_data = [];
  177. switch ($orderStatus) {
  178. case 1: // 提现成功
  179. Util::WriteLog('SafePay', 'SafePay提现成功');
  180. $withdraw_data = [
  181. 'State' => 2,
  182. 'agent' => $agentID,
  183. 'finishDate' => $now
  184. ];
  185. // 根据配置计算代付手续费: 费率% * 提现金额 + 固定$
  186. // 例: pay_rate=[0.5,0.3] → 0.5% + $0.3
  187. $payConfigService = new PayConfig();
  188. $outConfig = $payConfigService->getConfig('SafePayOut');
  189. $payRates = $outConfig['pay_rate'] ?? null;
  190. if (is_array($payRates)) {
  191. $payMethod = $query->PixType ?? 1;
  192. $payRate = $payRates[$payMethod] ?? $payRates;
  193. $feePercent = $payRate[0] ?? 0.5;
  194. $feeFixed = $payRate[1] ?? 0.3;
  195. $withdraw_data['withdraw_fee'] = intval(($query->WithDraw * $feePercent) / 100)
  196. + (int)($feeFixed * NumConfig::NUM_VALUE);
  197. }
  198. // 增加提现记录
  199. $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  200. ->where('UserID', $UserID)->first();
  201. if ($first) {
  202. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  203. ->where('UserID', $UserID)
  204. ->increment('TakeMoney', $TakeMoney);
  205. } else {
  206. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  207. ->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  208. try {
  209. PrivateMail::praiseSendMail($UserID);
  210. } catch (\Exception $e) {
  211. // 忽略邮件发送失败
  212. }
  213. }
  214. // 免审的时候,修改免审状态
  215. $withdrawal_position_log = DB::connection('write')
  216. ->table('agent.dbo.withdrawal_position_log')
  217. ->where('order_sn', $OrderId)
  218. ->first();
  219. if ($withdrawal_position_log) {
  220. DB::connection('write')->table('agent.dbo.withdrawal_position_log')
  221. ->where('order_sn', $OrderId)
  222. ->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
  223. }
  224. try {
  225. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  226. } catch (\Exception $exception) {
  227. Util::WriteLog('StoredProcedure', $exception);
  228. }
  229. $ServiceFee = $query->ServiceFee;
  230. // 增加用户提现值
  231. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  232. // 数据统计后台 -- 提现记录添加
  233. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, $withdraw_data['withdraw_fee'] ?? 0, $ServiceFee);
  234. $redis = Redis::connection();
  235. $redis->incr('draw_' . date('Ymd') . $UserID);
  236. PrivateMail::successMail($UserID, $OrderId, $TakeMoney);
  237. break;
  238. case 2: // 提现失败
  239. $msg = 'Encomenda rejeitada pelo banco';
  240. $bonus = '30000,' . $TakeMoney;
  241. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  242. Util::WriteLog('SafePayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  243. $withdraw_data = [
  244. 'State' => 6,
  245. 'agent' => $agentID,
  246. 'remark' => $post['result_mes'] ?? ''
  247. ];
  248. WithdrawalPayoutMonitor::handleFailedCallback(self::AGENT, $post, $OrderId);
  249. $notify_data['state'] = 2;
  250. break;
  251. }
  252. $RecordData = [
  253. 'before_state' => $query->State,
  254. 'after_state' => $withdraw_data['State'] ?? 0,
  255. 'RecordID' => $query->RecordID,
  256. 'update_at' => date('Y-m-d H:i:s')
  257. ];
  258. // 添加用户提现操作记录
  259. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
  260. ->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
  261. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  262. ->where('OrderId', $query->OrderId)
  263. ->update($withdraw_data);
  264. if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
  265. // 单控标签
  266. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  267. }
  268. return 'SUCCESS';
  269. } catch (\Exception $exception) {
  270. Util::WriteLog('SafePay', 'SafePay异步业务逻辑处理失败:' . $exception->getMessage());
  271. return 'SUCCESS';
  272. }
  273. }
  274. }