queryTraces(WaybillCodes::parse($body, self::MAX_CODES)); $rows = []; $count = 0; foreach ($codes as $code) { $traces = isset($traceMap[$code]) ? $traceMap[$code] : []; $count += count($traces); $rows[] = [ 'waybillNo' => $code, 'trace' => $traces, ]; } \think\Log::info('[WmsNotify] waybill.getTrace 处理完成: 共 ' . count($codes) . ' 单,轨迹 ' . $count . ' 条'); return new RawResponse($rows); } /** * 批量查询轨迹(10 单并发) * * @param array $items [{waybill_code, phone}, ...] * @return array [运单号 => 轨迹数组] */ protected function queryTraces(array $items) { $map = []; $inputs = []; foreach ($items as $item) { $map[$item['waybill_code']] = []; $inputs[] = [ 'postnum' => $item['waybill_code'], 'phone' => $item['phone'], ]; } if (empty($inputs)) { return $map; } try { $traceOptions = [ 'timeout' => self::TRACE_TIMEOUT, 'concurrency' => self::TRACE_CONCURRENCY, 'batch_size' => 1, 'retries' => 0, ]; $traceBaseUrl = config('wms.trace_base_url'); if (!empty($traceBaseUrl)) { $traceOptions['base_url'] = $traceBaseUrl; } $trace = new Trace($traceOptions); $list = $trace->query($inputs); } catch (\Throwable $e) { \think\Log::error('[WmsNotify] waybill.getTrace 轨迹查询异常: ' . $e->getMessage()); return $map; } foreach ($list as $index => $result) { $code = isset($inputs[$index]['postnum']) ? $inputs[$index]['postnum'] : ''; if ($code === '' || empty($result['ok']) || empty($result['raw'])) { continue; } $map[$code] = $this->flattenTraces($result['raw']); } return $map; } /** * 上游返回 [{waybillNo, trace:{opTime,...}}, ...],这里取内层 trace 对象, * 输出成调用方需要的 [{opTime, outBizCode, memo, opOrgCityName, weight, scanType}, ...] * * @param array $raw * @return array */ protected function flattenTraces($raw) { if (!is_array($raw)) { return []; } $traces = []; foreach ($raw as $item) { if (!is_array($item)) { continue; } if (isset($item['trace']) && is_array($item['trace'])) { $traces[] = $item['trace']; } else { $traces[] = $item; } } return $traces; } }