2
0

SupefinaSpeiCashierLogic.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. <?php
  2. namespace App\Http\logic\api;
  3. use App\dao\Estatisticas\RechargeWithDraw;
  4. use App\Inter\CashierInterFace;
  5. use App\Models\PrivateMail;
  6. use App\Models\RecordUserDataStatistics;
  7. use App\Services\SupefinaSpei;
  8. use App\Services\StoredProcedure;
  9. use App\Util;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Log;
  12. use Illuminate\Support\Facades\Redis;
  13. class SupefinaSpeiCashierLogic implements CashierInterFace
  14. {
  15. /**
  16. * 代付渠道标识,对应 agent.dbo.admin_configs.config_value(type=cash)。
  17. * 使用前请在后台配置同名渠道值。
  18. */
  19. const AGENT = 106;
  20. /**
  21. * 创建 Supefina SPEI 代付订单。
  22. */
  23. public function payment($RecordID, $amount, $accountName, $phone, $email, $OrderId, $PixNum, $PixType, $IFSCNumber, $BranchBank, $BankNO)
  24. {
  25. // 查询提现订单
  26. $query = DB::connection('write')
  27. ->table('QPAccountsDB.dbo.OrderWithDraw')
  28. ->where('RecordID', $RecordID)
  29. ->first();
  30. if (!$query) {
  31. Util::WriteLog('SupefinaSpei', 'withdraw order not found: '.$RecordID);
  32. return 'fail';
  33. }
  34. $service = new SupefinaSpei('SupefinaSpeiOut');
  35. $config = $service->config;
  36. $merId = $config['merId'] ?? '';
  37. $baseUrl = $config['baseUrl'] ?? '';
  38. $payoutPath = $config['payoutPath'] ?? '/api/supefina/transactions/payout';
  39. $callbackUrl = $config['callbackUrl'] ?? '';
  40. $countryId = $config['countryId'] ?? 'MEX';
  41. $currency = $config['currency'] ?? 'MXN';
  42. if ($merId === '' || $baseUrl === '' || empty($config['key'])) {
  43. Util::WriteLog('SupefinaSpei_error', 'config missing merId/baseUrl/key');
  44. return 'fail';
  45. }
  46. // 账户号:优先 PixNum,其次 BankNO
  47. $account = $PixNum ?: $BankNO;
  48. if (!$account) {
  49. Util::WriteLog('SupefinaSpei_error', 'missing account for withdraw: '.$OrderId);
  50. return 'fail';
  51. }
  52. // 银行编号:优先 BankNO(如果看作 bankId),否则使用配置默认
  53. $bankId = $config['defaultBankId'] ?? '';
  54. if (!empty($BankNO) && ctype_digit((string)$BankNO)) {
  55. $bankId = (string)$BankNO;
  56. }
  57. if ($bankId === '') {
  58. Util::WriteLog('SupefinaSpei_error', 'missing bankId for withdraw: '.$OrderId);
  59. return 'fail';
  60. }
  61. // payProduct:15=CLABE,16=卡号,简单按 PixType 区分,前端/配置需约定
  62. $payProduct = '15';
  63. if ((int)$PixType === 2) {
  64. $payProduct = '16';
  65. }
  66. // 提现金额是以分存储,转成两位小数金额
  67. $orderAmount = number_format($amount / 100, 2, '.', '');
  68. $customerName = $accountName ?: ($email ?: ('U'.$query->UserID));
  69. $params = [
  70. 'account' => (string)$account,
  71. 'bankId' => (string)$bankId,
  72. 'callbackUrl' => $callbackUrl,
  73. 'countryId' => $countryId,
  74. 'currency' => $currency,
  75. 'customerName' => $customerName,
  76. 'description' => 'withdraw_'.$OrderId,
  77. 'merId' => (string)$merId,
  78. 'merOrderNo' => (string)$OrderId,
  79. 'nonceStr' => $service->generateNonceStr(32),
  80. 'orderAmount' => $orderAmount,
  81. 'payProduct' => (string)$payProduct,
  82. ];
  83. $signedParams = $service->sign($params);
  84. $url = rtrim($baseUrl, '/').$payoutPath;
  85. Util::WriteLog('SupefinaSpei', 'payout request: '.$url.' | '.json_encode($signedParams, JSON_UNESCAPED_UNICODE));
  86. try {
  87. $result = $service->postJson($url, $signedParams);
  88. } catch (\Throwable $e) {
  89. Util::WriteLog('SupefinaSpei_error', 'payout request exception: '.$e->getMessage());
  90. return 'fail';
  91. }
  92. Util::WriteLog('SupefinaSpei', 'payout response: '.$result);
  93. try {
  94. $data = \GuzzleHttp\json_decode($result, true);
  95. } catch (\Throwable $e) {
  96. Util::WriteLog('SupefinaSpei_error', ['decode fail', $result, $e->getMessage()]);
  97. return 'fail';
  98. }
  99. // 文档示例:code=200 且 data.transactionStatus = "00" 表示下单成功
  100. if (isset($data['code']) && (string)$data['code'] === '200') {
  101. $transactionStatus = $data['data']['transactionStatus'] ?? null;
  102. if ((string)$transactionStatus === '00') {
  103. return $data;
  104. }
  105. }
  106. // 同步下单失败:如果订单在处理中(State=5),退回资金并标记失败
  107. if ((int)$query->State === 5) {
  108. $msg = $data['msg'] ?? 'Supefina payout failed';
  109. $WithDraw = $query->WithDraw + $query->ServiceFee;
  110. $bonus = '30000,'.$WithDraw;
  111. PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
  112. $withdraw_data = [
  113. 'State' => 6,
  114. 'agent' => self::AGENT,
  115. 'finishDate' => now(),
  116. 'remark' => json_encode($data),
  117. ];
  118. DB::connection('write')
  119. ->table('QPAccountsDB.dbo.OrderWithDraw')
  120. ->where('OrderId', $query->OrderId)
  121. ->update($withdraw_data);
  122. $RecordData = ['after_state' => 6, 'update_at' => now()];
  123. DB::connection('write')
  124. ->table('QPAccountsDB.dbo.AccountsRecord')
  125. ->where('type', 1)
  126. ->where('RecordID', $RecordID)
  127. ->update($RecordData);
  128. }
  129. return 'fail';
  130. }
  131. /**
  132. * Supefina SPEI 代付回调。
  133. *
  134. * @param array<string,mixed>|string $post
  135. */
  136. public function notify($post)
  137. {
  138. if (!is_array($post)) {
  139. $post = \GuzzleHttp\json_decode($post, true);
  140. }
  141. Util::WriteLog('SupefinaSpei', 'payout notify: '.json_encode($post, JSON_UNESCAPED_UNICODE));
  142. $service = new SupefinaSpei('SupefinaSpeiOut');
  143. // 验签
  144. if (!$service->verify($post)) {
  145. Util::WriteLog('SupefinaSpei_error', 'notify sign invalid');
  146. return 'fail';
  147. }
  148. // 只处理代付类型(02)
  149. if (($post['transactionType'] ?? '') !== '02') {
  150. Util::WriteLog('SupefinaSpei', 'ignore non-payout notify, transactionType='.$post['transactionType'] ?? '');
  151. return 'SUCCESS';
  152. }
  153. $OrderId = $post['merOrderId'] ?? $post['merOrderNo'] ?? '';
  154. if ($OrderId === '') {
  155. Util::WriteLog('SupefinaSpei_error', 'notify missing merOrderId');
  156. return 'fail';
  157. }
  158. $query = DB::connection('write')
  159. ->table('QPAccountsDB.dbo.OrderWithDraw')
  160. ->where('OrderId', $OrderId)
  161. ->first();
  162. if (!$query) {
  163. Util::WriteLog('SupefinaSpei_error', 'withdraw order not found in notify: '.$OrderId);
  164. return 'SUCCESS';
  165. }
  166. // 只处理 State=5 或 7 的订单,避免重复
  167. if (!in_array((int)$query->State, [5, 7], true)) {
  168. Util::WriteLog('SupefinaSpei', 'withdraw already handled: '.$OrderId);
  169. return 'SUCCESS';
  170. }
  171. // 映射交易状态:以 Supefina 文档为准,示例中仅说明状态码存在,此处按常规约定:
  172. // 01/02/00 视为成功,其它(如 03/04 等)视为失败;实际项目中可按回调字典表精细化。
  173. $status = (string)($post['status'] ?? '');
  174. $orderStatus = 0;
  175. if (in_array($status, ['00', '01', '02', 'SUCCESS'], true)) {
  176. $orderStatus = 1; // 成功
  177. } elseif ($status !== '') {
  178. $orderStatus = 2; // 失败
  179. }
  180. if ($orderStatus === 0) {
  181. Util::WriteLog('SupefinaSpei', 'payout processing: '.$OrderId.' status='.$status);
  182. return 'SUCCESS';
  183. }
  184. $agentID = DB::connection('write')
  185. ->table('agent.dbo.admin_configs')
  186. ->where('config_value', self::AGENT)
  187. ->where('type', 'cash')
  188. ->value('id') ?? '';
  189. $now = now();
  190. $UserID = $query->UserID;
  191. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  192. // Supefina 回调里带有 amount/fee 和 realityAmount/realityFee
  193. // 提醒:这里仍以我们订单金额为准做账,仅将真实金额用于日志,可根据需要扩展到统计侧。
  194. $realityAmount = isset($post['realityAmount']) ? (float)$post['realityAmount'] : null;
  195. $realityFee = isset($post['realityFee']) ? (float)$post['realityFee'] : null;
  196. Util::WriteLog('SupefinaSpei', 'payout reality: amount='.$realityAmount.', fee='.$realityFee.', orderId='.$OrderId);
  197. $withdraw_data = [];
  198. switch ($orderStatus) {
  199. case 1: // 提现成功
  200. $withdraw_data = [
  201. 'State' => 2,
  202. 'agent' => $agentID,
  203. 'finishDate' => $now,
  204. ];
  205. // 增加提现记录
  206. $first = DB::connection('write')
  207. ->table('QPAccountsDB.dbo.UserTabData')
  208. ->where('UserID', $UserID)
  209. ->first();
  210. if ($first) {
  211. DB::connection('write')
  212. ->table('QPAccountsDB.dbo.UserTabData')
  213. ->where('UserID', $UserID)
  214. ->increment('TakeMoney', $TakeMoney);
  215. } else {
  216. DB::connection('write')
  217. ->table('QPAccountsDB.dbo.UserTabData')
  218. ->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  219. try {
  220. PrivateMail::praiseSendMail($UserID);
  221. } catch (\Throwable $e) {
  222. // 忽略邮件发送失败
  223. }
  224. }
  225. // 免审记录
  226. $withdrawal_position_log = DB::connection('write')
  227. ->table('agent.dbo.withdrawal_position_log')
  228. ->where('order_sn', $OrderId)
  229. ->first();
  230. if ($withdrawal_position_log) {
  231. DB::connection('write')
  232. ->table('agent.dbo.withdrawal_position_log')
  233. ->where('order_sn', $OrderId)
  234. ->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
  235. }
  236. try {
  237. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  238. } catch (\Throwable $exception) {
  239. Util::WriteLog('StoredProcedure', $exception->getMessage());
  240. }
  241. $ServiceFee = $query->ServiceFee;
  242. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  243. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney);
  244. $redis = Redis::connection();
  245. $redis->incr('draw_'.date('Ymd').$UserID);
  246. break;
  247. case 2: // 提现失败
  248. $msg = $post['msg'] ?? 'Withdraw rejected';
  249. $bonus = '30000,'.$TakeMoney;
  250. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  251. Util::WriteLog('SupefinaSpeiEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  252. $withdraw_data = [
  253. 'State' => 6,
  254. 'agent' => $agentID,
  255. 'remark' => $msg,
  256. ];
  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. DB::connection('write')
  266. ->table('QPAccountsDB.dbo.AccountsRecord')
  267. ->updateOrInsert(
  268. ['RecordID' => $query->RecordID, 'type' => 1],
  269. $RecordData
  270. );
  271. DB::connection('write')
  272. ->table('QPAccountsDB.dbo.OrderWithDraw')
  273. ->where('OrderId', $OrderId)
  274. ->update($withdraw_data);
  275. if (isset($withdraw_data['State']) && (int)$withdraw_data['State'] === 2) {
  276. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  277. }
  278. return 'SUCCESS';
  279. }
  280. }