mirror of
https://gitee.com/liuxioabin/fengketrade.git
synced 2026-04-17 21:03:17 +08:00
721 lines
29 KiB
PHP
721 lines
29 KiB
PHP
<?php
|
||
|
||
namespace addons\shopro\library\ccblife;
|
||
|
||
use app\admin\model\shopro\order\Order;
|
||
use app\admin\model\shopro\Pay as PayModel;
|
||
use think\Db;
|
||
use think\Log;
|
||
|
||
/**
|
||
* 建行生活支付服务类
|
||
* 处理支付串生成、支付回调、支付验证等业务
|
||
*/
|
||
class CcbPaymentService
|
||
{
|
||
/**
|
||
* 配置信息
|
||
*/
|
||
private $config;
|
||
|
||
/**
|
||
* 订单服务实例
|
||
*/
|
||
private $orderService;
|
||
|
||
/**
|
||
* 构造函数
|
||
*/
|
||
public function __construct()
|
||
{
|
||
// 加载插件配置文件
|
||
$configFile = __DIR__ . '/../../config/ccblife.php';
|
||
if (file_exists($configFile)) {
|
||
$this->config = include $configFile;
|
||
} else {
|
||
throw new \Exception('建行生活配置文件不存在');
|
||
}
|
||
|
||
// ✅ 修复: 删除processPemKeys()调用
|
||
// 密钥格式化统一由CcbRSA类处理,避免重复格式化导致OpenSSL ASN1解析错误
|
||
// CcbRSA::formatPublicKey/formatPrivateKey 会在加密/解密时自动处理密钥格式
|
||
|
||
$this->orderService = new CcbOrderService();
|
||
}
|
||
|
||
/**
|
||
* 生成建行支付串
|
||
* 用于前端JSBridge调用建行收银台
|
||
*
|
||
* ⚠️ 注意:必须包含所有必需参数,签名前按ASCII排序
|
||
*
|
||
* @param int $orderId Shopro订单ID
|
||
* @param string $payFlowId 支付流水号(由控制器统一生成)
|
||
* @return array ['status' => bool, 'message' => string, 'data' => array]
|
||
*/
|
||
public function generatePaymentString($orderId, $payFlowId)
|
||
{
|
||
// ⚠️ 开启事务保护,确保数据一致性
|
||
Db::startTrans();
|
||
|
||
try {
|
||
// 获取订单信息
|
||
$order = Order::find($orderId);
|
||
if (!$order) {
|
||
throw new \Exception('订单不存在');
|
||
}
|
||
|
||
// 检查订单状态
|
||
if ($order['status'] != 'unpaid') {
|
||
throw new \Exception('订单状态不正确');
|
||
}
|
||
|
||
// 获取用户建行生活ID(用于订单推送)
|
||
$user = Db::name('user')->where('id', $order['user_id'])
|
||
->field('ccb_user_id')
|
||
->find();
|
||
if (empty($user['ccb_user_id'])) {
|
||
throw new \Exception('用户未绑定建行生活账号');
|
||
}
|
||
|
||
// ✅ 使用控制器传入的统一支付流水号(确保与订单推送使用同一流水号)
|
||
if (empty($payFlowId)) {
|
||
throw new \Exception('支付流水号不能为空');
|
||
}
|
||
|
||
// ⚠️ 关键:建行要求参数按照文档表格定义的顺序拼接,不是ASCII排序!
|
||
// 根据建行文档4.1和4.2,必须严格按照参数表顺序构建签名字符串
|
||
|
||
// 1. 定义参与MAC签名的参数数组(按文档表格顺序)
|
||
$macParams = [];
|
||
|
||
// 1.1 商户信息(必填,二选一:建行商户号组合 或 外部平台商户号)
|
||
$usePlatMctId = !empty($this->config['plat_mct_id']);
|
||
if ($usePlatMctId) {
|
||
// 使用外部平台商户号
|
||
$macParams['PLATMCTID'] = $this->config['plat_mct_id'];
|
||
} else {
|
||
// 使用建行商户号组合
|
||
$macParams['MERCHANTID'] = $this->config['merchant_id'];
|
||
$macParams['POSID'] = $this->config['pos_id'];
|
||
$macParams['BRANCHID'] = $this->config['branch_id'];
|
||
}
|
||
|
||
// 1.2 订单信息(必填)
|
||
$macParams['ORDERID'] = $payFlowId; // 支付流水号
|
||
$macParams['USER_ORDERID'] = $order['order_sn']; // 用户订单号
|
||
$payment = number_format($order['pay_fee'], 2, '.', '');
|
||
$macParams['PAYMENT'] = $payment; // 支付金额
|
||
$macParams['CURCODE'] = '01'; // 币种(01=人民币)
|
||
$macParams['TXCODE'] = '520100'; // 交易码
|
||
$macParams['REMARK1'] = ''; // 备注1(空字符串也要传)
|
||
$macParams['REMARK2'] = $this->config['service_id']; // 备注2(服务方编号)
|
||
$macParams['TYPE'] = '1'; // 接口类型(1=防钓鱼)
|
||
$macParams['GATEWAY'] = '0'; // 网关类型
|
||
$macParams['CLIENTIP'] = ''; // 客户端IP(建行生活环境送空)
|
||
$macParams['REGINFO'] = ''; // 客户注册信息(空字符串)
|
||
|
||
// 商品信息(escape编码)
|
||
$proinfo = $this->buildProductInfo($order);
|
||
$macParams['PROINFO'] = $proinfo;
|
||
Log::info('[建行支付] 商品信息原始: ' . mb_substr(implode(',', Db::name('shopro_order_item')->where('order_id', $order['id'])->limit(3)->column('goods_title')), 0, 50));
|
||
Log::info('[建行支付] 商品信息escape编码: ' . $proinfo);
|
||
|
||
$macParams['REFERER'] = ''; // 商户URL(空字符串)
|
||
|
||
// ✅ 修复:严格按照文档4.1表格顺序添加必填字段
|
||
// THIRDAPPINFO必须在INSTALLNUM之前(第17位基础字段)
|
||
$macParams['THIRDAPPINFO'] = 'comccbpay1234567890cloudmerchant'; // 客户端标识(固定值)
|
||
|
||
// 超时时间(第18位基础字段,必填)
|
||
if (!empty($this->config['timeout'])) {
|
||
$macParams['TIMEOUT'] = $this->config['timeout'];
|
||
} else {
|
||
// 默认30分钟超时
|
||
$macParams['TIMEOUT'] = date('YmdHis', strtotime('+30 minutes'));
|
||
}
|
||
|
||
// 记录关键参数
|
||
Log::info('[建行支付] 关键参数 order_id:' . $orderId . ' pay_flow_id:' . $payFlowId . ' user_orderid:' . $order['order_sn'] . ' payment:' . $payment);
|
||
Log::info('[建行支付] 商户信息 merchant_id:' . ($macParams['MERCHANTID'] ?? 'N/A') . ' pos_id:' . ($macParams['POSID'] ?? 'N/A') . ' branch_id:' . ($macParams['BRANCHID'] ?? 'N/A'));
|
||
|
||
// ========== ✅ 以下为可选参数(第19+位),按文档表格顺序添加 ==========
|
||
// 注意:根据文档4.2,橙色字段有值时才参与MAC,空值不参与
|
||
|
||
// 分期期数(第19位,可选参数)
|
||
if (!empty($this->config['install_num'])) {
|
||
$macParams['INSTALLNUM'] = $this->config['install_num'];
|
||
}
|
||
|
||
// 中国建设银行App环境参数
|
||
// if (!empty($this->config['user_id'])) {
|
||
// $macParams['USERID'] = $this->config['user_id'];
|
||
// }
|
||
// if (!empty($this->config['token'])) {
|
||
// $macParams['TOKEN'] = $this->config['token'];
|
||
// }
|
||
// if (!empty($this->config['pay_success_url'])) {
|
||
// // ⚠️ 不要在这里urlencode,会在构建最终支付串时统一编码
|
||
// $macParams['PAYSUCCESSURL'] = $this->config['pay_success_url'];
|
||
// }
|
||
|
||
// 支付位图和账户位图
|
||
// if (!empty($this->config['pay_bitmap'])) {
|
||
// $macParams['PAYBITMAP'] = $this->config['pay_bitmap'];
|
||
// }
|
||
// if (!empty($this->config['account_bitmap'])) {
|
||
// $macParams['ACCOUNTBITMAP'] = $this->config['account_bitmap'];
|
||
// }
|
||
|
||
// ✅ 严格按照文档4.1表格顺序添加参数(第27-40位)
|
||
// 积分活动编号(第27位)
|
||
if (!empty($this->config['point_avy_id'])) {
|
||
$macParams['POINTAVYID'] = $this->config['point_avy_id'];
|
||
}
|
||
|
||
// 数字人民币收款钱包编号(第28位)
|
||
if (!empty($this->config['dcep_dep_acc_no'])) {
|
||
$macParams['DCEPDEPACCNO'] = $this->config['dcep_dep_acc_no'];
|
||
}
|
||
|
||
// 有价券活动编号(第29位)
|
||
if (!empty($this->config['coupon_avy_id'])) {
|
||
$macParams['COUPONAVYID'] = $this->config['coupon_avy_id'];
|
||
}
|
||
|
||
// 限制信用卡支付标志(第30位)
|
||
if (!empty($this->config['only_credit_pay_flag'])) {
|
||
$macParams['ONLY_CREDIT_PAY_FLAG'] = $this->config['only_credit_pay_flag'];
|
||
}
|
||
|
||
// 固定抵扣积分值(第31位)
|
||
if (!empty($this->config['fixed_point_val'])) {
|
||
$macParams['FIXEDPOINTVAL'] = $this->config['fixed_point_val'];
|
||
}
|
||
|
||
// 最小使用积分抵扣限制(第32位)
|
||
if (!empty($this->config['min_point_limit'])) {
|
||
$macParams['MINPOINTLIMIT'] = $this->config['min_point_limit'];
|
||
}
|
||
|
||
// ⚠️ 特殊字段(仅中石化服务方使用,其他服务方禁止添加,否则MAC验证失败)
|
||
// Java代码中这两个字段已被注释,说明不参与正常流程的MAC签名
|
||
// if (!empty($this->config['identity_code'])) {
|
||
// $macParams['IDENTITYCODE'] = $this->config['identity_code'];
|
||
// }
|
||
// if (!empty($this->config['notify_url'])) {
|
||
// $macParams['NOTIFY_URL'] = $this->config['notify_url'];
|
||
// }
|
||
|
||
// 数字人民币商户类型(第35-38位)
|
||
if (!empty($this->config['dcep_mct_type'])) {
|
||
$macParams['DCEP_MCT_TYPE'] = $this->config['dcep_mct_type'];
|
||
if ($this->config['dcep_mct_type'] == '2') {
|
||
// 非融合商户需要填写数币商户号
|
||
if (!empty($this->config['dcep_merchant_id'])) {
|
||
$macParams['DCEP_MERCHANTID'] = $this->config['dcep_merchant_id'];
|
||
}
|
||
if (!empty($this->config['dcep_pos_id'])) {
|
||
$macParams['DCEP_POSID'] = $this->config['dcep_pos_id'];
|
||
}
|
||
if (!empty($this->config['dcep_branch_id'])) {
|
||
$macParams['DCEP_BRANCHID'] = $this->config['dcep_branch_id'];
|
||
}
|
||
}
|
||
}
|
||
|
||
// 二级商户参数
|
||
if (!empty($this->config['sub_mct_id'])) {
|
||
$macParams['SUB_MCT_ID'] = $this->config['sub_mct_id'];
|
||
}
|
||
if (!empty($this->config['sub_mct_name'])) {
|
||
$macParams['SUB_MCT_NAME'] = $this->config['sub_mct_name'];
|
||
}
|
||
if (!empty($this->config['sub_mct_mcc'])) {
|
||
$macParams['SUB_MCT_MCC'] = $this->config['sub_mct_mcc'];
|
||
}
|
||
|
||
// 扩展域(第43位)
|
||
if (!empty($this->config['extend_params'])) {
|
||
// ⚠️ 不要在这里urlencode,会在构建最终支付串时统一编码
|
||
$macParams['EXTENDPARAMS'] = $this->config['extend_params'];
|
||
}
|
||
|
||
// 2. 手动构建签名字符串(不能用http_build_query,避免URL编码破坏escape格式)
|
||
// ⚠️ 关键:按照建行文档4.2示例,签名字符串不进行URL编码
|
||
$signParts = [];
|
||
foreach ($macParams as $key => $value) {
|
||
$signParts[] = $key . '=' . $value;
|
||
}
|
||
$signString = implode('&', $signParts);
|
||
|
||
// 3. 添加PLATFORMPUB参与MD5签名(但不作为HTTP参数传递)
|
||
$platformPubKey = $this->config['public_key']; // 服务方公钥
|
||
$macSignString = $signString . '&PLATFORMPUB=' . $platformPubKey;
|
||
|
||
// 4. 生成MAC签名(32位小写MD5)
|
||
$mac = strtolower(md5($macSignString));
|
||
|
||
Log::info('[建行支付] MAC签名字符串(前500字符): ' . mb_substr($macSignString, 0, 500));
|
||
Log::info('[建行支付] 生成MAC: ' . $mac);
|
||
|
||
// 5. 构建不参与MAC的参数
|
||
$nonMacParams = [];
|
||
|
||
// 微信支付19位终端号(不参与MAC校验)
|
||
if (!empty($this->config['pos_id_19'])) {
|
||
$nonMacParams['POSID19'] = $this->config['pos_id_19'];
|
||
}
|
||
|
||
// 场景编号(埋点使用,不参与MAC校验)
|
||
if (!empty($this->config['scn_id'])) {
|
||
$nonMacParams['SCNID'] = $this->config['scn_id'];
|
||
}
|
||
if (!empty($this->config['scn_pltfrm_id'])) {
|
||
$nonMacParams['SCN_PLTFRM_ID'] = $this->config['scn_pltfrm_id'];
|
||
}
|
||
|
||
// 6. 生成ENCPUB(商户公钥密文,不参与MAC校验)
|
||
$encryptedMessage = $this->encryptPublicKeyLast30();
|
||
// 第二次BASE64编码
|
||
$encryptedMessage = base64_encode($encryptedMessage);
|
||
// 移除BASE64中的换行符
|
||
$encpub = str_replace(["\r", "\n", "\r\n"], '', $encryptedMessage);
|
||
// 7. 组装最终支付串(传给建行收银台的URL参数)
|
||
// 7.1 构建参与MAC的参数部分(不URL编码,与签名字符串保持一致)
|
||
$finalParts = [];
|
||
foreach ($macParams as $key => $value) {
|
||
// ✅ 不进行URL编码,保持与MAC签名字符串一致
|
||
$finalParts[] = $key . '=' . $value;
|
||
}
|
||
|
||
// 7.2 添加不参与MAC的参数
|
||
if (!empty($nonMacParams)) {
|
||
foreach ($nonMacParams as $key => $value) {
|
||
// ✅ 不URL编码
|
||
$finalParts[] = $key . '=' . $value;
|
||
}
|
||
}
|
||
// 7.3 添加MAC、PLATFORMID、ENCPUB
|
||
$finalParts[] = 'MAC=' . $mac;
|
||
$finalParts[] = 'PLATFORMID=' . $this->config['service_id'];
|
||
$finalParts[] = 'ENCPUB=' . $encpub;
|
||
|
||
// 7.4 拼接最终支付串
|
||
$finalPaymentString = implode('&', $finalParts);
|
||
|
||
Log::info('[建行支付] 最终支付串: ' . $finalPaymentString);
|
||
|
||
// 保存支付流水号到订单
|
||
Order::where('id', $orderId)->update([
|
||
'ccb_pay_flow_id' => $payFlowId,
|
||
'updatetime' => time()
|
||
]);
|
||
|
||
// 记录支付请求
|
||
$this->recordPaymentRequest($orderId, [
|
||
'payment_string' => $finalPaymentString,
|
||
'params' => $macParams,
|
||
'mac' => $mac,
|
||
'pay_flow_id' => $payFlowId
|
||
]);
|
||
|
||
// ✅ 提交事务
|
||
Db::commit();
|
||
|
||
return [
|
||
'status' => true,
|
||
'message' => '支付串生成成功',
|
||
'data' => [
|
||
'payment_string' => $finalPaymentString,
|
||
'mac' => $mac,
|
||
'order_sn' => $order['order_sn'],
|
||
'pay_flow_id' => $payFlowId,
|
||
'amount' => number_format($order['pay_fee'], 2, '.', ''),
|
||
'order_id' => $orderId // 补充order_id字段
|
||
]
|
||
];
|
||
|
||
} catch (\Exception $e) {
|
||
// ❌ 回滚事务
|
||
Db::rollback();
|
||
|
||
Log::error('建行支付串生成失败: ' . $e->getMessage());
|
||
return [
|
||
'status' => false,
|
||
'message' => $e->getMessage(),
|
||
'data' => null
|
||
];
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 获取客户端IP
|
||
*
|
||
* @return string
|
||
*/
|
||
private function getClientIp()
|
||
{
|
||
try {
|
||
$ip = request()->ip();
|
||
return $ip ?: '127.0.0.1';
|
||
} catch (\Exception $e) {
|
||
// CLI模式或其他异常情况,使用默认值
|
||
return '127.0.0.1';
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 实现JavaScript的escape()编码
|
||
* 用于REGINFO和PROINFO字段的中文编码
|
||
*
|
||
* 根据建行文档4.3:
|
||
* "使用js的escape()方法对REGINFO(客户注册信息)和PROINFO(商品信息)进行编码"
|
||
*
|
||
* @param string $str 要编码的字符串
|
||
* @return string 编码后的字符串
|
||
*/
|
||
private function jsEscape($str)
|
||
{
|
||
if (empty($str)) {
|
||
return '';
|
||
}
|
||
|
||
$result = '';
|
||
$length = mb_strlen($str, 'UTF-8');
|
||
|
||
for ($i = 0; $i < $length; $i++) {
|
||
$char = mb_substr($str, $i, 1, 'UTF-8');
|
||
|
||
// ASCII字符(数字、字母、部分符号)不编码
|
||
if (preg_match('/^[A-Za-z0-9@*_+\-.\\/]$/', $char)) {
|
||
$result .= $char;
|
||
} else {
|
||
// 非ASCII字符转为 %uXXXX 格式(如:小 -> %u5C0F)
|
||
$unicode = mb_ord($char, 'UTF-8');
|
||
$result .= '%u' . strtoupper(str_pad(dechex($unicode), 4, '0', STR_PAD_LEFT));
|
||
}
|
||
}
|
||
|
||
return $result;
|
||
}
|
||
|
||
/**
|
||
* 构建商品信息字符串
|
||
* 根据建行文档4.3:商品信息中文需使用escape()编码
|
||
*
|
||
* @param object $order 订单对象
|
||
* @return string escape编码后的商品信息
|
||
*/
|
||
private function buildProductInfo($order)
|
||
{
|
||
// 获取订单商品
|
||
$orderItems = Db::name('shopro_order_item')
|
||
->where('order_id', $order['id'])
|
||
->limit(3) // 最多取3个商品
|
||
->column('goods_title');
|
||
|
||
if (empty($orderItems)) {
|
||
$productInfo = '商城订单';
|
||
} else {
|
||
// 拼接商品名称,建议不超过50字符(编码前)
|
||
$productInfo = mb_substr(implode(',', $orderItems), 0, 50, 'UTF-8');
|
||
}
|
||
|
||
// ✅ 使用JavaScript的escape()编码中文
|
||
return $this->jsEscape($productInfo);
|
||
}
|
||
|
||
/**
|
||
* 生成ENCPUB(商户公钥密文)
|
||
*
|
||
* 根据建行文档4.4:
|
||
* "使用服务方公钥对商户公钥后30位进行RSA加密,再进行base64后,生成的密文串"
|
||
*
|
||
* 注意:这里的"商户公钥后30位"是指RSA公钥模数(modulus)的十六进制表示的后30位
|
||
* 不是BASE64字符串的后30位!
|
||
*
|
||
* @return string BASE64编码的加密密文
|
||
* @throws \Exception
|
||
*/
|
||
private function encryptPublicKeyLast30()
|
||
{
|
||
// 获取商户公钥(被加密的公钥)
|
||
$merchantPublicKey = $this->config['merchant_public_key'] ?? '';
|
||
|
||
// 获取服务方公钥(用于加密的公钥)
|
||
$servicePublicKey = $this->config['public_key'] ?? '';
|
||
|
||
if (empty($merchantPublicKey)) {
|
||
throw new \Exception('商户公钥未配置');
|
||
}
|
||
|
||
if (empty($servicePublicKey)) {
|
||
throw new \Exception('服务方公钥未配置');
|
||
}
|
||
|
||
// ✅ 关键修复:直接取商户公钥十六进制字符串的后30位
|
||
try {
|
||
// 商户公钥已经是十六进制格式,直接取后30位
|
||
$last30Chars = substr($merchantPublicKey, -30);
|
||
|
||
if (strlen($last30Chars) < 30) {
|
||
throw new \Exception('商户公钥长度不足30位');
|
||
}
|
||
|
||
Log::info('[建行支付] 商户公钥后30位: ' . $last30Chars);
|
||
|
||
// 使用服务方公钥加密这30位十六进制字符串
|
||
// CcbRSA::encrypt 会自动进行base64编码
|
||
$encpub = CcbRSA::encrypt($last30Chars, $servicePublicKey);
|
||
|
||
// ✅ 直接返回标准BASE64格式的ENCPUB
|
||
// 注意:建行要求标准BASE64(包含+和/),不是URL-safe格式
|
||
return $encpub;
|
||
|
||
} catch (\Exception $e) {
|
||
Log::error('[建行支付] ENCPUB生成失败: ' . $e->getMessage());
|
||
throw $e;
|
||
}
|
||
}
|
||
|
||
|
||
/**
|
||
* 处理异步通知
|
||
* 建行支付异步通知处理
|
||
*
|
||
* ⚠️ 注意:这是唯一可信的支付确认来源!
|
||
* 返回订单ID供控制器调用pushOrderToCcb()推送到外联系统
|
||
*
|
||
* @param array $params 通知参数
|
||
* @return array ['status' => 'success'|'fail', 'order_id' => int, 'order_sn' => string]
|
||
*/
|
||
public function handleNotify($params)
|
||
{
|
||
try {
|
||
// 优先使用USER_ORDERID查询,如果没有则用ccb_pay_flow_id查询
|
||
$payFlowId = $params['ORDERID'] ?? ''; // 支付流水号
|
||
$order = Order::where('ccb_pay_flow_id', $payFlowId)->find();
|
||
|
||
if (!$order) {
|
||
throw new \Exception('订单不存在');
|
||
}
|
||
|
||
// 如果订单已支付,直接返回成功(幂等性)
|
||
if ($order['status'] == 'paid') {
|
||
Log::info('[建行通知] 订单已支付,跳过处理 order_id:' . $order->id);
|
||
return [
|
||
'status' => 'success',
|
||
'order_id' => $order->id,
|
||
'order_sn' => $order->order_sn,
|
||
'already_paid' => true, // 标记为已支付
|
||
];
|
||
}
|
||
|
||
// 更新订单状态
|
||
$this->updateOrderPaymentStatus($order, $params);
|
||
|
||
Log::info('[建行通知] 订单状态更新成功 order_id:' . $order->id . ' order_sn:' . $order->order_sn);
|
||
|
||
// ✅ 返回订单ID供控制器推送到外联系统
|
||
return [
|
||
'status' => 'success',
|
||
'order_id' => $order->id,
|
||
'order_sn' => $order->order_sn,
|
||
'already_paid' => false, // 新支付
|
||
];
|
||
|
||
} catch (\Exception $e) {
|
||
Log::error('[建行通知] 处理失败: ' . $e->getMessage());
|
||
return [
|
||
'status' => 'fail',
|
||
'message' => $e->getMessage(),
|
||
];
|
||
}
|
||
}
|
||
|
||
|
||
/**
|
||
* 更新订单支付状态
|
||
* ✅ 修复:同时创建shopro_pay记录,确保退款逻辑能够正常工作
|
||
*
|
||
* @param object $order 订单对象
|
||
* @param array $params 支付参数(建行回调参数)
|
||
*/
|
||
private function updateOrderPaymentStatus($order, $params)
|
||
{
|
||
// 开启事务,确保订单状态和pay记录同时创建
|
||
Db::startTrans();
|
||
|
||
try {
|
||
// 1. 更新订单状态
|
||
Order::where('id', $order['id'])->update([
|
||
'status' => 'paid',
|
||
'paid_time' => time(),
|
||
'updatetime' => time()
|
||
]);
|
||
|
||
// 2. ✅ 创建shopro_pay支付记录(与其他支付方式保持一致)
|
||
// 检查是否已存在pay记录(幂等性保护)
|
||
$existingPay = PayModel::where('order_type', 'order')
|
||
->where('order_id', $order['id'])
|
||
->where('pay_type', 'ccb')
|
||
->find();
|
||
|
||
if (!$existingPay) {
|
||
// 不存在则创建新记录
|
||
$payModel = new PayModel();
|
||
$payModel->order_type = 'order';
|
||
$payModel->order_id = $order['id'];
|
||
$payModel->pay_sn = $order['ccb_pay_flow_id'] ?? ($params['ORDERID'] ?? ''); // 使用建行支付流水号
|
||
$payModel->user_id = $order['user_id'];
|
||
$payModel->pay_type = 'ccb'; // 建行支付类型
|
||
$payModel->pay_fee = $order['pay_fee']; // 支付金额
|
||
$payModel->real_fee = $order['pay_fee']; // 建行支付实际金额=订单金额
|
||
$payModel->transaction_id = $params['ORDERID'] ?? ''; // 建行交易流水号
|
||
$payModel->payment_json = json_encode($params, JSON_UNESCAPED_UNICODE); // 回调原始参数
|
||
$payModel->paid_time = time();
|
||
$payModel->status = PayModel::PAY_STATUS_PAID;
|
||
$payModel->refund_fee = 0; // 初始退款金额为0
|
||
$payModel->save();
|
||
|
||
Log::info('[建行支付] 创建shopro_pay记录成功 order_id:' . $order['id'] . ' pay_id:' . $payModel->id . ' pay_sn:' . $payModel->pay_sn);
|
||
} else {
|
||
// 已存在则更新状态(理论上不会执行到这里,但为了安全)
|
||
$existingPay->status = PayModel::PAY_STATUS_PAID;
|
||
$existingPay->paid_time = time();
|
||
$existingPay->transaction_id = $params['ORDERID'] ?? '';
|
||
$existingPay->payment_json = json_encode($params, JSON_UNESCAPED_UNICODE);
|
||
$existingPay->save();
|
||
|
||
Log::warning('[建行支付] shopro_pay记录已存在,更新状态 order_id:' . $order['id'] . ' pay_id:' . $existingPay->id);
|
||
}
|
||
|
||
// 3. 记录支付日志(原有逻辑)
|
||
$this->recordPaymentLog($order['id'], 'payment_success', $params);
|
||
|
||
// 提交事务
|
||
Db::commit();
|
||
|
||
} catch (\Exception $e) {
|
||
// 回滚事务
|
||
Db::rollback();
|
||
Log::error('[建行支付] 更新支付状态失败 order_id:' . $order['id'] . ' error:' . $e->getMessage());
|
||
throw $e;
|
||
}
|
||
}
|
||
|
||
|
||
/**
|
||
* 记录支付请求
|
||
*
|
||
* ⚠️ 幂等性说明:
|
||
* 1. 当用户多次点击支付按钮时,会复用同一个pay_flow_id
|
||
* 2. 本方法会先检查是否已存在记录,如果存在则更新,否则插入
|
||
* 3. 这样可以避免唯一键冲突,并记录最新的支付串生成时间
|
||
*
|
||
* @param int $orderId 订单ID
|
||
* @param array $paymentData 支付数据
|
||
*/
|
||
private function recordPaymentRequest($orderId, $paymentData)
|
||
{
|
||
// 获取订单信息
|
||
$order = Order::find($orderId);
|
||
$user = Db::name('user')->where('id', $order['user_id'])->field('ccb_user_id')->find();
|
||
|
||
$payFlowId = $paymentData['pay_flow_id'] ?? '';
|
||
|
||
// 检查是否已存在记录(根据pay_flow_id唯一键)
|
||
$existingLog = Db::name('ccb_payment_log')
|
||
->where('pay_flow_id', $payFlowId)
|
||
->find();
|
||
|
||
$logData = [
|
||
'order_id' => $orderId,
|
||
'order_sn' => $order['order_sn'],
|
||
'payment_string' => $paymentData['payment_string'] ?? '',
|
||
'user_id' => $order['user_id'],
|
||
'ccb_user_id' => $user['ccb_user_id'] ?? '',
|
||
'amount' => $order['pay_fee'], // 使用Shopro的pay_fee字段
|
||
'status' => 0, // 待支付
|
||
];
|
||
|
||
if ($existingLog) {
|
||
// 已存在记录,更新支付串(保留原create_time,重置status为待支付)
|
||
// 注意:用户重复点击支付时,会生成新的支付串,需要更新
|
||
Db::name('ccb_payment_log')
|
||
->where('pay_flow_id', $payFlowId)
|
||
->update([
|
||
'payment_string' => $logData['payment_string'],
|
||
'status' => 0, // 重置为待支付(因为是新的支付串)
|
||
'amount' => $logData['amount'], // 更新金额(订单金额可能变化)
|
||
]);
|
||
|
||
Log::info('[建行支付] 更新支付日志 pay_flow_id:' . $payFlowId . ' order_id:' . $orderId);
|
||
} else {
|
||
// 不存在记录,插入新记录
|
||
$logData['pay_flow_id'] = $payFlowId;
|
||
$logData['create_time'] = time();
|
||
Db::name('ccb_payment_log')->insert($logData);
|
||
|
||
Log::info('[建行支付] 插入支付日志 pay_flow_id:' . $payFlowId . ' order_id:' . $orderId);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 记录支付日志
|
||
*
|
||
* @param int $orderId 订单ID
|
||
* @param string $type 日志类型
|
||
* @param array $data 数据
|
||
*/
|
||
private function recordPaymentLog($orderId, $type, $data)
|
||
{
|
||
// 更新建行支付日志
|
||
if ($type == 'payment_success') {
|
||
Db::name('ccb_payment_log')
|
||
->where('order_id', $orderId)
|
||
->update([
|
||
'status' => 1, // 支付成功
|
||
'pay_time' => time(),
|
||
'trans_id' => $data['ORDERID'] ?? '',
|
||
'callback_data' => json_encode($data, JSON_UNESCAPED_UNICODE)
|
||
]);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 生成退款申请
|
||
*
|
||
* @param int $orderId 订单ID
|
||
* @param float $refundAmount 退款金额
|
||
* @param string $refundReason 退款原因
|
||
* @return array
|
||
*/
|
||
public function refund($orderId, $refundAmount, $refundReason = '')
|
||
{
|
||
try {
|
||
// 调用订单服务处理退款
|
||
$result = $this->orderService->refundOrder($orderId, $refundAmount, $refundReason);
|
||
|
||
if ($result['status']) {
|
||
// 记录退款日志
|
||
$this->recordPaymentLog($orderId, 'refund_request', [
|
||
'amount' => $refundAmount,
|
||
'reason' => $refundReason
|
||
]);
|
||
}
|
||
|
||
return $result;
|
||
|
||
} catch (\Exception $e) {
|
||
Log::error('建行退款申请失败: ' . $e->getMessage());
|
||
return [
|
||
'status' => false,
|
||
'message' => $e->getMessage(),
|
||
'data' => null
|
||
];
|
||
}
|
||
}
|
||
}
|