DispatchService.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. <?php
  2. namespace common\components\delivery\services;
  3. use biz\shop\classes\ShopClass;
  4. use bizGhs\express\classes\DeliveryAuthTokenClass;
  5. use bizGhs\order\classes\OrderItemClass;
  6. use common\components\delivery\helpers\HttpClient;
  7. use common\components\delivery\services\adapter\{ ShansongAdapter, HuolalaAdapter, FengniaoAdapter, ShunfengAdapter}; // MeituanAdapter, DadaAdapter, UUAdapter,
  8. use Yii;
  9. /**
  10. * 聚合调度逻辑(平台选择/优先级)
  11. * Class DispatchService
  12. * @package App\Services
  13. */
  14. class DispatchService
  15. {
  16. protected $adapters;
  17. protected $platformName = '';
  18. public function __construct($mainId, $platform='')
  19. {
  20. if ($platform == '') {
  21. $authPlatforms = DeliveryAuthTokenClass::getAllByCondition(['mainId'=>$mainId]);
  22. foreach($authPlatforms as $pt) {
  23. switch ($pt['platform']) {
  24. case 'shansong':
  25. $this->adapters['shansong'] = new ShansongAdapter($pt['accessToken']);
  26. break;
  27. case 'huolala':
  28. $this->adapters['huolala'] = new HuolalaAdapter($pt['accessToken']);
  29. break;
  30. case 'fengniao':
  31. $adapter = new FengniaoAdapter($pt['accessToken']);
  32. $adapter->setMerchantId($pt['merchantId']); // TODO: 确认是否需要使用动态的商户ID
  33. $this->adapters['fengniao'] = $adapter;
  34. break;
  35. case 'shunfeng':
  36. $this->adapters['shunfeng'] = new ShunfengAdapter($pt['accessToken'], $pt['shopId']);
  37. break;
  38. }
  39. //检测 token 是否即将过期
  40. $tokenExpireTime = $pt['expiresAt'];
  41. if ($tokenExpireTime < time() + 86400 * 5) {
  42. Yii::info('刷新 token: ' . $pt['platform'] . ',refreshToken: ' . $pt['refreshToken'] . ',merchantId: ' . $pt['merchantId']);
  43. $this->refreshToken($pt['platform'], $pt['refreshToken'], ['merchantId' => $pt['merchantId']]);
  44. }
  45. }
  46. } else {
  47. $authPlatform = DeliveryAuthTokenClass::getByCondition(['mainId'=>$mainId, 'platform'=>$platform]);
  48. switch ($platform) {
  49. case 'shansong':
  50. $this->adapters['shansong'] = new ShansongAdapter($authPlatform['accessToken']);
  51. break;
  52. case 'huolala':
  53. $this->adapters['huolala'] = new HuolalaAdapter($authPlatform['accessToken']);
  54. break;
  55. case 'fengniao':
  56. //$this->adapters['fengniao'] = new FengniaoAdapter($authPlatform['accessToken']);
  57. $adapter = new FengniaoAdapter($authPlatform['accessToken']);
  58. $adapter->setMerchantId($authPlatform['merchantId']); // TODO: 确认是否需要使用动态的商户ID
  59. $this->adapters['fengniao'] = $adapter;
  60. break;
  61. case 'shunfeng':
  62. $this->adapters['shunfeng'] = new ShunfengAdapter($authPlatform['accessToken'], $authPlatform['shopId']);
  63. break;
  64. }
  65. $this->platformName = $platform;
  66. if($authPlatform['expiresAt'] < time() + 86400 * 5) {
  67. Yii::info('刷新 token: ' . $platform . ',refreshToken: ' . $authPlatform['refreshToken'] . ',merchantId: ' . $authPlatform['merchantId']);
  68. $this->refreshToken($platform, $authPlatform['refreshToken'], ['merchantId' => $authPlatform['merchantId']]);
  69. }
  70. }
  71. }
  72. /**
  73. * 发单调度
  74. */
  75. public function createOrder($order, $shopId, $params)
  76. {
  77. $order = $order->toArray();
  78. $shop = ShopClass::getById($shopId, false, 'id,merchantName,fullAddress,lat,long,city,dist,floor,mobile,merchantName');
  79. $adapter = $this->getAdapter();
  80. $orderData = $adapter->formatOrderData($order, $shop, $params);
  81. return $adapter->createOrder($orderData);
  82. }
  83. /**
  84. *
  85. */
  86. public function addTip($data)
  87. {
  88. $adapter = $this->getAdapter();
  89. return $adapter->addTip($data);
  90. }
  91. /**
  92. * @param $orderId 平台订单号
  93. * @param string $thirdOrderNo xhGhsOrder.orderSn
  94. */
  95. public function selectOrder($orderId, $thirdOrderNo='')
  96. {
  97. $adapter = $this->getAdapter();
  98. if ($adapter instanceof ShansongAdapter) {
  99. return $adapter->selectOrder($orderId, $thirdOrderNo);
  100. }
  101. return $adapter->selectOrder($orderId);
  102. }
  103. public function cancelOrder($orderId, $reason)
  104. {
  105. $adapter = $this->getAdapter();
  106. return $adapter->cancelOrder($orderId, $reason);
  107. }
  108. public function getCancelReasonList($orderId)
  109. {
  110. $adapter = $this->getAdapter();
  111. return $adapter->getCancelReasonList($orderId);
  112. }
  113. public function getAdapter()
  114. {
  115. return $this->adapters[$this->platformName];
  116. }
  117. /**
  118. * 获取所有平台的最佳报价(使用 Guzzle 并发请求)
  119. *
  120. * 流程说明:
  121. * 1. 同步准备各平台的前置数据(如城市信息、订单商品等)
  122. * 2. 使用 Guzzle Pool 并发发送各平台的报价请求(5秒超时)
  123. * 3. 某个平台失败/超时不影响其他平台,继续等待结果
  124. *
  125. * @param array $order 订单信息
  126. * @param array $shop 店铺信息
  127. * @return array 返回所有平台的报价结果
  128. */
  129. public function getAllPlatformPrice($order, $shop, $orderTime)
  130. {
  131. // 第一步:准备前置数据(同步进行,因为某些平台需要这些数据)
  132. $preparedData = $this->preparePlatformData($order, $shop, $orderTime);
  133. if (empty($preparedData)) {
  134. return ['error' => '所有平台数据准备失败'];
  135. }
  136. // 第二步:并发调用各平台的报价接口
  137. $results = $this->concurrentGetPrices($preparedData, $orderTime);
  138. if (empty($results['success']) && empty($results['failed'])) {
  139. return ['error' => '没有可用的物流平台'];
  140. }
  141. // 格式化返回结果
  142. return [
  143. 'quotes' => array_values($results['success'] ?? []),
  144. 'failed' => $results['failed'] ?? [],
  145. ];
  146. }
  147. /**
  148. * 为各平台准备订单数据(前置数据同步获取)
  149. *
  150. * @param array $order 订单信息
  151. * @param array $shop 店铺信息
  152. * @return array 各平台的订单数据
  153. */
  154. private function preparePlatformData($order, $shop)
  155. {
  156. $preparedData = [];
  157. // 准备 Huolala 数据
  158. if (isset($this->adapters['huolala'])) {
  159. try {
  160. $preparedData['huolala'] = $this->prepareHuolalaData($order, $shop);
  161. } catch (\Exception $e) {
  162. Yii::warning("Huolala 数据准备失败: {$e->getMessage()}");
  163. }
  164. }
  165. // 准备 Fengniao 数据
  166. if (isset($this->adapters['fengniao'])) {
  167. try {
  168. $preparedData['fengniao'] = $this->prepareFengniaoData($order, $shop);
  169. } catch (\Exception $e) {
  170. Yii::warning("Fengniao 数据准备失败: {$e->getMessage()}");
  171. }
  172. }
  173. // 准备 Shansong 数据
  174. if (isset($this->adapters['shansong'])) {
  175. try {
  176. $preparedData['shansong'] = $this->prepareShansongData($order, $shop);
  177. } catch (\Exception $e) {
  178. Yii::warning("Shansong 数据准备失败: {$e->getMessage()}");
  179. }
  180. }
  181. // 准备顺丰订单数据
  182. if (isset($this->adapters['shunfeng'])) {
  183. try {
  184. $preparedData['shunfeng'] = $this->prepareShunfengData($order, $shop);
  185. } catch (\Exception $e) {
  186. Yii::warning("Shunfeng 数据准备失败: {$e->getMessage()}");
  187. }
  188. }
  189. return $preparedData;
  190. }
  191. /**
  192. * 准备货拉拉订单数据
  193. */
  194. private function prepareHuolalaData($order, $shop)
  195. {
  196. $formatCity = rtrim($order['city'], '市');
  197. $cities = include Yii::getAlias('@common/components/delivery/platform/huolala/cities.php');
  198. if (!isset($cities[$formatCity])) {
  199. throw new \Exception('城市编码表中没有找到城市: ' . $formatCity);
  200. }
  201. $cityId = $cities[$formatCity]['city_id'];
  202. $cityVehicleList = $this->adapters['huolala']->getCityVehicleList($cityId); // 产生外部请求
  203. $cityInfoRevision = $cityVehicleList['city_info_revision']; // 城市版本号
  204. $vehicleList = $cityVehicleList['vehicle_list']; // 所有车型列表
  205. if (empty($vehicleList)) {
  206. throw new \Exception('没有找到可选车型');
  207. }
  208. // 解析额外需求
  209. $specReqItem = $cityVehicleList['spec_req_item'] ?? [];
  210. $specReq = [];
  211. foreach ($specReqItem as $item) {
  212. $specReq[] = $item['type'] ?? null;
  213. }
  214. $specReq = array_filter($specReq);
  215. // 构建所有车型数据
  216. $vehicleTypeList = [];
  217. foreach ($vehicleList as $vehicle) {
  218. if(!in_array($vehicle['vehicle_name'], ['跑腿', '小面', '微面'])){ // && !$this->adapters['huolala']->getIsSandbox()
  219. continue;
  220. }
  221. $vehicleStd = [];
  222. $vehicleStd[] = count($vehicle['vehicle_std_item']) > 0 ? $vehicle['vehicle_std_item'][0]['name'] : '';
  223. $vehicleTypeList[$vehicle['order_vehicle_id']] = [
  224. 'order_vehicle_id' => $vehicle['order_vehicle_id'],
  225. 'city_info_revision' => $cityInfoRevision,
  226. 'order_time' => time() + 600,
  227. 'addr_info' => [
  228. [
  229. 'name' => $shop['merchantName'],
  230. 'addr' => $shop['province'] . $shop['city'] . $shop['dist'] . $shop['address'],
  231. 'city_id' => $cityId,
  232. 'city_name' => $shop['city'],
  233. 'district_name' => $shop['dist'],
  234. 'house_number' => $shop['floor'],
  235. 'contacts_name' => $shop['mobile'],
  236. 'contacts_phone_no' => $shop['mobile'],
  237. 'lat_lon' => ['lat' => (float)$shop['lat'], 'lon' => (float)$shop['long']],
  238. ],
  239. [
  240. 'name' => $order['customName'],
  241. 'addr' => $order['fullAddress'],
  242. 'city_id' => $cityId,
  243. 'city_name' => $order['city'],
  244. 'district_name' => $order['dist'],
  245. 'house_number' => $order['floor'],
  246. 'contacts_name' => $order['customName'],
  247. 'contacts_phone_no' => $order['customMobile'],
  248. 'lat_lon' => ['lat' => (float)$order['lat'], 'lon' => (float)$order['long']],
  249. ]
  250. ],
  251. 'vehicle_std' => $vehicleStd,
  252. 'spec_req' => array_values($specReq),
  253. 'coupon_id' => 123456, // TODO ???
  254. 'invoice_type' => 1,
  255. 'order_service_type' => 1,
  256. '_meta' => [
  257. 'vehicle_type' => $vehicle['vehicle_name'],
  258. 'city_info_revision' => $cityInfoRevision,
  259. ]
  260. ];
  261. }
  262. return [
  263. 'platform' => 'huolala',
  264. 'city_id' => $cityId,
  265. 'vehicle_type_list' => $vehicleTypeList,
  266. ];
  267. }
  268. /**
  269. * 准备蜂鸟订单数据
  270. */
  271. private function prepareFengniaoData($order, $shop)
  272. {
  273. $this->adapters['fengniao']->setMerchantId(14594092); // TODO: 确认是否需要使用动态的商户ID
  274. $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num');
  275. $goodsItemList = [];
  276. foreach ($itemInfos as $item) {
  277. $goodsItemList[] = [
  278. 'item_actual_amount_cent' => (int)($item['unitPrice'] * 100 * $item['num']),
  279. 'item_amount_cent' => (int)($item['unitPrice'] * 100),
  280. 'item_id' => $item['id'],
  281. 'item_name' => $item['name'],
  282. 'item_quantity' => $item['num'],
  283. ];
  284. }
  285. return [
  286. 'platform' => 'fengniao',
  287. 'partner_order_code' => $order['orderSn'],
  288. 'receiver_primary_phone' => $order['customMobile'],
  289. 'receiver_name' => $order['customName'],
  290. 'receiver_latitude' => (float)$order['lat'],
  291. 'receiver_longitude' => (float)$order['long'],
  292. 'receiver_address' => $order['fullAddress'],
  293. 'position_source' => 3,
  294. 'goods_count' => count($goodsItemList),
  295. 'goods_weight' => (float)$order['weight'],
  296. 'goods_total_amount_cent' => (int)($order['prePrice'] * 100),
  297. 'goods_actual_amount_cent' => (int)($order['actPrice'] * 100),
  298. 'goods_item_list' => $goodsItemList,
  299. 'order_type' => 1,
  300. 'chain_store_id' => 467788524,
  301. 'order_remark' => $order['remark'] ?? '',
  302. ];
  303. }
  304. /**
  305. * 准备闪送订单数据
  306. */
  307. private function prepareShansongData($order, $shop)
  308. {
  309. return [
  310. 'platform' => 'shansong',
  311. 'cityName' => $shop['city'],
  312. 'sender' => [
  313. 'fromAddress' => $shop['address'],
  314. 'fromAddressDetail' => $shop['floor'],
  315. 'fromSenderName' => $shop['shopName'],
  316. 'fromMobile' => $shop['mobile'],
  317. 'fromLatitude' => (float)$shop['lat'],
  318. 'fromLongitude' => (float)$shop['long'],
  319. ],
  320. 'receiverList' => [
  321. [
  322. 'orderNo' => $order['orderSn'],
  323. 'toAddress' => $order['address'],
  324. 'toAddressDetail' => $order['floor'],
  325. 'toReceiverName' => $order['customName'],
  326. 'toMobile' => $order['customMobile'],
  327. 'toLatitude' => (float)$order['lat'],
  328. 'toLongitude' => (float)$order['long'],
  329. 'goodType' => 7,
  330. 'weight' => (int)$order['weight'],
  331. 'remarks' => $order['remark'] ?? '',
  332. ]
  333. ],
  334. 'appointType' => 0,
  335. 'appointmentDate' => '',
  336. 'travelWay' => 0,
  337. 'deliveryType' => 1,
  338. 'expectStartTime' => null,
  339. 'expectEndTime' => null,
  340. ];
  341. }
  342. /**
  343. * 准备顺丰订单数据
  344. */
  345. private function prepareShunfengData($order, $shop)
  346. {
  347. // 获取订单商品信息
  348. $itemInfos = OrderItemClass::getAllByCondition(['orderSn' => $order['orderSn']], null, 'id, name, unitPrice, num, unitWeight');
  349. // 计算商品总重量(单位:克)
  350. $totalWeight = 0;
  351. foreach ($itemInfos as $item) {
  352. $totalWeight += (int)($item['unitWeight'] * $item['num']) * 1000;
  353. }
  354. // 如果没有商品重量,使用订单重量
  355. if ($totalWeight == 0 && isset($order['weight'])) {
  356. $totalWeight = (int)$order['weight'] * 1000;
  357. }
  358. // 默认重量为1000克(1公斤)
  359. if ($totalWeight == 0) {
  360. $totalWeight = 1000;
  361. }
  362. return [
  363. 'platform' => 'shunfeng',
  364. 'user_lng' => (string)$order['long'], // 用户地址经度
  365. 'user_lat' => (string)$order['lat'], // 用户地址纬度
  366. 'user_address' => $order['fullAddress'], // 用户详细地址
  367. 'weight' => $totalWeight, // 物品重量(单位:克)
  368. 'product_type' => 4, // 物品类型(4:鲜花绿植)
  369. 'push_time' => time(), // 推单时间(秒级时间戳)
  370. 'shop' => [ // 发货店铺信息
  371. 'shop_name' => $shop['merchantName'], // 店铺名称
  372. 'shop_address' => $shop['address'], // 店铺地址
  373. 'shop_lng' => (string)$shop['long'], // 店铺经度
  374. 'shop_lat' => (string)$shop['lat'], // 店铺纬度
  375. 'shop_phone' => $shop['mobile'], // 店铺联系电话
  376. ],
  377. //-------------------------- 非必填 -------------------------------
  378. 'city_name' => $order['city'], // 发单城市
  379. //'order_source' => '6', // 订单接入来源(6:京东秒送,可自定义)
  380. 'source_origin_order_id' => $order['orderSn'], // 商流订单号
  381. 'total_price' => (int)($order['actPrice'] * 100), // 用户订单总金额(单位:分)
  382. 'is_appoint' => 0, // 是否预约单(0:非预约单)
  383. 'appoint_type' => 0, // TODO 预约单类型(0:立即单)
  384. 'expect_time' => 0, // TODO 用户期望送达时间
  385. //'expect_pickup_time' => 0, // TODO 用户期望上门时间 -- appoint_type=2时需必传,秒级时间戳
  386. 'shop_expect_time' => 0, // TODO 商家期望送达时间 -- 格式为:{timestamp},
  387. 'lbs_type' => 2, // 坐标类型(2:高德坐标)
  388. 'is_insured' => 0, // 是否保价(0:非保价)
  389. 'is_person_direct' => 0, // 是否专人直送(0:否)
  390. 'vehicle' => 0, // 配送交通工具(0:否)
  391. //'four_wheeler_type' => 0, // 车型 -- 只有vehicle = 2,⻋型字段才有效。
  392. 'declared_value' => 0, // 保价金额(单位:分)
  393. 'gratuity_fee' => 0, // 订单小费(单位:分)
  394. 'rider_pick_method' => 1, // 物流流向(1:从门店取件送至用户)
  395. 'return_flag' => 511, // 返回字段控制标志位(511:全部返回)
  396. 'multi_pickup_info' => [], // 多点取货信息(暂不使用)
  397. ];
  398. }
  399. /**
  400. * 并发获取各平台报价(核心实现)
  401. *
  402. * 使用 HttpClient::postConcurrent 实现真正的并发调用,每个平台请求 5 秒超时。
  403. * 某个平台的超时或失败不会影响其他平台的执行。
  404. *
  405. * @param array $preparedData 准备好的各平台数据
  406. * @param string $orderTime 配送时间
  407. * @return array 包含成功和失败结果
  408. */
  409. private function concurrentGetPrices($preparedData, $orderTime)
  410. {
  411. $results = [
  412. 'success' => [],
  413. 'failed' => [],
  414. ];
  415. // 第一步:收集所有平台的请求信息
  416. $allRequests = [];
  417. $platformMapping = []; // 用于将请求标识映射回平台名称
  418. foreach ($preparedData as $platform => $data) {
  419. try {
  420. if (!isset($this->adapters[$platform])) {
  421. $results['failed'][$platform] = '平台适配器未初始化';
  422. continue;
  423. }
  424. $adapter = $this->adapters[$platform];
  425. // 根据平台类型调用相应的 buildPriceRequest(s) 方法
  426. if ($platform === 'huolala') {
  427. // 货拉拉返回多个请求(一个请求对应一个车型)
  428. $priceRequests = $adapter->buildPriceRequest($data, $orderTime);
  429. foreach ($priceRequests as $requestKey => $requestInfo) {
  430. $allRequests[$requestKey] = $requestInfo;
  431. $platformMapping[$requestKey] = ['platform' => 'huolala', 'data' => $data];
  432. }
  433. } else {
  434. // 其他平台(蜂鸟、闪送、顺丰)各返回一个请求
  435. $requestInfo = $adapter->buildPriceRequest($data, $orderTime);
  436. $requestKey = "{$platform}_quote";
  437. $allRequests[$requestKey] = $requestInfo;
  438. $platformMapping[$requestKey] = ['platform' => $platform, 'data' => $data];
  439. }
  440. } catch (\Throwable $e) {
  441. $results['failed'][$platform] = "构建请求失败: {$e->getMessage()}";
  442. Yii::error("[DispatchService] {$platform} 构建请求异常: {$e->getMessage()}");
  443. }
  444. }
  445. if (empty($allRequests)) {
  446. return $results;
  447. }
  448. // 第二步:使用 postConcurrent 并发发送所有请求
  449. $startTime = microtime(true);
  450. $concurrentResults = HttpClient::postConcurrent($allRequests, 3);
  451. $totalDuration = microtime(true) - $startTime;
  452. Yii::info("[DispatchService] 所有报价请求完成 (" . round($totalDuration * 1000) . "ms)");
  453. // 第三步:处理并发请求的结果
  454. foreach ($concurrentResults['success'] as $requestKey => $response) {
  455. if (!isset($platformMapping[$requestKey])) {
  456. continue;
  457. }
  458. $mapping = $platformMapping[$requestKey];
  459. $platform = $mapping['platform'];
  460. $data = $mapping['data'];
  461. try {
  462. $adapter = $this->adapters[$platform];
  463. $quote = null;
  464. if ($platform === 'huolala') {
  465. // 货拉拉的响应处理
  466. $quote = $adapter->processPriceResponse($response);
  467. if ($quote && !isset($results['success']['huolala'])) {
  468. // 第一次处理货拉拉的结果,初始化
  469. $results['success']['huolala'] = [
  470. 'platform' => 'huolala',
  471. 'city_id' => $data['city_id'],
  472. 'vehicle_type_list' => $data['vehicle_type_list'],
  473. 'price_info_list' => [],
  474. ];
  475. }
  476. $keyArr = explode('_', $requestKey);
  477. $vehicle_type_list_key = $keyArr[2];
  478. // 将该车型的报价加入到列表中
  479. if ($quote && isset($results['success']['huolala'])) {
  480. $results['success']['huolala']['price_info_list'][] = [
  481. 'calculate_price_info' => isset($quote['calculate_price_info_list']) ? $quote['calculate_price_info_list'][0] : [],
  482. 'vehicle_type' => $data['vehicle_type_list'][$vehicle_type_list_key]
  483. ];
  484. Yii::info("[DispatchService] {$platform} 报价成功: " . json_encode($quote));
  485. }
  486. } else {
  487. // 蜂鸟和闪送的响应处理
  488. $quote = $adapter->processPriceResponse($response);
  489. if ($quote && !isset($quote['error'])) {
  490. $quote['_duration'] = $totalDuration;
  491. $results['success'][$platform] = $quote;
  492. Yii::info("[DispatchService] {$platform} 报价成功: " . json_encode($quote));
  493. } else {
  494. $errorMsg = $quote['error'] ?? '报价返回数据为空';
  495. $results['failed'][$platform] = $errorMsg;
  496. Yii::warning("[DispatchService] {$platform} 报价返回错误: {$errorMsg}");
  497. }
  498. }
  499. } catch (\Throwable $e) {
  500. $platform = $mapping['platform'];
  501. $results['failed'][$platform] = "处理响应失败: {$e->getMessage()}";
  502. Yii::error("[DispatchService] {$platform} 处理响应异常: {$e->getMessage()}");
  503. }
  504. }
  505. // 第四步:处理失败的请求
  506. foreach ($concurrentResults['failed'] as $requestKey => $errorMsg) {
  507. if (!isset($platformMapping[$requestKey])) {
  508. continue;
  509. }
  510. $platform = $platformMapping[$requestKey]['platform'];
  511. // 对于货拉拉,只记录某个车型失败,不影响整体平台状态
  512. if ($platform === 'huolala') {
  513. Yii::warning("[DispatchService] huolala 车型报价失败 ({$requestKey}): {$errorMsg}");
  514. } else {
  515. if (!isset($results['failed'][$platform])) {
  516. $results['failed'][$platform] = $errorMsg;
  517. Yii::error("[DispatchService] {$platform} 报价请求失败: {$errorMsg}");
  518. }
  519. }
  520. }
  521. // 为货拉拉添加元数据
  522. if (isset($results['success']['huolala'])) {
  523. $results['success']['huolala']['_duration'] = $totalDuration;
  524. }
  525. return $results;
  526. }
  527. public function openCitiesLists($platform)
  528. {
  529. $ap = $this->adapters[$platform];
  530. return $ap->cityList();
  531. }
  532. /**
  533. * 刷新 token
  534. */
  535. public function refreshToken($platform, $refreshToken, $data=[])
  536. {
  537. switch($platform) {
  538. case 'shansong':
  539. $auth = new \common\components\delivery\platform\shansong\Auth();
  540. $auth->refreshAccessToken($refreshToken);
  541. break;
  542. case 'huolala':
  543. $auth = new \common\components\delivery\platform\huolala\Auth();
  544. $auth->refreshAccessToken($refreshToken);
  545. break;
  546. case 'fengniao':
  547. $auth = new \common\components\delivery\platform\fengniao\Auth();
  548. $auth->refreshAccessToken($refreshToken, $data['merchantId']);
  549. break;
  550. case 'shunfeng':
  551. $auth = new \common\components\delivery\platform\shunfeng\Auth();
  552. $auth->refreshAccessToken($refreshToken);
  553. break;
  554. }
  555. }
  556. }