feat(wms): 新增运单揽收状态查询回调 waybill.getreceive
- express/Recognizer:按字母前缀 + 位数号段识别运单快递公司(p01~p35)
- express/Trace:批量并发查轨迹(curl_multi,默认 10 并发),解析状态/首末轨迹/中转签收时效
- notify/WaybillReceiveHandler:外部传入运单号自动识别公司后查轨迹,轨迹非空即已揽收,
已揽收结果缓存 24h(命中不再请求接口),未揽收/查不到/识别不出/接口异常一律返回 0
- notify/RawResponse:支持裸数组响应透出,不套 {code,msg,data} 外壳
- new_wms_notify 输出 [{"waybill_code","is_galaxy_receive"}]
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
parent
7d9d754f72
commit
4e5c05dfc3
@ -11900,6 +11900,12 @@ class Wms extends Frontend
|
||||
$dispatcher = new \app\index\library\new_wms\notify\Dispatcher();
|
||||
$result = $dispatcher->handle($queryParams, $rawBody);
|
||||
|
||||
// 原样响应(裸数组):不套 {code,msg,data} 外壳,如 waybill.getreceive
|
||||
if ($result instanceof \app\index\library\new_wms\notify\RawResponse) {
|
||||
\think\Log::error("[new_wms_notify] 出参(原样): " . json_encode($result->data, JSON_UNESCAPED_UNICODE));
|
||||
return json($result->data, $result->httpCode);
|
||||
}
|
||||
|
||||
\think\Log::error("[new_wms_notify] 出参: " . json_encode($result, JSON_UNESCAPED_UNICODE));
|
||||
|
||||
return json($result);
|
||||
|
||||
194
application/index/library/express/Recognizer.php
Normal file
194
application/index/library/express/Recognizer.php
Normal file
@ -0,0 +1,194 @@
|
||||
<?php
|
||||
|
||||
namespace app\index\library\express;
|
||||
|
||||
/**
|
||||
* 运单号快递公司识别
|
||||
*
|
||||
* 外部传入的运单号通常不带快递公司,而查询轨迹接口需要 postcode(p01~p35)。
|
||||
* 这里按「字母前缀 → 位数 → 号段前缀」的顺序做本地规则识别,不产生任何网络请求。
|
||||
*
|
||||
* 说明:
|
||||
* - 识别只做启发式判断,返回 confidence 供调用方决定是否采用;
|
||||
* - 纯数字单号只按「位数 + 前 1~2 位」判定,同位数不同公司的号段可能重叠,属于已知局限;
|
||||
* - 需要新增规则时用 Recognizer::addPattern() / Recognizer::addDigitRule(),或直接改 $patterns / $digitRules。
|
||||
*
|
||||
* 用法:
|
||||
* $r = Recognizer::recognize('771234567890123');
|
||||
* // ['postnum'=>'771234567890123','postcode'=>'p02','company'=>'申通',
|
||||
* // 'confidence'=>'medium','matched_by'=>'prefix','length'=>15]
|
||||
*/
|
||||
class Recognizer
|
||||
{
|
||||
/**
|
||||
* 带字母前缀的单号:命中即可直接判定,置信度 high
|
||||
* @var array [正则, postcode, 置信度]
|
||||
*/
|
||||
protected static $patterns = [
|
||||
['/^SF\d{10,16}$/', 'p05', 'high'], // 顺丰 SF+数字
|
||||
['/^YT\d{10,16}$/', 'p01', 'high'], // 圆通 YT+数字
|
||||
['/^JT\d{10,16}$/', 'p32', 'high'], // 极兔 JT+数字
|
||||
['/^JD[A-Z0-9]{8,20}$/', 'p10', 'high'], // 京东 JDVA/JDX...
|
||||
['/^DPK\d{8,16}$/', 'p26', 'high'], // 德邦 DPK+数字
|
||||
['/^[A-Z]{2}\d{9}CN$/', 'p07', 'high'], // EMS EA123456789CN
|
||||
];
|
||||
|
||||
/**
|
||||
* 纯数字单号:按位数 + 号段前缀判定
|
||||
* @var array [位数, 前缀数组, postcode, 置信度]
|
||||
*/
|
||||
protected static $digitRules = [
|
||||
[15, ['77', '88', '66'], 'p02', 'medium'], // 申通 15 位
|
||||
[15, ['10', '12', '19', '31', '32', '42', '43', '46', '50', '51', '52', '53', '57', '58', '59'], 'p03', 'medium'], // 韵达 15 位
|
||||
[14, ['7', '8', '9'], 'p04', 'medium'], // 中通 14 位
|
||||
[12, ['66', '68', '71', '72', '73', '76', '77', '78', '86', '88'], 'p01', 'low'], // 圆通 12 位
|
||||
];
|
||||
|
||||
/** @var array postcode => 快递公司名,与 api/controller/Configs.php 的 $pcodes 保持一致 */
|
||||
protected static $companies = [
|
||||
'p01' => '圆通',
|
||||
'p02' => '申通',
|
||||
'p03' => '韵达',
|
||||
'p04' => '中通',
|
||||
'p05' => '顺丰',
|
||||
'p06' => '百世快运',
|
||||
'p07' => 'EMS',
|
||||
'p08' => '京广速运',
|
||||
'p09' => '百世极兔/百世快递',
|
||||
'p10' => '京东',
|
||||
'p16' => '安能',
|
||||
'p17' => '优速',
|
||||
'p18' => '自提',
|
||||
'p19' => '零担',
|
||||
'p20' => '整车',
|
||||
'p21' => '运通速运',
|
||||
'p22' => '邮政',
|
||||
'p23' => '跨越',
|
||||
'p24' => '韵达国际',
|
||||
'p25' => '中通快运',
|
||||
'p26' => '德邦快递/德邦物流',
|
||||
'p27' => '壹米滴答',
|
||||
'p30' => '其他',
|
||||
'p32' => '极兔速递',
|
||||
'p34' => '丰网速运',
|
||||
'p35' => '邮政标快',
|
||||
];
|
||||
|
||||
/**
|
||||
* 清洗运单号:转大写并去掉空格、横杠、中文等非字母数字字符
|
||||
* @param string $number
|
||||
* @return string
|
||||
*/
|
||||
public static function clean($number)
|
||||
{
|
||||
return preg_replace('/[^A-Z0-9]/', '', strtoupper(trim((string)$number)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 识别单个运单号
|
||||
* @param string $number 运单号(可含空格、分隔符)
|
||||
* @return array
|
||||
*/
|
||||
public static function recognize($number)
|
||||
{
|
||||
$standard = self::clean($number);
|
||||
$length = strlen($standard);
|
||||
|
||||
if ($length === 0) {
|
||||
return self::build($standard, 'UNKNOWN', 'none', 'none', $length);
|
||||
}
|
||||
|
||||
foreach (self::$patterns as $rule) {
|
||||
if (preg_match($rule[0], $standard)) {
|
||||
return self::build($standard, $rule[1], $rule[2], 'pattern', $length);
|
||||
}
|
||||
}
|
||||
|
||||
if (ctype_digit($standard)) {
|
||||
foreach (self::$digitRules as $rule) {
|
||||
if ($rule[0] !== $length) {
|
||||
continue;
|
||||
}
|
||||
foreach ($rule[1] as $prefix) {
|
||||
if (strpos($standard, $prefix) === 0) {
|
||||
return self::build($standard, $rule[2], $rule[3], 'prefix', $length);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return self::build($standard, 'UNKNOWN', 'none', 'none', $length);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量识别
|
||||
* @param array $numbers
|
||||
* @return array 与输入下标一致的识别结果
|
||||
*/
|
||||
public static function batch(array $numbers)
|
||||
{
|
||||
$results = [];
|
||||
foreach ($numbers as $key => $number) {
|
||||
$results[$key] = self::recognize($number);
|
||||
}
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增字母前缀规则(优先于内置规则)
|
||||
* @param string $pattern 正则,如 '/^SF\d{10,16}$/'
|
||||
* @param string $postcode
|
||||
* @param string $confidence high|medium|low
|
||||
*/
|
||||
public static function addPattern($pattern, $postcode, $confidence = 'high')
|
||||
{
|
||||
array_unshift(self::$patterns, [$pattern, $postcode, $confidence]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增纯数字号段规则(优先于内置规则)
|
||||
* @param int $length 位数
|
||||
* @param array|string $prefixes 号段前缀
|
||||
* @param string $postcode
|
||||
* @param string $confidence high|medium|low
|
||||
*/
|
||||
public static function addDigitRule($length, $prefixes, $postcode, $confidence = 'medium')
|
||||
{
|
||||
array_unshift(self::$digitRules, [(int)$length, (array)$prefixes, $postcode, $confidence]);
|
||||
}
|
||||
|
||||
/**
|
||||
* postcode 转公司名
|
||||
* @param string $postcode
|
||||
* @return string
|
||||
*/
|
||||
public static function companyName($postcode)
|
||||
{
|
||||
if (isset(self::$companies[$postcode])) {
|
||||
return self::$companies[$postcode];
|
||||
}
|
||||
return ($postcode === 'UNKNOWN' || $postcode === '') ? '未知快递' : $postcode;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否识别成功
|
||||
* @param array $result recognize() 的返回值
|
||||
* @return bool
|
||||
*/
|
||||
public static function isRecognized(array $result)
|
||||
{
|
||||
return isset($result['postcode']) && $result['postcode'] !== 'UNKNOWN';
|
||||
}
|
||||
|
||||
protected static function build($standard, $postcode, $confidence, $matchedBy, $length)
|
||||
{
|
||||
return [
|
||||
'postnum' => $standard,
|
||||
'postcode' => $postcode,
|
||||
'company' => self::companyName($postcode),
|
||||
'confidence' => $confidence,
|
||||
'matched_by' => $matchedBy,
|
||||
'length' => $length,
|
||||
];
|
||||
}
|
||||
}
|
||||
687
application/index/library/express/Trace.php
Normal file
687
application/index/library/express/Trace.php
Normal file
@ -0,0 +1,687 @@
|
||||
<?php
|
||||
|
||||
namespace app\index\library\express;
|
||||
|
||||
/**
|
||||
* 快递轨迹查询(批量 + 并发)
|
||||
*
|
||||
* 数据源沿用现网接口:POST http://express.gztbyc.com/query_tasks2
|
||||
* 请求体:["单号|单号|公司代码", ...]
|
||||
* 响应体:[{"trace":{"opTime":"","memo":"","scanType":""},"opOrgCityName":""}, ...]
|
||||
*
|
||||
* 特点:
|
||||
* 1. 外部只传运单号也能用:内部调用 Recognizer 识别快递公司(postcode)
|
||||
* 2. 一次传入多条(建议 ≤10),用 curl_multi 并发请求,耗时接近单条
|
||||
* 3. 返回数组与输入顺序一一对应,已解析好轨迹 / 状态 / 时效
|
||||
* 4. batch_size > 1 时一个请求带多单,接口若无法按单号拆分响应会自动降级为逐单请求
|
||||
*
|
||||
* 用法:
|
||||
* use app\index\library\express\Trace;
|
||||
*
|
||||
* $trace = new Trace(['concurrency' => 10]);
|
||||
* $list = $trace->query(['771234567890123', '78123456789012']);
|
||||
* foreach ($list as $item) {
|
||||
* $item['postnum']; // 标准单号
|
||||
* $item['postcode']; // p02 ...
|
||||
* $item['ok']; // 是否查询成功
|
||||
* $item['traces']; // [['op_time'=>..,'memo'=>..,'scan_type'=>..,'city'=>..], ...]
|
||||
* $item['status']; // 1 正常件 / 0 异常件
|
||||
* $item['type']; // 0 无轨迹 1 运输中 2 异常 4 退回 6 签收
|
||||
* $item['zzss']; // 中转时效(小时)
|
||||
* $item['qsss']; // 签收时效(小时)
|
||||
* }
|
||||
*
|
||||
* // 也可以直接传已识别好的单号
|
||||
* $trace->query(['postnum' => '771234567890123', 'postcode' => 'p02']);
|
||||
*/
|
||||
class Trace
|
||||
{
|
||||
const DEFAULT_BASE_URL = 'http://express.gztbyc.com';
|
||||
const DEFAULT_ENDPOINT = '/query_tasks2';
|
||||
|
||||
/** @var string 接口域名 */
|
||||
protected $baseUrl;
|
||||
/** @var string 接口路径 */
|
||||
protected $endpoint;
|
||||
/** @var int 单次请求超时(秒) */
|
||||
protected $timeout;
|
||||
/** @var int 并发请求数 */
|
||||
protected $concurrency;
|
||||
/** @var int 一个请求携带的单号数量 */
|
||||
protected $batchSize;
|
||||
/** @var int 超时 / 网络错误重试次数 */
|
||||
protected $retries;
|
||||
/** @var bool 未识别出快递公司时是否跳过查询 */
|
||||
protected $skipUnknown;
|
||||
/** @var bool 相同单号是否只请求一次 */
|
||||
protected $dedupe;
|
||||
/** @var array 轨迹状态关键词表 */
|
||||
protected $lists;
|
||||
|
||||
/** @var array type => 状态文案 */
|
||||
protected static $typeTexts = ['无轨迹', '运输中', '异常', '超时未中转完成', '退回', '超时未签收', '签收'];
|
||||
|
||||
/**
|
||||
* @param array $options base_url / endpoint / timeout / concurrency / batch_size /
|
||||
* retries / skip_unknown / dedupe / lists
|
||||
*/
|
||||
public function __construct(array $options = [])
|
||||
{
|
||||
$this->baseUrl = rtrim((string)$this->pick($options, 'base_url', self::DEFAULT_BASE_URL), '/');
|
||||
$this->endpoint = (string)$this->pick($options, 'endpoint', self::DEFAULT_ENDPOINT);
|
||||
$this->timeout = max(1, (int)$this->pick($options, 'timeout', 40));
|
||||
$this->concurrency = max(1, (int)$this->pick($options, 'concurrency', 10));
|
||||
$this->batchSize = max(1, (int)$this->pick($options, 'batch_size', 1));
|
||||
$this->retries = max(0, (int)$this->pick($options, 'retries', 1));
|
||||
$this->skipUnknown = (bool)$this->pick($options, 'skip_unknown', true);
|
||||
$this->dedupe = (bool)$this->pick($options, 'dedupe', true);
|
||||
$this->lists = (array)$this->pick($options, 'lists', []) + self::defaultLists();
|
||||
}
|
||||
|
||||
/**
|
||||
* 静态快捷方式:Trace::batch(['单号1', '单号2'])
|
||||
* @param string|array $numbers
|
||||
* @param array $options
|
||||
* @return array
|
||||
*/
|
||||
public static function batch($numbers, array $options = [])
|
||||
{
|
||||
$instance = new self($options);
|
||||
return $instance->query($numbers, $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* 识别运单号对应的快递公司
|
||||
* @param string $number
|
||||
* @return array 见 Recognizer::recognize()
|
||||
*/
|
||||
public static function recognize($number)
|
||||
{
|
||||
return Recognizer::recognize($number);
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量查询轨迹
|
||||
* @param string|array $numbers 运单号、运单号数组,或 ['postnum'=>..,'postcode'=>..]
|
||||
* @param array $options 覆盖构造参数:concurrency / batch_size / timeout / retries /
|
||||
* skip_unknown / dedupe / postcode / on_progress
|
||||
* @return array 与输入顺序一一对应的结果数组
|
||||
*/
|
||||
public function query($numbers, array $options = [])
|
||||
{
|
||||
$opts = $this->resolveOptions($options);
|
||||
$list = is_array($numbers) ? array_values($numbers) : [$numbers];
|
||||
$results = [];
|
||||
if (empty($list)) {
|
||||
return $results;
|
||||
}
|
||||
|
||||
// 1. 识别 + 过滤未识别 + 合并重复单号
|
||||
$tasks = [];
|
||||
$taskIndex = [];
|
||||
foreach ($list as $i => $input) {
|
||||
$item = $this->prepare($input, $opts);
|
||||
$results[$i] = null;
|
||||
if ($opts['skip_unknown'] && $item['postcode'] === 'UNKNOWN') {
|
||||
$results[$i] = $this->emptyResult($item, [
|
||||
'code' => 'UNKNOWN_COMPANY',
|
||||
'message' => '未识别的快递公司,已跳过查询',
|
||||
], 0);
|
||||
continue;
|
||||
}
|
||||
$key = $item['postnum'];
|
||||
if ($opts['dedupe'] && isset($taskIndex[$key])) {
|
||||
$tasks[$taskIndex[$key]]['indexes'][] = $i;
|
||||
continue;
|
||||
}
|
||||
$taskIndex[$key] = count($tasks);
|
||||
$tasks[] = [
|
||||
'postnum' => $item['postnum'],
|
||||
'postcode' => $item['postcode'],
|
||||
'indexes' => [$i],
|
||||
];
|
||||
}
|
||||
|
||||
// 2. 分批 + 并发
|
||||
if (!empty($tasks)) {
|
||||
$chunks = array_chunk($tasks, $opts['batch_size']);
|
||||
$raw = $this->requestBatches($chunks, $opts);
|
||||
foreach ($chunks as $chunkIndex => $chunk) {
|
||||
$chunkResult = isset($raw[$chunkIndex]) ? $raw[$chunkIndex] : null;
|
||||
$items = $this->resolveChunk($chunk, $chunkResult, $opts);
|
||||
foreach ($items as $k => $result) {
|
||||
foreach ($chunk[$k]['indexes'] as $index) {
|
||||
$results[$index] = $result;
|
||||
}
|
||||
}
|
||||
if ($opts['on_progress']) {
|
||||
call_user_func($opts['on_progress'], count($results), count($list));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ksort($results);
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询单个运单号
|
||||
* @param string|array $number
|
||||
* @param array $options
|
||||
* @return array|null
|
||||
*/
|
||||
public function queryOne($number, array $options = [])
|
||||
{
|
||||
$list = $this->query([$number], $options);
|
||||
return isset($list[0]) ? $list[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 只取轨迹数组
|
||||
* @param string|array $number
|
||||
* @param array $options
|
||||
* @return array
|
||||
*/
|
||||
public function traces($number, array $options = [])
|
||||
{
|
||||
$result = $this->queryOne($number, $options);
|
||||
return $result && $result['ok'] ? $result['traces'] : [];
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 内部
|
||||
|
||||
/**
|
||||
* 归一化单条输入
|
||||
* @param mixed $input
|
||||
* @param array $opts
|
||||
* @return array
|
||||
*/
|
||||
protected function prepare($input, array $opts)
|
||||
{
|
||||
$postnum = '';
|
||||
$postcode = '';
|
||||
if (is_array($input)) {
|
||||
if (isset($input['postnum'])) {
|
||||
$postnum = $input['postnum'];
|
||||
} elseif (isset($input['number'])) {
|
||||
$postnum = $input['number'];
|
||||
}
|
||||
if (isset($input['postcode'])) {
|
||||
$postcode = $input['postcode'];
|
||||
}
|
||||
} else {
|
||||
$postnum = $input;
|
||||
}
|
||||
|
||||
$recognized = Recognizer::recognize($postnum);
|
||||
if ($postcode === '') {
|
||||
$postcode = $opts['postcode'] !== '' ? $opts['postcode'] : $recognized['postcode'];
|
||||
}
|
||||
|
||||
return [
|
||||
'postnum' => $recognized['postnum'],
|
||||
'postcode' => $postcode,
|
||||
'recognized' => $recognized,
|
||||
];
|
||||
}
|
||||
|
||||
protected function buildQueryString(array $task)
|
||||
{
|
||||
return $task['postnum'] . '|' . $task['postnum'] . '|' . $task['postcode'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 用 curl_multi 并发跑完所有批次
|
||||
* @param array $batches 每项是一组任务
|
||||
* @param array $opts
|
||||
* @return array [批次下标 => ['ok'=>bool,'data'=>mixed,'error'=>array|null,'elapsed'=>float]]
|
||||
*/
|
||||
protected function requestBatches(array $batches, array $opts)
|
||||
{
|
||||
$results = [];
|
||||
if (empty($batches)) {
|
||||
return $results;
|
||||
}
|
||||
|
||||
$queue = array_keys($batches);
|
||||
$handles = [];
|
||||
$startedAt = [];
|
||||
$attempts = [];
|
||||
$maxAttempts = $opts['retries'] + 1;
|
||||
$window = $opts['concurrency'];
|
||||
|
||||
$mh = curl_multi_init();
|
||||
|
||||
while (true) {
|
||||
while (!empty($queue) && count($handles) < $window) {
|
||||
$index = array_shift($queue);
|
||||
$payload = [];
|
||||
foreach ($batches[$index] as $task) {
|
||||
$payload[] = $this->buildQueryString($task);
|
||||
}
|
||||
$ch = $this->createHandle($payload, $opts['timeout']);
|
||||
curl_multi_add_handle($mh, $ch);
|
||||
$handles[self::handleKey($ch)] = ['index' => $index, 'handle' => $ch];
|
||||
if (!isset($startedAt[$index])) {
|
||||
$startedAt[$index] = microtime(true);
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($handles)) {
|
||||
break;
|
||||
}
|
||||
|
||||
do {
|
||||
$status = curl_multi_exec($mh, $active);
|
||||
} while ($status === CURLM_CALL_MULTI_PERFORM);
|
||||
|
||||
$finished = false;
|
||||
while ($info = curl_multi_info_read($mh)) {
|
||||
$finished = true;
|
||||
$ch = $info['handle'];
|
||||
$key = self::handleKey($ch);
|
||||
if (!isset($handles[$key])) {
|
||||
continue;
|
||||
}
|
||||
$index = $handles[$key]['index'];
|
||||
unset($handles[$key]);
|
||||
|
||||
$errno = $info['result'];
|
||||
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$body = curl_multi_getcontent($ch);
|
||||
curl_multi_remove_handle($mh, $ch);
|
||||
curl_close($ch);
|
||||
|
||||
$attempts[$index] = isset($attempts[$index]) ? $attempts[$index] + 1 : 1;
|
||||
$failure = $this->describeFailure($errno, $httpCode, $body);
|
||||
|
||||
if ($failure !== null && $attempts[$index] < $maxAttempts && $this->isRetryable($errno, $httpCode)) {
|
||||
$queue[] = $index;
|
||||
continue;
|
||||
}
|
||||
|
||||
$elapsed = round(microtime(true) - $startedAt[$index], 3);
|
||||
if ($failure !== null) {
|
||||
$results[$index] = ['ok' => false, 'data' => null, 'error' => $failure, 'elapsed' => $elapsed];
|
||||
continue;
|
||||
}
|
||||
|
||||
$data = json_decode($body, true);
|
||||
if ($data === null && trim($body) !== 'null') {
|
||||
$results[$index] = ['ok' => false, 'data' => null, 'elapsed' => $elapsed, 'error' => [
|
||||
'code' => 'BAD_JSON',
|
||||
'message' => '接口返回内容不是合法 JSON',
|
||||
]];
|
||||
continue;
|
||||
}
|
||||
$results[$index] = ['ok' => true, 'data' => $data, 'error' => null, 'elapsed' => $elapsed];
|
||||
}
|
||||
|
||||
if (!$finished && !empty($handles)) {
|
||||
if (curl_multi_select($mh, 1.0) === -1) {
|
||||
usleep(1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
curl_multi_close($mh);
|
||||
ksort($results);
|
||||
return $results;
|
||||
}
|
||||
|
||||
protected function createHandle(array $payload, $timeout)
|
||||
{
|
||||
$ch = curl_init();
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_URL => $this->baseUrl . $this->endpoint,
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
|
||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_ENCODING => '',
|
||||
CURLOPT_CONNECTTIMEOUT => min(10, (int)$timeout),
|
||||
CURLOPT_TIMEOUT => (int)$timeout,
|
||||
]);
|
||||
return $ch;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array|null null 表示成功
|
||||
*/
|
||||
protected function describeFailure($errno, $httpCode, $body)
|
||||
{
|
||||
if ($errno !== CURLE_OK) {
|
||||
return ['code' => 'CURL_' . $errno, 'message' => curl_strerror($errno)];
|
||||
}
|
||||
if ($httpCode === 0 || $httpCode >= 400) {
|
||||
return ['code' => 'HTTP_' . $httpCode, 'message' => '接口返回 HTTP ' . $httpCode];
|
||||
}
|
||||
if (trim((string)$body) === '') {
|
||||
return ['code' => 'EMPTY_BODY', 'message' => '接口返回空内容'];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected function isRetryable($errno, $httpCode)
|
||||
{
|
||||
if ($errno === CURLE_OPERATION_TIMEOUTED || $errno === CURLE_COULDNT_CONNECT || $errno === CURLE_GOT_NOTHING) {
|
||||
return true;
|
||||
}
|
||||
return $httpCode === 0 || $httpCode >= 500;
|
||||
}
|
||||
|
||||
protected static function handleKey($handle)
|
||||
{
|
||||
return is_object($handle) ? spl_object_id($handle) : (int)$handle;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析一个批次的结果
|
||||
* @param array $chunk
|
||||
* @param array|null $raw
|
||||
* @param array $opts
|
||||
* @return array 与 $chunk 顺序一致的结果
|
||||
*/
|
||||
protected function resolveChunk(array $chunk, $raw, array $opts)
|
||||
{
|
||||
if (empty($raw) || empty($raw['ok'])) {
|
||||
if (count($chunk) === 1) {
|
||||
$error = !empty($raw['error']) ? $raw['error'] : ['code' => 'UNKNOWN', 'message' => '查询失败'];
|
||||
return [$this->emptyResult($chunk[0], $error, isset($raw['elapsed']) ? $raw['elapsed'] : 0)];
|
||||
}
|
||||
// 一包多单失败 → 逐单重试,避免整包丢结果
|
||||
return $this->queryIndividually($chunk, $opts);
|
||||
}
|
||||
|
||||
$lists = $this->splitResponse($raw['data'], $chunk);
|
||||
if ($lists !== null) {
|
||||
$out = [];
|
||||
foreach ($chunk as $k => $task) {
|
||||
$out[] = $this->parseResult($task, $lists[$k], isset($raw['elapsed']) ? $raw['elapsed'] : 0);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
// 一包多单的响应无法按单号拆分 → 降级为逐单请求
|
||||
return $this->queryIndividually($chunk, $opts);
|
||||
}
|
||||
|
||||
protected function queryIndividually(array $chunk, array $opts)
|
||||
{
|
||||
$batches = [];
|
||||
foreach ($chunk as $task) {
|
||||
$batches[] = [$task];
|
||||
}
|
||||
$raw = $this->requestBatches($batches, $opts);
|
||||
|
||||
$out = [];
|
||||
foreach ($chunk as $k => $task) {
|
||||
$result = isset($raw[$k]) ? $raw[$k] : null;
|
||||
if (!empty($result['ok'])) {
|
||||
$lists = $this->splitResponse($result['data'], [$task]);
|
||||
$out[] = $this->parseResult($task, $lists ? $lists[0] : [], isset($result['elapsed']) ? $result['elapsed'] : 0);
|
||||
} else {
|
||||
$error = !empty($result['error']) ? $result['error'] : ['code' => 'UNKNOWN', 'message' => '查询失败'];
|
||||
$out[] = $this->emptyResult($task, $error, isset($result['elapsed']) ? $result['elapsed'] : 0);
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一次响应拆成「每单一份轨迹数组」
|
||||
* 支持 [[轨迹...], [轨迹...]]、[{trace:[轨迹...]}, ...]、[单号 => 轨迹数组]、单条轨迹数组
|
||||
* @return array|null 无法按单号拆分时返回 null
|
||||
*/
|
||||
protected function splitResponse($data, array $tasks)
|
||||
{
|
||||
$count = count($tasks);
|
||||
|
||||
if ($count === 1) {
|
||||
if (!is_array($data)) {
|
||||
return [[]];
|
||||
}
|
||||
if (!self::isList($data)) {
|
||||
return isset($data['trace']) && is_array($data['trace']) ? [$data['trace']] : [[]];
|
||||
}
|
||||
return [$data];
|
||||
}
|
||||
|
||||
if (!is_array($data)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (self::isList($data)) {
|
||||
if (count($data) !== $count) {
|
||||
return null;
|
||||
}
|
||||
$parts = [];
|
||||
foreach ($data as $part) {
|
||||
if (!is_array($part)) {
|
||||
return null;
|
||||
}
|
||||
if (self::isList($part)) {
|
||||
$parts[] = $part;
|
||||
continue;
|
||||
}
|
||||
$list = null;
|
||||
foreach (['trace', 'traces', 'data'] as $field) {
|
||||
if (isset($part[$field]) && is_array($part[$field]) && self::isList($part[$field])) {
|
||||
$list = $part[$field];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($list === null) {
|
||||
return null;
|
||||
}
|
||||
$parts[] = $list;
|
||||
}
|
||||
return $parts;
|
||||
}
|
||||
|
||||
// 关联数组:以单号做 key
|
||||
$parts = [];
|
||||
foreach ($tasks as $task) {
|
||||
if (!isset($data[$task['postnum']]) || !is_array($data[$task['postnum']])) {
|
||||
return null;
|
||||
}
|
||||
$parts[] = $data[$task['postnum']];
|
||||
}
|
||||
return $parts;
|
||||
}
|
||||
|
||||
protected static function isList(array $arr)
|
||||
{
|
||||
$i = 0;
|
||||
foreach ($arr as $key => $value) {
|
||||
if ($key !== $i++) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 单条轨迹统一成 ['op_time','memo','scan_type','city']
|
||||
*/
|
||||
protected function normalizeTrace($raw)
|
||||
{
|
||||
if (is_array($raw) && isset($raw['trace']) && is_array($raw['trace'])) {
|
||||
$trace = $raw['trace'];
|
||||
$city = isset($raw['opOrgCityName']) ? $raw['opOrgCityName'] : '';
|
||||
} else {
|
||||
$trace = is_array($raw) ? $raw : [];
|
||||
$city = isset($trace['opOrgCityName']) ? $trace['opOrgCityName'] : '';
|
||||
}
|
||||
|
||||
return [
|
||||
'op_time' => $this->firstValue($trace, ['opTime', 'op_time', 'time']),
|
||||
'memo' => $this->firstValue($trace, ['memo', 'content', 'remark']),
|
||||
'scan_type' => $this->firstValue($trace, ['scanType', 'scan_type', 'status']),
|
||||
'city' => $city,
|
||||
];
|
||||
}
|
||||
|
||||
protected function firstValue(array $data, array $keys)
|
||||
{
|
||||
foreach ($keys as $key) {
|
||||
if (isset($data[$key]) && $data[$key] !== '') {
|
||||
return $data[$key];
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 判定状态:返回 [status(1 正常 / 0 异常), type(0~6)]
|
||||
*/
|
||||
protected function classify(array $traces)
|
||||
{
|
||||
$type = count($traces) > 0 ? 1 : 0;
|
||||
foreach ($traces as $trace) {
|
||||
$scanType = $trace['scan_type'];
|
||||
if (in_array($scanType, $this->lists['back'], true)) {
|
||||
$type = 4;
|
||||
}
|
||||
if (in_array($scanType, $this->lists['yunshu'], true) && $type !== 4 && $type !== 6) {
|
||||
$type = 1;
|
||||
}
|
||||
if (in_array($scanType, $this->lists['yichang'], true) && $type !== 4 && $type !== 6) {
|
||||
$type = 2;
|
||||
}
|
||||
if (in_array($scanType, $this->lists['qianshou'], true) && $type !== 4) {
|
||||
$type = 6;
|
||||
}
|
||||
}
|
||||
$status = ($type === 1 || $type === 4 || $type === 6) ? 1 : 0;
|
||||
return [$status, $type];
|
||||
}
|
||||
|
||||
protected function parseResult(array $task, $rawTraces, $elapsed)
|
||||
{
|
||||
$raw = is_array($rawTraces) && self::isList($rawTraces) ? $rawTraces : [];
|
||||
$traces = [];
|
||||
foreach ($raw as $item) {
|
||||
$traces[] = $this->normalizeTrace($item);
|
||||
}
|
||||
|
||||
list($status, $type) = $this->classify($traces);
|
||||
$count = count($traces);
|
||||
$first = $count > 0 ? $traces[0] : null;
|
||||
$last = $count > 0 ? $traces[$count - 1] : null;
|
||||
|
||||
return [
|
||||
'postnum' => $task['postnum'],
|
||||
'postcode' => $task['postcode'],
|
||||
'company' => Recognizer::companyName($task['postcode']),
|
||||
'ok' => true,
|
||||
'traces' => $traces,
|
||||
'status' => $status,
|
||||
'type' => $type,
|
||||
'type_text' => self::typeText($type),
|
||||
'first_time' => $first ? $first['op_time'] : '',
|
||||
'first_info' => $first ? $first['memo'] : '',
|
||||
'last_time' => $last ? $last['op_time'] : '',
|
||||
'last_info' => $last ? $last['memo'] : '',
|
||||
// 中转时效:第 1 条 → 第 3 条轨迹的小时差
|
||||
'zzss' => $count > 2 ? $this->hoursDiff($traces[0]['op_time'], $traces[2]['op_time']) : 0,
|
||||
// 签收时效:签收件从第 1 条到最后一条的小时差
|
||||
'qsss' => ($type === 6 && $count > 1) ? $this->hoursDiff($traces[0]['op_time'], $last['op_time']) : 0,
|
||||
'error' => null,
|
||||
'elapsed' => $elapsed,
|
||||
];
|
||||
}
|
||||
|
||||
protected function emptyResult(array $task, array $error, $elapsed)
|
||||
{
|
||||
return [
|
||||
'postnum' => isset($task['postnum']) ? $task['postnum'] : '',
|
||||
'postcode' => isset($task['postcode']) ? $task['postcode'] : 'UNKNOWN',
|
||||
'company' => Recognizer::companyName(isset($task['postcode']) ? $task['postcode'] : 'UNKNOWN'),
|
||||
'ok' => false,
|
||||
'traces' => [],
|
||||
'status' => 0,
|
||||
'type' => 0,
|
||||
'type_text' => self::typeText(0),
|
||||
'first_time' => '',
|
||||
'first_info' => '',
|
||||
'last_time' => '',
|
||||
'last_info' => '',
|
||||
'zzss' => 0,
|
||||
'qsss' => 0,
|
||||
'error' => $error,
|
||||
'elapsed' => $elapsed,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 两个时间之间的小时差,保留 2 位小数
|
||||
*/
|
||||
protected function hoursDiff($startTime, $endTime)
|
||||
{
|
||||
$start = $this->toTimestamp($startTime);
|
||||
$end = $this->toTimestamp($endTime);
|
||||
if ($start === null || $end === null) {
|
||||
return 0;
|
||||
}
|
||||
return round(($end - $start) / 3600, 2);
|
||||
}
|
||||
|
||||
protected function toTimestamp($value)
|
||||
{
|
||||
if ($value === null || $value === '') {
|
||||
return null;
|
||||
}
|
||||
$time = strtotime(str_replace('/', '-', (string)$value));
|
||||
return $time === false ? null : $time;
|
||||
}
|
||||
|
||||
protected static function typeText($type)
|
||||
{
|
||||
return isset(self::$typeTexts[$type]) ? self::$typeTexts[$type] : '';
|
||||
}
|
||||
|
||||
protected function resolveOptions(array $options)
|
||||
{
|
||||
return [
|
||||
'concurrency' => max(1, (int)$this->pick($options, 'concurrency', $this->concurrency)),
|
||||
'batch_size' => max(1, (int)$this->pick($options, 'batch_size', $this->batchSize)),
|
||||
'timeout' => max(1, (int)$this->pick($options, 'timeout', $this->timeout)),
|
||||
'retries' => max(0, (int)$this->pick($options, 'retries', $this->retries)),
|
||||
'skip_unknown' => (bool)$this->pick($options, 'skip_unknown', $this->skipUnknown),
|
||||
'dedupe' => (bool)$this->pick($options, 'dedupe', $this->dedupe),
|
||||
'postcode' => (string)$this->pick($options, 'postcode', ''),
|
||||
'on_progress' => isset($options['on_progress']) && is_callable($options['on_progress'])
|
||||
? $options['on_progress'] : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 取配置值,同时兼容下划线(batch_size)和小驼峰(batchSize)
|
||||
*/
|
||||
protected function pick(array $options, $key, $default)
|
||||
{
|
||||
if (array_key_exists($key, $options) && $options[$key] !== null) {
|
||||
return $options[$key];
|
||||
}
|
||||
$camel = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
|
||||
if (array_key_exists($camel, $options) && $options[$camel] !== null) {
|
||||
return $options[$camel];
|
||||
}
|
||||
return $default;
|
||||
}
|
||||
|
||||
protected static function defaultLists()
|
||||
{
|
||||
return [
|
||||
'qianshou' => ['快件取出', '代取快递', '派件入柜', '柜机代收', '驿站代收', '第三方代收', '签收', '签收成功',
|
||||
'自提柜入柜', '第三方妥投', '出站签收', '快件取出扫描', '快件签收', '已签收'],
|
||||
'yunshu' => ['收件', '发件', '到件', '派件', '改地址件', '接单', '修改预约取件时间', '已揽收', '已收入', '已发出',
|
||||
'转寄', '第三方代派', '派件中', '第三方代收入库', '航空发货', '航空提货', '快件揽收', '发件扫描', '到件扫描',
|
||||
'出仓扫描', '入库扫描', '代理点收入扫描', '出库扫描', '安检扫描', '收件扫描', '揽件扫描', '入中转', '出中转',
|
||||
'第三方代收快递员取出', '其他', '清关开始', '清关结束', '干线到达', '干线离开', '转单'],
|
||||
'yichang' => ['问题件', '留仓件', '签收失败', '揽收失败', '问题件扫描', '其他扫描', '拒收', '清关失败'],
|
||||
'back' => ['退回件', '退回', '退件扫描'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -55,6 +55,9 @@ class Dispatcher
|
||||
if (!isset(self::$handlers['notify.reply'])) {
|
||||
self::register('notify.reply', [new ReplyHandler(), 'handle']);
|
||||
}
|
||||
if (!isset(self::$handlers['waybill.getreceive'])) {
|
||||
self::register('waybill.getreceive', [new WaybillReceiveHandler(), 'handle']);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 处理器注册 ====================
|
||||
@ -98,7 +101,8 @@ class Dispatcher
|
||||
*
|
||||
* @param array $queryParams URL query 参数($_GET)
|
||||
* @param string $rawBody 原始请求体(php://input)
|
||||
* @return array ['code' => int, 'msg' => string, 'data' => mixed]
|
||||
* @return array|RawResponse 默认 ['code' => int, 'msg' => string, 'data' => mixed];
|
||||
* 处理器返回 RawResponse 时原样透出(裸数组响应,如 waybill.getreceive)
|
||||
*/
|
||||
public function handle(array $queryParams, $rawBody)
|
||||
{
|
||||
@ -140,6 +144,9 @@ class Dispatcher
|
||||
// ---- 5. 调用处理器 ----
|
||||
try {
|
||||
$result = call_user_func(self::$handlers[$method], $body, $queryParams);
|
||||
if ($result instanceof RawResponse) {
|
||||
return $result;
|
||||
}
|
||||
return is_array($result) ? $result : ['code' => 1, 'msg' => 'ok', 'data' => $result];
|
||||
} catch (\Throwable $e) {
|
||||
\think\Log::error("[WmsNotify] {$method} 处理器异常: " . $e->getMessage());
|
||||
|
||||
31
application/index/library/new_wms/notify/RawResponse.php
Normal file
31
application/index/library/new_wms/notify/RawResponse.php
Normal file
@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace app\index\library\new_wms\notify;
|
||||
|
||||
/**
|
||||
* 原样响应
|
||||
*
|
||||
* 入站处理器默认返回 ['code' => int, 'msg' => string, 'data' => mixed] 外壳,
|
||||
* 由 new_wms_notify 统一 json 输出。
|
||||
*
|
||||
* 个别方法(如 waybill.getreceive)外部约定直接返回裸数组,不允许套壳,
|
||||
* 此时处理器返回本对象,Dispatcher 原样透出,控制器按 $data 输出。
|
||||
*/
|
||||
class RawResponse
|
||||
{
|
||||
/** @var mixed 直接作为响应体的数据 */
|
||||
public $data;
|
||||
|
||||
/** @var int HTTP 状态码 */
|
||||
public $httpCode;
|
||||
|
||||
/**
|
||||
* @param mixed $data
|
||||
* @param int $httpCode
|
||||
*/
|
||||
public function __construct($data, $httpCode = 200)
|
||||
{
|
||||
$this->data = $data;
|
||||
$this->httpCode = $httpCode;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
namespace app\index\library\new_wms\notify;
|
||||
|
||||
use app\index\library\express\Trace;
|
||||
|
||||
/**
|
||||
* waybill.getreceive — 运单揽收状态查询
|
||||
*
|
||||
* 调用方(WMS 平台)按仓库异步任务批量询问:这些运单是否已被我们(银河仓)揽收。
|
||||
* 单批最多 10 单,签名模式 simple:md5(appSecret + timestamp + bodyJson)。
|
||||
*
|
||||
* 请求体:
|
||||
* {"request":{"waybill_codes":["773361284774644","321457247679904"]}}
|
||||
* 响应体(裸数组,不套 {code,msg,data} 外壳):
|
||||
* [{"waybill_code":"773361284774644","is_galaxy_receive":1},
|
||||
* {"waybill_code":"321457247679904","is_galaxy_receive":0}]
|
||||
*
|
||||
* 判定口径:
|
||||
* - 只查快递轨迹接口(express\Trace),与本地订单/快递/揽收记录无关;
|
||||
* - 轨迹非空即视为「已揽收」;
|
||||
* - 已揽收结果缓存 24 小时,命中缓存直接返回、不再请求轨迹接口(不做负缓存);
|
||||
* - 未揽收 / 查不到 / 识别不出快递公司 / 接口失败 一律返回 0。
|
||||
*/
|
||||
class WaybillReceiveHandler
|
||||
{
|
||||
/** 单次最多处理的运单号数量(调用方 10 单一批,这里放宽兜底) */
|
||||
const MAX_CODES = 50;
|
||||
|
||||
/** 已揽收结果缓存时长(秒) */
|
||||
const CACHE_TTL = 86400;
|
||||
|
||||
/** 缓存 key 前缀 */
|
||||
const CACHE_PREFIX = 'wms_waybill_receive:';
|
||||
|
||||
/** 轨迹接口超时(秒),需保证整体小于调用方 30s 回调超时 */
|
||||
const TRACE_TIMEOUT = 10;
|
||||
|
||||
/** 轨迹接口并发数 */
|
||||
const TRACE_CONCURRENCY = 10;
|
||||
|
||||
/**
|
||||
* 处理 waybill.getreceive
|
||||
*
|
||||
* @param array $body 请求体 { request: { waybill_codes: [...] } },兼容平铺的 waybill_codes
|
||||
* @param array $query URL query 参数
|
||||
* @return RawResponse
|
||||
*/
|
||||
public function handle(array $body, array $query)
|
||||
{
|
||||
$codes = $this->extractCodes($body);
|
||||
if (empty($codes)) {
|
||||
return new RawResponse([]);
|
||||
}
|
||||
|
||||
$received = $this->resolve($codes);
|
||||
|
||||
$rows = [];
|
||||
foreach ($codes as $code) {
|
||||
$rows[] = [
|
||||
'waybill_code' => $code,
|
||||
'is_galaxy_receive' => !empty($received[$code]) ? 1 : 0,
|
||||
];
|
||||
}
|
||||
|
||||
\think\Log::info('[WmsNotify] waybill.getreceive 处理完成: 共 ' . count($codes) . ' 单,已揽收 ' . count(array_filter($received)) . ' 单');
|
||||
|
||||
return new RawResponse($rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取并清洗运单号(去空、去重、保序、限量)
|
||||
*
|
||||
* @param array $body
|
||||
* @return array
|
||||
*/
|
||||
protected function extractCodes(array $body)
|
||||
{
|
||||
$raw = [];
|
||||
if (isset($body['request']['waybill_codes'])) {
|
||||
$raw = $body['request']['waybill_codes'];
|
||||
} elseif (isset($body['request']['waybillCodes'])) {
|
||||
$raw = $body['request']['waybillCodes'];
|
||||
} elseif (isset($body['waybill_codes'])) {
|
||||
$raw = $body['waybill_codes'];
|
||||
} elseif (isset($body['waybillCodes'])) {
|
||||
$raw = $body['waybillCodes'];
|
||||
}
|
||||
|
||||
if (!is_array($raw)) {
|
||||
$raw = [$raw];
|
||||
}
|
||||
|
||||
$codes = [];
|
||||
foreach ($raw as $item) {
|
||||
if (is_array($item) || is_object($item)) {
|
||||
continue;
|
||||
}
|
||||
$code = trim((string)$item);
|
||||
if ($code === '' || isset($codes[$code])) {
|
||||
continue;
|
||||
}
|
||||
$codes[$code] = $code;
|
||||
if (count($codes) >= self::MAX_CODES) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return array_values($codes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 逐单判定是否已揽收:缓存优先,其余并发查询轨迹接口
|
||||
*
|
||||
* @param array $codes
|
||||
* @return array [运单号 => 1|0]
|
||||
*/
|
||||
protected function resolve(array $codes)
|
||||
{
|
||||
$received = array_fill_keys($codes, 0);
|
||||
$redis = $this->connectRedis();
|
||||
|
||||
$pending = [];
|
||||
foreach ($codes as $code) {
|
||||
if ($redis !== null && $this->cacheHit($redis, $code)) {
|
||||
$received[$code] = 1;
|
||||
continue;
|
||||
}
|
||||
$pending[] = $code;
|
||||
}
|
||||
|
||||
if (empty($pending)) {
|
||||
\think\Log::info('[WmsNotify] waybill.getreceive 命中缓存,跳过轨迹接口: ' . count($codes) . ' 单');
|
||||
return $received;
|
||||
}
|
||||
|
||||
try {
|
||||
$traceOptions = [
|
||||
'timeout' => self::TRACE_TIMEOUT,
|
||||
'concurrency' => self::TRACE_CONCURRENCY,
|
||||
'batch_size' => 1,
|
||||
'retries' => 0,
|
||||
];
|
||||
// 轨迹接口地址可通过 application/extra/wms.php 的 trace_base_url 覆盖(便于测试/灰度)
|
||||
$traceBaseUrl = config('wms.trace_base_url');
|
||||
if (!empty($traceBaseUrl)) {
|
||||
$traceOptions['base_url'] = $traceBaseUrl;
|
||||
}
|
||||
$trace = new Trace($traceOptions);
|
||||
$list = $trace->query($pending);
|
||||
} catch (\Throwable $e) {
|
||||
\think\Log::error('[WmsNotify] waybill.getreceive 轨迹查询异常: ' . $e->getMessage());
|
||||
return $received;
|
||||
}
|
||||
|
||||
foreach ($list as $index => $item) {
|
||||
$code = isset($pending[$index]) ? $pending[$index] : '';
|
||||
if ($code === '' || empty($item['ok']) || empty($item['traces'])) {
|
||||
continue;
|
||||
}
|
||||
$received[$code] = 1;
|
||||
if ($redis !== null) {
|
||||
$this->cacheSet($redis, $code);
|
||||
}
|
||||
}
|
||||
|
||||
return $received;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return \Redis|null
|
||||
*/
|
||||
protected function connectRedis()
|
||||
{
|
||||
if (!class_exists('\Redis')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$config = (array)config('cache.redis');
|
||||
$host = !empty($config['host']) ? $config['host'] : '127.0.0.1';
|
||||
$port = !empty($config['port']) ? (int)$config['port'] : 6379;
|
||||
|
||||
try {
|
||||
$redis = new \Redis();
|
||||
$redis->connect($host, $port, 1.5);
|
||||
if (!empty($config['password'])) {
|
||||
$redis->auth($config['password']);
|
||||
}
|
||||
if (!empty($config['select'])) {
|
||||
$redis->select((int)$config['select']);
|
||||
}
|
||||
return $redis;
|
||||
} catch (\Exception $e) {
|
||||
\think\Log::error('[WmsNotify] waybill.getreceive Redis 连接失败: ' . $e->getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
protected function cacheHit($redis, $code)
|
||||
{
|
||||
try {
|
||||
return (string)$redis->get(self::CACHE_PREFIX . $code) === '1';
|
||||
} catch (\Exception $e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected function cacheSet($redis, $code)
|
||||
{
|
||||
try {
|
||||
$redis->setex(self::CACHE_PREFIX . $code, self::CACHE_TTL, '1');
|
||||
} catch (\Exception $e) {
|
||||
// 缓存失败不影响本次结果
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user