feat: 初始化雄戈商城服务端代码与Webhook自动部署配置
这个提交包含在:
@@ -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();
|
||||
}
|
||||
在新工单中引用
屏蔽一个用户