feat: 初始化雄戈商城服务端代码与Webhook自动部署配置
这个提交包含在:
@@ -0,0 +1,19 @@
|
||||
# Shopro 阿里云快递查询插件
|
||||
|
||||
对接阿里云云市场全国快递查询接口(cmapi00066593),支持 Provider 切换:
|
||||
|
||||
- `aliyun`:阿里云全国快递(`https://expr.market.alicloudapi.com/query`)
|
||||
- `kdniao`:快递鸟官方 API
|
||||
- `expressbird`:阿里云市场快递鸟 8002
|
||||
|
||||
## 安装
|
||||
|
||||
1. FastAdmin 后台 → 插件管理 → 安装 `shopro_aliyun_express`
|
||||
2. 或 CLI:`php think shopro_aliyun_express:install`(需已在 `application/command.php` 注册命令类)
|
||||
3. 进入 **Shopro → 阿里云快递查询 → 配置**,填写 APPCODE 并选择 Provider
|
||||
|
||||
## API
|
||||
|
||||
- 小程序包裹详情:`GET /addons/shopro/order_express/detail`(内部走 Bridge)
|
||||
- 独立查询:`GET /addons/shopro_aliyun_express/express/query?waybill_number=&phone=`
|
||||
- 后台测试:`POST /admin/shopro_aliyun_express/config/test`
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express;
|
||||
|
||||
use addons\shopro_aliyun_express\library\Installer;
|
||||
use app\common\library\Menu;
|
||||
use think\Addons;
|
||||
|
||||
class Shopro_aliyun_express 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_aliyun_express');
|
||||
Menu::delete('shopro_aliyun_express/config');
|
||||
Menu::delete('shopro_aliyun_express/query');
|
||||
return true;
|
||||
}
|
||||
|
||||
public function enable()
|
||||
{
|
||||
Menu::enable('shopro_aliyun_express/config');
|
||||
Menu::enable('shopro_aliyun_express/query');
|
||||
return true;
|
||||
}
|
||||
|
||||
public function disable()
|
||||
{
|
||||
Menu::disable('shopro_aliyun_express/config');
|
||||
Menu::disable('shopro_aliyun_express/query');
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace app\admin\controller\shopro_aliyun_express;
|
||||
|
||||
use addons\shopro_aliyun_express\library\ExpressConfig;
|
||||
use addons\shopro_aliyun_express\library\ExpressQueryService;
|
||||
use app\common\controller\Backend;
|
||||
use think\Db;
|
||||
|
||||
class Config extends Backend
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
if ($this->request->isAjax()) {
|
||||
$data = ExpressConfig::getInstance()->all();
|
||||
$defaults = [
|
||||
'express_enable' => '1',
|
||||
'express_provider' => 'aliyun',
|
||||
'aliyun_appcode' => '',
|
||||
'aliyun_api_url' => '',
|
||||
'aliyun_api_mode' => 'auto',
|
||||
'aliyun_http_method' => 'auto',
|
||||
'expressbird_appcode' => '',
|
||||
'cache_ttl' => '300',
|
||||
];
|
||||
return $this->success('操作成功', null, array_merge($defaults, $data));
|
||||
}
|
||||
return $this->view->fetch();
|
||||
}
|
||||
|
||||
public function save()
|
||||
{
|
||||
$params = $this->request->post('row/a');
|
||||
if (!$params) {
|
||||
$this->error('参数错误');
|
||||
}
|
||||
|
||||
$allowed = [
|
||||
'express_enable',
|
||||
'express_provider',
|
||||
'aliyun_appcode',
|
||||
'aliyun_api_url',
|
||||
'aliyun_api_mode',
|
||||
'aliyun_http_method',
|
||||
'expressbird_appcode',
|
||||
'cache_ttl',
|
||||
];
|
||||
|
||||
foreach ($allowed as $name) {
|
||||
if (!array_key_exists($name, $params)) {
|
||||
continue;
|
||||
}
|
||||
$exists = Db::name('shopro_aliyun_express_config')->where('name', $name)->find();
|
||||
if ($exists) {
|
||||
Db::name('shopro_aliyun_express_config')->where('name', $name)->update(['value' => $params[$name]]);
|
||||
} else {
|
||||
Db::name('shopro_aliyun_express_config')->insert(['name' => $name, 'value' => $params[$name]]);
|
||||
}
|
||||
}
|
||||
|
||||
ExpressConfig::reload();
|
||||
$this->success('保存成功');
|
||||
}
|
||||
|
||||
public function test()
|
||||
{
|
||||
$waybillNo = trim($this->request->post('waybill_number', ''));
|
||||
$phone = trim($this->request->post('phone', ''));
|
||||
$expressCode = trim($this->request->post('express_code', ''));
|
||||
$provider = trim($this->request->post('express_provider', ''));
|
||||
|
||||
if ($waybillNo === '') {
|
||||
$this->error('请填写快递单号');
|
||||
}
|
||||
|
||||
try {
|
||||
$service = new ExpressQueryService();
|
||||
$normalized = $service->queryTrack($waybillNo, $phone, $expressCode, $provider ?: null, false);
|
||||
if (empty($normalized['success'])) {
|
||||
$raw = !empty($normalized['raw']) ? json_encode($normalized['raw'], JSON_UNESCAPED_UNICODE) : '';
|
||||
$this->error('测试查询失败:未获取到有效轨迹' . ($raw ? ':' . mb_substr($raw, 0, 300) : ''));
|
||||
}
|
||||
$this->success('测试查询成功', null, $normalized);
|
||||
} catch (\think\exception\HttpResponseException $e) {
|
||||
throw $e;
|
||||
} catch (\Throwable $e) {
|
||||
$msg = trim($e->getMessage());
|
||||
$this->error('测试查询失败:' . ($msg !== '' ? $msg : get_class($e)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace app\admin\controller\shopro_aliyun_express;
|
||||
|
||||
use addons\shopro_aliyun_express\library\Bridge;
|
||||
use addons\shopro_aliyun_express\library\ExpressConfig;
|
||||
use app\admin\model\shopro\order\OrderExpress;
|
||||
use app\common\controller\Backend;
|
||||
|
||||
class Query extends Backend
|
||||
{
|
||||
/**
|
||||
* 按包裹ID查询轨迹
|
||||
*/
|
||||
public function index()
|
||||
{
|
||||
$expressId = intval($this->request->get('express_id', 0));
|
||||
if ($expressId <= 0) {
|
||||
$this->error('请提供 express_id');
|
||||
}
|
||||
|
||||
if (!ExpressConfig::getInstance()->isEnabled()) {
|
||||
$this->error('快递查询插件未启用');
|
||||
}
|
||||
|
||||
$orderExpress = OrderExpress::with('order')->where('id', $expressId)->find();
|
||||
if (!$orderExpress) {
|
||||
$this->error('包裹不存在');
|
||||
}
|
||||
|
||||
$phone = $orderExpress->order ? $orderExpress->order->phone : '';
|
||||
try {
|
||||
$result = Bridge::queryTrack($orderExpress['express_no'], $phone, $orderExpress['express_code'], false);
|
||||
$this->success('查询成功', null, $result);
|
||||
} catch (\think\exception\HttpResponseException $e) {
|
||||
throw $e;
|
||||
} catch (\Throwable $e) {
|
||||
$msg = trim($e->getMessage());
|
||||
$this->error($msg !== '' ? $msg : '查询失败');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<link rel="stylesheet" href="__CDN__/assets/addons/shopro/libs/element/element.css">
|
||||
<style>
|
||||
.express-test-result { margin-top: 16px; }
|
||||
.express-test-summary { margin-bottom: 16px; }
|
||||
.express-test-summary .el-descriptions { margin-top: 8px; }
|
||||
.express-test-timeline { max-height: 420px; overflow-y: auto; padding-right: 8px; }
|
||||
.express-test-timeline .trace-time { font-size: 13px; color: #909399; margin-bottom: 4px; }
|
||||
.express-test-timeline .trace-desc { font-size: 14px; color: #303133; line-height: 1.6; }
|
||||
.express-test-timeline .trace-location { font-size: 12px; color: #606266; margin-top: 4px; }
|
||||
.express-test-empty { color: #909399; text-align: center; padding: 24px 0; }
|
||||
</style>
|
||||
<div id="aliyunExpressConfigIndex" 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.express_enable" active-value="1" inactive-value="0"></el-switch>
|
||||
</el-form-item>
|
||||
<el-form-item label="查询 Provider">
|
||||
<el-select v-model="form.express_provider" placeholder="请选择">
|
||||
<el-option label="阿里云全国快递" value="aliyun"></el-option>
|
||||
<el-option label="快递鸟官方" value="kdniao"></el-option>
|
||||
<el-option label="ExpressBird(阿里云市场快递鸟)" value="expressbird"></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="轨迹缓存(秒)">
|
||||
<el-input v-model="form.cache_ttl" placeholder="建议 300"></el-input>
|
||||
</el-form-item>
|
||||
|
||||
<template v-if="form.express_provider === 'aliyun'">
|
||||
<el-divider content-position="left">阿里云全国快递配置</el-divider>
|
||||
<el-alert type="warning" show-icon :closable="false" style="margin-bottom:16px;"
|
||||
title="接口地址必须从云市场 → 已购买服务 → 该商品 →「API 调试」复制完整 URL(含域名和路径)。"></el-alert>
|
||||
<el-form-item label="APPCODE">
|
||||
<el-input v-model="form.aliyun_appcode" placeholder="云市场 AppCode 页签"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="接口地址">
|
||||
<el-input v-model="form.aliyun_api_url" placeholder="从 API 调试页复制完整 URL"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="接口模板">
|
||||
<el-select v-model="form.aliyun_api_mode" placeholder="请选择">
|
||||
<el-option label="自动(GET/POST 都试)" value="auto"></el-option>
|
||||
<el-option label="快证 kzexpress (expressNo+mobile)" value="kzexpress"></el-option>
|
||||
<el-option label="文档 expr POST (waybillNumber)" value="expr_post"></el-option>
|
||||
<el-option label="文档 expr GET (waybillNumber)" value="expr_get"></el-option>
|
||||
<el-option label="wuliu/kdi (no+type=auto)" value="wuliu_kdi"></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="请求方式">
|
||||
<el-select v-model="form.aliyun_http_method" placeholder="auto 时先 GET 再 POST">
|
||||
<el-option label="自动" value="auto"></el-option>
|
||||
<el-option label="GET" value="get"></el-option>
|
||||
<el-option label="POST" value="post"></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
</template>
|
||||
|
||||
<template v-if="form.express_provider === 'expressbird'">
|
||||
<el-divider content-position="left">ExpressBird 配置</el-divider>
|
||||
<el-form-item label="APPCODE">
|
||||
<el-input v-model="form.expressbird_appcode" placeholder="ExpressBird APPCODE"></el-input>
|
||||
</el-form-item>
|
||||
</template>
|
||||
|
||||
<el-alert v-if="form.express_provider === 'kdniao'" type="info" show-icon :closable="false" style="margin-bottom:16px;"
|
||||
title="快递鸟官方 API 请在 Shopro → 第三方服务 → 快递配置 中填写 ebusiness_id 与 appkey。"></el-alert>
|
||||
|
||||
<el-divider content-position="left">测试查询</el-divider>
|
||||
<el-form-item label="快递单号">
|
||||
<el-input v-model="testForm.waybill_number" placeholder="快递单号"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item label="手机号/后四位">
|
||||
<el-input v-model="testForm.phone" placeholder="顺丰/中通建议填写后四位"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="form.express_provider === 'kdniao'" label="快递公司编码">
|
||||
<el-input v-model="testForm.express_code" placeholder="快递鸟 Provider 时必填,如 SF"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" @click="save">保存配置</el-button>
|
||||
<el-button type="success" :loading="testLoading" @click="testQuery">测试查询</el-button>
|
||||
</el-form-item>
|
||||
|
||||
<div v-if="testError" class="express-test-result">
|
||||
<el-alert :title="testError" type="error" show-icon :closable="false"></el-alert>
|
||||
</div>
|
||||
|
||||
<div v-if="testData" class="express-test-result">
|
||||
<el-card shadow="never" class="express-test-summary">
|
||||
<div slot="header" class="clearfix">
|
||||
<span>查询结果</span>
|
||||
<el-tag size="mini" type="success" style="float:right;" v-if="testData.success">查询成功</el-tag>
|
||||
</div>
|
||||
<el-descriptions :column="2" border size="small">
|
||||
<el-descriptions-item label="快递公司">{{ testData.expressCompanyName || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="公司编码">{{ testData.expressCompanyCode || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="运单号">{{ testData.expressNo || testForm.waybill_number || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="物流状态">
|
||||
<el-tag size="mini" type="warning" v-if="testData.expressStatus">{{ testData.expressStatus }}</el-tag>
|
||||
<span v-else>-</span>
|
||||
</el-descriptions-item>
|
||||
<el-descriptions-item label="最新时间" :span="2">{{ testData.lastTime || '-' }}</el-descriptions-item>
|
||||
<el-descriptions-item label="最新描述" :span="2">{{ testData.lastDescription || '-' }}</el-descriptions-item>
|
||||
</el-descriptions>
|
||||
</el-card>
|
||||
|
||||
<el-card shadow="never" style="margin-bottom:12px;">
|
||||
<div slot="header">物流轨迹({{ (testData.trackList || []).length }} 条)</div>
|
||||
<div v-if="!(testData.trackList || []).length" class="express-test-empty">暂无轨迹节点</div>
|
||||
<el-timeline v-else class="express-test-timeline">
|
||||
<el-timeline-item
|
||||
v-for="(item, index) in testData.trackList"
|
||||
:key="index"
|
||||
:timestamp="item.AcceptTime"
|
||||
placement="top">
|
||||
<div class="trace-desc">{{ item.AcceptStation || '—' }}</div>
|
||||
<div class="trace-location" v-if="item.Location">{{ item.Location }}</div>
|
||||
</el-timeline-item>
|
||||
</el-timeline>
|
||||
</el-card>
|
||||
|
||||
<el-collapse>
|
||||
<el-collapse-item title="查看原始 JSON(调试)" name="raw">
|
||||
<pre style="max-height:320px;overflow:auto;background:#f5f7fa;padding:12px;border-radius:4px;font-size:12px;line-height:1.5;">{{ testRawJson }}</pre>
|
||||
</el-collapse-item>
|
||||
</el-collapse>
|
||||
</div>
|
||||
</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_aliyun_express/config.js"></script>
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\command;
|
||||
|
||||
use addons\shopro_aliyun_express\library\Installer;
|
||||
use think\console\Command;
|
||||
use think\console\Input;
|
||||
use think\console\Output;
|
||||
|
||||
class InstallFull extends Command
|
||||
{
|
||||
protected function configure()
|
||||
{
|
||||
$this->setName('shopro_aliyun_express:install')
|
||||
->setDescription('安装 Shopro 阿里云快递查询插件');
|
||||
}
|
||||
|
||||
protected function execute(Input $input, Output $output)
|
||||
{
|
||||
Installer::run($output);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
[
|
||||
'name' => 'status',
|
||||
'title' => '插件状态',
|
||||
'type' => 'radio',
|
||||
'content' => ['0' => '禁用', '1' => '启用'],
|
||||
'value' => '1',
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
[
|
||||
'type' => 'file',
|
||||
'name' => 'shopro_aliyun_express/config',
|
||||
'title' => '阿里云快递查询',
|
||||
'icon' => 'fa fa-truck',
|
||||
'ismenu' => 1,
|
||||
'weigh' => 5,
|
||||
'sublist' => [
|
||||
['type' => 'file', 'name' => 'shopro_aliyun_express/config/index', 'title' => '配置', 'ismenu' => 0],
|
||||
['type' => 'file', 'name' => 'shopro_aliyun_express/config/save', 'title' => '保存', 'ismenu' => 0],
|
||||
['type' => 'file', 'name' => 'shopro_aliyun_express/config/test', 'title' => '测试查询', 'ismenu' => 0],
|
||||
[
|
||||
'type' => 'file',
|
||||
'name' => 'shopro_aliyun_express/query',
|
||||
'title' => '轨迹查询',
|
||||
'icon' => 'fa fa-search',
|
||||
'ismenu' => 1,
|
||||
'weigh' => 4,
|
||||
'sublist' => [
|
||||
['type' => 'file', 'name' => 'shopro_aliyun_express/query/index', 'title' => '查询', 'ismenu' => 0],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\controller;
|
||||
|
||||
use addons\shopro\controller\Base;
|
||||
use addons\shopro_aliyun_express\library\Bridge;
|
||||
use addons\shopro_aliyun_express\library\ExpressConfig;
|
||||
|
||||
class Express extends Base
|
||||
{
|
||||
protected $noNeedLogin = [];
|
||||
protected $noNeedRight = ['*'];
|
||||
|
||||
/**
|
||||
* 独立快递查询 API(小程序/调试)
|
||||
* GET waybill_number, phone, express_code(可选)
|
||||
*/
|
||||
public function query()
|
||||
{
|
||||
if (!ExpressConfig::getInstance()->isEnabled()) {
|
||||
$this->error('快递查询插件未启用');
|
||||
}
|
||||
|
||||
$waybillNo = trim($this->request->get('waybill_number', ''));
|
||||
$phone = trim($this->request->get('phone', ''));
|
||||
$expressCode = trim($this->request->get('express_code', ''));
|
||||
|
||||
if ($waybillNo === '') {
|
||||
$this->error('请提供快递单号');
|
||||
}
|
||||
|
||||
try {
|
||||
$result = Bridge::queryTrack($waybillNo, $phone, $expressCode, false);
|
||||
$this->success('查询成功', $result);
|
||||
} catch (\Exception $e) {
|
||||
$this->error($e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
name = shopro_aliyun_express
|
||||
title = Shopro阿里云快递查询
|
||||
intro = 对接阿里云云市场全国快递查询接口,支持多Provider切换
|
||||
author = Shopro
|
||||
website = https://market.aliyun.com/detail/cmapi00066593
|
||||
version = 1.0.0
|
||||
state = 0
|
||||
url = /addons/shopro_aliyun_express
|
||||
first_menu = shopro_aliyun_express/config
|
||||
license = regular
|
||||
@@ -0,0 +1,36 @@
|
||||
-- Shopro 阿里云快递查询插件
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `__PREFIX__shopro_aliyun_express_config` (
|
||||
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`name` varchar(50) NOT NULL,
|
||||
`value` text,
|
||||
`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_aliyun_express_query_log` (
|
||||
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`provider` varchar(32) NOT NULL DEFAULT '',
|
||||
`waybill_number` varchar(64) NOT NULL DEFAULT '',
|
||||
`phone` varchar(20) NOT NULL DEFAULT '',
|
||||
`express_code` varchar(32) NOT NULL DEFAULT '',
|
||||
`status_code` int(11) NOT NULL DEFAULT 0,
|
||||
`success` tinyint(1) NOT NULL DEFAULT 0,
|
||||
`message` varchar(255) NOT NULL DEFAULT '',
|
||||
`duration_ms` int(11) NOT NULL DEFAULT 0,
|
||||
`createtime` int(10) NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `waybill_number` (`waybill_number`),
|
||||
KEY `createtime` (`createtime`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='快递查询日志';
|
||||
|
||||
INSERT IGNORE INTO `__PREFIX__shopro_aliyun_express_config` (`name`, `value`, `description`) VALUES
|
||||
('express_enable', '1', '快递查询总开关'),
|
||||
('express_provider', 'aliyun', '查询Provider: aliyun/kdniao/expressbird'),
|
||||
('aliyun_appcode', '', '阿里云APPCODE'),
|
||||
('aliyun_api_url', '', '阿里云查询完整URL,从云市场API调试复制'),
|
||||
('aliyun_api_mode', 'auto', '接口模板 auto/expr_post/expr_get/wuliu_kdi'),
|
||||
('aliyun_http_method', 'auto', 'HTTP方法 auto/get/post'),
|
||||
('expressbird_appcode', '', 'ExpressBird APPCODE'),
|
||||
('cache_ttl', '300', '轨迹缓存秒数');
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\library;
|
||||
|
||||
use fast\ExpressBird;
|
||||
|
||||
class Bridge
|
||||
{
|
||||
public static function isEnabled()
|
||||
{
|
||||
return ExpressConfig::getInstance()->isEnabled();
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一轨迹查询入口
|
||||
*/
|
||||
public static function queryTrack($waybillNo, $phone = '', $expressCode = '', $useCache = true)
|
||||
{
|
||||
$waybillNo = ExpressSanitizer::waybillNo($waybillNo);
|
||||
$phone = ExpressSanitizer::phone($phone);
|
||||
$expressCode = ExpressSanitizer::expressCode($expressCode);
|
||||
|
||||
if ($waybillNo === '') {
|
||||
throw new \Exception('快递单号不能为空');
|
||||
}
|
||||
|
||||
if (self::isEnabled()) {
|
||||
$service = new ExpressQueryService();
|
||||
return $service->queryTrack($waybillNo, $phone, $expressCode, null, $useCache);
|
||||
}
|
||||
|
||||
return self::fallbackQuery($waybillNo, $phone);
|
||||
}
|
||||
|
||||
/**
|
||||
* 兼容旧 ExpressBird 返回格式(Success + Traces)
|
||||
*/
|
||||
public static function queryTrackLegacy($waybillNo, $phone = '', $expressCode = '', $useCache = true)
|
||||
{
|
||||
if (self::isEnabled()) {
|
||||
$service = new ExpressQueryService();
|
||||
$normalized = $service->queryTrack($waybillNo, $phone, $expressCode, null, $useCache);
|
||||
return $service->toKdniaoExpressFormat($normalized);
|
||||
}
|
||||
|
||||
return self::fallbackQueryLegacy($waybillNo, $phone);
|
||||
}
|
||||
|
||||
protected static function fallbackQuery($waybillNo, $phone)
|
||||
{
|
||||
$legacy = self::fallbackQueryLegacy($waybillNo, $phone);
|
||||
return [
|
||||
'success' => !empty($legacy['Success']),
|
||||
'trackList' => TrackNormalizer::fixDeliveringIcons($legacy['Traces'] ?? []),
|
||||
'expressStatus' => '',
|
||||
'expressCompanyName' => '',
|
||||
'expressCompanyCode' => '',
|
||||
'provider' => 'expressbird',
|
||||
];
|
||||
}
|
||||
|
||||
protected static function fallbackQueryLegacy($waybillNo, $phone)
|
||||
{
|
||||
$bird = new ExpressBird();
|
||||
return $bird->queryTrack($waybillNo, $phone);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\library;
|
||||
|
||||
use think\Db;
|
||||
|
||||
class ExpressConfig
|
||||
{
|
||||
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_aliyun_express_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 isEnabled()
|
||||
{
|
||||
if ($this->get('express_enable', '1') !== '1') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 已写入插件配置表则视为可用(避免 info.ini state=0 时业务 API 与后台测试行为不一致)
|
||||
try {
|
||||
if (\think\Db::name('shopro_aliyun_express_config')->count() > 0) {
|
||||
return true;
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
// ignore
|
||||
}
|
||||
|
||||
if (!function_exists('get_addon_info')) {
|
||||
return false;
|
||||
}
|
||||
$info = get_addon_info('shopro_aliyun_express');
|
||||
return $info && intval($info['state'] ?? 0) === 1;
|
||||
}
|
||||
|
||||
public function getProvider()
|
||||
{
|
||||
$provider = strtolower(trim($this->get('express_provider', 'aliyun')));
|
||||
if (!in_array($provider, ['aliyun', 'kdniao', 'expressbird'], true)) {
|
||||
return 'aliyun';
|
||||
}
|
||||
return $provider;
|
||||
}
|
||||
|
||||
public function getCacheTtl()
|
||||
{
|
||||
$ttl = intval($this->get('cache_ttl', 300));
|
||||
return $ttl > 0 ? $ttl : 300;
|
||||
}
|
||||
|
||||
public function getAliyunAppcode()
|
||||
{
|
||||
return trim($this->get('aliyun_appcode', ''));
|
||||
}
|
||||
|
||||
public function getAliyunApiUrl()
|
||||
{
|
||||
$url = trim($this->get('aliyun_api_url', ''));
|
||||
return $url;
|
||||
}
|
||||
|
||||
public function getAliyunApiMode()
|
||||
{
|
||||
$mode = strtolower(trim($this->get('aliyun_api_mode', 'auto')));
|
||||
$allowed = ['auto', 'expr_post', 'expr_get', 'wuliu_kdi', 'kzexpress'];
|
||||
return in_array($mode, $allowed, true) ? $mode : 'auto';
|
||||
}
|
||||
|
||||
public function getAliyunHttpMethod()
|
||||
{
|
||||
$method = strtolower(trim($this->get('aliyun_http_method', 'auto')));
|
||||
return in_array($method, ['auto', 'get', 'post'], true) ? $method : 'auto';
|
||||
}
|
||||
|
||||
public function getExpressBirdAppcode()
|
||||
{
|
||||
return trim($this->get('expressbird_appcode', ''));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\library;
|
||||
|
||||
use addons\shopro_aliyun_express\library\provider\AliyunExpressProvider;
|
||||
use addons\shopro_aliyun_express\library\provider\ExpressBirdProvider;
|
||||
use addons\shopro_aliyun_express\library\provider\KdniaoExpressProvider;
|
||||
use addons\shopro_aliyun_express\library\provider\ProviderInterface;
|
||||
|
||||
class ExpressProviderRouter
|
||||
{
|
||||
public static function resolve($provider = null)
|
||||
{
|
||||
$provider = $provider ?: ExpressConfig::getInstance()->getProvider();
|
||||
|
||||
switch ($provider) {
|
||||
case 'kdniao':
|
||||
return new KdniaoExpressProvider();
|
||||
case 'expressbird':
|
||||
return new ExpressBirdProvider();
|
||||
case 'aliyun':
|
||||
default:
|
||||
return new AliyunExpressProvider();
|
||||
}
|
||||
}
|
||||
|
||||
public static function query($waybillNo, $phone = '', $expressCode = '', $provider = null)
|
||||
{
|
||||
/** @var ProviderInterface $instance */
|
||||
$instance = self::resolve($provider);
|
||||
return $instance->query($waybillNo, $phone, $expressCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\library;
|
||||
|
||||
use think\Cache;
|
||||
|
||||
class ExpressQueryService
|
||||
{
|
||||
protected $config;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->config = ExpressConfig::getInstance();
|
||||
}
|
||||
|
||||
public function queryTrack($waybillNo, $phone = '', $expressCode = '', $provider = null, $useCache = true)
|
||||
{
|
||||
$waybillNo = ExpressSanitizer::waybillNo($waybillNo);
|
||||
$phone = ExpressSanitizer::phone($phone);
|
||||
$expressCode = ExpressSanitizer::expressCode($expressCode);
|
||||
if ($waybillNo === '') {
|
||||
throw new \Exception('快递单号不能为空');
|
||||
}
|
||||
|
||||
$provider = $provider ?: $this->config->getProvider();
|
||||
$cacheKey = $this->buildCacheKey($provider, $waybillNo, $phone, $expressCode);
|
||||
|
||||
if ($useCache) {
|
||||
$cached = Cache::get($cacheKey);
|
||||
if (is_array($cached)) {
|
||||
return $cached;
|
||||
}
|
||||
}
|
||||
|
||||
$started = microtime(true);
|
||||
$providerResult = null;
|
||||
$errorMessage = '';
|
||||
|
||||
try {
|
||||
$providerResult = ExpressProviderRouter::query($waybillNo, $phone, $expressCode, $provider);
|
||||
$normalized = TrackNormalizer::normalize($providerResult);
|
||||
$normalized['trackList'] = TrackNormalizer::fixDeliveringIcons($normalized['trackList']);
|
||||
$normalized['provider'] = $provider;
|
||||
$normalized['raw'] = $providerResult['raw'] ?? null;
|
||||
|
||||
QueryLogger::log(
|
||||
$provider,
|
||||
$waybillNo,
|
||||
$phone,
|
||||
$expressCode,
|
||||
!empty($normalized['success']),
|
||||
200,
|
||||
'ok',
|
||||
(int) round((microtime(true) - $started) * 1000)
|
||||
);
|
||||
|
||||
if ($useCache && !empty($normalized['success'])) {
|
||||
Cache::set($cacheKey, $normalized, $this->config->getCacheTtl());
|
||||
}
|
||||
|
||||
return $normalized;
|
||||
} catch (\Exception $e) {
|
||||
$errorMessage = $e->getMessage();
|
||||
QueryLogger::log(
|
||||
$provider,
|
||||
$waybillNo,
|
||||
$phone,
|
||||
$expressCode,
|
||||
false,
|
||||
500,
|
||||
$errorMessage,
|
||||
(int) round((microtime(true) - $started) * 1000)
|
||||
);
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function toKdniaoExpressFormat(array $normalized)
|
||||
{
|
||||
return [
|
||||
'Success' => !empty($normalized['success']),
|
||||
'Traces' => $normalized['trackList'] ?? [],
|
||||
'State' => self::guessStateFromTrackList($normalized['trackList'] ?? []),
|
||||
'Reason' => $normalized['success'] ? '' : '查询失败',
|
||||
];
|
||||
}
|
||||
|
||||
protected static function guessStateFromTrackList(array $trackList)
|
||||
{
|
||||
if (empty($trackList)) {
|
||||
return '0';
|
||||
}
|
||||
$action = $trackList[0]['Action'] ?? 2;
|
||||
if (in_array($action, [3, 304], true)) {
|
||||
return '3';
|
||||
}
|
||||
if ($action == 4) {
|
||||
return '4';
|
||||
}
|
||||
if ($action == 1) {
|
||||
return '1';
|
||||
}
|
||||
return '2';
|
||||
}
|
||||
|
||||
protected function buildCacheKey($provider, $waybillNo, $phone, $expressCode)
|
||||
{
|
||||
return 'shopro_aliyun_express:' . md5(implode('|', [$provider, $waybillNo, $phone, $expressCode]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\library;
|
||||
|
||||
class ExpressSanitizer
|
||||
{
|
||||
/**
|
||||
* 清理运单号(去除空格、换行等)
|
||||
*/
|
||||
public static function waybillNo($value)
|
||||
{
|
||||
$value = (string) $value;
|
||||
$value = preg_replace('/[\s\x{00A0}\x{3000}]+/u', '', $value);
|
||||
return trim($value);
|
||||
}
|
||||
|
||||
public static function phone($value)
|
||||
{
|
||||
return trim(preg_replace('/[\s\x{00A0}\x{3000}]+/u', '', (string) $value));
|
||||
}
|
||||
|
||||
public static function expressCode($value)
|
||||
{
|
||||
$value = self::waybillNo($value);
|
||||
return strtoupper($value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\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_aliyun_express' . DS;
|
||||
$name = 'shopro_aliyun_express';
|
||||
|
||||
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, '注册 CLI 命令...');
|
||||
self::registerCliCommand($output);
|
||||
|
||||
self::log($output, '注册菜单...');
|
||||
self::installMenu($output);
|
||||
|
||||
\app\common\library\Menu::enable('shopro_aliyun_express/config');
|
||||
\app\common\library\Menu::enable('shopro_aliyun_express/query');
|
||||
self::grantRulesToShoproGroups($output);
|
||||
self::clearMenuCache();
|
||||
self::setAddonState($name, 1, $output);
|
||||
|
||||
Service::refresh();
|
||||
self::log($output, '安装完成: /admin/shopro_aliyun_express/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_aliyun_express' . 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_aliyun_express/config', ['shopro_aliyun_express']);
|
||||
\app\common\library\Menu::refresh('shopro_aliyun_express', $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_aliyun_express/config'),
|
||||
\app\common\library\Menu::getAuthRuleIdsByName('shopro_aliyun_express/query')
|
||||
);
|
||||
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 registerCliCommand($output = null)
|
||||
{
|
||||
$commandClass = 'addons\\shopro_aliyun_express\\command\\InstallFull';
|
||||
$commandFile = ROOT_PATH . 'application' . DS . 'command.php';
|
||||
if (!is_file($commandFile)) {
|
||||
self::log($output, ' [warn] application/command.php 不存在,跳过 CLI 注册');
|
||||
return;
|
||||
}
|
||||
|
||||
$content = file_get_contents($commandFile);
|
||||
if (strpos($content, $commandClass) !== false) {
|
||||
return;
|
||||
}
|
||||
|
||||
$entry = " '" . $commandClass . "',\n";
|
||||
if (preg_match('/\];\s*$/', $content)) {
|
||||
$content = preg_replace('/\];\s*$/', $entry . "];\n", $content);
|
||||
} else {
|
||||
$content = rtrim($content) . "\n" . $entry;
|
||||
}
|
||||
|
||||
file_put_contents($commandFile, $content, LOCK_EX);
|
||||
self::log($output, '已注册 php think shopro_aliyun_express:install');
|
||||
}
|
||||
|
||||
protected static function log($output, $message)
|
||||
{
|
||||
if ($output) {
|
||||
$output->writeln($message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\library;
|
||||
|
||||
use think\Db;
|
||||
|
||||
class QueryLogger
|
||||
{
|
||||
public static function log($provider, $waybillNo, $phone, $expressCode, $success, $statusCode, $message, $durationMs)
|
||||
{
|
||||
try {
|
||||
Db::name('shopro_aliyun_express_query_log')->insert([
|
||||
'provider' => $provider,
|
||||
'waybill_number' => $waybillNo,
|
||||
'phone' => self::maskPhone($phone),
|
||||
'express_code' => $expressCode,
|
||||
'status_code' => intval($statusCode),
|
||||
'success' => $success ? 1 : 0,
|
||||
'message' => mb_substr((string) $message, 0, 255),
|
||||
'duration_ms' => intval($durationMs),
|
||||
'createtime' => time(),
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
// ignore logging failures
|
||||
}
|
||||
}
|
||||
|
||||
protected static function maskPhone($phone)
|
||||
{
|
||||
$phone = trim((string) $phone);
|
||||
if (strlen($phone) <= 4) {
|
||||
return $phone;
|
||||
}
|
||||
return str_repeat('*', max(0, strlen($phone) - 4)) . substr($phone, -4);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\library;
|
||||
|
||||
class TrackNormalizer
|
||||
{
|
||||
/**
|
||||
* 将 Provider 原始响应归一化为统一 trackList
|
||||
*/
|
||||
public static function normalize(array $providerResult)
|
||||
{
|
||||
$provider = $providerResult['provider'] ?? '';
|
||||
switch ($provider) {
|
||||
case 'aliyun':
|
||||
return self::fromAliyun($providerResult);
|
||||
case 'kdniao':
|
||||
case 'expressbird':
|
||||
return self::fromKdniao($providerResult);
|
||||
default:
|
||||
return [
|
||||
'success' => false,
|
||||
'trackList' => [],
|
||||
'expressStatus' => '',
|
||||
'expressCompanyName' => '',
|
||||
'expressCompanyCode' => '',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
protected static function fromAliyun(array $providerResult)
|
||||
{
|
||||
$root = $providerResult['raw'] ?? ($providerResult['data'] ?? []);
|
||||
|
||||
// kzexpress:logisticsTraceDetailList / logisticsTraceDetails
|
||||
$dataBlock = $root['data'] ?? $root;
|
||||
$traceDetails = self::pickKzexpressTraceList($dataBlock);
|
||||
if (!empty($traceDetails)) {
|
||||
return self::fromKzexpressTrace($providerResult, $dataBlock, $traceDetails);
|
||||
}
|
||||
|
||||
// 文档格式:data.logisticsEvents
|
||||
if (!empty($root['data']['logisticsEvents'])) {
|
||||
return self::fromExprLogisticsEvents($providerResult, $root['data']);
|
||||
}
|
||||
|
||||
// wuliu.market alicloudapi.com/kdi
|
||||
if (!empty($root['result']['list'])) {
|
||||
return self::fromWuliuResult($providerResult, $root['result'], $root);
|
||||
}
|
||||
|
||||
// expQuery 等:data[] 含 context/time
|
||||
if (!empty($root['data']) && is_array($root['data']) && isset($root['data'][0]['context'])) {
|
||||
return self::fromExpQueryData($providerResult, $root);
|
||||
}
|
||||
|
||||
$data = $root['data'] ?? $root;
|
||||
if (!empty($data['logisticsEvents'])) {
|
||||
return self::fromExprLogisticsEvents($providerResult, $data);
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => !empty($providerResult['success']),
|
||||
'trackList' => [],
|
||||
'expressStatus' => is_string($data['status'] ?? null) ? $data['status'] : '',
|
||||
'expressCompanyName' => $data['expressCompanyName'] ?? ($root['expTextName'] ?? ''),
|
||||
'expressCompanyCode' => $data['expressCompany'] ?? ($root['expSpellName'] ?? ''),
|
||||
'lastDescription' => $root['msg'] ?? '',
|
||||
'lastTime' => '',
|
||||
];
|
||||
}
|
||||
|
||||
protected static function pickKzexpressTraceList(array $data)
|
||||
{
|
||||
foreach (['logisticsTraceDetailList', 'logisticsTraceDetails', 'logisticsTraceDetail'] as $key) {
|
||||
if (!empty($data[$key]) && is_array($data[$key])) {
|
||||
return $data[$key];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
protected static function fromKzexpressTrace(array $providerResult, array $data, array $traceDetails)
|
||||
{
|
||||
$trackList = [];
|
||||
foreach ($traceDetails as $item) {
|
||||
$time = $item['timeDesc'] ?? '';
|
||||
if ($time === '' && !empty($item['time']) && is_numeric($item['time'])) {
|
||||
$ts = (string) $item['time'];
|
||||
if (strlen($ts) >= 13) {
|
||||
$time = date('Y-m-d H:i:s', (int) floor($item['time'] / 1000));
|
||||
} elseif (strlen($ts) === 10) {
|
||||
$time = date('Y-m-d H:i:s', (int) $item['time']);
|
||||
}
|
||||
}
|
||||
|
||||
$desc = trim((string) ($item['desc'] ?? ($item['description'] ?? '')));
|
||||
if ($desc === '') {
|
||||
$area = trim((string) ($item['areaName'] ?? ($item['location'] ?? '')));
|
||||
$statusText = trim((string) ($item['subLogisticsStatus'] ?? ($item['logisticsStatus'] ?? '')));
|
||||
$desc = trim($area . ($statusText !== '' ? ' ' . $statusText : ''));
|
||||
}
|
||||
|
||||
$trackList[] = [
|
||||
'AcceptTime' => $time,
|
||||
'AcceptStation' => $desc,
|
||||
'Location' => $item['areaName'] ?? ($item['city'] ?? ''),
|
||||
'Action' => self::mapAliyunStateToAction($item['logisticsStatus'] ?? ($item['subLogisticsStatus'] ?? '')),
|
||||
];
|
||||
}
|
||||
|
||||
usort($trackList, function ($a, $b) {
|
||||
return strcmp($b['AcceptTime'], $a['AcceptTime']);
|
||||
});
|
||||
|
||||
return [
|
||||
'success' => !empty($providerResult['success']),
|
||||
'trackList' => $trackList,
|
||||
'expressStatus' => $data['logisticsStatusDesc'] ?? ($data['logisticsStatus'] ?? ''),
|
||||
'expressCompanyName' => $data['logisticsCompanyName'] ?? ($data['cpName'] ?? ''),
|
||||
'expressCompanyCode' => $data['cpCode'] ?? '',
|
||||
'expressNo' => $data['mailNo'] ?? ($data['expressNo'] ?? ''),
|
||||
'lastDescription' => $data['theLastMessage'] ?? (!empty($trackList) ? ($trackList[0]['AcceptStation'] ?? '') : ''),
|
||||
'lastTime' => $data['theLastTime'] ?? (!empty($trackList) ? ($trackList[0]['AcceptTime'] ?? '') : ''),
|
||||
];
|
||||
}
|
||||
|
||||
protected static function fromExprLogisticsEvents(array $providerResult, array $data)
|
||||
{
|
||||
$trackList = [];
|
||||
foreach ($data['logisticsEvents'] ?? [] as $event) {
|
||||
$trackList[] = [
|
||||
'AcceptTime' => $event['date'] ?? '',
|
||||
'AcceptStation' => $event['description'] ?? '',
|
||||
'Location' => $event['location'] ?? ($event['city'] ?? ''),
|
||||
'Action' => self::mapAliyunStateToAction($event['state'] ?? ''),
|
||||
];
|
||||
}
|
||||
usort($trackList, function ($a, $b) {
|
||||
return strcmp($b['AcceptTime'], $a['AcceptTime']);
|
||||
});
|
||||
|
||||
return [
|
||||
'success' => !empty($providerResult['success']),
|
||||
'trackList' => $trackList,
|
||||
'expressStatus' => $data['status'] ?? '',
|
||||
'expressCompanyName' => $data['expressCompanyName'] ?? '',
|
||||
'expressCompanyCode' => $data['expressCompany'] ?? '',
|
||||
'lastDescription' => $data['lastDescription'] ?? '',
|
||||
'lastTime' => $data['lastTime'] ?? '',
|
||||
];
|
||||
}
|
||||
|
||||
protected static function fromWuliuResult(array $providerResult, array $result, array $root)
|
||||
{
|
||||
$trackList = [];
|
||||
foreach ($result['list'] ?? [] as $item) {
|
||||
$trackList[] = [
|
||||
'AcceptTime' => $item['time'] ?? ($item['ftime'] ?? ''),
|
||||
'AcceptStation' => $item['status'] ?? ($item['context'] ?? ''),
|
||||
'Location' => $item['location'] ?? '',
|
||||
'Action' => self::mapAliyunStateToAction($item['status'] ?? ''),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => !empty($providerResult['success']),
|
||||
'trackList' => $trackList,
|
||||
'expressStatus' => $result['deliverystatus'] ?? ($root['msg'] ?? ''),
|
||||
'expressCompanyName' => $result['expName'] ?? ($result['type'] ?? ''),
|
||||
'expressCompanyCode' => $result['type'] ?? '',
|
||||
'lastDescription' => !empty($trackList) ? ($trackList[0]['AcceptStation'] ?? '') : '',
|
||||
'lastTime' => !empty($trackList) ? ($trackList[0]['AcceptTime'] ?? '') : '',
|
||||
];
|
||||
}
|
||||
|
||||
protected static function fromExpQueryData(array $providerResult, array $root)
|
||||
{
|
||||
$trackList = [];
|
||||
foreach ($root['data'] as $item) {
|
||||
$trackList[] = [
|
||||
'AcceptTime' => $item['time'] ?? '',
|
||||
'AcceptStation' => $item['context'] ?? '',
|
||||
'Location' => $item['location'] ?? '',
|
||||
'Action' => self::mapAliyunStateToAction($item['status'] ?? ''),
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
'success' => !empty($providerResult['success']),
|
||||
'trackList' => $trackList,
|
||||
'expressStatus' => $root['updateStr'] ?? ($root['msg'] ?? ''),
|
||||
'expressCompanyName' => $root['expTextName'] ?? '',
|
||||
'expressCompanyCode' => $root['expSpellName'] ?? '',
|
||||
'lastDescription' => !empty($trackList) ? ($trackList[0]['AcceptStation'] ?? '') : '',
|
||||
'lastTime' => !empty($trackList) ? ($trackList[0]['AcceptTime'] ?? '') : '',
|
||||
];
|
||||
}
|
||||
|
||||
protected static function fromKdniao(array $providerResult)
|
||||
{
|
||||
$data = $providerResult['data'] ?? [];
|
||||
$traces = $data['Traces'] ?? [];
|
||||
$trackList = [];
|
||||
|
||||
foreach ($traces as $trace) {
|
||||
$trackList[] = [
|
||||
'AcceptTime' => $trace['AcceptTime'] ?? '',
|
||||
'AcceptStation' => $trace['AcceptStation'] ?? '',
|
||||
'Location' => $trace['Location'] ?? '',
|
||||
'Action' => $trace['Action'] ?? ($data['State'] ?? 0),
|
||||
];
|
||||
}
|
||||
|
||||
$statusMap = [
|
||||
'0' => '暂无轨迹',
|
||||
'1' => '已揽收',
|
||||
'2' => '运输中',
|
||||
'3' => '已签收',
|
||||
'4' => '问题件',
|
||||
];
|
||||
$state = (string) ($data['State'] ?? '');
|
||||
|
||||
return [
|
||||
'success' => !empty($providerResult['success']),
|
||||
'trackList' => $trackList,
|
||||
'expressStatus' => $statusMap[$state] ?? '',
|
||||
'expressCompanyName' => $data['ShipperCode'] ?? '',
|
||||
'expressCompanyCode' => $data['ShipperCode'] ?? '',
|
||||
'lastDescription' => !empty($trackList) ? ($trackList[0]['AcceptStation'] ?? '') : '',
|
||||
'lastTime' => !empty($trackList) ? ($trackList[0]['AcceptTime'] ?? '') : '',
|
||||
];
|
||||
}
|
||||
|
||||
public static function mapAliyunStateToAction($state)
|
||||
{
|
||||
$state = trim((string) $state);
|
||||
$map = [
|
||||
'已揽收' => 1,
|
||||
'收件扫描' => 1,
|
||||
'ACCEPT' => 1,
|
||||
'运送中' => 2,
|
||||
'运输中' => 2,
|
||||
'转运中' => 2,
|
||||
'入中转' => 2,
|
||||
'出中转' => 2,
|
||||
'TRANSPORT'=> 2,
|
||||
'派送中' => 202,
|
||||
'待派送' => 202,
|
||||
'DELIVERING' => 202,
|
||||
'已签收' => 3,
|
||||
'SIGN' => 3,
|
||||
'STA_SIGN' => 3,
|
||||
'AGENT_SIGN' => 304,
|
||||
'第三方代收' => 304,
|
||||
'AGENT_SIGN' => 304,
|
||||
'问题件' => 4,
|
||||
'拒收' => 4,
|
||||
'退回件' => 4,
|
||||
'FAILED' => 4,
|
||||
];
|
||||
|
||||
if (isset($map[$state])) {
|
||||
return $map[$state];
|
||||
}
|
||||
|
||||
foreach ($map as $keyword => $action) {
|
||||
if ($state !== '' && mb_strpos($state, $keyword) !== false) {
|
||||
return $action;
|
||||
}
|
||||
}
|
||||
|
||||
return 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* 修正派件图标(与原 OrderExpress::detail 逻辑一致)
|
||||
*/
|
||||
public static function fixDeliveringIcons(array $trackList)
|
||||
{
|
||||
if (empty($trackList)) {
|
||||
return $trackList;
|
||||
}
|
||||
|
||||
foreach ($trackList as $k => &$v) {
|
||||
if (($v['Action'] ?? null) == 202) {
|
||||
if ($k >= 2) {
|
||||
$trackList[$k - 2]['Action'] = 3;
|
||||
$trackList[$k - 1]['Action'] = 4;
|
||||
}
|
||||
}
|
||||
}
|
||||
unset($v);
|
||||
|
||||
return $trackList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\library\provider;
|
||||
|
||||
use addons\shopro_aliyun_express\library\ExpressConfig;
|
||||
|
||||
class AliyunExpressProvider implements ProviderInterface
|
||||
{
|
||||
protected $config;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->config = ExpressConfig::getInstance();
|
||||
}
|
||||
|
||||
public function getName()
|
||||
{
|
||||
return 'aliyun';
|
||||
}
|
||||
|
||||
public function query($waybillNo, $phone = '', $expressCode = '')
|
||||
{
|
||||
$appcode = $this->config->getAliyunAppcode();
|
||||
if ($appcode === '') {
|
||||
throw new \Exception('请配置阿里云 APPCODE');
|
||||
}
|
||||
|
||||
$apiUrl = $this->config->getAliyunApiUrl();
|
||||
if ($apiUrl === '') {
|
||||
throw new \Exception('请填写「接口地址」(从云市场该商品 API 调试页复制完整 URL)');
|
||||
}
|
||||
|
||||
$phoneParam = $this->resolvePhone($waybillNo, $phone);
|
||||
$attempts = $this->buildAttempts($waybillNo, $phone, $phoneParam, $expressCode);
|
||||
|
||||
$errors = [];
|
||||
foreach ($attempts as $attempt) {
|
||||
try {
|
||||
$http = $this->sendHttp($appcode, $attempt);
|
||||
$parsed = $this->parseResponseBody($http['body']);
|
||||
if (!$this->isBusinessSuccess($parsed)) {
|
||||
throw new \Exception($this->extractBusinessError($parsed));
|
||||
}
|
||||
|
||||
return [
|
||||
'provider' => $this->getName(),
|
||||
'success' => true,
|
||||
'raw' => $parsed,
|
||||
'data' => $parsed,
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
$label = ($attempt['label'] ?? 'request') . ' [' . ($attempt['method'] ?? '') . ' ' . ($attempt['url'] ?? '') . ']';
|
||||
$errors[] = $label . ':' . $e->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
$message = implode(';', $errors);
|
||||
if ($message === '') {
|
||||
$message = '阿里云快递查询失败';
|
||||
}
|
||||
throw new \Exception($message);
|
||||
}
|
||||
|
||||
protected function buildAttempts($waybillNo, $phone, $phoneParam, $expressCode)
|
||||
{
|
||||
$mode = $this->config->getAliyunApiMode();
|
||||
$apiUrl = $this->config->getAliyunApiUrl();
|
||||
$httpMethod = strtolower($this->config->getAliyunHttpMethod());
|
||||
|
||||
if ($mode === 'auto' && $this->isKzexpressUrl($apiUrl)) {
|
||||
$mode = 'kzexpress';
|
||||
}
|
||||
|
||||
if ($mode === 'kzexpress') {
|
||||
$params = $this->kzexpressParams($waybillNo, $phone, $phoneParam, $expressCode);
|
||||
$attempts = [
|
||||
['label' => 'kzexpress_get', 'method' => 'GET', 'url' => $apiUrl, 'query' => $params],
|
||||
['label' => 'kzexpress_post', 'method' => 'POST', 'url' => $apiUrl, 'body' => $params],
|
||||
];
|
||||
if ($httpMethod === 'get') {
|
||||
return [ $attempts[0] ];
|
||||
}
|
||||
if ($httpMethod === 'post') {
|
||||
return [ $attempts[1] ];
|
||||
}
|
||||
return $attempts;
|
||||
}
|
||||
|
||||
if ($mode === 'wuliu_kdi') {
|
||||
$url = $apiUrl !== '' && stripos($apiUrl, 'wuliu') !== false
|
||||
? $apiUrl
|
||||
: 'https://wuliu.market.alicloudapi.com/kdi';
|
||||
return [[
|
||||
'label' => 'wuliu_kdi',
|
||||
'method' => 'GET',
|
||||
'url' => $url,
|
||||
'query' => array_filter([
|
||||
'no' => $waybillNo,
|
||||
'type' => $expressCode !== '' ? strtolower($expressCode) : 'auto',
|
||||
]),
|
||||
]];
|
||||
}
|
||||
|
||||
if ($mode === 'expr_get') {
|
||||
return [[
|
||||
'label' => 'expr_get',
|
||||
'method' => 'GET',
|
||||
'url' => $apiUrl,
|
||||
'query' => $this->exprParams($waybillNo, $phoneParam),
|
||||
]];
|
||||
}
|
||||
|
||||
if ($mode === 'expr_post') {
|
||||
return [[
|
||||
'label' => 'expr_post',
|
||||
'method' => 'POST',
|
||||
'url' => $apiUrl,
|
||||
'body' => $this->exprParams($waybillNo, $phoneParam),
|
||||
]];
|
||||
}
|
||||
|
||||
// auto:按配置优先,404/格式错误时自动换 GET/POST
|
||||
$attempts = [];
|
||||
if ($httpMethod === 'get') {
|
||||
$attempts[] = ['label' => 'expr_get', 'method' => 'GET', 'url' => $apiUrl, 'query' => $this->exprParams($waybillNo, $phoneParam)];
|
||||
} elseif ($httpMethod === 'post') {
|
||||
$attempts[] = ['label' => 'expr_post', 'method' => 'POST', 'url' => $apiUrl, 'body' => $this->exprParams($waybillNo, $phoneParam)];
|
||||
} else {
|
||||
$attempts[] = ['label' => 'expr_get', 'method' => 'GET', 'url' => $apiUrl, 'query' => $this->exprParams($waybillNo, $phoneParam)];
|
||||
$attempts[] = ['label' => 'expr_post', 'method' => 'POST', 'url' => $apiUrl, 'body' => $this->exprParams($waybillNo, $phoneParam)];
|
||||
}
|
||||
|
||||
return $attempts;
|
||||
}
|
||||
|
||||
protected function isKzexpressUrl($url)
|
||||
{
|
||||
return stripos($url, 'kzexpress.market.alicloudapi.com') !== false
|
||||
|| stripos($url, '/api-mall/api/express/query') !== false;
|
||||
}
|
||||
|
||||
protected function kzexpressParams($waybillNo, $phone, $phoneParam, $expressCode)
|
||||
{
|
||||
$mobile = trim((string) $phone);
|
||||
if ($mobile === '' && $phoneParam !== '') {
|
||||
$mobile = $phoneParam;
|
||||
} elseif (strlen($mobile) > 4) {
|
||||
// 顺丰/京东等常用后四位;若接口需要完整手机号可改为不截取
|
||||
$mobile = substr($mobile, -4);
|
||||
}
|
||||
|
||||
$params = [
|
||||
'expressNo' => $waybillNo,
|
||||
];
|
||||
if ($mobile !== '') {
|
||||
$params['mobile'] = $mobile;
|
||||
}
|
||||
if ($expressCode !== '') {
|
||||
$params['cpCode'] = $expressCode;
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
protected function exprParams($waybillNo, $phoneParam)
|
||||
{
|
||||
return array_filter([
|
||||
'waybillNumber' => $waybillNo,
|
||||
'phoneNumber' => $phoneParam,
|
||||
'phone' => $phoneParam,
|
||||
'nu' => $waybillNo,
|
||||
'com' => 'auto',
|
||||
], function ($v) {
|
||||
return $v !== '' && $v !== null;
|
||||
});
|
||||
}
|
||||
|
||||
protected function sendHttp($appcode, array $attempt)
|
||||
{
|
||||
$method = strtoupper($attempt['method'] ?? 'GET');
|
||||
$url = trim($attempt['url'] ?? '');
|
||||
if ($url === '') {
|
||||
throw new \Exception('接口地址为空');
|
||||
}
|
||||
|
||||
$headers = [
|
||||
'Authorization: APPCODE ' . $appcode,
|
||||
'Accept: application/json',
|
||||
];
|
||||
|
||||
if ($method === 'GET') {
|
||||
$query = $attempt['query'] ?? [];
|
||||
if (!empty($query)) {
|
||||
$url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($query);
|
||||
}
|
||||
$postFields = null;
|
||||
} else {
|
||||
$body = $attempt['body'] ?? [];
|
||||
$postFields = is_array($body) ? http_build_query($body) : (string) $body;
|
||||
$headers[] = 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8';
|
||||
}
|
||||
|
||||
$ch = curl_init();
|
||||
$opts = [
|
||||
CURLOPT_URL => $url,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_CONNECTTIMEOUT => 10,
|
||||
CURLOPT_TIMEOUT => 15,
|
||||
CURLOPT_SSL_VERIFYPEER => false,
|
||||
CURLOPT_SSL_VERIFYHOST => false,
|
||||
CURLOPT_HTTPHEADER => $headers,
|
||||
];
|
||||
if ($method === 'POST') {
|
||||
$opts[CURLOPT_POST] = true;
|
||||
$opts[CURLOPT_POSTFIELDS] = $postFields;
|
||||
} else {
|
||||
$opts[CURLOPT_CUSTOMREQUEST] = 'GET';
|
||||
}
|
||||
curl_setopt_array($ch, $opts);
|
||||
|
||||
$response = curl_exec($ch);
|
||||
$errno = curl_errno($ch);
|
||||
$error = curl_error($ch);
|
||||
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($response === false || $errno) {
|
||||
throw new \Exception('网络错误 ' . ($error ?: ('errno ' . $errno)));
|
||||
}
|
||||
|
||||
if ($httpCode === 404) {
|
||||
throw new \Exception('HTTP 404 接口不存在,请核对云市场控制台中的完整 URL');
|
||||
}
|
||||
if ($httpCode >= 400) {
|
||||
$detail = $this->previewBody($response);
|
||||
if ($detail === '' && $response !== '') {
|
||||
$detail = $this->previewBody($response);
|
||||
}
|
||||
$jsonHint = json_decode($response, true);
|
||||
if (is_array($jsonHint)) {
|
||||
foreach (['msg', 'message', 'errorMsg', 'errMsg'] as $key) {
|
||||
if (!empty($jsonHint[$key])) {
|
||||
$detail = (string) $jsonHint[$key];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new \Exception('HTTP ' . $httpCode . ($detail !== '' ? ':' . $detail : '(请检查 expressNo/mobile 参数及 APPCODE)'));
|
||||
}
|
||||
|
||||
return ['body' => $response, 'http_code' => $httpCode];
|
||||
}
|
||||
|
||||
protected function parseResponseBody($body)
|
||||
{
|
||||
$body = trim((string) $body);
|
||||
if ($body === '') {
|
||||
throw new \Exception('返回空响应');
|
||||
}
|
||||
if (substr($body, 0, 3) === "\xEF\xBB\xBF") {
|
||||
$body = substr($body, 3);
|
||||
}
|
||||
$parsed = json_decode($body, true);
|
||||
if (!is_array($parsed)) {
|
||||
throw new \Exception('非 JSON:' . $this->previewBody($body));
|
||||
}
|
||||
return $parsed;
|
||||
}
|
||||
|
||||
protected function isBusinessSuccess(array $parsed)
|
||||
{
|
||||
if (array_key_exists('success', $parsed) && ($parsed['success'] === false || $parsed['success'] === 'false' || $parsed['success'] === 0)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isset($parsed['code']) && in_array((string) $parsed['code'], ['200', '0'], true)) {
|
||||
if (!empty($parsed['data']['logisticsTraceDetailList'])
|
||||
|| !empty($parsed['data']['logisticsTraceDetails'])
|
||||
|| !empty($parsed['logisticsTraceDetails'])) {
|
||||
return true;
|
||||
}
|
||||
if (!empty($parsed['data']['logisticsEvents']) || !empty($parsed['result']['list'])) {
|
||||
return true;
|
||||
}
|
||||
if (isset($parsed['data']) && is_array($parsed['data']) && !empty($parsed['data']['expressNo'])) {
|
||||
return true;
|
||||
}
|
||||
if (!isset($parsed['data']) || !array_key_exists('success', $parsed)) {
|
||||
return true;
|
||||
}
|
||||
return !empty($parsed['success']);
|
||||
}
|
||||
if (isset($parsed['status']) && (string) $parsed['status'] === '200') {
|
||||
return true;
|
||||
}
|
||||
if (isset($parsed['status']) && (string) $parsed['status'] === '0') {
|
||||
return true;
|
||||
}
|
||||
if (isset($parsed['ret_code']) && intval($parsed['ret_code']) === 0) {
|
||||
return true;
|
||||
}
|
||||
if (!empty($parsed['Success'])) {
|
||||
return true;
|
||||
}
|
||||
if (!empty($parsed['success']) && $parsed['success'] !== false) {
|
||||
return true;
|
||||
}
|
||||
if (!empty($parsed['data']['logisticsEvents']) || !empty($parsed['result']['list'])) {
|
||||
return true;
|
||||
}
|
||||
if (!empty($parsed['data']['logisticsTraceDetailList'])
|
||||
|| !empty($parsed['data']['logisticsTraceDetails'])
|
||||
|| !empty($parsed['logisticsTraceDetails'])) {
|
||||
return true;
|
||||
}
|
||||
if (isset($parsed['data']) && is_array($parsed['data']) && !empty($parsed['data']['mailNo'])) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
protected function extractBusinessError(array $parsed)
|
||||
{
|
||||
foreach (['msg', 'message', 'Reason', 'error_msg', 'errMsg', 'errorMsg'] as $key) {
|
||||
if (!empty($parsed[$key])) {
|
||||
return (string) $parsed[$key];
|
||||
}
|
||||
}
|
||||
if (!empty($parsed['data']['message'])) {
|
||||
return (string) $parsed['data']['message'];
|
||||
}
|
||||
if (isset($parsed['code']) && !in_array((string) $parsed['code'], ['200', '0'], true)) {
|
||||
return '接口返回 code=' . $parsed['code'];
|
||||
}
|
||||
return '业务返回失败';
|
||||
}
|
||||
|
||||
protected function previewBody($body)
|
||||
{
|
||||
$text = trim(strip_tags((string) $body));
|
||||
$text = preg_replace('/\s+/', ' ', $text);
|
||||
if (function_exists('mb_substr')) {
|
||||
return mb_substr($text, 0, 200);
|
||||
}
|
||||
return substr($text, 0, 200);
|
||||
}
|
||||
|
||||
protected function resolvePhone($waybillNo, $phone)
|
||||
{
|
||||
$phone = trim((string) $phone);
|
||||
if ($phone === '') {
|
||||
return '';
|
||||
}
|
||||
if (strlen($phone) >= 4) {
|
||||
return substr($phone, -4);
|
||||
}
|
||||
return $phone;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\library\provider;
|
||||
|
||||
use addons\shopro_aliyun_express\library\ExpressConfig;
|
||||
use fast\ExpressBird;
|
||||
|
||||
class ExpressBirdProvider implements ProviderInterface
|
||||
{
|
||||
public function getName()
|
||||
{
|
||||
return 'expressbird';
|
||||
}
|
||||
|
||||
public function query($waybillNo, $phone = '', $expressCode = '')
|
||||
{
|
||||
$appcode = ExpressConfig::getInstance()->getExpressBirdAppcode();
|
||||
if ($appcode === '') {
|
||||
throw new \Exception('请配置 ExpressBird APPCODE');
|
||||
}
|
||||
|
||||
$bird = new ExpressBird($appcode);
|
||||
$result = $bird->queryTrack($waybillNo, $phone);
|
||||
|
||||
return [
|
||||
'provider' => $this->getName(),
|
||||
'success' => !empty($result['Success']),
|
||||
'raw' => $result,
|
||||
'data' => $result,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\library\provider;
|
||||
|
||||
class KdniaoExpressProvider implements ProviderInterface
|
||||
{
|
||||
public function getName()
|
||||
{
|
||||
return 'kdniao';
|
||||
}
|
||||
|
||||
public function query($waybillNo, $phone = '', $expressCode = '')
|
||||
{
|
||||
if ($expressCode === '') {
|
||||
throw new \Exception('快递鸟查询需要快递公司编码');
|
||||
}
|
||||
|
||||
$expressLib = new \addons\shopro\library\Express();
|
||||
$order = (object) ['phone' => $phone, 'order_sn' => ''];
|
||||
|
||||
$result = $expressLib->search([
|
||||
'express_code' => $expressCode,
|
||||
'express_no' => $waybillNo,
|
||||
], null, $order);
|
||||
|
||||
return [
|
||||
'provider' => $this->getName(),
|
||||
'success' => !empty($result['Success']),
|
||||
'raw' => $result,
|
||||
'data' => $result,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace addons\shopro_aliyun_express\library\provider;
|
||||
|
||||
interface ProviderInterface
|
||||
{
|
||||
/**
|
||||
* 查询快递轨迹
|
||||
*
|
||||
* @param string $waybillNo 快递单号
|
||||
* @param string $phone 手机号或后四位
|
||||
* @param string $expressCode 快递公司编码(部分Provider需要)
|
||||
* @return array 原始Provider响应
|
||||
*/
|
||||
public function query($waybillNo, $phone = '', $expressCode = '');
|
||||
|
||||
/**
|
||||
* Provider标识
|
||||
*/
|
||||
public function getName();
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
define(['jquery', 'bootstrap', 'backend', 'form'], function ($, undefined, Backend, Form) {
|
||||
|
||||
var Controller = {
|
||||
|
||||
index: function () {
|
||||
|
||||
new Vue({
|
||||
|
||||
el: '#aliyunExpressConfigIndex',
|
||||
|
||||
data: {
|
||||
|
||||
form: {
|
||||
|
||||
express_enable: '1',
|
||||
|
||||
express_provider: 'aliyun',
|
||||
|
||||
aliyun_appcode: '',
|
||||
|
||||
aliyun_api_url: '',
|
||||
|
||||
aliyun_api_mode: 'auto',
|
||||
|
||||
aliyun_http_method: 'auto',
|
||||
|
||||
expressbird_appcode: '',
|
||||
|
||||
cache_ttl: '300'
|
||||
|
||||
},
|
||||
|
||||
testForm: {
|
||||
|
||||
waybill_number: '',
|
||||
|
||||
phone: '',
|
||||
|
||||
express_code: ''
|
||||
|
||||
},
|
||||
|
||||
testLoading: false,
|
||||
|
||||
testData: null,
|
||||
|
||||
testRawJson: '',
|
||||
|
||||
testError: ''
|
||||
|
||||
},
|
||||
|
||||
mounted: function () {
|
||||
|
||||
var vm = this;
|
||||
|
||||
$.getJSON('shopro_aliyun_express/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_aliyun_express/config/save', { row: vm.form }, function (ret) {
|
||||
|
||||
Backend.api.toastr[ret.code === 1 ? 'success' : 'error'](ret.msg);
|
||||
|
||||
});
|
||||
|
||||
},
|
||||
|
||||
testQuery: function () {
|
||||
|
||||
var vm = this;
|
||||
|
||||
if (!vm.testForm.waybill_number) {
|
||||
|
||||
Backend.api.toastr.error('请填写快递单号');
|
||||
|
||||
return;
|
||||
|
||||
}
|
||||
|
||||
vm.testLoading = true;
|
||||
|
||||
vm.testError = '';
|
||||
|
||||
vm.testData = null;
|
||||
|
||||
vm.testRawJson = '';
|
||||
|
||||
$.post('shopro_aliyun_express/config/test', {
|
||||
|
||||
waybill_number: vm.testForm.waybill_number,
|
||||
|
||||
phone: vm.testForm.phone,
|
||||
|
||||
express_code: vm.testForm.express_code,
|
||||
|
||||
express_provider: vm.form.express_provider
|
||||
|
||||
}, function (ret) {
|
||||
|
||||
vm.testLoading = false;
|
||||
|
||||
if (ret.code === 1) {
|
||||
|
||||
vm.testData = ret.data || null;
|
||||
|
||||
vm.testRawJson = JSON.stringify(ret.data, null, 2);
|
||||
|
||||
Backend.api.toastr.success(ret.msg || '测试查询成功');
|
||||
|
||||
} else {
|
||||
|
||||
vm.testError = ret.msg || '测试查询失败';
|
||||
|
||||
Backend.api.toastr.error(vm.testError);
|
||||
|
||||
}
|
||||
|
||||
}).fail(function () {
|
||||
|
||||
vm.testLoading = false;
|
||||
|
||||
vm.testError = '请求失败,请检查网络或登录状态';
|
||||
|
||||
Backend.api.toastr.error(vm.testError);
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
return Controller;
|
||||
|
||||
});
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/library/TrackNormalizer.php';
|
||||
|
||||
use addons\shopro_aliyun_express\library\TrackNormalizer;
|
||||
|
||||
$result = TrackNormalizer::normalize([
|
||||
'provider' => 'aliyun',
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'status' => '已签收',
|
||||
'expressCompanyName' => '顺丰速运',
|
||||
'logisticsEvents' => [
|
||||
[
|
||||
'date' => '2025-02-24 10:32:44',
|
||||
'location' => '北京',
|
||||
'description' => '已签收',
|
||||
'state' => '已签收',
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
assert($result['success'] === true);
|
||||
assert($result['trackList'][0]['Action'] === 3);
|
||||
assert($result['expressStatus'] === '已签收');
|
||||
|
||||
$kdniao = TrackNormalizer::normalize([
|
||||
'provider' => 'kdniao',
|
||||
'success' => true,
|
||||
'data' => [
|
||||
'Success' => true,
|
||||
'State' => '3',
|
||||
'Traces' => [
|
||||
[
|
||||
'AcceptTime' => '2025-02-24 10:32:44',
|
||||
'AcceptStation' => '签收',
|
||||
'Location' => '北京',
|
||||
'Action' => 3,
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
assert($kdniao['trackList'][0]['AcceptStation'] === '签收');
|
||||
|
||||
$kz = TrackNormalizer::normalize([
|
||||
'provider' => 'aliyun',
|
||||
'success' => true,
|
||||
'raw' => [
|
||||
'code' => 200,
|
||||
'success' => true,
|
||||
'msg' => '成功',
|
||||
'data' => [
|
||||
'cpCode' => 'ZTO',
|
||||
'mailNo' => '79139342513829',
|
||||
'logisticsCompanyName' => '中通快递',
|
||||
'logisticsStatusDesc' => '运输中',
|
||||
'theLastTime' => '2026-09-11 02:56:45',
|
||||
'theLastMessage' => '快件已发往粤西转运中心',
|
||||
'logisticsTraceDetailList' => [
|
||||
[
|
||||
'areaName' => '四川省,成都市',
|
||||
'subLogisticsStatus' => 'ACCEPT',
|
||||
'timeDesc' => '2026-09-10 09:59:27',
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
|
||||
assert($kz['expressCompanyName'] === '中通快递');
|
||||
assert($kz['expressStatus'] === '运输中');
|
||||
assert(count($kz['trackList']) === 1);
|
||||
assert($kz['trackList'][0]['AcceptTime'] === '2026-09-10 09:59:27');
|
||||
|
||||
echo "TrackNormalizer tests passed\n";
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP TABLE IF EXISTS `__PREFIX__shopro_aliyun_express_query_log`;
|
||||
DROP TABLE IF EXISTS `__PREFIX__shopro_aliyun_express_config`;
|
||||
在新工单中引用
屏蔽一个用户