SafePayCashierLogic.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. if ($query->State == 5) {
  89. $msg = 'Liquidation failure';
  90. $WithDraw = $query->WithDraw + $query->ServiceFee;
  91. $bonus = '30000,' . $WithDraw;
  92. PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
  93. $withdraw_data = [
  94. 'State' => 6,
  95. 'agent' => 1060,
  96. 'finishDate' => now(),
  97. 'remark' => json_encode($data)
  98. ];
  99. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  100. ->where('OrderId', $query->OrderId)
  101. ->update($withdraw_data);
  102. $RecordData = ['after_state' => 6, 'update_at' => now()];
  103. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
  104. ->where('type', 1)
  105. ->where('RecordID', $RecordID)
  106. ->update($RecordData);
  107. }
  108. return 'fail';
  109. }
  110. /**
  111. * 代付异步回调处理
  112. *
  113. * SafePay 代付回调格式(POST JSON):
  114. * {
  115. * "mer_no": 600000,
  116. * "order_no": "xxx",
  117. * "order_amount": "10.00",
  118. * "order_reality_amount": "10.00",
  119. * "currency": "USD",
  120. * "result": "success", // success=成功, fail=失败
  121. * "sys_no": "212073",
  122. * "sign": "xxx"
  123. * }
  124. */
  125. public function notify($post)
  126. {
  127. if (!is_array($post)) $post = \GuzzleHttp\json_decode($post, true);
  128. Util::WriteLog('SafePay', 'SafePay 提现回调:' . json_encode($post));
  129. try {
  130. // 判断订单是否存在
  131. $OrderId = $post['order_no'] ?? '';
  132. $query = DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  133. ->where('OrderId', $OrderId)
  134. ->first();
  135. if (!$query) {
  136. Util::WriteLog('SafePay', '提现订单不存在: ' . $OrderId);
  137. return 'SUCCESS';
  138. }
  139. // 订单已完成处理
  140. if ($query->State != 5 && $query->State != 7) {
  141. Util::WriteLog('SafePay', $OrderId . '_订单状态已完成');
  142. return 'SUCCESS';
  143. }
  144. $agentID = DB::connection('write')->table('agent.dbo.admin_configs')
  145. ->where('config_value', self::AGENT)
  146. ->where('type', 'cash')
  147. ->select('id')
  148. ->first()->id ?? '';
  149. $now = now();
  150. $notify_data = [
  151. 'state' => 1,
  152. 'finish_at' => $now,
  153. 'casOrdNo' => $post['sys_no'] ?? '',
  154. 'extra' => \GuzzleHttp\json_encode($post),
  155. 'created_at' => $now,
  156. 'updated_at' => $now,
  157. 'order_sn' => $OrderId,
  158. 'amount' => $query->WithDraw,
  159. ];
  160. // 判断回调结果: result=success=成功, result=fail=失败
  161. $result = $post['result'] ?? '';
  162. $orderStatus = 0;
  163. if ($result === 'success') {
  164. $orderStatus = 1; // 成功
  165. } elseif ($result === 'fail') {
  166. $orderStatus = 2; // 失败
  167. }
  168. if (!$orderStatus) {
  169. Util::WriteLog('SafePay', 'SafePay 提现处理中:' . $OrderId);
  170. return 'SUCCESS';
  171. }
  172. Util::WriteLog('SafePay', 'SafePay 提现结果:' . $OrderId . '_' . $orderStatus);
  173. $UserID = $query->UserID;
  174. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  175. $withdraw_data = [];
  176. switch ($orderStatus) {
  177. case 1: // 提现成功
  178. Util::WriteLog('SafePay', 'SafePay提现成功');
  179. $withdraw_data = [
  180. 'State' => 2,
  181. 'agent' => $agentID,
  182. 'finishDate' => $now
  183. ];
  184. // 根据配置计算代付手续费: 费率% * 提现金额 + 固定$
  185. // 例: pay_rate=[0.5,0.3] → 0.5% + $0.3
  186. $payConfigService = new PayConfig();
  187. $outConfig = $payConfigService->getConfig('SafePayOut');
  188. $payRates = $outConfig['pay_rate'] ?? null;
  189. if (is_array($payRates)) {
  190. $payMethod = $query->PixType ?? 1;
  191. $payRate = $payRates[$payMethod] ?? $payRates;
  192. $feePercent = $payRate[0] ?? 0.5;
  193. $feeFixed = $payRate[1] ?? 0.3;
  194. $withdraw_data['withdraw_fee'] = intval(($query->WithDraw * $feePercent) / 100)
  195. + (int)($feeFixed * NumConfig::NUM_VALUE);
  196. }
  197. // 增加提现记录
  198. $first = DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  199. ->where('UserID', $UserID)->first();
  200. if ($first) {
  201. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  202. ->where('UserID', $UserID)
  203. ->increment('TakeMoney', $TakeMoney);
  204. } else {
  205. DB::connection('write')->table('QPAccountsDB.dbo.UserTabData')
  206. ->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  207. try {
  208. PrivateMail::praiseSendMail($UserID);
  209. } catch (\Exception $e) {
  210. // 忽略邮件发送失败
  211. }
  212. }
  213. // 免审的时候,修改免审状态
  214. $withdrawal_position_log = DB::connection('write')
  215. ->table('agent.dbo.withdrawal_position_log')
  216. ->where('order_sn', $OrderId)
  217. ->first();
  218. if ($withdrawal_position_log) {
  219. DB::connection('write')->table('agent.dbo.withdrawal_position_log')
  220. ->where('order_sn', $OrderId)
  221. ->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
  222. }
  223. try {
  224. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  225. } catch (\Exception $exception) {
  226. Util::WriteLog('StoredProcedure', $exception);
  227. }
  228. $ServiceFee = $query->ServiceFee;
  229. // 增加用户提现值
  230. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  231. // 数据统计后台 -- 提现记录添加
  232. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, $withdraw_data['withdraw_fee'] ?? 0, $ServiceFee);
  233. $redis = Redis::connection();
  234. $redis->incr('draw_' . date('Ymd') . $UserID);
  235. PrivateMail::successMail($UserID, $OrderId, $TakeMoney);
  236. break;
  237. case 2: // 提现失败
  238. $msg = 'Encomenda rejeitada pelo banco';
  239. $bonus = '30000,' . $TakeMoney;
  240. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  241. Util::WriteLog('SafePayEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  242. $withdraw_data = [
  243. 'State' => 6,
  244. 'agent' => $agentID,
  245. 'remark' => $post['result_mes'] ?? ''
  246. ];
  247. WithdrawalPayoutMonitor::handleFailedCallback(self::AGENT, $post, $OrderId);
  248. $notify_data['state'] = 2;
  249. break;
  250. }
  251. $RecordData = [
  252. 'before_state' => $query->State,
  253. 'after_state' => $withdraw_data['State'] ?? 0,
  254. 'RecordID' => $query->RecordID,
  255. 'update_at' => date('Y-m-d H:i:s')
  256. ];
  257. // 添加用户提现操作记录
  258. DB::connection('write')->table('QPAccountsDB.dbo.AccountsRecord')
  259. ->updateOrInsert(['RecordID' => $query->RecordID, 'type' => 1], $RecordData);
  260. DB::connection('write')->table('QPAccountsDB.dbo.OrderWithDraw')
  261. ->where('OrderId', $query->OrderId)
  262. ->update($withdraw_data);
  263. if (isset($withdraw_data['State']) && $withdraw_data['State'] == 2) {
  264. // 单控标签
  265. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  266. }
  267. return 'SUCCESS';
  268. } catch (\Exception $exception) {
  269. Util::WriteLog('SafePay', 'SafePay异步业务逻辑处理失败:' . $exception->getMessage());
  270. return 'SUCCESS';
  271. }
  272. }
  273. }