feat(shopro_huifu): 优化分账确认金额计算逻辑并增强调试功能 - 添加previewConfirmPayFee方法用于预览汇付确认基数 - 实现更精确的分账确认金额计算,支持多种场景:待确认金额、结算金额、交易金额减手续费 - 新增辅助方法pickTransAmt、pickFeeAmt、isPositiveMoney和queryFieldRecursive - 支持递归查询嵌套数据结构中的字段值 - 在测试脚本中添加详细的调试输出,包括汇付确认基数对比和查单摘要 - 增强错误处理,显示最新的分账记录详情便于问题排查 - 改进分账执行结果的反馈信息,提供更清晰的成功/失败状态说明 ```
366 行
14 KiB
PHP
366 行
14 KiB
PHP
<?php
|
|
|
|
namespace addons\shopro_huifu\library;
|
|
|
|
use addons\shopro\library\split\SplitCalculator;
|
|
use addons\shopro\library\split\Config as SplitConfig;
|
|
use addons\shopro\model\Order;
|
|
use addons\shopro\model\split\SplitOrder;
|
|
use addons\shopro\model\split\SplitOrderReceiver;
|
|
use think\Db;
|
|
|
|
class HuifuSplitService
|
|
{
|
|
protected $client;
|
|
protected $config;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->config = HuifuConfig::getInstance();
|
|
$this->client = new HuifuClient();
|
|
}
|
|
|
|
public function executeByOrderId($orderId)
|
|
{
|
|
$order = Order::get($orderId);
|
|
if (!$order || $order['pay_type'] !== 'huifu_wechat') {
|
|
return false;
|
|
}
|
|
|
|
$done = SplitOrder::where('order_id', $orderId)->where('channel', 'huifu')->where('status', 2)->find();
|
|
if ($done) {
|
|
return true;
|
|
}
|
|
SplitOrder::where('order_id', $orderId)->where('channel', 'huifu')->where('status', 'in', [1, 4])->delete();
|
|
|
|
$calculator = new SplitCalculator();
|
|
$items = $calculator->calculate($orderId);
|
|
if (empty($items)) {
|
|
$rewardCount = \addons\shopro\model\commission\Reward::where('order_id', $orderId)->where('status', '>=', 0)->count();
|
|
$regionalCount = \addons\shopro\model\regional_agent\Reward::where('order_id', $orderId)->where('status', '>=', 0)->count();
|
|
if ($rewardCount + $regionalCount > 0) {
|
|
\think\Log::warning('[shopro_huifu] split skipped order_id=' . $orderId . ' reason=receiver_missing_or_no_huifu_id');
|
|
}
|
|
$msg = '分账明细为空:请检查分账金额来源、汇付接收方(huifu_id)与佣金/规则是否大于0';
|
|
$this->markFailed($orderId, 'HFPS' . date('YmdHis') . $orderId, $order, [], $msg);
|
|
return false;
|
|
}
|
|
|
|
$payFee = number_format((float) $order['pay_fee'], 2, '.', '');
|
|
$confirmBase = $this->resolveConfirmPayFee($order['order_sn'], $payFee);
|
|
if (bccomp($confirmBase, $payFee, 2) !== 0) {
|
|
\think\Log::info('[shopro_huifu] split confirm base: order_id=' . $orderId
|
|
. ' pay_fee=' . $payFee . ' confirm_base=' . $confirmBase);
|
|
}
|
|
$allocated = '0.00';
|
|
foreach ($items as $item) {
|
|
$allocated = bcadd($allocated, number_format((float) $item['amount'], 2, '.', ''), 2);
|
|
}
|
|
if (bccomp($allocated, $confirmBase, 2) > 0) {
|
|
$items = $this->scaleSplitItemsToCap($items, $allocated, $confirmBase);
|
|
}
|
|
$acctInfos = $this->buildAcctInfos($items, $confirmBase);
|
|
$splitAmount = '0.00';
|
|
foreach ($items as $item) {
|
|
$splitAmount = bcadd($splitAmount, number_format((float) $item['amount'], 2, '.', ''), 2);
|
|
}
|
|
|
|
$outOrderNo = 'HFPS' . date('YmdHis') . $orderId;
|
|
$ext = HuifuPayService::getPayExt($orderId);
|
|
|
|
Db::startTrans();
|
|
try {
|
|
$splitOrder = SplitOrder::create([
|
|
'order_id' => $orderId,
|
|
'order_sn' => $order['order_sn'],
|
|
'channel' => 'huifu',
|
|
'transaction_id' => $order['transaction_id'],
|
|
'out_order_no' => $outOrderNo,
|
|
'total_amount' => $order['pay_fee'],
|
|
'split_amount' => $splitAmount,
|
|
'status' => 1,
|
|
]);
|
|
|
|
foreach ($items as $item) {
|
|
SplitOrderReceiver::create([
|
|
'split_order_id' => $splitOrder->id,
|
|
'receiver_id' => $item['receiver_id'],
|
|
'role_type' => $item['role_type'],
|
|
'amount' => $item['amount'],
|
|
'description' => $item['description'],
|
|
'status' => 0,
|
|
]);
|
|
}
|
|
|
|
$confirmResult = $this->confirm($ext, $acctInfos, $outOrderNo);
|
|
$splitOrder->status = 2;
|
|
$splitOrder->confirm_hf_seq_id = $confirmResult['hf_seq_id'] ?? ($confirmResult['confirm_hf_seq_id'] ?? '');
|
|
$splitOrder->hf_req_seq_id = $outOrderNo;
|
|
$splitOrder->wx_result = json_encode($confirmResult, JSON_UNESCAPED_UNICODE);
|
|
$splitOrder->save();
|
|
|
|
SplitOrderReceiver::where('split_order_id', $splitOrder->id)->update(['status' => 1]);
|
|
HuifuPayService::savePayExt($orderId, $order['order_sn'], [
|
|
'confirm_hf_seq_id' => $splitOrder->confirm_hf_seq_id,
|
|
'confirm_status' => 'S',
|
|
]);
|
|
Db::commit();
|
|
return true;
|
|
} catch (\Exception $e) {
|
|
Db::rollback();
|
|
$this->markFailed($orderId, $outOrderNo, $order, $items, $e->getMessage());
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public function retry($splitOrderId)
|
|
{
|
|
$splitOrder = SplitOrder::where('id', $splitOrderId)->find();
|
|
if (!$splitOrder || $splitOrder['channel'] !== 'huifu') {
|
|
return false;
|
|
}
|
|
return $this->executeByOrderId((int) $splitOrder['order_id']);
|
|
}
|
|
|
|
public function retryByOrderId($orderId)
|
|
{
|
|
$orderId = (int) $orderId;
|
|
if ($orderId <= 0) {
|
|
return false;
|
|
}
|
|
return $this->executeByOrderId($orderId);
|
|
}
|
|
|
|
protected function confirm($ext, array $acctInfos, $confirmReqSeqId)
|
|
{
|
|
SdkLoader::requireRequest('V2TradePaymentDelaytransConfirmRequest.php');
|
|
$request = new \BsPaySdk\request\V2TradePaymentDelaytransConfirmRequest();
|
|
$request->setReqDate(date('Ymd'));
|
|
$request->setReqSeqId($confirmReqSeqId);
|
|
$request->setHuifuId($this->config->get('huifu_id'));
|
|
|
|
$acctSplitBunch = json_encode(['acct_infos' => $acctInfos], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
|
$request->setExtendInfo([
|
|
'org_req_date' => $ext['req_date'],
|
|
'org_req_seq_id' => $ext['req_seq_id'],
|
|
'org_hf_seq_id' => $ext['hf_seq_id'] ?? '',
|
|
'acct_split_bunch' => $acctSplitBunch,
|
|
]);
|
|
|
|
$result = $this->client->postRequest($request);
|
|
return $this->client->parseResponse($result);
|
|
}
|
|
|
|
protected function buildAcctInfos(array $items, $payFee)
|
|
{
|
|
$infos = [];
|
|
$allocated = '0.00';
|
|
foreach ($items as $item) {
|
|
$amt = number_format((float) $item['amount'], 2, '.', '');
|
|
if (bccomp($amt, '0.00', 2) <= 0) {
|
|
continue;
|
|
}
|
|
$infos[] = [
|
|
'huifu_id' => $item['receiver_account'],
|
|
'div_amt' => $amt,
|
|
];
|
|
$allocated = bcadd($allocated, $amt, 2);
|
|
}
|
|
|
|
$platformHuifuId = (new SplitConfig())->all()['platform_huifu_id'] ?? $this->config->get('huifu_id');
|
|
$remain = bcsub($payFee, $allocated, 2);
|
|
if (bccomp($remain, '0.00', 2) > 0) {
|
|
$infos[] = [
|
|
'huifu_id' => $platformHuifuId,
|
|
'div_amt' => $remain,
|
|
];
|
|
}
|
|
|
|
$sum = '0.00';
|
|
foreach ($infos as $info) {
|
|
$sum = bcadd($sum, $info['div_amt'], 2);
|
|
}
|
|
if (bccomp($sum, $payFee, 2) !== 0) {
|
|
throw new \RuntimeException('分账金额之和必须等于订单实付');
|
|
}
|
|
return $infos;
|
|
}
|
|
|
|
/**
|
|
* 延时分账确认总额须与汇付「待确认/交易金额」一致;内扣手续费时往往小于商城 pay_fee。
|
|
*/
|
|
public function previewConfirmPayFee($orderSn, $orderPayFee)
|
|
{
|
|
return $this->resolveConfirmPayFee($orderSn, $orderPayFee);
|
|
}
|
|
|
|
protected function resolveConfirmPayFee($orderSn, $orderPayFee)
|
|
{
|
|
$fallback = number_format((float) $orderPayFee, 2, '.', '');
|
|
try {
|
|
$query = (new HuifuQueryService())->queryByOrderSn($orderSn);
|
|
$delayAcct = strtoupper(trim((string) ($this->queryFieldRecursive($query, 'delay_acct_flag') ?? ''))) === 'Y';
|
|
|
|
$unconfirm = $this->queryFieldRecursive($query, 'unconfirm_amt');
|
|
if ($this->isPositiveMoney($unconfirm)) {
|
|
return number_format((float) $unconfirm, 2, '.', '');
|
|
}
|
|
|
|
$settlement = $this->queryFieldRecursive($query, 'settlement_amt');
|
|
if ($this->isPositiveMoney($settlement) && bccomp((string) $settlement, $fallback, 2) < 0) {
|
|
return number_format((float) $settlement, 2, '.', '');
|
|
}
|
|
|
|
$transAmt = $this->pickTransAmt($query);
|
|
$feeAmt = $this->pickFeeAmt($query);
|
|
if ($transAmt !== null && $feeAmt !== null) {
|
|
$net = bcsub($transAmt, $feeAmt, 2);
|
|
if (bccomp($net, '0.00', 2) > 0 && bccomp($net, $fallback, 2) <= 0) {
|
|
\think\Log::info('[shopro_huifu] split confirm base from trans-fee: trans=' . $transAmt . ' fee=' . $feeAmt . ' net=' . $net);
|
|
return $net;
|
|
}
|
|
}
|
|
|
|
if ($transAmt !== null && !$delayAcct && bccomp($transAmt, '0.00', 2) > 0) {
|
|
return $transAmt;
|
|
}
|
|
|
|
if ($delayAcct && $transAmt !== null && bccomp($transAmt, $fallback, 2) === 0) {
|
|
\think\Log::warning('[shopro_huifu] split confirm base: delay_acct=Y but unconfirm/fee missing, still using pay_fee=' . $fallback
|
|
. ' query_keys=' . implode(',', array_slice(array_keys($query), 0, 20)));
|
|
}
|
|
} catch (\Throwable $e) {
|
|
\think\Log::warning('[shopro_huifu] split confirm amount query fallback: ' . $e->getMessage());
|
|
}
|
|
return $fallback;
|
|
}
|
|
|
|
protected function pickTransAmt(array $query)
|
|
{
|
|
$raw = $this->queryFieldRecursive($query, 'trans_amt');
|
|
if (!$this->isPositiveMoney($raw)) {
|
|
return null;
|
|
}
|
|
return number_format((float) $raw, 2, '.', '');
|
|
}
|
|
|
|
protected function pickFeeAmt(array $query)
|
|
{
|
|
foreach (['actual_fee_amt', 'receivable_fee_amt', 'fee_amt', 'fee_amount', 'trans_fee', 'combinedpay_fee_amt'] as $key) {
|
|
$raw = $this->queryFieldRecursive($query, $key);
|
|
if ($this->isPositiveMoney($raw)) {
|
|
return number_format((float) $raw, 2, '.', '');
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
protected function isPositiveMoney($value)
|
|
{
|
|
if ($value === null || $value === '') {
|
|
return false;
|
|
}
|
|
if (!is_numeric($value)) {
|
|
return false;
|
|
}
|
|
return bccomp(number_format((float) $value, 2, '.', ''), '0.00', 2) > 0;
|
|
}
|
|
|
|
/**
|
|
* @param array|string|mixed $data
|
|
*/
|
|
protected function queryFieldRecursive($data, $key)
|
|
{
|
|
if (is_string($data)) {
|
|
$trim = trim($data);
|
|
if ($trim !== '' && ($trim[0] === '{' || $trim[0] === '[')) {
|
|
$decoded = json_decode($trim, true);
|
|
if (is_array($decoded)) {
|
|
return $this->queryFieldRecursive($decoded, $key);
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
if (!is_array($data)) {
|
|
return null;
|
|
}
|
|
if (array_key_exists($key, $data) && $data[$key] !== '' && $data[$key] !== null) {
|
|
return $data[$key];
|
|
}
|
|
foreach ($data as $value) {
|
|
$found = $this->queryFieldRecursive($value, $key);
|
|
if ($found !== null && $found !== '') {
|
|
return $found;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
protected function scaleSplitItemsToCap(array $items, $allocated, $cap)
|
|
{
|
|
if (empty($items) || bccomp($allocated, '0.00', 2) <= 0) {
|
|
return $items;
|
|
}
|
|
$cap = number_format((float) $cap, 2, '.', '');
|
|
$allocated = number_format((float) $allocated, 2, '.', '');
|
|
if (bccomp($allocated, $cap, 2) <= 0) {
|
|
return $items;
|
|
}
|
|
$scaled = [];
|
|
$sum = '0.00';
|
|
$count = count($items);
|
|
foreach ($items as $index => $item) {
|
|
if ($index === $count - 1) {
|
|
$item['amount'] = (float) bcsub($cap, $sum, 2);
|
|
} else {
|
|
$ratio = bcdiv($item['amount'], $allocated, 8);
|
|
$part = bcmul($cap, $ratio, 2);
|
|
$item['amount'] = (float) $part;
|
|
$sum = bcadd($sum, $part, 2);
|
|
}
|
|
if ($item['amount'] > 0) {
|
|
$scaled[] = $item;
|
|
}
|
|
}
|
|
return $scaled;
|
|
}
|
|
|
|
public function querySplit($hfSeqId)
|
|
{
|
|
SdkLoader::requireRequest('V2TradeTransSplitQueryRequest.php');
|
|
$request = new \BsPaySdk\request\V2TradeTransSplitQueryRequest();
|
|
$request->setHuifuId($this->config->get('huifu_id'));
|
|
$request->setHfSeqId($hfSeqId);
|
|
$request->setOrdType('consume');
|
|
$result = $this->client->postRequest($request);
|
|
return $this->client->parseResponse($result);
|
|
}
|
|
|
|
protected function markFailed($orderId, $outOrderNo, $order, $items, $message)
|
|
{
|
|
$splitOrder = SplitOrder::where('order_id', $orderId)->where('channel', 'huifu')->find();
|
|
$splitConfig = new SplitConfig();
|
|
if (!$splitOrder) {
|
|
SplitOrder::create([
|
|
'order_id' => $orderId,
|
|
'order_sn' => $order['order_sn'],
|
|
'channel' => 'huifu',
|
|
'transaction_id' => $order['transaction_id'] ?? '',
|
|
'out_order_no' => $outOrderNo,
|
|
'total_amount' => $order['pay_fee'],
|
|
'split_amount' => array_sum(array_column($items, 'amount')),
|
|
'status' => 4,
|
|
'wx_result' => $message,
|
|
'retry_count' => 1,
|
|
'next_retry_time'=> time() + $splitConfig->getRetryInterval(),
|
|
]);
|
|
} else {
|
|
$splitOrder->status = 4;
|
|
$splitOrder->wx_result = $message;
|
|
$splitOrder->retry_count = $splitOrder['retry_count'] + 1;
|
|
$splitOrder->next_retry_time = time() + $splitConfig->getRetryInterval();
|
|
$splitOrder->save();
|
|
}
|
|
}
|
|
}
|