liufumingren 4e5c05dfc3 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>
2026-11-11 03:22:21 +08:00

688 lines
25 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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' => ['退回件', '退回', '退件扫描'],
];
}
}