Browse Source

mex-payment

Tree 6 hours ago
parent
commit
33a1b532d8

+ 146 - 0
app/Http/Controllers/Api/SupefinaSpeiController.php

@@ -0,0 +1,146 @@
+<?php
+
+namespace App\Http\Controllers\Api;
+
+use App\Http\logic\api\SupefinaSpeiLogic;
+use App\Http\logic\api\SupefinaSpeiCashierLogic;
+use App\Inter\PayMentInterFace;
+use App\Notification\TelegramBot;
+use App\Services\SupefinaSpei;
+use App\Util;
+use App\Utility\SetNXLock;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Redis;
+
+class SupefinaSpeiController implements PayMentInterFace
+{
+    private $retryTimes = 0;
+
+    public function pay_order($userId, $payAmt, $userName, $userEmail, $userPhone, $GiftsID, $buyIP, $AdId, $eventType, $pay_method = '')
+    {
+        $logic = new SupefinaSpeiLogic();
+        try {
+            $res = $logic->pay_order($userId, $payAmt, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType, $pay_method);
+        } catch (\Exception $exception) {
+            Redis::set('PayErro_SupefinaSpei', 1);
+            Redis::expire('PayErro_SupefinaSpei', 600);
+            Util::WriteLog('SupefinaSpei_error', $exception->getMessage() . json_encode($logic->result ?? []));
+            TelegramBot::getDefault()->sendProgramNotify('SupefinaSpei Except ', $exception->getMessage(), $exception);
+            return apiReturnFail($logic->getError());
+        }
+
+        if (!empty($res) && isset($res['code']) && (string)$res['code'] === '200' && !empty($res['data'])) {
+            $data = $res['data'];
+            $content = $data['url'] ?? '';
+            if (empty($content) && !empty($data['identifier'])) {
+                $content = 'CLABE:' . $data['identifier'];
+            }
+            return apiReturnSuc([
+                'content' => $content,
+                'money'   => $payAmt,
+                'prdOrdNo' => $data['merOrderNo'] ?? '',
+                'identifier' => $data['identifier'] ?? '',
+            ]);
+        }
+
+        if ($res === false) {
+            return apiReturnFail($logic->getError());
+        }
+
+        if ($this->retryTimes > 0) {
+            Redis::set('PayErro_SupefinaSpei', 1);
+            Redis::expire('PayErro_SupefinaSpei', 600);
+            TelegramBot::getDefault()->sendProgramNotify('SupefinaSpei ReturnFail ', $logic->getError() . ' | ' . json_encode($res));
+            return apiReturnFail($logic->getError());
+        }
+        $this->retryTimes++;
+        return $this->pay_order($userId, $payAmt, $userName, $userEmail, $userPhone, $GiftsID, $buyIP, $AdId, $eventType, $pay_method);
+    }
+
+    /**
+     * 统一回调入口:代收(01) + 代付(02),验签后按 transactionType 分发
+     */
+    public function notify(Request $request)
+    {
+        $payload = $request->getContent();
+        $post = json_decode($payload, true);
+        if (!is_array($post)) {
+            $post = $request->all();
+        }
+
+        Util::WriteLog('SupefinaSpei', "raw notify\n" . $payload);
+
+        $transactionType = $post['transactionType'] ?? '';
+        $orderId = $post['merOrderId'] ?? $post['merOrderNo'] ?? '';
+
+        $configKey = $transactionType === '02' ? 'SupefinaSpeiOut' : 'SupefinaSpei';
+        $service = new SupefinaSpei($configKey);
+        if (!$service->verify($post)) {
+            Util::WriteLog('SupefinaSpei_error', 'notify sign invalid');
+            return 'fail';
+        }
+
+        $lockKey = '';
+        if ($orderId) {
+            $lockKey = 'pay_notify_SupefinaSpei_' . $transactionType . '_' . $orderId;
+            if (!SetNXLock::getExclusiveLock($lockKey, 60)) {
+                Util::WriteLog('SupefinaSpei', 'notify concurrent, ignore: ' . $orderId);
+                return 'SUCCESS';
+            }
+        }
+
+        try {
+            if ($transactionType === '01') {
+                $logic = new SupefinaSpeiLogic();
+                $ret = $logic->notify($post);
+            } elseif ($transactionType === '02') {
+                $logic = new SupefinaSpeiCashierLogic();
+                $ret = $logic->notify($post);
+            } else {
+                Util::WriteLog('SupefinaSpei', 'ignore transactionType: ' . $transactionType);
+                $ret = 'SUCCESS';
+            }
+        } finally {
+            if ($lockKey !== '') {
+                SetNXLock::release($lockKey);
+            }
+        }
+
+        return $ret;
+    }
+
+    /**
+     * 代付回调(保留兼容,建议统一用 notify)
+     */
+    public function cash_notify(Request $request)
+    {
+        $payload = $request->getContent();
+        $post = json_decode($payload, true);
+        if (!is_array($post)) {
+            $post = $request->all();
+        }
+
+        Util::WriteLog('SupefinaSpei', "raw payout notify\n" . $payload);
+
+        $orderId = $post['merOrderId'] ?? $post['merOrderNo'] ?? '';
+        $lockKey = '';
+        if ($orderId) {
+            $lockKey = 'pay_notify_SupefinaSpei_02_' . $orderId;
+            if (!SetNXLock::getExclusiveLock($lockKey, 60)) {
+                Util::WriteLog('SupefinaSpei', 'payout notify concurrent, ignore: ' . $orderId);
+                return 'SUCCESS';
+            }
+        }
+
+        try {
+            $logic = new SupefinaSpeiCashierLogic();
+            $ret = $logic->notify($post);
+        } finally {
+            if ($lockKey !== '') {
+                SetNXLock::release($lockKey);
+            }
+        }
+
+        return $ret;
+    }
+}

+ 5 - 4
app/Http/Controllers/Game/PaymentEntryController.php

@@ -34,13 +34,14 @@ class PaymentEntryController {
         $where[] = ['status', 1];
         $where[] = ['id', $pay_type];
 
-//        $payMethods = [
-//            'cashapp' => 1,
+        $pay_method = 1;
+        $payMethods = [
+            'SPEI' => 1,
 //            'paypal' => 2,
 //            'applepay' => 4,
 //            'googlepay' => 8,
-//
-//        ];
+
+        ];
 
 
         $query = DB::table('agent.dbo.admin_configs')->where($where)->value('config_key');

+ 343 - 0
app/Http/logic/api/SupefinaSpeiCashierLogic.php

@@ -0,0 +1,343 @@
+<?php
+
+namespace App\Http\logic\api;
+
+use App\dao\Estatisticas\RechargeWithDraw;
+use App\Inter\CashierInterFace;
+use App\Models\PrivateMail;
+use App\Models\RecordUserDataStatistics;
+use App\Services\SupefinaSpei;
+use App\Services\StoredProcedure;
+use App\Util;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
+use Illuminate\Support\Facades\Redis;
+
+class SupefinaSpeiCashierLogic implements CashierInterFace
+{
+    /**
+     * 代付渠道标识,对应 agent.dbo.admin_configs.config_value(type=cash)。
+     * 使用前请在后台配置同名渠道值。
+     */
+    const AGENT = 106;
+
+    /**
+     * 创建 Supefina SPEI 代付订单。
+     */
+    public function payment($RecordID, $amount, $accountName, $phone, $email, $OrderId, $PixNum, $PixType, $IFSCNumber, $BranchBank, $BankNO)
+    {
+        // 查询提现订单
+        $query = DB::connection('write')
+            ->table('QPAccountsDB.dbo.OrderWithDraw')
+            ->where('RecordID', $RecordID)
+            ->first();
+
+        if (!$query) {
+            Util::WriteLog('SupefinaSpei', 'withdraw order not found: '.$RecordID);
+            return 'fail';
+        }
+
+        $service = new SupefinaSpei('SupefinaSpeiOut');
+        $config = $service->config;
+
+        $merId = $config['merId'] ?? '';
+        $baseUrl = $config['baseUrl'] ?? '';
+        $payoutPath = $config['payoutPath'] ?? '/api/supefina/transactions/payout';
+        $callbackUrl = $config['callbackUrl'] ?? '';
+        $countryId = $config['countryId'] ?? 'MEX';
+        $currency = $config['currency'] ?? 'MXN';
+
+        if ($merId === '' || $baseUrl === '' || empty($config['key'])) {
+            Util::WriteLog('SupefinaSpei_error', 'config missing merId/baseUrl/key');
+            return 'fail';
+        }
+
+        // 账户号:优先 PixNum,其次 BankNO
+        $account = $PixNum ?: $BankNO;
+        if (!$account) {
+            Util::WriteLog('SupefinaSpei_error', 'missing account for withdraw: '.$OrderId);
+            return 'fail';
+        }
+
+        // 银行编号:优先 BankNO(如果看作 bankId),否则使用配置默认
+        $bankId = $config['defaultBankId'] ?? '';
+        if (!empty($BankNO) && ctype_digit((string)$BankNO)) {
+            $bankId = (string)$BankNO;
+        }
+
+        if ($bankId === '') {
+            Util::WriteLog('SupefinaSpei_error', 'missing bankId for withdraw: '.$OrderId);
+            return 'fail';
+        }
+
+        // payProduct:15=CLABE,16=卡号,简单按 PixType 区分,前端/配置需约定
+        $payProduct = '15';
+        if ((int)$PixType === 2) {
+            $payProduct = '16';
+        }
+
+        // 提现金额是以分存储,转成两位小数金额
+        $orderAmount = number_format($amount / 100, 2, '.', '');
+
+        $customerName = $accountName ?: ($email ?: ('U'.$query->UserID));
+
+        $params = [
+            'account'       => (string)$account,
+            'bankId'        => (string)$bankId,
+            'callbackUrl'   => $callbackUrl,
+            'countryId'     => $countryId,
+            'currency'      => $currency,
+            'customerName'  => $customerName,
+            'description'   => 'withdraw_'.$OrderId,
+            'merId'         => (string)$merId,
+            'merOrderNo'    => (string)$OrderId,
+            'nonceStr'      => $service->generateNonceStr(32),
+            'orderAmount'   => $orderAmount,
+            'payProduct'    => (string)$payProduct,
+        ];
+
+        $signedParams = $service->sign($params);
+
+        $url = rtrim($baseUrl, '/').$payoutPath;
+
+        Util::WriteLog('SupefinaSpei', 'payout request: '.$url.' | '.json_encode($signedParams, JSON_UNESCAPED_UNICODE));
+
+        try {
+            $result = $service->postJson($url, $signedParams);
+        } catch (\Throwable $e) {
+            Util::WriteLog('SupefinaSpei_error', 'payout request exception: '.$e->getMessage());
+            return 'fail';
+        }
+
+        Util::WriteLog('SupefinaSpei', 'payout response: '.$result);
+
+        try {
+            $data = \GuzzleHttp\json_decode($result, true);
+        } catch (\Throwable $e) {
+            Util::WriteLog('SupefinaSpei_error', ['decode fail', $result, $e->getMessage()]);
+            return 'fail';
+        }
+
+        // 文档示例:code=200 且 data.transactionStatus = "00" 表示下单成功
+        if (isset($data['code']) && (string)$data['code'] === '200') {
+            $transactionStatus = $data['data']['transactionStatus'] ?? null;
+            if ((string)$transactionStatus === '00') {
+                return $data;
+            }
+        }
+
+        // 同步下单失败:如果订单在处理中(State=5),退回资金并标记失败
+        if ((int)$query->State === 5) {
+            $msg = $data['msg'] ?? 'Supefina payout failed';
+            $WithDraw = $query->WithDraw + $query->ServiceFee;
+            $bonus = '30000,'.$WithDraw;
+
+            PrivateMail::failMail($query->UserID, $OrderId, $WithDraw, $msg, $bonus);
+
+            $withdraw_data = [
+                'State'      => 6,
+                'agent'      => self::AGENT,
+                'finishDate' => now(),
+                'remark'     => json_encode($data),
+            ];
+
+            DB::connection('write')
+                ->table('QPAccountsDB.dbo.OrderWithDraw')
+                ->where('OrderId', $query->OrderId)
+                ->update($withdraw_data);
+
+            $RecordData = ['after_state' => 6, 'update_at' => now()];
+
+            DB::connection('write')
+                ->table('QPAccountsDB.dbo.AccountsRecord')
+                ->where('type', 1)
+                ->where('RecordID', $RecordID)
+                ->update($RecordData);
+        }
+
+        return 'fail';
+    }
+
+    /**
+     * Supefina SPEI 代付回调。
+     *
+     * @param array<string,mixed>|string $post
+     */
+    public function notify($post)
+    {
+        if (!is_array($post)) {
+            $post = \GuzzleHttp\json_decode($post, true);
+        }
+
+        Util::WriteLog('SupefinaSpei', 'payout notify: '.json_encode($post, JSON_UNESCAPED_UNICODE));
+
+        $service = new SupefinaSpei('SupefinaSpeiOut');
+
+        // 验签
+        if (!$service->verify($post)) {
+            Util::WriteLog('SupefinaSpei_error', 'notify sign invalid');
+            return 'fail';
+        }
+
+        // 只处理代付类型(02)
+        if (($post['transactionType'] ?? '') !== '02') {
+            Util::WriteLog('SupefinaSpei', 'ignore non-payout notify, transactionType='.$post['transactionType'] ?? '');
+            return 'SUCCESS';
+        }
+
+        $OrderId = $post['merOrderId'] ?? $post['merOrderNo'] ?? '';
+        if ($OrderId === '') {
+            Util::WriteLog('SupefinaSpei_error', 'notify missing merOrderId');
+            return 'fail';
+        }
+
+        $query = DB::connection('write')
+            ->table('QPAccountsDB.dbo.OrderWithDraw')
+            ->where('OrderId', $OrderId)
+            ->first();
+
+        if (!$query) {
+            Util::WriteLog('SupefinaSpei_error', 'withdraw order not found in notify: '.$OrderId);
+            return 'SUCCESS';
+        }
+
+        // 只处理 State=5 或 7 的订单,避免重复
+        if (!in_array((int)$query->State, [5, 7], true)) {
+            Util::WriteLog('SupefinaSpei', 'withdraw already handled: '.$OrderId);
+            return 'SUCCESS';
+        }
+
+        // 映射交易状态:以 Supefina 文档为准,示例中仅说明状态码存在,此处按常规约定:
+        // 01/02/00 视为成功,其它(如 03/04 等)视为失败;实际项目中可按回调字典表精细化。
+        $status = (string)($post['status'] ?? '');
+        $orderStatus = 0;
+        if (in_array($status, ['00', '01', '02', 'SUCCESS'], true)) {
+            $orderStatus = 1; // 成功
+        } elseif ($status !== '') {
+            $orderStatus = 2; // 失败
+        }
+
+        if ($orderStatus === 0) {
+            Util::WriteLog('SupefinaSpei', 'payout processing: '.$OrderId.' status='.$status);
+            return 'SUCCESS';
+        }
+
+        $agentID = DB::connection('write')
+            ->table('agent.dbo.admin_configs')
+            ->where('config_value', self::AGENT)
+            ->where('type', 'cash')
+            ->value('id') ?? '';
+
+        $now = now();
+
+        $UserID = $query->UserID;
+        $TakeMoney = $query->WithDraw + $query->ServiceFee;
+
+        // Supefina 回调里带有 amount/fee 和 realityAmount/realityFee
+        // 提醒:这里仍以我们订单金额为准做账,仅将真实金额用于日志,可根据需要扩展到统计侧。
+        $realityAmount = isset($post['realityAmount']) ? (float)$post['realityAmount'] : null;
+        $realityFee = isset($post['realityFee']) ? (float)$post['realityFee'] : null;
+        Util::WriteLog('SupefinaSpei', 'payout reality: amount='.$realityAmount.', fee='.$realityFee.', orderId='.$OrderId);
+
+        $withdraw_data = [];
+
+        switch ($orderStatus) {
+            case 1: // 提现成功
+                $withdraw_data = [
+                    'State'      => 2,
+                    'agent'      => $agentID,
+                    'finishDate' => $now,
+                ];
+
+                // 增加提现记录
+                $first = DB::connection('write')
+                    ->table('QPAccountsDB.dbo.UserTabData')
+                    ->where('UserID', $UserID)
+                    ->first();
+
+                if ($first) {
+                    DB::connection('write')
+                        ->table('QPAccountsDB.dbo.UserTabData')
+                        ->where('UserID', $UserID)
+                        ->increment('TakeMoney', $TakeMoney);
+                } else {
+                    DB::connection('write')
+                        ->table('QPAccountsDB.dbo.UserTabData')
+                        ->insert(['TakeMoney' => $TakeMoney, 'UserID' => $UserID]);
+                    try {
+                        PrivateMail::praiseSendMail($UserID);
+                    } catch (\Throwable $e) {
+                        // 忽略邮件发送失败
+                    }
+                }
+
+                // 免审记录
+                $withdrawal_position_log = DB::connection('write')
+                    ->table('agent.dbo.withdrawal_position_log')
+                    ->where('order_sn', $OrderId)
+                    ->first();
+
+                if ($withdrawal_position_log) {
+                    DB::connection('write')
+                        ->table('agent.dbo.withdrawal_position_log')
+                        ->where('order_sn', $OrderId)
+                        ->update(['take_effect' => 2, 'update_at' => date('Y-m-d H:i:s')]);
+                }
+
+                try {
+                    StoredProcedure::addPlatformData($UserID, 4, $TakeMoney);
+                } catch (\Throwable $exception) {
+                    Util::WriteLog('StoredProcedure', $exception->getMessage());
+                }
+
+                $ServiceFee = $query->ServiceFee;
+                RecordUserDataStatistics::updateOrAdd($UserID, $TakeMoney, 0, $ServiceFee);
+
+                (new RechargeWithDraw())->withDraw($UserID, $TakeMoney);
+
+                $redis = Redis::connection();
+                $redis->incr('draw_'.date('Ymd').$UserID);
+                break;
+
+            case 2: // 提现失败
+                $msg = $post['msg'] ?? 'Withdraw rejected';
+                $bonus = '30000,'.$TakeMoney;
+                PrivateMail::failMail($query->UserID, $OrderId, $TakeMoney, $msg, $bonus);
+
+                Util::WriteLog('SupefinaSpeiEmail', [$query->UserID, $OrderId, $TakeMoney, $msg, $bonus]);
+
+                $withdraw_data = [
+                    'State'  => 6,
+                    'agent'  => $agentID,
+                    'remark' => $msg,
+                ];
+                break;
+        }
+
+        $RecordData = [
+            'before_state' => $query->State,
+            'after_state'  => $withdraw_data['State'] ?? 0,
+            'RecordID'     => $query->RecordID,
+            'update_at'    => date('Y-m-d H:i:s'),
+        ];
+
+        DB::connection('write')
+            ->table('QPAccountsDB.dbo.AccountsRecord')
+            ->updateOrInsert(
+                ['RecordID' => $query->RecordID, 'type' => 1],
+                $RecordData
+            );
+
+        DB::connection('write')
+            ->table('QPAccountsDB.dbo.OrderWithDraw')
+            ->where('OrderId', $OrderId)
+            ->update($withdraw_data);
+
+        if (isset($withdraw_data['State']) && (int)$withdraw_data['State'] === 2) {
+            StoredProcedure::user_label($UserID, 2, $TakeMoney);
+        }
+
+        return 'SUCCESS';
+    }
+}
+

+ 202 - 0
app/Http/logic/api/SupefinaSpeiLogic.php

@@ -0,0 +1,202 @@
+<?php
+
+namespace App\Http\logic\api;
+
+use App\dao\Pay\PayController;
+use App\Http\helper\CreateOrder;
+use App\Http\helper\NumConfig;
+use App\Jobs\Order;
+use App\Services\OrderServices;
+use App\Services\PayConfig;
+use App\Services\SupefinaSpei;
+use App\Services\CreateLog;
+use App\Util;
+use Illuminate\Support\Facades\DB;
+
+/**
+ * Supefina SPEI 墨西哥代收(充值)逻辑
+ * 文档:https://docs.supefina.net/huan-ying-shi-yong-supefina-de-api-wen-dang/dai-shou/mo-xi-ge/spei
+ * 代收回调以 realityAmount 为准入账(处理用户实转金额与订单金额不一致)
+ */
+class SupefinaSpeiLogic extends BaseApiLogic
+{
+    public $result;
+
+    public function pay_order($userId, $pay_amount, $userPhone, $userEmail, $userName, $GiftsID, $buyIP, $AdId, $eventType, $pay_method = '')
+    {
+        $PayVerify = new PayController();
+        $pay_amount = $PayVerify->verify($userId, $GiftsID, $pay_amount);
+        if ($PayVerify->verify($userId, $GiftsID, $pay_amount) === false) {
+            $this->error = $PayVerify->getError();
+            return false;
+        }
+        if ($pay_amount < 0) {
+            $this->error = 'Payment error_4';
+            return false;
+        }
+
+        $service = new SupefinaSpei('SupefinaSpei');
+        $config = $service->config;
+
+        $merId = $config['merId'] ?? '';
+        $baseUrl = $config['baseUrl'] ?? '';
+        $payinPath = $config['payinPath'] ?? '/api/supefina/transactions/collection';
+        $callbackUrl = $config['callbackUrl'] ?? '';
+        $countryId = $config['countryId'] ?? 'MEX';
+        $currency = $config['currency'] ?? 'MXN';
+        $minOrderAmount = $config['minOrderAmount'] ?? '10.00';
+        $maxOrderAmount = $config['maxOrderAmount'] ?? '15000.00';
+
+        if ($merId === '' || $baseUrl === '' || empty($config['key']) || $callbackUrl === '') {
+            $this->error = 'Payment config error';
+            return false;
+        }
+
+        $order_sn = CreateOrder::order_sn($userId);
+
+        $logic = new OrderLogic();
+        $amount = (int) round($pay_amount * NumConfig::NUM_VALUE);
+        $logic->orderCreate($order_sn, $amount, 'SupefinaSpei', $userId, $pay_method, $GiftsID, $AdId, $eventType);
+
+        $orderAmount = (string) (int) $pay_amount;
+        if ($pay_amount != (int) $pay_amount) {
+            $orderAmount = number_format($pay_amount, 2, '.', '');
+        }
+
+        $params = [
+            'callbackUrl'    => $callbackUrl,
+            'countryId'      => $countryId,
+            'currency'      => $currency,
+            'maxOrderAmount' => $maxOrderAmount,
+            'merId'          => (string) $merId,
+            'merOrderNo'     => $order_sn,
+            'minOrderAmount' => $minOrderAmount,
+            'nonceStr'       => $service->generateNonceStr(32),
+            'orderAmount'    => $orderAmount,
+            'payProduct'     => '15',
+            'repeat'         => 'true',
+        ];
+
+        $signedParams = $service->sign($params);
+
+        $request_extra = \GuzzleHttp\json_encode($signedParams);
+        CreateLog::pay_request($userPhone, $request_extra, $order_sn, $userEmail, $userId, $userName);
+
+        $url = rtrim($baseUrl, '/') . $payinPath;
+        Util::WriteLog('SupefinaSpei', 'payin request: ' . $url . ' | ' . $request_extra);
+
+        try {
+            $result = $service->postJson($url, $signedParams);
+        } catch (\Throwable $e) {
+            Util::WriteLog('SupefinaSpei_error', 'payin request exception: ' . $e->getMessage());
+            $this->error = 'Payment processing error';
+            return false;
+        }
+
+        Util::WriteLog('SupefinaSpei', 'payin response: ' . $result);
+
+        try {
+            $data = \GuzzleHttp\json_decode($result, true);
+        } catch (\Throwable $e) {
+            Util::WriteLog('SupefinaSpei_error', [$result, $e->getMessage()]);
+            $this->error = 'Payment processing error';
+            return false;
+        }
+
+        if (!isset($data['code']) || (string)$data['code'] !== '200') {
+            $this->error = $data['msg'] ?? 'Payment request failed';
+            return false;
+        }
+
+        $this->result = $data;
+        return $data;
+    }
+
+    /**
+     * 代收回调:仅代收存在“实际金额与订单金额不一致”,以 realityAmount 入账
+     *
+     * @param array<string,mixed> $post
+     */
+    public function notify($post)
+    {
+        $order_sn = $post['merOrderId'] ?? $post['merOrderNo'] ?? '';
+        if ($order_sn === '') {
+            Util::WriteLog('SupefinaSpei_error', 'payin notify missing merOrderId');
+            return 'fail';
+        }
+
+        try {
+            $order = DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->first();
+            if (!$order) {
+                Util::WriteLog('SupefinaSpei', 'payin order not found: ' . $order_sn);
+                return 'SUCCESS';
+            }
+
+            if (!empty($order->pay_at) || !empty($order->finished_at)) {
+                return 'SUCCESS';
+            }
+
+            $status = (string)($post['status'] ?? '');
+            if ($status === '03') {
+                $body = ['pay_status' => 2, 'updated_at' => date('Y-m-d H:i:s')];
+                DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->update($body);
+                return 'SUCCESS';
+            }
+
+            if ($status !== '01') {
+                Util::WriteLog('SupefinaSpei', 'payin notify status not success: ' . $status);
+                return 'SUCCESS';
+            }
+
+            $GiftsID = $order->GiftsID ?: '';
+            $userID = $order->user_id ?: '';
+            $AdId = $order->AdId ?: '';
+            $eventType = $order->eventType ?: '';
+
+            $realityAmount = isset($post['realityAmount']) ? (float)$post['realityAmount'] : (float)($post['amount'] ?? 0);
+            if ($realityAmount <= 0) {
+                Util::WriteLog('SupefinaSpei_error', 'payin notify invalid realityAmount: ' . json_encode($post));
+                return 'fail';
+            }
+
+            $payAmt = round($realityAmount, 2);
+            $amountInScore = (int) round($payAmt * NumConfig::NUM_VALUE);
+
+            $body = [
+                'payment_sn'   => $post['supefinaOrderId'] ?? $post['reference'] ?? '',
+                'pay_status'   => 1,
+                'pay_at'       => date('Y-m-d H:i:s'),
+                'finished_at'  => date('Y-m-d H:i:s'),
+                'amount'       => $amountInScore,
+                'updated_at'   => date('Y-m-d H:i:s'),
+            ];
+
+            $config = (new PayConfig())->getConfig('SupefinaSpei');
+            $body['payment_fee'] = isset($config['payin_fee']) ? $amountInScore * $config['payin_fee'] : 0;
+
+            $service = new OrderServices();
+            if ((int)$order->amount != $amountInScore) {
+                $body['GiftsID'] = 0;
+                $body['amount'] = $amountInScore;
+                $Recharge = $payAmt;
+                $give = 0;
+                $favorable_price = $Recharge + $give;
+                $czReason = 1;
+                $cjReason = 45;
+            } else {
+                [$give, $favorable_price, $Recharge, $czReason, $cjReason] = $service->getPayInfo($GiftsID, $userID, $payAmt);
+            }
+
+            [$Score] = $service->addRecord($userID, $payAmt, $favorable_price, $order_sn, $GiftsID, $Recharge, $czReason, $give, $cjReason, $AdId, $eventType);
+            Order::dispatch([$userID, $payAmt, $Score, $favorable_price, $GiftsID, $order_sn]);
+
+            DB::connection('write')->table('agent.dbo.order')->where('order_sn', $order_sn)->update($body);
+
+            Util::WriteLog('SupefinaSpei', 'payin success, order_sn=' . $order_sn . ', realityAmount=' . $realityAmount);
+            return 'SUCCESS';
+        } catch (\Throwable $exception) {
+            Util::WriteLog('SupefinaSpei_error', $exception->getMessage() . "\n" . $exception->getTraceAsString());
+            throw $exception;
+        }
+    }
+}

+ 4 - 0
app/Services/CashService.php

@@ -9,6 +9,7 @@ use App\Http\logic\api\CoinPayCashierLogic;
 use App\Http\logic\api\AiPayCashierLogic;
 use App\Http\logic\api\PagYeepPayCashierLogic;
 use App\Http\logic\api\AiNewPayCashierLogic;
+use App\Http\logic\api\SupefinaSpeiCashierLogic;
 
 
 class CashService
@@ -36,6 +37,9 @@ class CashService
             case AiNewPayCashierLogic::AGENT:
                 return new AiNewPayCashierLogic();
 
+            case SupefinaSpeiCashierLogic::AGENT:
+                return new SupefinaSpeiCashierLogic();
+
         }
     }
 }

+ 4 - 0
app/Services/PayMentService.php

@@ -15,6 +15,7 @@ use App\Http\Controllers\Api\CoinPayController;
 use App\Http\Controllers\Api\AiPayController;
 use App\Http\Controllers\Api\PagYeepPayController;
 use App\Http\Controllers\Api\AiNewPayController;
+use App\Http\Controllers\Api\SupefinaSpeiController;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Redis;
@@ -44,6 +45,9 @@ class PayMentService
             case 'AiNewPay':
                 return new AiNewPayController();
 
+            case 'SupefinaSpei':
+                return new SupefinaSpeiController();
+
             case 'apple':
                 return new AppleStorePayController();
 

+ 171 - 0
app/Services/SupefinaSpei.php

@@ -0,0 +1,171 @@
+<?php
+
+namespace App\Services;
+
+use App\Util;
+
+class SupefinaSpei
+{
+    /**
+     * @var array<string,mixed>
+     */
+    public $config = [];
+
+    public function __construct(string $configKey = 'SupefinaSpeiOut')
+    {
+        $payConfigService = new PayConfig();
+        $this->config = $payConfigService->getConfig($configKey) ?? [];
+    }
+
+    /**
+     * 生成随机字符串
+     */
+    public function generateNonceStr(int $length = 32): string
+    {
+        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
+        $str = '';
+        $max = strlen($chars) - 1;
+        for ($i = 0; $i < $length; $i++) {
+            $str .= $chars[mt_rand(0, $max)];
+        }
+        return $str;
+    }
+
+    /**
+     * 对参数进行签名(MD5,大写),完全遵循 Supefina 文档:
+     * 1. 排除 sign、null、空字符串
+     * 2. 参数名 ASCII 升序
+     * 3. key1=value1&key2=value2&...&key=商户密钥
+     * 4. boolean 转成 "true"/"false",与 Java toString() 一致
+     *
+     * @param array<string,mixed> $params
+     * @return array<string,mixed>
+     */
+    public function sign(array $params): array
+    {
+        $key = trim((string)($this->config['key'] ?? ''));
+        if ($key === '') {
+            throw new \RuntimeException('SupefinaSpei key missing in config');
+        }
+
+        $signStr = $this->buildSignString($params, $key);
+        $sign = strtoupper(md5($signStr));
+
+        Util::WriteLog('SupefinaSpei', 'sign string (key redacted): ' . str_replace($key, '***', $signStr));
+
+        $params['sign'] = $sign;
+        return $params;
+    }
+
+    /**
+     * 按 Supefina 文档构建待签名字符串
+     */
+    private function buildSignString(array $params, string $merchantKey): string
+    {
+        $filtered = [];
+        foreach ($params as $k => $v) {
+            if (strtolower($k) === 'sign') {
+                continue;
+            }
+            if ($v === null) {
+                continue;
+            }
+            if ($v === '' || (is_string($v) && trim($v) === '')) {
+                continue;
+            }
+            $filtered[$k] = $this->valueToString($v);
+        }
+        ksort($filtered);
+
+        $parts = [];
+        foreach ($filtered as $k => $v) {
+            $parts[] = $k . '=' . $v;
+        }
+        $parts[] = 'key=' . $merchantKey;
+
+        return implode('&', $parts);
+    }
+
+    /**
+     * 将值转为签名字符串,与 Java toString() 行为一致
+     */
+    private function valueToString($v): string
+    {
+        if (is_bool($v)) {
+            return $v ? 'true' : 'false';
+        }
+        if (is_array($v)) {
+            return json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
+        }
+        return (string)$v;
+    }
+
+    /**
+     * 验证回调签名。
+     *
+     * @param array<string,mixed> $data
+     */
+    public function verify(array $data): bool
+    {
+        if (!isset($data['sign'])) {
+            return false;
+        }
+        $key = trim((string)($this->config['key'] ?? ''));
+        if ($key === '') {
+            return false;
+        }
+
+        $sign = strtoupper(trim((string)$data['sign']));
+        $params = $data;
+        unset($params['sign']);
+
+        $signStr = $this->buildSignString($params, $key);
+        $expected = strtoupper(md5($signStr));
+
+        return $sign === $expected;
+    }
+
+    /**
+     * 发送 JSON POST 请求。
+     *
+     * @param array<string,mixed> $payload
+     */
+    public function postJson(string $url, array $payload, int $timeout = 20): string
+    {
+        $data = json_encode($payload, JSON_UNESCAPED_UNICODE);
+
+        $headers = [
+            'Content-Type: application/json',
+        ];
+
+        $ch = curl_init();
+        curl_setopt($ch, CURLOPT_URL, $url);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+        curl_setopt($ch, CURLOPT_POST, 1);
+        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
+        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
+        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
+
+        $result = curl_exec($ch);
+        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
+
+        if (curl_errno($ch)) {
+            $error = curl_error($ch);
+            Util::WriteLog('SupefinaSpei_error', 'CURL Error: '.$error);
+            curl_close($ch);
+            throw new \RuntimeException('CURL error: '.$error);
+        }
+
+        if ($httpCode !== 200) {
+            Util::WriteLog('SupefinaSpei_error', 'HTTP Code: '.$httpCode.' | Response: '.$result);
+        }
+
+        curl_close($ch);
+
+        return (string)$result;
+    }
+}
+

+ 2 - 1
config/app.php

@@ -66,7 +66,8 @@ return [
      */
 
 //    'timezone'        => 'PRC',
-    'timezone'        => env('APP_TIMEZONE', 'America/New_York'), # ÃÀ¹ú¶«²¿Ê±Çø (EST/EDT)
+
+    'timezone'        => env('APP_TIMEZONE', 'Etc/GMT+6'),
 
     /*
     |--------------------------------------------------------------------------

+ 27 - 1
config/payTest.php

@@ -15,6 +15,32 @@ return [
         'return' => env('APP_URL', '').'/api/wiwipay/return',
         'cashNotify' => env('APP_URL', '').'/api/wiwipay/payout_notify',
         'cash_url' => env('APP_URL', '').'/api/payout/create'
-    ]
+    ],
+
+    // Supefina SPEI 墨西哥代收(充值)- 测试环境
+    'SupefinaSpei' => [
+        'merId'        => env('SUPEFINA_MER_ID', ''),
+        'key'          => env('SUPEFINA_KEY', ''),
+        'baseUrl'      => 'https://api.supefina.tech',
+        'payinPath'    => '/api/supefina/transactions/collection',
+        'countryId'    => 'MEX',
+        'currency'     => 'MXN',
+        'minOrderAmount' => '10.00',
+        'maxOrderAmount' => '15000.00',
+        'callbackUrl'  => env('APP_URL', '') . '/api/supefina/notify',
+        'payin_fee'    => 0,
+    ],
+
+    // Supefina SPEI 墨西哥代付(提现)- 测试环境
+    'SupefinaSpeiOut' => [
+        'merId'         => env('SUPEFINA_MER_ID', ''),
+        'key'           => env('SUPEFINA_KEY', ''),
+        'baseUrl'       => 'https://api.supefina.tech',
+        'payoutPath'    => '/api/supefina/transactions/payout',
+        'countryId'     => 'MEX',
+        'currency'      => 'MXN',
+        'defaultBankId' => env('SUPEFINA_DEFAULT_BANK_ID', ''),
+        'callbackUrl'   => env('APP_URL', '') . '/api/supefina/notify',
+    ],
 
 ];

+ 5 - 0
routes/api.php

@@ -390,6 +390,11 @@ Route::any('/karopay/cash_notify', 'Api\KaroPayController@cash_notify');
 //Route::any('/bet_cat_pay/agent_cash_notify', 'Api\BetCatPayController@agent_cash_notify');
 
 
+// Supefina SPEI 统一回调(代收 01 + 代付 02)
+Route::any('/supefina/notify', 'Api\SupefinaSpeiController@notify');
+Route::any('/supefina/payout_notify', 'Api\SupefinaSpeiController@cash_notify');
+
+
 Route::any('/clear_cache', function () {
     $path = app()->basePath('/public/cache/');
     $dir = opendir($path);