NewSupefinaSpeiLogic.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. <?php
  2. namespace App\Http\logic\api;
  3. use App\dao\Estatisticas\RechargeWithDraw;
  4. use App\dao\Pay\PayController;
  5. use App\Http\helper\CreateOrder;
  6. use App\Http\helper\NumConfig;
  7. use App\Jobs\Order;
  8. use App\Models\PrivateMail;
  9. use App\Models\RecordUserDataStatistics;
  10. use App\Services\Aes;
  11. use App\Services\OrderServices;
  12. use App\Services\PayConfig;
  13. use App\Services\StoredProcedure;
  14. use App\Services\SupefinaSpei;
  15. use App\Services\CreateLog;
  16. use App\Util;
  17. use GuzzleHttp\Client;
  18. use Illuminate\Support\Facades\DB;
  19. use Illuminate\Support\Facades\Redis;
  20. /**
  21. * Supefina SPEI
  22. *
  23. */
  24. class NewSupefinaSpeiLogic extends BaseApiLogic
  25. {
  26. const AGENT = 108;
  27. public $result;
  28. public function pay_order($userId, $pay_amount, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType, $pay_method = '')
  29. {
  30. $PayVerify = new PayController();
  31. $pay_amount = $PayVerify->verify($userId, $GiftsID, $pay_amount);
  32. if ($PayVerify->verify($userId, $GiftsID, $pay_amount) === false) {
  33. $this->error = $PayVerify->getError();
  34. return false;
  35. }
  36. if ($pay_amount < 0) {
  37. $this->error = 'Payment error_4';
  38. return false;
  39. }
  40. $service = new SupefinaSpei('NewSupefinaSpei');
  41. $config = $service->config;
  42. $merId = $config['merId'] ?? '';
  43. $baseUrl = $config['baseUrl'] ?? '';
  44. $payinPath = $config['payinPath'] ?? '/api/supefina/transactions/collection';
  45. $callbackUrl = $config['callbackUrl'] ?? '';
  46. $countryId = $config['countryId'] ?? 'MX';
  47. $currency = $config['currency'] ?? 'MXN';
  48. $aesKey = $config['aesKey'] ?? '';
  49. $privateKey = $config['privateKey'] ?? '';
  50. if ($merId === '' || $baseUrl === '' || empty($privateKey) || $callbackUrl === '') {
  51. $this->error = 'Payment config error';
  52. return false;
  53. }
  54. $order_sn = CreateOrder::order_sn($userId);
  55. $logic = new OrderLogic();
  56. $amount = (int)round($pay_amount * NumConfig::NUM_VALUE);
  57. $logic->orderCreate($order_sn, $amount, 'NewSupefinaSpei', $userId, $pay_method, $GiftsID, $AdId, $eventType);
  58. $orderAmount = (string)(int)$pay_amount;
  59. if ($pay_amount != (int)$pay_amount) {
  60. $orderAmount = number_format($pay_amount, 2, '.', '');
  61. }
  62. $params = [
  63. 'merchantOrderNo' => $order_sn,
  64. 'amount' => $orderAmount,
  65. 'country' => $countryId,
  66. 'currency' => $currency,
  67. 'notifyUrl' => $callbackUrl,
  68. ];
  69. $headers = [
  70. 'version' => '1.0.0',
  71. 'merchantNo' => $merId,
  72. 'requestId' => mt_rand(100000, 999999) . time(),
  73. 'requestTime' => time() * 1000,
  74. ];
  75. $body = [
  76. 'productNo' => 'CLABE',
  77. 'data' => Aes::encrypt(json_encode($params), base64_decode($aesKey)),
  78. ];
  79. $sign = $this->sign($headers, $body, $privateKey);
  80. $headers['sign'] = $sign;
  81. $request_extra = \GuzzleHttp\json_encode(array_merge($headers, $params));
  82. CreateLog::pay_request($userPhone, $request_extra, $order_sn, $userEmail, $userId, $userName);
  83. $url = rtrim($baseUrl, '/') . $payinPath;
  84. Util::WriteLog('NewSupefinaSpei', 'payin request: ' . $url . ' | ' . $request_extra);
  85. try {
  86. $client = new Client();
  87. $result = $client->post($url, [
  88. 'headers' => $headers,
  89. 'json' => $body,
  90. ])->getBody()->getContents();
  91. } catch (\Throwable $e) {
  92. Util::WriteLog('NewSupefinaSpei_error', 'payin request exception: ' . $e->getMessage());
  93. $this->error = 'Payment processing error';
  94. return false;
  95. }
  96. Util::WriteLog('NewSupefinaSpei', 'payin response: ' . $result);
  97. try {
  98. $data = \GuzzleHttp\json_decode($result, true);
  99. } catch (\Throwable $e) {
  100. Util::WriteLog('NewSupefinaSpei_error', [$result, $e->getMessage()]);
  101. $this->error = 'Payment processing error';
  102. return false;
  103. }
  104. if (!isset($data['success']) || $data['success'] !== true) {
  105. $this->error = $data['message'] ?? 'Payment request failed';
  106. return false;
  107. }
  108. $decryptData = Aes::decrypt($data['data'], base64_decode($aesKey));
  109. Util::WriteLog('NewSupefinaSpei', 'payin response1: ' . $decryptData);
  110. $this->result = json_decode($decryptData, true);
  111. return $this->result;
  112. }
  113. /**
  114. * 代收回调:仅代收存在“实际金额与订单金额不一致”,以 realityAmount 入账
  115. *
  116. * @param array<string,mixed> $post
  117. */
  118. public function notify($post)
  119. {
  120. $order_sn = $post['merchantOrderNo'];
  121. if ($order_sn === '') {
  122. Util::WriteLog('NewSupefinaSpei_error', 'payin notify missing merchantOrderNo');
  123. return 'fail';
  124. }
  125. try {
  126. $order = DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->first();
  127. if (!$order) {
  128. Util::WriteLog('NewSupefinaSpei', 'payin order not found: ' . $order_sn);
  129. return '{"success":true}';
  130. }
  131. if (!empty($order->pay_at) || !empty($order->finished_at)) {
  132. if ($order->payment_sn != $post['platformOrderNo']) {
  133. $logic = new OrderLogic();
  134. $amount = 100;
  135. $order_sn = $order_sn . '#' . time();
  136. $logic->orderCreate($order_sn, $amount, 'NewSupefinaSpei', $order->user_id);
  137. $order = DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)
  138. ->first();
  139. } else {
  140. return '{"success":true}';
  141. }
  142. }
  143. $status = (string)($post['transStatus'] ?? '');
  144. if (in_array($status, ['FAILED', 'CLOSED', 'CANCELED'])) {
  145. $body = ['pay_status' => 2, 'updated_at' => date('Y-m-d H:i:s')];
  146. DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->update($body);
  147. return '{"success":true}';
  148. }
  149. if (in_array($status, ['REFUNDING', 'PARTIAL_REFUND', 'REFUNDED'])) {
  150. Util::WriteLog('NewSupefinaSpei', 'payin notify status refund: ' . $order_sn);
  151. return '{"success":true}';
  152. }
  153. if ($status !== 'SUCCESS') {
  154. Util::WriteLog('NewSupefinaSpei', 'payin notify status not success: ' . $order_sn);
  155. return '{"success":true}';
  156. }
  157. $GiftsID = $order->GiftsID ?: '';
  158. $userID = $order->user_id ?: '';
  159. $AdId = $order->AdId ?: '';
  160. $eventType = $order->eventType ?: '';
  161. $realityAmount = isset($post['amount']) ? (float)$post['amount'] : (float)($post['amount'] ?? 0);
  162. if ($realityAmount <= 0) {
  163. Util::WriteLog('NewSupefinaSpei_error', 'payin notify invalid realityAmount: ' . json_encode($post));
  164. return 'fail';
  165. }
  166. $payAmt = round($realityAmount, 2);
  167. $amountInScore = (int)round($payAmt * NumConfig::NUM_VALUE);
  168. $body = [
  169. 'payment_sn' => $post['platformOrderNo'] ?? '',
  170. 'pay_status' => 1,
  171. 'pay_at' => date('Y-m-d H:i:s'),
  172. 'finished_at' => date('Y-m-d H:i:s'),
  173. 'amount' => $amountInScore,
  174. 'updated_at' => date('Y-m-d H:i:s'),
  175. ];
  176. $body['payment_fee'] = $post['fee'] ?? 0;
  177. $service = new OrderServices();
  178. if ((int)$order->amount != $amountInScore) {
  179. $body['GiftsID'] = 0;
  180. $body['amount'] = $amountInScore;
  181. $Recharge = $payAmt;
  182. $give = 0;
  183. $favorable_price = $Recharge + $give;
  184. $czReason = 1;
  185. $cjReason = 45;
  186. } else {
  187. [$give, $favorable_price, $Recharge, $czReason, $cjReason] = $service->getPayInfo($GiftsID, $userID, $payAmt);
  188. }
  189. [$Score] = $service->addRecord($userID, $payAmt, $favorable_price, $order_sn, $GiftsID, $Recharge, $czReason, $give, $cjReason, $AdId, $eventType,
  190. $body['payment_fee'] ?? 0);
  191. Order::dispatch([$userID, $payAmt, $Score, $favorable_price, $GiftsID, $order_sn]);
  192. DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->update($body);
  193. Util::WriteLog('NewSupefinaSpei', 'payin success, order_sn=' . $order_sn . ', realityAmount=' . $realityAmount);
  194. return '{"success":true}';
  195. } catch (\Throwable $exception) {
  196. Util::WriteLog('NewSupefinaSpei_error', $exception->getMessage() . "\n" . $exception->getTraceAsString());
  197. throw $exception;
  198. }
  199. }
  200. public function payment($RecordID, $amount, $accountName, $phone, $email, $OrderId, $PixNum, $PixType, $IFSCNumber, $BranchBank, $BankNO)
  201. {
  202. // 查询提现订单
  203. $query = DB::connection('write')
  204. ->table('QPAccountsDB.dbo.OrderWithDraw')
  205. ->where('RecordID', $RecordID)
  206. ->first();
  207. if (!$query) {
  208. Util::WriteLog('NewSupefinaSpei', 'withdraw order not found: ' . $RecordID);
  209. return 'fail';
  210. }
  211. $config = (new PayConfig())->getConfig('NewSupefinaSpei');
  212. // 账户号:优先 PixNum,其次 BankNO
  213. $account = $PixNum ?: $BankNO;
  214. if (!$account) {
  215. Util::WriteLog('NewSupefinaSpei_error', 'missing account for withdraw: ' . $OrderId);
  216. return 'fail';
  217. }
  218. // 银行编号:优先 BankNO(如果看作 bankId),否则使用配置默认
  219. $bankId = $BranchBank;
  220. if ($bankId === '') {
  221. Util::WriteLog('NewSupefinaSpei_error', 'missing bankId for withdraw: ' . $OrderId);
  222. return 'fail';
  223. }
  224. // 提现金额是以分存储,转成两位小数金额
  225. $orderAmount = number_format($amount / 100, 2, '.', '');
  226. $bankList = config('games.mex_bank_list');
  227. try {
  228. $now = time() * 1000;
  229. $data = [
  230. 'transTime' => $now,
  231. 'merchantOrderNo' => $OrderId,
  232. 'amount' => (string)$orderAmount,
  233. 'country' => $config['country'] ?? 'MX',
  234. 'currency' => $config['currency'] ?? 'MXN',
  235. 'payeeInfo' => [
  236. 'accountInfo' => [
  237. 'accountNo' => $account,
  238. 'accountType' => mb_strlen($account) == 16 ? '20' : '10',
  239. ],
  240. 'bankInfo' => [
  241. 'bankCode' => $bankId,
  242. 'bankName' => $bankList[$bankId] ?? 'bank',
  243. ],
  244. 'payeeName' => $accountName ?: 'slot777',
  245. ],
  246. 'notifyUrl' => $config['cashCallbackUrl'],
  247. ];
  248. $url = $config['baseUrl'] . $config['transferPath'];
  249. $result = $this->sendRequest($url, 'TRANSFER', $data);
  250. if ($result === false) {
  251. return 'fail';
  252. }
  253. } catch (\Throwable $e) {
  254. Util::WriteLog('NewSupefinaSpei_error', 'payout request exception: ' . $e->getMessage());
  255. return '';
  256. }
  257. try {
  258. $responseData = \GuzzleHttp\json_decode($result, true);
  259. } catch (\Throwable $e) {
  260. Util::WriteLog('NewSupefinaSpei_error', [$result, $e->getMessage()]);
  261. $this->error = 'Payment processing error';
  262. return false;
  263. }
  264. if (!isset($responseData['success']) || $responseData['success'] !== true) {
  265. $this->error = $responseData['message'] ?? 'request failed';
  266. // 同步下单失败:如果订单在处理中(State=5),退回资金并标记失败
  267. if ((int)$query->State === 5) {
  268. $msg = $data['msg'] ?? 'NewSupefinaSpei payout failed';
  269. $WithDraw = $query->WithDraw + $query->ServiceFee;
  270. $bonus = '30000,' . $WithDraw;
  271. PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
  272. $withdraw_data = [
  273. 'State' => 6,
  274. 'agent' => self::AGENT,
  275. 'finishDate' => now(),
  276. 'remark' => json_encode($data),
  277. ];
  278. DB::connection('write')
  279. ->table('QPAccountsDB.dbo.OrderWithDraw')
  280. ->where('OrderId', $query->OrderId)
  281. ->update($withdraw_data);
  282. $RecordData = ['after_state' => 6, 'update_at' => now()];
  283. DB::connection('write')
  284. ->table('QPAccountsDB.dbo.AccountsRecord')
  285. ->where('type', 1)
  286. ->where('RecordID', $RecordID)
  287. ->update($RecordData);
  288. }
  289. return 'fail';
  290. }
  291. $decryptData = Aes::decrypt($responseData['data'], base64_decode($config['aesKey']));
  292. Util::WriteLog('NewSupefinaSpei', 'transfer decrypt response: ' . $decryptData);
  293. $this->result = json_decode($decryptData, true);
  294. return $this->result;
  295. }
  296. public function cashNotify($post)
  297. {
  298. $OrderId = $post['merchantOrderNo'];
  299. if ($OrderId === '') {
  300. Util::WriteLog('NewSupefinaSpei_error', 'payout notify missing merchantOrderNo');
  301. return 'fail';
  302. }
  303. $query = DB::connection('write')
  304. ->table('QPAccountsDB.dbo.OrderWithDraw')
  305. ->where('OrderId', $OrderId)
  306. ->first();
  307. if (!$query) {
  308. Util::WriteLog('NewSupefinaSpei_error', 'withdraw order not found in notify: '.$OrderId);
  309. return '{"success":true}';
  310. }
  311. // 只处理 State=5 或 7 的订单,避免重复
  312. if (!in_array((int)$query->State, [5, 7], true)) {
  313. Util::WriteLog('NewSupefinaSpei', 'withdraw already handled: '.$OrderId);
  314. return '{"success":true}';
  315. }
  316. $status = $post['transStatus'] ?? '';
  317. $orderStatus = 0;
  318. if (in_array($status, ['SUCCESS'], true)) {
  319. $orderStatus = 1; // 成功
  320. } elseif (in_array($status, ['FAILED', 'CANCELED', 'REFUNDED'])) {
  321. $orderStatus = 2; // 失败
  322. }
  323. if ($orderStatus === 0) {
  324. Util::WriteLog('NewSupefinaSpei', 'payout processing: '.$OrderId.' status='.$status);
  325. return '{"success":true}';
  326. }
  327. $agentID = DB::connection('write')
  328. ->table('agent.dbo.admin_configs')
  329. ->where('config_value', self::AGENT)
  330. ->where('type', 'cash')
  331. ->value('id') ?? '';
  332. $now = now();
  333. $UserID = $query->UserID;
  334. $TakeMoney = $query->WithDraw + $query->ServiceFee;
  335. // Supefina 回调里带有 amount/fee 和 realityAmount/realityFee
  336. // 提醒:这里仍以我们订单金额为准做账,仅将真实金额用于日志,可根据需要扩展到统计侧。
  337. $realityAmount = isset($post['amount']) ? (float)$post['amount'] : null;
  338. $realityFee = isset($post['fee']) ? (float)$post['fee'] : null;
  339. Util::WriteLog('NewSupefinaSpei', 'payout reality: amount='.$realityAmount.', fee='.$realityFee.', orderId='.$OrderId);
  340. $withdraw_data = [];
  341. switch ($orderStatus) {
  342. case 1: // 提现成功
  343. $withdraw_data = [
  344. 'State' => 2,
  345. 'agent' => $agentID,
  346. 'finishDate' => $now,
  347. ];
  348. // 增加提现记录
  349. $first = DB::connection('write')
  350. ->table('QPAccountsDB.dbo.UserTabData')
  351. ->where('UserID', $UserID)
  352. ->first();
  353. if ($first) {
  354. DB::connection('write')
  355. ->table('QPAccountsDB.dbo.UserTabData')
  356. ->where('UserID', $UserID)
  357. ->increment('TakeMoney', $TakeMoney);
  358. } else {
  359. DB::connection('write')
  360. ->table('QPAccountsDB.dbo.UserTabData')
  361. ->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
  362. try {
  363. PrivateMail::praiseSendMail($UserID);
  364. } catch (\Throwable $e) {
  365. // 忽略邮件发送失败
  366. }
  367. }
  368. // 免审记录
  369. $withdrawal_position_log = DB::connection('write')
  370. ->table('agent.dbo.withdrawal_position_log')
  371. ->where('order_sn', $OrderId)
  372. ->first();
  373. if ($withdrawal_position_log) {
  374. DB::connection('write')
  375. ->table('agent.dbo.withdrawal_position_log')
  376. ->where('order_sn', $OrderId)
  377. ->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
  378. }
  379. try {
  380. StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
  381. } catch (\Throwable $exception) {
  382. Util::WriteLog('StoredProcedure', $exception->getMessage());
  383. }
  384. $ServiceFee = $query->ServiceFee;
  385. RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
  386. $fee = DB::table('QPAccountsDB.dbo.OrderWithDraw')->where('OrderId', $OrderId)
  387. ->value('withdraw_fee');
  388. (new RechargeWithDraw())->withDraw($UserID, $TakeMoney, $fee, $ServiceFee);
  389. $redis = Redis::connection();
  390. $redis->incr('draw_'.date('Ymd').$UserID);
  391. break;
  392. case 2: // 提现失败
  393. $msg = $post['msg'] ?? 'Withdraw rejected';
  394. $bonus = '30000,'.$TakeMoney;
  395. PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
  396. Util::WriteLog('SupefinaSpeiEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
  397. $withdraw_data = [
  398. 'State' => 6,
  399. 'agent' => $agentID,
  400. 'remark' => $msg,
  401. ];
  402. break;
  403. }
  404. $RecordData = [
  405. 'before_state' => $query->State,
  406. 'after_state' => $withdraw_data['State'] ?? 0,
  407. 'RecordID' => $query->RecordID,
  408. 'update_at' => date('Y-m-d H:i:s'),
  409. ];
  410. DB::connection('write')
  411. ->table('QPAccountsDB.dbo.AccountsRecord')
  412. ->updateOrInsert(
  413. ['RecordID' => $query->RecordID, 'type' => 1],
  414. $RecordData
  415. );
  416. DB::connection('write')
  417. ->table('QPAccountsDB.dbo.OrderWithDraw')
  418. ->where('OrderId', $OrderId)
  419. ->update($withdraw_data);
  420. if (isset($withdraw_data['State']) && (int)$withdraw_data['State'] === 2) {
  421. StoredProcedure::user_label($UserID, 2, $TakeMoney);
  422. }
  423. return '{"success":true}';
  424. }
  425. public function getSignString($headers, $data)
  426. {
  427. $params = array_merge($headers, $data);
  428. $filtered = [];
  429. foreach ($params as $k => $v) {
  430. if (strtolower($k) === 'sign') {
  431. continue;
  432. }
  433. if ($v === null) {
  434. continue;
  435. }
  436. $filtered[$k] = $v;
  437. }
  438. ksort($filtered);
  439. $parts = [];
  440. foreach ($filtered as $k => $v) {
  441. $parts[] = $k . '=' . $v;
  442. }
  443. $signString = implode('&', $parts);
  444. return $signString;
  445. }
  446. public function sign($headers, $data, $key)
  447. {
  448. $signString = $this->getSignString($headers, $data);
  449. $res = openssl_pkey_get_private("-----BEGIN PRIVATE KEY-----\n" . $key . "\n-----END PRIVATE KEY-----");
  450. openssl_sign(
  451. $signString,
  452. $signature,
  453. $res,
  454. OPENSSL_ALGO_SHA256 // RSA2 核心
  455. );
  456. return base64_encode($signature);
  457. }
  458. public function verifySign($data, $sign, $key)
  459. {
  460. $res = openssl_pkey_get_public("-----BEGIN PUBLIC KEY-----\n" . $key . "\n-----END PUBLIC KEY-----");
  461. $result = openssl_verify(
  462. $data,
  463. base64_decode($sign),
  464. $res,
  465. OPENSSL_ALGO_SHA256
  466. );
  467. return $result === 1;
  468. }
  469. private function sendRequest($url, $productNo, $data)
  470. {
  471. $config = (new PayConfig())->getConfig('NewSupefinaSpei');
  472. $headers = [
  473. 'version' => '1.0.0',
  474. 'merchantNo' => $config['merId'] ?? '',
  475. 'requestId' => mt_rand(100000, 999999) . time(),
  476. 'requestTime' => time() * 1000,
  477. ];
  478. $body = [
  479. 'productNo' => $productNo,
  480. 'data' => Aes::encrypt(json_encode($data), base64_decode($config['aesKey'])),
  481. ];
  482. $sign = $this->sign($headers, $body, $config['privateKey']);
  483. $headers['sign'] = $sign;
  484. try {
  485. $client = new Client();
  486. Util::WriteLog('NewSupefinaSpei', $productNo . ' request: ' . $url . ' | ' . json_encode($data) . '|' . json_encode($headers));
  487. $result = $client->post($url, [
  488. 'headers' => $headers,
  489. 'json' => $body,
  490. ])->getBody()->getContents();
  491. Util::WriteLog('NewSupefinaSpei', $productNo . ' response: ' . $result);
  492. return $result;
  493. } catch (\Throwable $e) {
  494. Util::WriteLog('NewSupefinaSpei_error', $productNo . ' request exception: ' . $e->getMessage());
  495. $this->error = 'Payment processing error';
  496. return false;
  497. }
  498. }
  499. }