feat: 初始化雄戈商城服务端代码与Webhook自动部署配置

这个提交包含在:
wikiboss
2026-09-12 16:40:24 +08:00
当前提交 e90ec58e61
共有 6438 个文件被更改,包括 1136083 次插入 和 0 次删除

查看文件

@@ -0,0 +1,41 @@
<?php
namespace addons\shopro_wechat_trade\library;
use think\Db;
class Bridge
{
public static function isEnabled()
{
if (!function_exists('get_addon_info')) {
return false;
}
$info = get_addon_info('shopro_wechat_trade');
if (!$info || intval($info['state'] ?? 0) !== 1) {
return false;
}
return WxTradeConfig::getInstance()->get('wechat_trade_enable', '1') === '1';
}
public static function shouldHandleOrder($order)
{
if (!self::isEnabled()) {
return false;
}
if (!$order) {
return false;
}
if (($order['platform'] ?? '') !== 'wxMiniProgram') {
return false;
}
$payType = $order['pay_type'] ?? '';
if (!in_array($payType, ['wechat', 'huifu_wechat'], true)) {
return false;
}
if (intval($order['status'] ?? 0) <= 0) {
return false;
}
return WxOrderContext::resolveTransactionId($order) !== '';
}
}

查看文件

@@ -0,0 +1,161 @@
<?php
namespace addons\shopro_wechat_trade\library;
use app\admin\model\AuthRule;
use think\addons\Service;
use think\Cache;
use think\Db;
class Installer
{
public static function run($output = null)
{
$addonDir = ADDON_PATH . 'shopro_wechat_trade' . DS;
$name = 'shopro_wechat_trade';
self::log($output, '复制后台文件...');
foreach (['application', 'public'] as $dir) {
$source = $addonDir . $dir;
if (is_dir($source)) {
copydirs($source, ROOT_PATH . $dir);
}
}
self::log($output, '执行 install.sql...');
self::importSqlFile($addonDir . 'install.sql', $output);
self::log($output, '注册菜单...');
self::installMenu($output);
\app\common\library\Menu::enable('shopro_wechat_trade/config');
\app\common\library\Menu::enable('shopro_wechat_trade/sync');
self::grantRulesToShoproGroups($output);
self::clearMenuCache();
self::setAddonState($name, 1, $output);
try {
(new WxOrderPathService())->updatePath();
self::log($output, '已配置微信订单详情路径');
} catch (\Exception $e) {
self::log($output, ' [warn] 订单详情路径配置失败: ' . $e->getMessage());
if (strpos($e->getMessage(), '10060035') !== false) {
self::log($output, ' [warn] 10060035 常见原因:小程序线上/提审版尚未包含 pages/order/detail,请先发布小程序后再执行 php think shopro_wechat_trade:init-path');
self::log($output, ' [warn] 或在小程序后台手动填写 path: pages/order/detail?id=${商品订单号}');
} elseif (strpos($e->getMessage(), '10060034') !== false) {
self::log($output, ' [warn] 请先在小程序后台签署订单中心授权协议');
}
}
Service::refresh();
self::log($output, '安装完成: /admin/shopro_wechat_trade/config');
}
public static function setAddonState($name, $state, $output = null)
{
$file = ADDON_PATH . $name . DS . 'info.ini';
if (!is_file($file)) {
return false;
}
$content = file_get_contents($file);
$state = intval($state);
if (preg_match('/^state\s*=\s*\d+/m', $content)) {
$content = preg_replace('/^state\s*=\s*\d+/m', 'state = ' . $state, $content);
} else {
$content = rtrim($content) . "\nstate = " . $state . "\n";
}
file_put_contents($file, $content, LOCK_EX);
\think\Config::set($name, null, 'addoninfo');
return true;
}
public static function installMenu($output = null)
{
$menuFile = ADDON_PATH . 'shopro_wechat_trade' . DS . 'config' . DS . 'menu.php';
if (!is_file($menuFile)) {
return false;
}
$menu = include $menuFile;
if (!$menu) {
return false;
}
$parent = self::resolveMenuParent();
self::recreateMenu($menu, $parent, 'shopro_wechat_trade/config', ['shopro_wechat_trade']);
\app\common\library\Menu::refresh('shopro_wechat_trade', $menu);
return $parent;
}
protected static function resolveMenuParent()
{
foreach (['shopro/config', 'shopro'] as $name) {
$rule = AuthRule::getByName($name);
if ($rule && $rule['status'] === 'normal') {
return $name;
}
}
return 0;
}
protected static function recreateMenu(array $menu, $parent, $rootName, array $legacyNames = [])
{
foreach (array_merge($legacyNames, [$rootName]) as $name) {
\app\common\library\Menu::delete($name);
}
\app\common\library\Menu::create($menu, $parent);
}
protected static function grantRulesToShoproGroups($output = null)
{
$ruleIds = array_merge(
\app\common\library\Menu::getAuthRuleIdsByName('shopro_wechat_trade/config'),
\app\common\library\Menu::getAuthRuleIdsByName('shopro_wechat_trade/sync')
);
if (!$ruleIds) {
return;
}
$groups = Db::name('auth_group')->where('name', 'like', '%shopro%')->select();
foreach ($groups as $group) {
$rules = array_filter(explode(',', $group['rules']));
$merged = array_unique(array_merge($rules, $ruleIds));
Db::name('auth_group')->where('id', $group['id'])->update(['rules' => implode(',', $merged)]);
}
}
protected static function importSqlFile($file, $output = null, $ignoreError = false)
{
if (!is_file($file)) {
return;
}
$prefix = config('database.prefix');
$sql = str_replace('__PREFIX__', $prefix, file_get_contents($file));
$statements = array_filter(array_map('trim', explode(';', $sql)));
foreach ($statements as $statement) {
if ($statement === '') {
continue;
}
try {
Db::execute($statement);
} catch (\Exception $e) {
if (!$ignoreError) {
self::log($output, ' [warn] SQL: ' . $e->getMessage());
}
}
}
}
protected static function clearMenuCache()
{
try {
Cache::rm('__menu__');
} catch (\Exception $e) {
// ignore
}
}
protected static function log($output, $message)
{
if ($output) {
$output->writeln($message);
}
}
}

查看文件

@@ -0,0 +1,73 @@
<?php
namespace addons\shopro_wechat_trade\library;
use think\Db;
class SyncLogger
{
public static function create($order, $syncType, array $payload = [], $orderItemId = 0, $deliveryMode = 1)
{
$order = is_object($order) && method_exists($order, 'toArray') ? $order->toArray() : (array) $order;
$now = time();
$id = Db::name('shopro_wechat_trade_sync')->insertGetId([
'order_id' => intval($order['id'] ?? 0),
'order_sn' => $order['order_sn'] ?? '',
'order_item_id' => intval($orderItemId),
'sync_type' => $syncType,
'status' => 'pending',
'delivery_mode' => intval($deliveryMode),
'request_payload' => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
'retry_count' => 0,
'createtime' => $now,
'updatetime' => $now,
]);
return $id;
}
public static function markSuccess($logId, array $response, array $request = null)
{
$update = [
'status' => 'success',
'response_payload' => json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
'errcode' => 0,
'errmsg' => 'ok',
'updatetime' => time(),
];
if ($request !== null) {
$update['request_payload'] = json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
Db::name('shopro_wechat_trade_sync')->where('id', $logId)->update($update);
}
public static function markFailed($logId, \Exception $e, array $response = [], array $request = null)
{
$row = Db::name('shopro_wechat_trade_sync')->where('id', $logId)->find();
$retryCount = intval($row['retry_count'] ?? 0) + 1;
$interval = WxTradeConfig::getInstance()->getRetryInterval();
$maxRetry = WxTradeConfig::getInstance()->getMaxRetry();
$update = [
'status' => $retryCount >= $maxRetry ? 'failed' : 'pending',
'response_payload' => json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
'errcode' => intval($response['errcode'] ?? -1),
'errmsg' => mb_substr($e->getMessage(), 0, 250),
'retry_count' => $retryCount,
'next_retry_time' => time() + $interval,
'updatetime' => time(),
];
if ($request !== null) {
$update['request_payload'] = json_encode($request, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
Db::name('shopro_wechat_trade_sync')->where('id', $logId)->update($update);
}
public static function hasSuccessfulConfirm($orderId)
{
return (bool) Db::name('shopro_wechat_trade_sync')
->where('order_id', $orderId)
->where('sync_type', 'confirm')
->where('status', 'success')
->find();
}
}

查看文件

@@ -0,0 +1,29 @@
<?php
namespace addons\shopro_wechat_trade\library;
/**
* Shopro 快递公司编码 → 微信运力编码(常见快递公司默认同码)
*/
class WxExpressMapper
{
protected static $alias = [
'HTKY' => 'HTKY',
'HHTT' => 'HHTT',
'YZPY' => 'YZPY',
'DBL' => 'DBL',
'ZJS' => 'ZJS',
];
public static function toWechatCode($shoproCode)
{
$code = strtoupper(trim((string) $shoproCode));
if ($code === '') {
return '';
}
if (isset(self::$alias[$code])) {
return self::$alias[$code];
}
return $code;
}
}

查看文件

@@ -0,0 +1,145 @@
<?php
namespace addons\shopro_wechat_trade\library;
use addons\shopro\model\UserOauth;
use think\Db;
class WxOrderContext
{
public static function resolveTransactionId($order)
{
$order = self::normalizeOrder($order);
$payType = $order['pay_type'] ?? '';
if ($payType === 'huifu_wechat') {
$ext = self::getHuifuPayExt($order['id']);
if ($ext) {
$extra = self::decodeHuifuExtra($ext['extra'] ?? '');
if (!empty($extra['wx_transaction_id'])) {
return $extra['wx_transaction_id'];
}
}
}
$txn = trim((string) ($order['transaction_id'] ?? ''));
if ($txn !== '' && self::looksLikeWxTransactionId($txn)) {
return $txn;
}
$payment = self::decodePaymentJson($order['payment_json'] ?? '');
if (!empty($payment['transaction_id']) && self::looksLikeWxTransactionId($payment['transaction_id'])) {
return $payment['transaction_id'];
}
if ($payType === 'huifu_wechat' && !empty($payment['out_trans_id'])) {
return $payment['out_trans_id'];
}
if ($payType === 'huifu_wechat') {
$wxResp = $payment['wx_response'] ?? [];
if (is_string($wxResp)) {
$wxResp = json_decode($wxResp, true) ?: [];
}
if (!empty($wxResp['transaction_id'])) {
return $wxResp['transaction_id'];
}
}
return $txn;
}
public static function resolveOpenid($order)
{
$order = self::normalizeOrder($order);
$payType = $order['pay_type'] ?? '';
if ($payType === 'huifu_wechat') {
$ext = self::getHuifuPayExt($order['id']);
if ($ext) {
$extra = self::decodeHuifuExtra($ext['extra'] ?? '');
if (!empty($extra['wx_sub_openid'])) {
return $extra['wx_sub_openid'];
}
}
}
$payment = self::decodePaymentJson($order['payment_json'] ?? '');
if (!empty($payment['sub_openid'])) {
return $payment['sub_openid'];
}
if (!empty($payment['openid'])) {
return $payment['openid'];
}
$oauth = UserOauth::where('user_id', $order['user_id'])
->where('platform', 'wxMiniProgram')
->order('id', 'desc')
->find();
return $oauth['openid'] ?? '';
}
public static function resolveMchid($order)
{
$order = self::normalizeOrder($order);
if (($order['pay_type'] ?? '') === 'huifu_wechat') {
$ext = self::getHuifuPayExt($order['id']);
if ($ext) {
$extra = self::decodeHuifuExtra($ext['extra'] ?? '');
if (!empty($extra['wx_sub_mch_id'])) {
return $extra['wx_sub_mch_id'];
}
}
$payment = self::decodePaymentJson($order['payment_json'] ?? '');
$wxResp = $payment['wx_response'] ?? [];
if (is_string($wxResp)) {
$wxResp = json_decode($wxResp, true) ?: [];
}
if (!empty($wxResp['sub_mch_id'])) {
return $wxResp['sub_mch_id'];
}
}
return '';
}
protected static function normalizeOrder($order)
{
if (is_object($order) && method_exists($order, 'toArray')) {
return $order->toArray();
}
return (array) $order;
}
protected static function getHuifuPayExt($orderId)
{
try {
return Db::name('shopro_huifu_pay_ext')->where('order_id', $orderId)->find();
} catch (\Exception $e) {
return null;
}
}
protected static function decodeHuifuExtra($extra)
{
if (class_exists('\\addons\\shopro_huifu\\library\\HuifuWxNotifyHelper')) {
return \addons\shopro_huifu\library\HuifuWxNotifyHelper::decodeExtra($extra);
}
if (!$extra) {
return [];
}
$decoded = json_decode($extra, true);
return is_array($decoded) ? $decoded : [];
}
protected static function decodePaymentJson($json)
{
if (!$json) {
return [];
}
$decoded = json_decode($json, true);
return is_array($decoded) ? $decoded : [];
}
protected static function looksLikeWxTransactionId($txn)
{
return (bool) preg_match('/^\d{20,}$/', (string) $txn);
}
}

查看文件

@@ -0,0 +1,70 @@
<?php
namespace addons\shopro_wechat_trade\library;
class WxOrderPathService
{
protected $client;
protected $config;
public function __construct()
{
$this->client = new WxTradeClient();
$this->config = WxTradeConfig::getInstance();
}
public function updatePath($path = null)
{
$path = self::normalizePath($path ?: $this->config->getOrderDetailPath());
$response = $this->client->postJson('/wxa/sec/order/update_order_detail_path', [
'path' => $path,
]);
return $this->client->callOrThrow($response, '配置订单详情路径');
}
/**
* 微信要求:不含前导 /;必须含 ${商品订单号};页面须已存在于线上或提审版本
*/
public static function normalizePath($path)
{
$path = trim((string) $path);
$path = ltrim($path, '/');
if (strpos($path, '${商品订单号}') === false) {
throw new \InvalidArgumentException('path 必须包含 ${商品订单号}');
}
return $path;
}
public static function defaultPath()
{
return 'pages/order/detail?id=${商品订单号}';
}
public static function explainPathError($errcode, $errmsg = '')
{
$code = intval($errcode);
if ($code === 10060034) {
return '请先在小程序后台签署订单中心授权协议(支付与交易 → 订单管理/购物订单)';
}
if ($code === 10060035) {
return '无效的路径(10060035):请确认 ① path 为 pages/order/detail?id=${商品订单号}(无前导/,参数名建议用 id)'
. ' ② 该页面已存在于小程序当前线上版或提审版(需先发布含订单详情页的小程序代码)'
. ' ③ 也可在小程序后台手动配置订单详情 path,不必强依赖 API';
}
if ($code === 10060036) {
return '请求编码须为 UTF-8(10060036)';
}
return trim($errmsg) ?: '未知错误';
}
public function getPath()
{
$response = $this->client->postJson('/wxa/sec/order/get_order_detail_path', []);
return $this->client->callOrThrow($response, '查询订单详情路径');
}
public function isTradeManaged()
{
return $this->client->getJson('/wxa/sec/order/is_trade_managed');
}
}

查看文件

@@ -0,0 +1,161 @@
<?php
namespace addons\shopro_wechat_trade\library;
use addons\shopro\model\OrderItem;
class WxShippingPayload
{
protected static $logisticsMap = [
'express' => 1,
'store' => 2,
'autosend' => 3,
'selfetch' => 4,
];
public static function mapLogisticsType($dispatchType)
{
return self::$logisticsMap[$dispatchType] ?? 1;
}
public static function buildUploadPayload($order, array $items, $triggerItem = null)
{
$transactionId = WxOrderContext::resolveTransactionId($order);
$openid = WxOrderContext::resolveOpenid($order);
if ($transactionId === '') {
throw new \RuntimeException('缺少微信 transaction_id,无法同步发货');
}
if ($openid === '') {
throw new \RuntimeException('缺少用户 openid,无法同步发货');
}
$shippableItems = self::filterShippableItems($items);
if (!$shippableItems) {
throw new \RuntimeException('没有可同步的已发货商品');
}
$allItems = self::filterAllActiveItems($items);
$deliveryMode = count($shippableItems) >= count($allItems) ? 1 : 2;
$logisticsType = self::mapLogisticsType($triggerItem['dispatch_type'] ?? ($shippableItems[0]['dispatch_type'] ?? 'express'));
$shippingList = [];
foreach ($shippableItems as $item) {
$shippingList[] = self::buildShippingListItem($item, $order);
}
return [
'payload' => [
'order_key' => [
'order_number_type' => 2,
'transaction_id' => $transactionId,
],
'logistics_type' => $logisticsType,
'delivery_mode' => $deliveryMode,
'shipping_list' => $shippingList,
'upload_time' => self::formatUploadTime(time()),
'payer' => ['openid' => $openid],
],
'meta' => [
'transaction_id' => $transactionId,
'delivery_mode' => $deliveryMode,
'logistics_type' => $logisticsType,
],
];
}
public static function buildConfirmPayload($order)
{
$transactionId = WxOrderContext::resolveTransactionId($order);
if ($transactionId === '') {
throw new \RuntimeException('缺少微信 transaction_id,无法同步确认收货');
}
$confirmTime = time();
$ext = is_array($order['ext_arr'] ?? null) ? $order['ext_arr'] : [];
if (!empty($ext['confirm_time'])) {
$confirmTime = intval($ext['confirm_time']);
}
return [
'order_key' => [
'order_number_type' => 2,
'transaction_id' => $transactionId,
],
'received_time' => self::formatUploadTime($confirmTime),
];
}
protected static function buildShippingListItem(array $item, $order)
{
$dispatchType = $item['dispatch_type'] ?? 'express';
$desc = mb_substr($item['goods_title'] ?? '商城商品', 0, 120);
$entry = ['item_desc' => $desc];
if (in_array($dispatchType, ['express', 'store'], true)) {
$trackingNo = trim((string) ($item['express_no'] ?? ''));
$expressCode = WxExpressMapper::toWechatCode($item['express_code'] ?? '');
if ($trackingNo === '') {
throw new \RuntimeException('快递发货缺少物流单号: item#' . ($item['id'] ?? ''));
}
if ($expressCode === '') {
throw new \RuntimeException('快递公司编码未映射: ' . ($item['express_code'] ?? ''));
}
$entry['tracking_no'] = $trackingNo;
$entry['express_company'] = $expressCode;
} else {
$entry['tracking_no'] = $order['order_sn'] ?? ('ITEM' . ($item['id'] ?? ''));
}
if (!empty($order['phone'])) {
$entry['contact'] = [
'receiver_contact' => self::maskPhone($order['phone']),
];
}
return $entry;
}
protected static function filterShippableItems(array $items)
{
$result = [];
foreach ($items as $item) {
$item = is_object($item) && method_exists($item, 'toArray') ? $item->toArray() : (array) $item;
if (intval($item['dispatch_status'] ?? 0) < OrderItem::DISPATCH_STATUS_SENDED) {
continue;
}
if (in_array(intval($item['refund_status'] ?? 0), [OrderItem::REFUND_STATUS_OK, OrderItem::REFUND_STATUS_FINISH], true)) {
continue;
}
$result[] = $item;
}
return $result;
}
protected static function filterAllActiveItems(array $items)
{
$result = [];
foreach ($items as $item) {
$item = is_object($item) && method_exists($item, 'toArray') ? $item->toArray() : (array) $item;
if (in_array(intval($item['refund_status'] ?? 0), [OrderItem::REFUND_STATUS_OK, OrderItem::REFUND_STATUS_FINISH], true)) {
continue;
}
$result[] = $item;
}
return $result;
}
protected static function formatUploadTime($timestamp)
{
$dt = new \DateTime('@' . intval($timestamp));
$dt->setTimezone(new \DateTimeZone('Asia/Shanghai'));
return $dt->format('Y-m-d\TH:i:s.vP');
}
protected static function maskPhone($phone)
{
$phone = trim((string) $phone);
if (strlen($phone) >= 11) {
return substr($phone, 0, 3) . '****' . substr($phone, -4);
}
return $phone;
}
}

查看文件

@@ -0,0 +1,163 @@
<?php
namespace addons\shopro_wechat_trade\library;
use addons\shopro\model\Order;
use addons\shopro\model\OrderItem;
use think\Db;
use think\Log;
class WxShippingService
{
protected $client;
public function __construct()
{
$this->client = new WxTradeClient();
}
public function syncOrderShipping($orderId, $triggerItemId = 0)
{
if (!Bridge::isEnabled()) {
return false;
}
$order = Order::with('item')->where('id', $orderId)->find();
if (!$order || !Bridge::shouldHandleOrder($order)) {
return false;
}
$items = [];
if (!empty($order->item)) {
foreach ($order->item as $item) {
$items[] = is_object($item) && method_exists($item, 'toArray') ? $item->toArray() : (array) $item;
}
}
$triggerItem = null;
if ($triggerItemId) {
foreach ($items as $item) {
$itemArr = is_object($item) ? $item->toArray() : $item;
if (intval($itemArr['id']) === intval($triggerItemId)) {
$triggerItem = $itemArr;
break;
}
}
}
$built = WxShippingPayload::buildUploadPayload($order, $items, $triggerItem);
$payload = $built['payload'];
$logId = SyncLogger::create($order, 'shipping', $payload, $triggerItemId, $built['meta']['delivery_mode']);
try {
$response = $this->client->postJson('/wxa/sec/order/upload_shipping_info', $payload);
$this->client->callOrThrow($response, '上传发货信息');
SyncLogger::markSuccess($logId, $response, $payload);
return true;
} catch (\Exception $e) {
$response = isset($response) && is_array($response) ? $response : [];
SyncLogger::markFailed($logId, $e, $response, $payload);
Log::error('[shopro_wechat_trade] shipping sync fail order#' . $orderId . ': ' . $e->getMessage());
throw $e;
}
}
public function syncOrderConfirm($orderId)
{
if (!Bridge::isEnabled()) {
return false;
}
if (SyncLogger::hasSuccessfulConfirm($orderId)) {
return true;
}
$order = Order::with('item')->where('id', $orderId)->find();
if (!$order || !Bridge::shouldHandleOrder($order)) {
return false;
}
$pending = OrderItem::where('order_id', $orderId)
->where('dispatch_status', '<>', OrderItem::DISPATCH_STATUS_GETED)
->count();
if ($pending > 0) {
return false;
}
$payload = WxShippingPayload::buildConfirmPayload($order);
$logId = SyncLogger::create($order, 'confirm', $payload);
try {
$response = $this->client->postJson('/wxa/sec/order/notify_confirm_receive', $payload);
$this->client->callOrThrow($response, '同步确认收货');
SyncLogger::markSuccess($logId, $response, $payload);
return true;
} catch (\Exception $e) {
$response = isset($response) && is_array($response) ? $response : [];
SyncLogger::markFailed($logId, $e, $response, $payload);
Log::error('[shopro_wechat_trade] confirm sync fail order#' . $orderId . ': ' . $e->getMessage());
throw $e;
}
}
public function backfillShippedOrders($limit = 50)
{
$rows = Db::name('shopro_order')
->alias('o')
->join('shopro_order_item oi', 'oi.order_id = o.id')
->where('o.platform', 'wxMiniProgram')
->where('o.pay_type', 'in', ['wechat', 'huifu_wechat'])
->where('o.status', '>', 0)
->where('oi.dispatch_status', '>=', OrderItem::DISPATCH_STATUS_SENDED)
->group('o.id')
->order('o.id', 'desc')
->limit($limit)
->column('o.id');
$count = 0;
foreach ($rows as $orderId) {
$hasSuccess = Db::name('shopro_wechat_trade_sync')
->where('order_id', $orderId)
->where('sync_type', 'shipping')
->where('status', 'success')
->find();
if ($hasSuccess) {
continue;
}
try {
$this->syncOrderShipping($orderId);
$count++;
} catch (\Exception $e) {
// logged
}
}
return $count;
}
public function retryFailed($limit = 50)
{
$now = time();
$rows = Db::name('shopro_wechat_trade_sync')
->where('status', 'pending')
->where('retry_count', '>', 0)
->where('next_retry_time', '<=', $now)
->order('id', 'asc')
->limit($limit)
->select();
$count = 0;
foreach ($rows as $row) {
try {
if ($row['sync_type'] === 'confirm') {
$this->syncOrderConfirm($row['order_id']);
} else {
$this->syncOrderShipping($row['order_id'], $row['order_item_id']);
}
$count++;
} catch (\Exception $e) {
// logged
}
}
return $count;
}
}

查看文件

@@ -0,0 +1,73 @@
<?php
namespace addons\shopro_wechat_trade\library;
use addons\shopro\library\Wechat;
use fast\Http;
use think\Log;
class WxTradeClient
{
protected $wechat;
public function __construct()
{
$this->wechat = new Wechat('wxMiniProgram');
}
public function getAccessToken()
{
$token = $this->wechat->getAccessToken();
if (is_array($token) && !empty($token['access_token'])) {
return $token['access_token'];
}
if (is_string($token)) {
return $token;
}
throw new \RuntimeException('无法获取小程序 access_token');
}
public function postJson($path, array $body)
{
$token = $this->getAccessToken();
$url = 'https://api.weixin.qq.com' . $path . '?access_token=' . urlencode($token);
$headers = ['Content-Type: application/json'];
$options = [CURLOPT_HTTPHEADER => $headers];
$result = Http::sendRequest($url, json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), 'POST', $options);
if (!isset($result['ret']) || !$result['ret']) {
throw new \RuntimeException('微信 API 请求失败: ' . ($result['msg'] ?? 'unknown'));
}
$decoded = json_decode($result['msg'], true);
if (!is_array($decoded)) {
throw new \RuntimeException('微信 API 响应解析失败');
}
return $decoded;
}
public function getJson($path, array $query = [])
{
$token = $this->getAccessToken();
$query['access_token'] = $token;
$url = 'https://api.weixin.qq.com' . $path . '?' . http_build_query($query);
$result = Http::sendRequest($url, [], 'GET');
if (!isset($result['ret']) || !$result['ret']) {
throw new \RuntimeException('微信 API 请求失败: ' . ($result['msg'] ?? 'unknown'));
}
$decoded = json_decode($result['msg'], true);
if (!is_array($decoded)) {
throw new \RuntimeException('微信 API 响应解析失败');
}
return $decoded;
}
public function callOrThrow(array $response, $action = '微信接口')
{
$errcode = intval($response['errcode'] ?? 0);
if ($errcode !== 0) {
$msg = ($response['errmsg'] ?? 'unknown') . ' (' . $errcode . ')';
Log::write('[shopro_wechat_trade] ' . $action . ' fail: ' . $msg);
throw new \RuntimeException($action . '失败: ' . $msg);
}
return $response;
}
}

查看文件

@@ -0,0 +1,68 @@
<?php
namespace addons\shopro_wechat_trade\library;
use think\Db;
class WxTradeConfig
{
protected static $instance;
protected $values = [];
public static function getInstance()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
public static function reload()
{
self::$instance = null;
return self::getInstance();
}
protected function __construct()
{
try {
$rows = Db::name('shopro_wechat_trade_config')->select();
foreach ($rows as $row) {
$this->values[$row['name']] = $row['value'];
}
} catch (\Exception $e) {
$this->values = [];
}
}
public function get($name, $default = '')
{
return array_key_exists($name, $this->values) ? $this->values[$name] : $default;
}
public function all()
{
return $this->values;
}
public function getOrderDetailPath()
{
$path = trim($this->get('order_detail_path', WxOrderPathService::defaultPath()));
if ($path === '') {
$path = WxOrderPathService::defaultPath();
}
return $path;
}
public function getMaxRetry()
{
$v = intval($this->get('max_retry', 5));
return $v > 0 ? $v : 5;
}
public function getRetryInterval()
{
$v = intval($this->get('retry_interval', 300));
return $v > 0 ? $v : 300;
}
}