SafePayCashierLogic.php 12 KB

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