初始化项目:添加后端代码、ThinkPHP框架、前端资源

This commit is contained in:
amb
2026-09-03 12:42:39 +08:00
commit 482bece22e
3726 changed files with 416708 additions and 0 deletions
@@ -0,0 +1,109 @@
<?php
namespace app\common\library\app\physical\express;
use think\exception\HttpResponseException;
use app\common\model\app\physical\OrderExpress;
class Express
{
protected $driver = null;
protected $config = [];
public function __construct($driver = 'aliyun', $config = [])
{
$this->driver = $driver;
$this->config = $config;
}
public function provider($driver = null)
{
$driver = $driver ?: $this->getDefaultDriver();
$class = "\\app\\common\\library\\app\\physical\\express\\provider\\" . \think\helper\Str::studly($driver);
if (class_exists($class)) {
return new $class($this->config);
}
throw new \Exception('物流平台类型不支持');
}
/**
* 更新订单的所有包裹物流信息
*
* @param mixed $orderExpress 订单ID或发货单ID
* @return void
*/
public function updateOrderExpress($orderExpress = 0)
{
try {
// 如果传入的是订单ID,获取该订单的所有发货单
if (is_numeric($orderExpress)) {
$orderExpresses = OrderExpress::where('order_id', $orderExpress)
->where('uniacid', UNIACID)
->select();
} else {
$orderExpresses = [$orderExpress];
}
// 遍历更新每个发货单的物流信息
foreach ($orderExpresses as $orderExpress) {
$this->updateExpress($orderExpress);
}
} catch (HttpResponseException $e) {
$data = $e->getResponse()->getData();
$message = $data ? ($data['msg'] ?? '') : $e->getMessage();
\think\Log::error('updateOrderExpress.HttpResponseException: ' . $message);
} catch(\Exception $e) {
\think\Log::error('updateOrderExpress.Exception: 获取物流信息错误 - ' . $e->getMessage());
}
}
/**
* 更新单个包裹的物流信息
*
* @param \think\Model $orderExpress 发货单模型
* @return bool
*/
public function updateExpress($orderExpress)
{
// 只有未签收的包裹才更新物流
if ($orderExpress->status == 'signfor') {
return true;
}
// 检查缓存,避免频繁查询(5分钟缓存)
$key = 'express:' . $orderExpress->id . ':code:' . $orderExpress->express_no;
if (cache('?'.$key)) {
return true;
}
try {
// 查询物流信息
$this->provider()->search([
'order_id' => $orderExpress['order_id'],
'express_code' => $orderExpress['express_code'],
'express_no' => $orderExpress['express_no'],
'mobile' => $orderExpress['sender_mobile'] ?? ''
], $orderExpress);
// 缓存 300 秒(5分钟)
cache($key, time(), 300);
return true;
} catch (\Exception $e) {
\think\Log::error('updateExpress.Exception: ' . $e->getMessage());
return false;
}
}
public function getDefaultDriver()
{
return $this->driver;
}
public function __call($funcname, $arguments)
{
return $this->provider()->{$funcname}(...$arguments);
}
}
@@ -0,0 +1,136 @@
<?php
namespace app\common\library\app\physical\express\adapter;
use fast\Http;
class Kdniao
{
const REQURL = "https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";
const SUBURL = "https://api.kdniao.com/api/dist";
const EORDER = "https://api.kdniao.com/api/EOrderService";
protected $sender = [];
protected $config = [];
public function __construct()
{
$this->config = $this->getConfig();
}
public function search($data)
{
$requestParams = $this->getRequestParams($data);
$requestData = $this->getRequestData($requestParams);
$requestData['RequestType'] = $this->config['type'] == 'free' ? '1002' : '8001';
$result = Http::post(self::REQURL, $requestData);
$result = $this->getResponse($result, '没有物流信息');
return $result;
}
public function subscribe($data)
{
$requestParams = $this->getRequestParams($data);
$requestData = $this->getRequestData($requestParams);
$requestData['RequestType'] = $this->config['type'] == 'free' ? '1008' : '8008';
$result = Http::post(self::SUBURL, $requestData);
$result = $this->getResponse($result, '订阅失败');
return $result;
}
public function cancel($data)
{
$requestData = $data;
$requestData = $this->getRequestData($data);
$requestData['RequestType'] = '1147';
$result = Http::post(self::EORDER, $requestData);
$result = $this->getResponse($result, '电子面单取消失败');
return $result;
}
public function eOrder($data)
{
$requestData = $this->getRequestData($data);
$requestData['RequestType'] = '1007';
$result = Http::post(self::EORDER, $requestData);
$result = $this->getResponse($result, '电子面单下单失败');
return $result;
}
public function pushResult($success, $reason)
{
$result = [
"EBusinessID" => $this->config['ebusiness_id'],
"UpdateTime" => date('Y-m-d H:i:s'),
"Success" => $success,
'Reason' => $reason
];
return $result;
}
private function getRequestData($requestParams)
{
$requestParams = is_array($requestParams) ? json_encode($requestParams, JSON_UNESCAPED_UNICODE) : $requestParams;
$requestData = [
'EBusinessID' => $this->config['ebusiness_id'],
'RequestData' => urlencode($requestParams),
'DataType' => '2',
];
$requestData['DataSign'] = $this->encrypt($requestParams, $this->config['app_key']);
return $requestData;
}
private function getRequestParams($data = [])
{
$params = [
'ShipperCode' => $data['express_code'],
'LogisticCode' => $data['express_no'],
];
if ($data['express_code'] == 'JD') {
$params['CustomerName'] = $this->config['jd_code'] ?? '';
} else {
$params['CustomerName'] = $data['mobile'] ?? '';
}
return $params;
}
private function getResponse($result, $msg = '')
{
$result = json_decode($result, true);
if (!$result['Success']) {
throw new \Exception($result['Reason'] ?: $msg);
}
return $result;
}
private function encrypt($data, $app_key)
{
return urlencode(base64_encode(md5($data . $app_key)));
}
protected function getConfig()
{
return [
'type' => 'free',
'ebusiness_id' => '1914053',
'app_key' => 'f583d954-1709-4e34-9ac0-73f5079e2452',
'jd_code' => ''
];
}
}
@@ -0,0 +1,14 @@
<?php
namespace app\common\library\app\physical\express\contract;
interface ExpressInterface
{
public function search(array $data, $orderExpress = null);
public function subscribe(array $data);
public function push(array $data);
public function eOrder(array $data, $items);
}
@@ -0,0 +1,278 @@
<?php
namespace app\common\library\app\physical\express\provider;
/**
* 阿里云物流查询驱动
*
* 服务文档:https://market.aliyun.com/detail/cmapi00071922
*
* 接口地址:https://swexquery.market.alicloudapi.com/query/expressquery
* 请求方式:POST
* 认证方式:APPCODE
*
* 配置信息:
* - AppKey203944259
* - AppSecretR8rx9QLNZlRKxHtvgjBlocFI8f0hq12J
* - AppCoded6beec8b9be945bfa3c07b9c712f6bce
*/
class Aliyun extends Base
{
protected $config = [];
public function __construct($config = [])
{
parent::__construct();
$this->config = $config;
}
/**
* 查询物流信息
*
* @param array $data
* @param mixed $orderExpress
* @return array|null
*/
public function search(array $data, $orderExpress = null)
{
$host = "https://swexquery.market.alicloudapi.com";
$path = "/query/expressquery";
$method = "POST";
// 优先使用 AppCode,如果未配置则使用 AppKey 和 AppSecret 生成签名
$appcode = $this->config['appcode'] ?? '';
if (empty($appcode)) {
$appkey = $this->config['appkey'] ?? '';
$appsecret = $this->config['appsecret'] ?? '';
if (empty($appkey) || empty($appsecret)) {
throw new \Exception('阿里云AppCode或AppKey/AppSecret未配置');
}
// 使用 AppKey 和 AppSecret 生成 AppCode(参考阿里云文档)
$appcode = base64_encode($appkey . ':' . $appsecret);
}
$headers = [];
$headers[] = "Authorization:APPCODE " . $appcode;
$headers[] = "Content-Type:application/x-www-form-urlencoded; charset=UTF-8";
// 构建请求参数
$expressNumber = $data['express_no'] ?? '';
$expressType = $data['express_code'] ?? '';
$phoneNumber = $data['mobile'] ?? '';
$bodys = "express_number=" . urlencode($expressNumber);
// if (!empty($expressType)) {
// $bodys .= "&express_type=" . urlencode($expressType);
// }
if (!empty($phoneNumber)) {
$bodys .= "&phone_number=" . urlencode($phoneNumber);
}
$url = $host . $path;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
if (1 == strpos("$" . $host, "https://")) {
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
$response = curl_exec($curl);
$httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($httpCode != 200 || empty($response)) {
throw new \Exception('阿里云物流查询接口请求失败');
}
$result = json_decode($response, true);
if (empty($result)) {
throw new \Exception('阿里云物流查询接口返回数据解析失败');
}
// 解析阿里云返回的数据
$expressData = $this->parseResponse($result);
if ($orderExpress) {
$this->updateExpress($expressData, $orderExpress);
}
return $expressData;
}
/**
* 解析阿里云返回的数据
*
* @param array $result
* @return array
*/
protected function parseResponse($result)
{
// 阿里云返回格式参考
// 成功格式:
// {
// "charge": 1,
// "result": {
// "info": [
// {
// "cpCode": "STO",
// "theLastTime": "2025-09-08 18:55:18",
// "mailNo": "772****722",
// "theLastMessage": "已签收,签收人凭取货码签收",
// "cpMobile": "95543",
// "logisticsCompanyName": "申通快递",
// "cpUrl": "http://www.sto.cn",
// "takeTime": "1天18小时7分",
// "courier": "**路北**14-8店",
// "courierPhone": "135**3135",
// "logisticsStatusDesc": "已签收",
// "logisticsTraceDetailList": [
// {
// "areaCode": "CN110100000000",
// "areaName": "北京,北京市",
// "subLogisticsStatus": "ACCEPT",
// "time": "1773037503000",
// "logisticsStatus": "ACCEPT",
// "desc": "顺丰速运 已收取快件,您的期待,我们定竭诚守护,不负所托。"
// }
// ],
// "logisticsStatus": "SIGN"
// }
// ]
// },
// "result_code": "0000",
// "result_msg": "调用成功",
// "request_id": "TID762ff34c093040b69e4c04b5f01a560a"
// }
//
// 失败格式:
// {
// "charge": 2,
// "result_code": "2102",
// "result_msg": "请求参数错误",
// "request_id": "TID7b21ec5e862d445fac39b0af4c36008d"
// }
// 检查错误格式
if (isset($result['result_code'])) {
if ($result['result_code'] != '0000') {
$msg = $result['result_msg'] ?? '查询失败';
throw new \Exception('阿里云物流查询:' . $msg);
}
}
// 获取物流信息
$infoList = $result['result']['info'] ?? [];
if (empty($infoList)) {
throw new \Exception('阿里云物流查询:未找到物流信息');
}
$info = $infoList[0];
// 转换物流状态
$status = $this->convertStatus($info['logisticsStatus'] ?? '');
// 转换物流轨迹
$traces = [];
$traceList = $info['logisticsTraceDetailList'] ?? [];
if (is_array($traceList)) {
foreach ($traceList as $trace) {
$timestamp = $trace['time'] ?? '';
$changeDate = '';
if (!empty($timestamp)) {
// 时间戳转换为日期格式
if (strlen($timestamp) == 13) {
$changeDate = date('Y-m-d H:i:s', $timestamp / 1000);
} else {
$changeDate = date('Y-m-d H:i:s', $timestamp);
}
}
$traces[] = [
'content' => $trace['desc'] ?? $trace['content'] ?? '',
'change_date' => $changeDate ?: date('Y-m-d H:i:s'),
'status' => $status
];
}
}
return [
'status' => $status,
'traces' => $traces
];
}
/**
* 转换物流状态
*
* @param string $status
* @return string
*/
protected function convertStatus($status)
{
// 阿里云状态映射到系统状态
$statusMap = [
'NOINFO' => 'noinfo', // 无信息
'ACCEPT' => 'collect', // 已揽件
'TRANSPORT' => 'transport', // 运输中
'DELIVERY' => 'delivery', // 派送中
'SIGN' => 'signfor', // 已签收
'REFUSE' => 'refuse', // 拒收
'DIFFICULTY' => 'difficulty', // 问题件
'INVALID' => 'invalid', // 无效件
'TIMEOUT' => 'timeout', // 超时
'FAIL' => 'fail', // 签收失败
'BACK' => 'back' // 退回
];
return $statusMap[$status] ?? 'noinfo';
}
/**
* 订阅物流信息推送
*
* @param array $data
* @return void
*/
public function subscribe(array $data)
{
throw new \Exception('阿里云物流查询不支持订阅功能');
}
/**
* 接收物流推送
*
* @param array $data
* @return void
*/
public function push(array $data)
{
throw new \Exception('阿里云物流查询不支持推送功能');
}
/**
* 电子面单
*
* @param array $data
* @param array $items
* @return void
*/
public function eOrder(array $data, $items)
{
throw new \Exception('阿里云物流查询不支持电子面单功能');
}
}
@@ -0,0 +1,75 @@
<?php
namespace app\common\library\app\physical\express\provider;
use app\common\library\app\physical\express\contract\ExpressInterface;
use app\common\model\app\physical\OrderExpress;
use app\common\model\app\physical\OrderExpressLog;
class Base implements ExpressInterface
{
public function __construct()
{
}
public function search(array $data, $orderExpress = 0)
{
return null;
}
public function subscribe(array $data)
{
throw new \Exception('当前快递驱动不支持物流信息订阅');
}
public function push(array $data)
{
throw new \Exception('当前快递驱动不支持接受推送');
}
public function eOrder(array $data, $items)
{
throw new \Exception('当前快递驱动不支持电子面单');
}
protected function updateExpress(array $data, $orderExpress)
{
if (is_numeric($orderExpress)) {
$orderExpress = OrderExpress::find($orderExpress);
}
if ($orderExpress) {
$orderExpress->status = $data['status'];
$orderExpress->save();
$this->syncTraces($data['traces'], $orderExpress);
}
}
protected function syncTraces($traces, $orderExpress)
{
$orderExpressLog = OrderExpressLog::where('order_express_id', $orderExpress->id)->select();
$log_count = count($orderExpressLog);
if ($log_count > 0) {
if (is_array($traces)) {
array_splice($traces, 0, $log_count);
}
}
if (is_array($traces)) {
foreach ($traces as $k => $trace) {
$orderExpressLog = new OrderExpressLog();
$orderExpressLog->uniacid = UNIACID;
$orderExpressLog->user_id = $orderExpress['user_id'];
$orderExpressLog->order_id = $orderExpress['order_id'];
$orderExpressLog->order_express_id = $orderExpress['id'];
$orderExpressLog->content = $trace['content'];
$orderExpressLog->change_date = $trace['change_date'];
$orderExpressLog->status = $trace['status'];
$orderExpressLog->save();
}
}
}
}
@@ -0,0 +1,253 @@
<?php
namespace app\common\library\app\physical\express\provider;
use think\Log;
use think\exception\HttpResponseException;
use app\common\library\app\physical\express\adapter\Kdniao as KdniaoServer;
use app\common\model\app\physical\OrderExpress;
class Kdniao extends Base
{
public function __construct()
{
$this->server = new KdniaoServer();
}
public $status = [
'0' => 'noinfo',
'1' => 'collect',
'2' => 'transport',
'201' => 'transport',
'202' => 'delivery',
'211' => 'delivery',
'3' => 'signfor',
'301' => 'signfor',
'302' => 'signfor',
'311' => 'signfor',
'4' => 'difficulty',
'401' => 'invalid',
'402' => 'timeout',
'403' => 'timeout',
'404' => 'refuse',
'412' => 'timeout',
];
public function search($data, $orderExpress = 0)
{
$requestData = $this->formatRequest($data);
$result = $this->server->search($requestData);
$traces = $result['Traces'] ?? [];
$status = $result['State'];
$formatResult = $this->formatResult([
'status' => $status,
'traces' => $traces
]);
if ($orderExpress) {
$this->updateExpress($formatResult, $orderExpress);
}
return $formatResult;
}
public function subscribe($data)
{
$requestData = $this->formatRequest($data);
$result = $this->server->subscribe($requestData);
return $result;
}
public function cancel($data)
{
$config = $this->getConfig();
$this->server->cancel([
'ShipperCode' => $data['express_code'],
'OrderCode' => $data['order_code'],
'ExpNo' => $data['express_no'],
"CustomerName" => $config['customer_name'],
"CustomerPwd" => $config['customer_pwd']
]);
}
public function push(array $data)
{
$success = true;
$reason = '';
try {
$data = json_decode(html_entity_decode($data['RequestData']), true);
$expressData = $data['Data'];
foreach ($expressData as $key => $express) {
$orderExpress = OrderExpress::where('express_no', $express['LogisticCode'])->where('express_code', $express['ShipperCode'])->find();
if (!$orderExpress) {
Log::error('order-express-notfound:' . json_encode($express));
continue;
}
if (!$express['Success']) {
if (isset($express['Reason']) && (strpos($express['Reason'], '三天无轨迹') !== false || strpos($express['Reason'], '七天内无轨迹变化') !== false)) {
$this->subscribe([
'express_code' => $express['ShipperCode'],
'express_no' => $express['LogisticCode']
]);
}
Log::error('order-express-resubscribe:' . json_encode($express));
continue;
}
$traces = $express['Traces'] ?? [];
$status = $express['State'];
$formatResult = $this->formatResult([
'status' => $status,
'traces' => $traces
]);
$this->updateExpress($formatResult, $orderExpress);
}
} catch (HttpResponseException $e) {
$data = $e->getResponse()->getData();
$reason = $data ? ($data['msg'] ?? '') : $e->getMessage();
} catch (\Exception $e) {
$success = false;
$reason = $e->getMessage();
}
return $this->server->pushResult($success, $reason);
}
public function eOrder($data, $items)
{
$config = $this->getConfig();
if ($config['type'] !== 'vip') {
throw new \Exception('仅快递鸟标准版接口支持电子面单功能!');
}
$consignee = $data['consignee'];
$order = $data['order'];
$sender = $data['sender'] ?? $config['sender'] ?? [];
if (empty($sender)) {
throw new \Exception('请配置默认发货人信息');
}
$requestData = [
"CustomerName" => $config['customer_name'],
"CustomerPwd" => $config['customer_pwd'],
"MonthCode" => $config['month_code'] ?? '',
"SendSite" => $config['send_site'] ?? '',
"SendStaff" => $config['send_staff'] ?? '',
"ShipperCode" => $config['express']['code'] ?? '',
"PayType" => $config['pay_type'] ?? 1,
"ExpType" => $config['exp_type'] ?? 1,
"IsReturnPrintTemplate" => 0,
"TemplateSize" => '130',
"Volume" => 0,
"OrderCode" => $order['order_sn'] . '_' . time(),
"Remark" => $order['remark'] ?? '小心轻放'
];
$requestData['Sender'] = [
'Name' => $sender['name'],
'Mobile' => $sender['mobile'],
'ProvinceName' => $sender['province_name'],
'CityName' => $sender['city_name'],
'ExpAreaName' => $sender['district_name'],
'Address' => $sender['address']
];
$requestData['Receiver'] = [
"Name" => $consignee['consignee'],
"Mobile" => $consignee['mobile'],
"ProvinceName" => $consignee['province_name'],
"CityName" => $consignee['city_name'],
"ExpAreaName" => $consignee['district_name'],
"Address" => $consignee['address']
];
$totalCount = 0;
$totalWeight = 0;
foreach ($items as $k => $item) {
$goodsName = $item['goods_title'] . ($item['goods_sku_text'] ? '-' . $item['goods_sku_text'] : '');
$requestData['Commodity'][] = [
"GoodsName" => $goodsName,
"Goodsquantity" => $item['goods_num'],
"GoodsWeight" => $item['goods_num'] * ($item['goods_weight'] ?? 0)
];
$totalCount += $item['goods_num'];
$totalWeight += $item['goods_num'] * ($item['goods_weight'] ?? 0);
}
$requestData['Quantity'] = $totalCount;
$requestData['Weight'] = $totalWeight;
$result = $this->server->eOrder($requestData);
if ($result['Success'] === true && $result['ResultCode'] === "100") {
return [
'code' => $config['express']['code'],
'name' => $config['express']['name'],
'no' => $result['Order']['LogisticCode'],
'ext' => $result,
'driver' => 'kdniao'
];
}
return false;
}
protected function formatRequest($data)
{
$requestData = [
'express_code' => $data['express_code'] ?? '',
'express_no' => $data['express_no'],
'mobile' => (isset($data['mobile']) && $data['mobile']) ? substr($data['mobile'], 7) : ''
];
return $requestData;
}
protected function formatResult($data)
{
$status = $this->status[$data['status']] ?? 'noinfo';
$traces = [];
if (is_array($data['traces'])) {
foreach ($data['traces'] as $trace) {
$action = $trace['Action'] ?? '';
if ($action !== '') {
$currentStatus = $this->status[$action] ?? 'noinfo';
}
$traces[] = [
'content' => $trace['AcceptStation'],
'change_date' => date('Y-m-d H:i:s', strtotime(substr($trace['AcceptTime'], 0, 19))),
'status' => $currentStatus ?? 'noinfo'
];
}
}
return compact('status', 'traces');
}
protected function getConfig()
{
return [
'type' => 'free',
'ebusiness_id' => '',
'app_key' => '',
'customer_name' => '',
'customer_pwd' => '',
'month_code' => '',
'send_site' => '',
'send_staff' => '',
'express' => [],
'pay_type' => 1,
'exp_type' => 1,
'sender' => []
];
}
}
@@ -0,0 +1,95 @@
<?php
namespace app\common\library\app\physical\express\provider;
use app\common\model\app\physical\OrderAddress;
use fast\Http;
class Thinkapi extends Base
{
protected $uri = 'https://api.topthink.com';
protected $appCode = '782d8799-ed40-4b95-a24b-dfc2259b910e';
public function __construct()
{
$this->appCode = $this->getConfig();
}
public $status = [
'1' => 'noinfo',
'2' => 'transport',
'3' => 'delivery',
'4' => 'signfor',
'5' => 'refuse',
'6' => 'difficulty',
'7' => 'invalid',
'8' => 'timeout',
'9' => 'fail',
'10' => 'back'
];
public function search($data, $orderExpress = 0)
{
$mobile = (isset($data['mobile']) && $data['mobile']) ? $data['mobile'] : '';
if (!$mobile && isset($data['order_id'])) {
$orderAddress = OrderAddress::where('order_id', $data['order_id'])->find();
$mobile = $orderAddress ? $orderAddress->mobile : $mobile;
}
$requestData = [
'appCode' => $this->appCode,
'com' => 'auto',
'nu' => $data['express_no'],
'phone' => substr($mobile, 7)
];
$result = Http::get($this->uri . '/express/query', $requestData);
$result = is_string($result) ? json_decode($result, true) : $result;
if (isset($result['code']) && $result['code'] != 0) {
$msg = $result['data']['msg'] ?? ($result['message'] ?? '');
throw new \Exception($msg);
}
$data = $result['data'] ?? [];
$traces = $data['data'] ?? [];
$status = $data['status'];
$formatResult = $this->formatResult([
'status' => $status,
'traces' => $traces
]);
if ($orderExpress) {
$this->updateExpress($formatResult, $orderExpress);
}
return $formatResult;
}
protected function formatResult($data)
{
$status = $this->status[$data['status']] ?? 'noinfo';
$traces = [];
if (is_array($data['traces'])) {
foreach ($data['traces'] as $trace) {
$traces[] = [
'content' => $trace['context'],
'change_date' => $trace['time'],
'status' => $trace['status'] ?? $status
];
}
}
$traces = array_reverse($traces);
return compact('status', 'traces');
}
protected function getConfig()
{
return '782d8799-ed40-4b95-a24b-dfc2259b910e';
}
}