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

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

查看文件

@@ -0,0 +1 @@
{"files":["application/admin/controller/shopro_wechat_trade/Config.php","application/admin/controller/shopro_wechat_trade/Sync.php","application/admin/view/shopro_wechat_trade/config/index.html","application/admin/view/shopro_wechat_trade/sync/index.html","public/assets/js/backend/shopro_wechat_trade/config.js","public/assets/js/backend/shopro_wechat_trade/sync.js"]}

查看文件

@@ -0,0 +1,49 @@
# Shopro 微信交易合规插件
微信小程序购物订单 + 发货信息同步(`upload_shipping_info` / `notify_confirm_receive`)。
## 运营前置(必做)
在小程序后台(AppID 与商城配置一致)完成:
1. 签署 **订单中心授权协议**(否则 `update_order_detail_path` 报错 `10060034`)
2. 开通 **发货信息管理服务**(支付与交易 → 订单管理 / 购物订单)
3. 满足实物交易类小程序运营规范
## 安装
```bash
# 上传 addons/shopro_wechat_trade 后
php think shopro_wechat_trade:install
php think shopro_wechat_trade:verify
```
后台:**系统管理 → 商城配置 → 微信交易合规**
## 汇付配合
若使用汇付小程序支付,需同步部署最新 `shopro_huifu`(支付通知会落库微信 `transaction_id`)。
## CLI
```bash
php think shopro_wechat_trade:init-path
php think shopro_wechat_trade:backfill
php think shopro_wechat_trade:retry-failed
```
## 触发点
- `order_send_after` → 异步 `upload_shipping_info`
- `order_confirm_after`(全部 item 已收货)→ `notify_confirm_receive`
## 小程序跳转
默认订单详情路径:`pages/order/detail?id=${商品订单号}`(微信官方示例用 `id` 传商户订单号)
### 安装报 10060035「无效的路径」
1. **先发布小程序**:微信会校验 path 是否存在于**当前线上版或提审版**代码中;未发布 `pages/order/detail` 时会报此错
2. **path 格式**:`pages/order/detail?id=${商品订单号}`(不要前导 `/`)
3. 发布后再执行:`php think shopro_wechat_trade:init-path`
4. 或在小程序后台 **支付与交易 → 订单管理** 手动填写相同 path

查看文件

@@ -0,0 +1,9 @@
<?php
namespace addons\shopro_wechat_trade;
require_once __DIR__ . '/Shopro_wechat_trade.php';
class ShoproWechatTrade extends Shopro_wechat_trade
{
}

查看文件

@@ -0,0 +1,67 @@
<?php
namespace addons\shopro_wechat_trade;
use addons\shopro_wechat_trade\library\Installer;
use app\common\library\Menu;
use think\Addons;
class Shopro_wechat_trade extends Addons
{
public function install()
{
Installer::run();
return true;
}
public function uninstall()
{
$sql = file_get_contents(__DIR__ . '/uninstall.sql');
$prefix = config('database.prefix');
$sql = str_replace('__PREFIX__', $prefix, $sql);
$statements = array_filter(array_map('trim', explode(';', $sql)));
foreach ($statements as $statement) {
if ($statement !== '') {
try {
\think\Db::execute($statement);
} catch (\Exception $e) {
// ignore
}
}
}
Menu::delete('shopro_wechat_trade');
Menu::delete('shopro_wechat_trade/config');
Menu::delete('shopro_wechat_trade/sync');
return true;
}
public function enable()
{
Menu::enable('shopro_wechat_trade/config');
Menu::enable('shopro_wechat_trade/sync');
return true;
}
public function disable()
{
Menu::disable('shopro_wechat_trade/config');
Menu::disable('shopro_wechat_trade/sync');
return true;
}
public function appInit()
{
if (!class_exists('\\addons\\shopro_wechat_trade\\library\\Bridge')) {
return;
}
if (!\addons\shopro_wechat_trade\library\Bridge::isEnabled()) {
return;
}
$hooks = require __DIR__ . '/hooks.php';
foreach ($hooks as $tag => $behaviors) {
foreach ((array) $behaviors as $behavior) {
\think\Hook::add($tag, $behavior, true);
}
}
}
}

查看文件

@@ -0,0 +1,69 @@
<?php
namespace app\admin\controller\shopro_wechat_trade;
use addons\shopro_wechat_trade\library\WxOrderPathService;
use addons\shopro_wechat_trade\library\WxTradeConfig;
use app\common\controller\Backend;
use think\Db;
class Config extends Backend
{
public function index()
{
if ($this->request->isAjax()) {
$list = Db::name('shopro_wechat_trade_config')->select();
$data = [];
foreach ($list as $item) {
$data[$item['name']] = $item['value'];
}
$mini = Db::name('shopro_config')->where('name', 'wxMiniProgram')->value('value');
$mini = json_decode($mini, true);
$data['mini_program_app_id'] = $mini['app_id'] ?? '';
return $this->success('操作成功', null, $data);
}
return $this->view->fetch();
}
public function save()
{
$params = $this->request->post('row/a');
if (!$params) {
$this->error('参数错误');
}
foreach ($params as $name => $value) {
Db::name('shopro_wechat_trade_config')->where('name', $name)->update(['value' => $value]);
}
WxTradeConfig::reload();
$this->success('保存成功');
}
public function check()
{
try {
$pathService = new WxOrderPathService();
$managed = $pathService->isTradeManaged();
$path = $pathService->getPath();
$this->success('检测完成', null, [
'is_trade_managed' => $managed,
'order_detail_path' => $path,
]);
} catch (\Exception $e) {
$this->error('检测失败:' . $e->getMessage());
}
}
public function initPath()
{
try {
$result = (new WxOrderPathService())->updatePath();
$this->success('订单详情路径已配置', null, $result);
} catch (\Exception $e) {
$msg = $e->getMessage();
if (preg_match('/\((\d{8})\)/', $msg, $m)) {
$msg .= ' — ' . WxOrderPathService::explainPathError($m[1]);
}
$this->error('配置失败:' . $msg);
}
}
}

查看文件

@@ -0,0 +1,49 @@
<?php
namespace app\admin\controller\shopro_wechat_trade;
use addons\shopro_wechat_trade\library\WxShippingService;
use app\common\controller\Backend;
use think\Db;
class Sync extends Backend
{
public function index()
{
if ($this->request->isAjax()) {
$page = max(1, intval($this->request->get('page', 1)));
$limit = max(1, min(100, intval($this->request->get('limit', 20))));
$status = trim($this->request->get('status', ''));
$query = Db::name('shopro_wechat_trade_sync')->order('id', 'desc');
if ($status !== '') {
$query->where('status', $status);
}
$total = $query->count();
$list = $query->page($page, $limit)->select();
return json(['total' => $total, 'rows' => $list]);
}
return $this->view->fetch();
}
public function retry()
{
$id = intval($this->request->post('id'));
$row = Db::name('shopro_wechat_trade_sync')->where('id', $id)->find();
if (!$row) {
$this->error('记录不存在');
}
try {
$service = new WxShippingService();
if ($row['sync_type'] === 'confirm') {
$service->syncOrderConfirm($row['order_id']);
} else {
$service->syncOrderShipping($row['order_id'], $row['order_item_id']);
}
$this->success('重试成功');
} catch (\Exception $e) {
$this->error('重试失败:' . $e->getMessage());
}
}
}

查看文件

@@ -0,0 +1,30 @@
<link rel="stylesheet" href="__CDN__/assets/addons/shopro/libs/element/element.css">
<div id="wxTradeConfigIndex" v-cloak style="padding:20px;max-width:960px;">
<el-form label-width="180px">
<el-divider content-position="left">微信交易合规</el-divider>
<el-form-item label="功能开关">
<el-switch v-model="form.wechat_trade_enable" active-value="1" inactive-value="0"></el-switch>
</el-form-item>
<el-form-item label="订单详情路径">
<el-input v-model="form.order_detail_path" placeholder="pages/order/detail?id=${商品订单号}"></el-input>
</el-form-item>
<el-form-item label="失败最大重试">
<el-input v-model="form.max_retry"></el-input>
</el-form-item>
<el-form-item label="重试间隔(秒)">
<el-input v-model="form.retry_interval"></el-input>
</el-form-item>
<el-form-item label="小程序AppID">
<el-input v-model="form.mini_program_app_id" readonly></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="save">保存</el-button>
<el-button @click="check">检测接入状态</el-button>
<el-button @click="initPath">初始化订单路径</el-button>
</el-form-item>
<el-alert v-if="checkResult" :title="checkResult" type="info" show-icon :closable="false" style="margin-top:10px;"></el-alert>
</el-form>
</div>
<script src="__CDN__/assets/addons/shopro/libs/vue.js"></script>
<script src="__CDN__/assets/addons/shopro/libs/element/element.js"></script>
<script src="__CDN__/assets/js/backend/shopro_wechat_trade/config.js"></script>

查看文件

@@ -0,0 +1,14 @@
<div class="panel panel-default panel-intro">
<div class="panel-heading">微信发货/确认收货同步日志</div>
<div class="panel-body">
<div id="toolbar" class="toolbar">
<select id="status-filter" class="form-control" style="width:160px;display:inline-block;">
<option value="">全部状态</option>
<option value="pending">pending</option>
<option value="success">success</option>
<option value="failed">failed</option>
</select>
</div>
<table id="table" class="table table-striped table-bordered table-hover" width="100%"></table>
</div>
</div>

查看文件

@@ -0,0 +1,26 @@
<?php
namespace addons\shopro_wechat_trade\command;
use addons\shopro_wechat_trade\library\WxShippingService;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
class BackfillShipping extends Command
{
protected function configure()
{
$this->setName('shopro_wechat_trade:backfill')
->addOption('limit', null, Option::VALUE_OPTIONAL, 'Max orders', 50)
->setDescription('Backfill WeChat shipping info for shipped orders');
}
protected function execute(Input $input, Output $output)
{
$limit = intval($input->getOption('limit') ?: 50);
$count = (new WxShippingService())->backfillShippedOrders($limit);
$output->writeln('Backfill attempted for ' . $count . ' order(s).');
}
}

查看文件

@@ -0,0 +1,34 @@
<?php
namespace addons\shopro_wechat_trade\command;
use addons\shopro_wechat_trade\library\WxOrderPathService;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class InitOrderPath extends Command
{
protected function configure()
{
$this->setName('shopro_wechat_trade:init-path')
->setDescription('Configure WeChat mini program order detail path');
}
protected function execute(Input $input, Output $output)
{
try {
$result = (new WxOrderPathService())->updatePath();
$output->writeln('Order detail path configured. errcode=0');
if (!empty($result['path'])) {
$output->writeln('path=' . $result['path']);
}
} catch (\Exception $e) {
$output->writeln('Failed: ' . $e->getMessage());
$output->writeln('');
$output->writeln('若 errcode=10060035:请先发布含 pages/order/detail 的小程序到微信线上/提审版,再重试。');
$output->writeln('发货同步(upload_shipping_info)不依赖本接口,可先配置发货管理并测试发货。');
$output->writeln('诊断: php think shopro_wechat_trade:probe-path');
}
}
}

查看文件

@@ -0,0 +1,23 @@
<?php
namespace addons\shopro_wechat_trade\command;
use addons\shopro_wechat_trade\library\Installer;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class InstallFull extends Command
{
protected function configure()
{
$this->setName('shopro_wechat_trade:install')
->setDescription('Install/repair shopro_wechat_trade plugin');
}
protected function execute(Input $input, Output $output)
{
Installer::run($output);
$output->writeln('Run: php think shopro_wechat_trade:verify');
}
}

查看文件

@@ -0,0 +1,66 @@
<?php
namespace addons\shopro_wechat_trade\command;
use addons\shopro_wechat_trade\library\WxOrderPathService;
use addons\shopro_wechat_trade\library\WxTradeConfig;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
class ProbeOrderPath extends Command
{
protected function configure()
{
$this->setName('shopro_wechat_trade:probe-path')
->setDescription('Diagnose WeChat order detail path (10060035)');
}
protected function execute(Input $input, Output $output)
{
$output->writeln('=== 微信订单详情 path 诊断 ===');
$mini = Db::name('shopro_config')->where('name', 'wxMiniProgram')->value('value');
$mini = json_decode($mini, true);
$appId = $mini['app_id'] ?? '';
$output->writeln('小程序 AppID(商城配置): ' . ($appId ?: '(未配置)'));
$config = WxTradeConfig::getInstance();
$path = WxOrderPathService::normalizePath($config->getOrderDetailPath());
$output->writeln('待配置 path: ' . $path);
$pathService = new WxOrderPathService();
try {
$current = $pathService->getPath();
$output->writeln('当前已配置 path: ' . ($current['path'] ?? '(空)'));
} catch (\Exception $e) {
$output->writeln('查询当前 path 失败: ' . $e->getMessage());
}
try {
$managed = $pathService->isTradeManaged();
$output->writeln('is_trade_managed: ' . json_encode($managed, JSON_UNESCAPED_UNICODE));
} catch (\Exception $e) {
$output->writeln('is_trade_managed 失败: ' . $e->getMessage());
}
$output->writeln('');
$output->writeln('尝试 update_order_detail_path ...');
try {
$result = $pathService->updatePath($path);
$output->writeln('[OK] 配置成功: ' . json_encode($result, JSON_UNESCAPED_UNICODE));
} catch (\Exception $e) {
$output->writeln('[FAIL] ' . $e->getMessage());
$output->writeln('');
$output->writeln('10060035 常见原因(按概率):');
$output->writeln(' 1. 小程序「线上版」或「审核中版本」里没有 pages/order/detail —— 须先上传并提审/发布');
$output->writeln(' 2. 商城配置的 AppID 与当前要开通能力的小程序不一致');
$output->writeln(' 3. 可在微信后台手动填 path,不必强依赖 API');
$output->writeln('');
$output->writeln('说明:upload_shipping_info 发货同步不依赖本 path;path 仅用于「购物订单」跳转详情');
$output->writeln('建议 path: pages/order/detail?id=${商品订单号}');
}
}
}

查看文件

@@ -0,0 +1,26 @@
<?php
namespace addons\shopro_wechat_trade\command;
use addons\shopro_wechat_trade\library\WxShippingService;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
class RetryFailed extends Command
{
protected function configure()
{
$this->setName('shopro_wechat_trade:retry-failed')
->addOption('limit', null, Option::VALUE_OPTIONAL, 'Max rows', 50)
->setDescription('Retry failed WeChat trade sync records');
}
protected function execute(Input $input, Output $output)
{
$limit = intval($input->getOption('limit') ?: 50);
$count = (new WxShippingService())->retryFailed($limit);
$output->writeln('Retried ' . $count . ' sync record(s).');
}
}

查看文件

@@ -0,0 +1,42 @@
<?php
namespace addons\shopro_wechat_trade\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
class VerifyInstall extends Command
{
protected function configure()
{
$this->setName('shopro_wechat_trade:verify')
->setDescription('Verify shopro_wechat_trade plugin installation');
}
protected function execute(Input $input, Output $output)
{
$checks = [
'addon_dir' => is_dir(ADDON_PATH . 'shopro_wechat_trade'),
'hooks' => is_file(ADDON_PATH . 'shopro_wechat_trade/hooks.php'),
'config_tbl' => $this->tableExists('shopro_wechat_trade_config'),
'sync_tbl' => $this->tableExists('shopro_wechat_trade_sync'),
'enabled' => intval(get_addon_info('shopro_wechat_trade')['state'] ?? 0) === 1,
];
foreach ($checks as $name => $ok) {
$output->writeln(sprintf('[%s] %s', $ok ? 'OK' : 'FAIL', $name));
}
}
protected function tableExists($name)
{
try {
Db::name($name)->limit(1)->select();
return true;
} catch (\Exception $e) {
return false;
}
}
}

查看文件

@@ -0,0 +1,11 @@
<?php
return [
[
'name' => 'status',
'title' => '插件状态',
'type' => 'radio',
'content' => ['0' => '禁用', '1' => '启用'],
'value' => '1',
],
];

查看文件

@@ -0,0 +1,30 @@
<?php
return [
[
'type' => 'file',
'name' => 'shopro_wechat_trade/config',
'title' => '微信交易合规',
'icon' => 'fa fa-wechat',
'ismenu' => 1,
'weigh' => 4,
'sublist' => [
['type' => 'file', 'name' => 'shopro_wechat_trade/config/index', 'title' => '配置', 'ismenu' => 0],
['type' => 'file', 'name' => 'shopro_wechat_trade/config/save', 'title' => '保存', 'ismenu' => 0],
['type' => 'file', 'name' => 'shopro_wechat_trade/config/check', 'title' => '检测', 'ismenu' => 0],
['type' => 'file', 'name' => 'shopro_wechat_trade/config/initPath', 'title' => '初始化路径', 'ismenu' => 0],
[
'type' => 'file',
'name' => 'shopro_wechat_trade/sync',
'title' => '同步日志',
'icon' => 'fa fa-list',
'ismenu' => 1,
'weigh' => 3,
'sublist' => [
['type' => 'file', 'name' => 'shopro_wechat_trade/sync/index', 'title' => '查看', 'ismenu' => 0],
['type' => 'file', 'name' => 'shopro_wechat_trade/sync/retry', 'title' => '重试', 'ismenu' => 0],
],
],
],
],
];

查看文件

@@ -0,0 +1,6 @@
<?php
return [
'order_send_after' => ['addons\\shopro_wechat_trade\\listener\\ShippingHook'],
'order_confirm_after' => ['addons\\shopro_wechat_trade\\listener\\ConfirmHook'],
];

查看文件

@@ -0,0 +1,10 @@
name = shopro_wechat_trade
title = Shopro微信交易合规
intro = 微信小程序购物订单与发货信息同步
author = Shopro
website = https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/business-capabilities/order_center/order_center.html
version = 1.0.0
state = 0
url = /addons/shopro_wechat_trade
first_menu = shopro_wechat_trade/config
license = regular

查看文件

@@ -0,0 +1,39 @@
-- Shopro 微信交易合规插件
CREATE TABLE IF NOT EXISTS `__PREFIX__shopro_wechat_trade_config` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`value` text,
`group` varchar(50) DEFAULT 'basic',
`description` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信交易合规配置';
CREATE TABLE IF NOT EXISTS `__PREFIX__shopro_wechat_trade_sync` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` int(11) NOT NULL DEFAULT 0,
`order_sn` varchar(64) NOT NULL DEFAULT '',
`order_item_id` int(11) NOT NULL DEFAULT 0,
`sync_type` varchar(16) NOT NULL DEFAULT 'shipping' COMMENT 'shipping/confirm',
`status` varchar(16) NOT NULL DEFAULT 'pending' COMMENT 'pending/success/failed',
`delivery_mode` tinyint(1) NOT NULL DEFAULT 1,
`request_payload` text,
`response_payload` text,
`errcode` int(11) DEFAULT NULL,
`errmsg` varchar(255) DEFAULT NULL,
`retry_count` int(11) NOT NULL DEFAULT 0,
`next_retry_time` int(10) DEFAULT NULL,
`createtime` int(10) NOT NULL,
`updatetime` int(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `order_id` (`order_id`),
KEY `order_sn` (`order_sn`),
KEY `status_retry` (`status`, `next_retry_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微信发货/确认收货同步日志';
INSERT IGNORE INTO `__PREFIX__shopro_wechat_trade_config` (`name`, `value`, `group`, `description`) VALUES
('wechat_trade_enable', '1', 'basic', '微信交易合规总开关'),
('order_detail_path', 'pages/order/detail?id=${商品订单号}', 'basic', '购物订单跳转路径'),
('max_retry', '5', 'basic', '失败最大重试次数'),
('retry_interval', '300', 'basic', '重试间隔秒');

查看文件

@@ -0,0 +1,28 @@
<?php
namespace addons\shopro_wechat_trade\job;
use addons\shopro_wechat_trade\library\WxShippingService;
use think\queue\Job;
class WxConfirmJob
{
public function notify(Job $job, $data)
{
try {
$orderId = intval($data['order_id'] ?? 0);
if ($orderId <= 0) {
$job->delete();
return;
}
(new WxShippingService())->syncOrderConfirm($orderId);
$job->delete();
} catch (\Exception $e) {
if ($job->attempts() >= 3) {
$job->delete();
} else {
$job->release(60);
}
}
}
}

查看文件

@@ -0,0 +1,29 @@
<?php
namespace addons\shopro_wechat_trade\job;
use addons\shopro_wechat_trade\library\WxShippingService;
use think\queue\Job;
class WxShippingJob
{
public function upload(Job $job, $data)
{
try {
$orderId = intval($data['order_id'] ?? 0);
$itemId = intval($data['order_item_id'] ?? 0);
if ($orderId <= 0) {
$job->delete();
return;
}
(new WxShippingService())->syncOrderShipping($orderId, $itemId);
$job->delete();
} catch (\Exception $e) {
if ($job->attempts() >= 3) {
$job->delete();
} else {
$job->release(60);
}
}
}
}

查看文件

@@ -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;
}
}

查看文件

@@ -0,0 +1,34 @@
<?php
namespace addons\shopro_wechat_trade\listener;
use addons\shopro\model\OrderItem;
use addons\shopro_wechat_trade\library\Bridge;
class ConfirmHook
{
public function orderConfirmAfter(&$params)
{
if (!Bridge::isEnabled()) {
return;
}
$order = $params['order'] ?? null;
if (!$order || !Bridge::shouldHandleOrder($order)) {
return;
}
$noConfirm = OrderItem::where('order_id', $order['id'])
->where('dispatch_status', '<>', OrderItem::DISPATCH_STATUS_GETED)
->count();
if ($noConfirm > 0) {
return;
}
\think\Queue::push(
'\\addons\\shopro_wechat_trade\\job\\WxConfirmJob@notify',
['order_id' => $order['id']],
'shopro'
);
}
}

查看文件

@@ -0,0 +1,30 @@
<?php
namespace addons\shopro_wechat_trade\listener;
use addons\shopro_wechat_trade\library\Bridge;
class ShippingHook
{
public function orderSendAfter(&$params)
{
if (!Bridge::isEnabled()) {
return;
}
$order = $params['order'] ?? null;
$item = $params['item'] ?? null;
if (!$order || !$item || !Bridge::shouldHandleOrder($order)) {
return;
}
\think\Queue::push(
'\\addons\\shopro_wechat_trade\\job\\WxShippingJob@upload',
[
'order_id' => $order['id'],
'order_item_id' => $item['id'],
],
'shopro'
);
}
}

查看文件

@@ -0,0 +1,51 @@
define(['jquery', 'bootstrap', 'backend', 'form'], function ($, undefined, Backend, Form) {
var Controller = {
index: function () {
new Vue({
el: '#wxTradeConfigIndex',
data: {
form: {
wechat_trade_enable: '1',
order_detail_path: 'pages/order/detail?id=${商品订单号}',
max_retry: '5',
retry_interval: '300',
mini_program_app_id: ''
},
checkResult: ''
},
mounted: function () {
var vm = this;
$.getJSON('shopro_wechat_trade/config/index', function (ret) {
if (ret.code === 1 && ret.data) {
vm.form = Object.assign(vm.form, ret.data);
}
});
},
methods: {
save: function () {
var vm = this;
$.post('shopro_wechat_trade/config/save', { row: vm.form }, function (ret) {
Backend.api.toastr[ret.code === 1 ? 'success' : 'error'](ret.msg);
});
},
check: function () {
var vm = this;
$.getJSON('shopro_wechat_trade/config/check', function (ret) {
if (ret.code === 1) {
vm.checkResult = JSON.stringify(ret.data, null, 2);
} else {
Backend.api.toastr.error(ret.msg);
}
});
},
initPath: function () {
$.post('shopro_wechat_trade/config/initPath', {}, function (ret) {
Backend.api.toastr[ret.code === 1 ? 'success' : 'error'](ret.msg);
});
}
}
});
}
};
return Controller;
});

查看文件

@@ -0,0 +1,68 @@
define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
var Controller = {
index: function () {
Table.api.init({
extend: {
index_url: 'shopro_wechat_trade/sync/index',
table: 'shopro_wechat_trade_sync'
}
});
var table = $("#table");
table.bootstrapTable({
url: $.fn.bootstrapTable.defaults.extend.index_url,
pk: 'id',
sortName: 'id',
sortOrder: 'desc',
queryParams: function (params) {
params.status = $('#status-filter').val();
return params;
},
columns: [
{ field: 'id', title: 'ID' },
{ field: 'order_sn', title: '订单号' },
{ field: 'sync_type', title: '类型' },
{ field: 'status', title: '状态' },
{ field: 'delivery_mode', title: '发货模式' },
{ field: 'errcode', title: 'errcode' },
{ field: 'errmsg', title: 'errmsg' },
{ field: 'retry_count', title: '重试次数' },
{
field: 'createtime',
title: '创建时间',
formatter: function (value) {
return value ? Table.api.formatter.datetime(value) : '';
}
},
{
field: 'operate',
title: '操作',
table: table,
events: Table.api.events.operate,
formatter: function (value, row) {
if (row.status === 'success') {
return '-';
}
return '<a href="javascript:;" class="btn btn-xs btn-warning btn-retry" data-id="' + row.id + '">重试</a>';
}
}
]
});
$('#status-filter').on('change', function () {
table.bootstrapTable('refresh');
});
table.on('click', '.btn-retry', function () {
var id = $(this).data('id');
$.post('shopro_wechat_trade/sync/retry', { id: id }, function (ret) {
Backend.api.toastr[ret.code === 1 ? 'success' : 'error'](ret.msg);
table.bootstrapTable('refresh');
});
});
Table.api.bindevent(table);
}
};
return Controller;
});

查看文件

@@ -0,0 +1,2 @@
DROP TABLE IF EXISTS `__PREFIX__shopro_wechat_trade_config`;
DROP TABLE IF EXISTS `__PREFIX__shopro_wechat_trade_sync`;