SupefinaSpeiCashierLogic.php 12 KB

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