SupefinaSpeiCashierLogic.php 12 KB

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