ye4s_wms/application/index/library/new_wms/notify/WaybillReceiveHandler.php
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

217 lines
6.7 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\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) {
// 缓存失败不影响本次结果
}
}
}