CallBackHandler.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. <?php
  2. namespace common\components\delivery\platform\shunfeng;
  3. use biz\common\classes\GhsNotifyClass;
  4. use biz\common\classes\HdNotifyClass;
  5. use bizGhs\express\classes\DeliveryAuthTokenClass;
  6. use bizGhs\express\classes\GhsDeliveryOrderClass;
  7. use bizHd\express\classes\HdDeliveryOrderClass;
  8. use bizGhs\order\classes\OrderClass;
  9. use bizHd\order\classes\OrderClass as HdOrderClass;
  10. use bizHd\purchase\classes\PurchaseClass;
  11. use common\components\noticeUtil;
  12. use common\components\util;
  13. use Yii;
  14. /**
  15. * 顺丰同城回调处理类
  16. * 处理顺丰平台的各种回调通知
  17. *
  18. * Class CallBackHandler
  19. * @package common\components\delivery\platform\shunfeng
  20. */
  21. class CallBackHandler
  22. {
  23. /**
  24. * 处理顺丰回调
  25. * 根据 url_index 参数判断回调类型并分发到对应的处理方法
  26. *
  27. * @param array $data 回调数据
  28. * @return bool 处理结果
  29. */
  30. public function handle($data)
  31. {
  32. try {
  33. // 记录回调原始数据
  34. Yii::info('顺丰同城回调 - 原始数据: ' . json_encode($data, JSON_UNESCAPED_UNICODE), 'shunfeng-callback');
  35. // 验证必要参数
  36. if (empty($data['url_index'])) {
  37. Yii::error('顺丰回调缺少 url_index 参数: ' . json_encode($data, JSON_UNESCAPED_UNICODE), 'shunfeng-callback');
  38. return false;
  39. }
  40. $urlIndex = $data['url_index'];
  41. // 根据回调类型分发处理
  42. switch ($urlIndex) {
  43. case 'rider_status':
  44. // 配送状态更改回调
  45. return $this->handleRiderStatus($data);
  46. case 'order_complete':
  47. // 订单完成回调
  48. return $this->handleOrderComplete($data);
  49. case 'sf_cancel':
  50. // 顺丰原因取消回调
  51. return $this->handleSfCancel($data);
  52. case 'rider_exception':
  53. // 订单异常回调
  54. return $this->handleRiderException($data);
  55. case 'rider_recall':
  56. // 骑士撤单回调
  57. return $this->handleRiderRecall($data);
  58. case 'bindnotify':
  59. // 授权状态回调
  60. return $this->handleBindNotify($data);
  61. case 'cancelbindnotify':
  62. // 取消授权状态回调
  63. return $this->handleCancelBindNotify($data);
  64. default:
  65. Yii::warning('未知的顺丰回调类型: ' . $urlIndex, 'shunfeng-callback');
  66. return false;
  67. }
  68. } catch (\Exception $e) {
  69. Yii::error('顺丰回调处理异常: ' . $e->getMessage() . ' | ' . $e->getTraceAsString(), 'shunfeng-callback');
  70. return false;
  71. }
  72. }
  73. /**
  74. * 通用订单回调处理逻辑
  75. *
  76. * @param array $data 回调数据
  77. * @param string $logDesc 日志描述
  78. * @param string $orderIdField 订单ID字段名
  79. * @param callable|null $extraHandler 额外处理逻辑,参数为 ($order, $sendStatus, $isGhs)
  80. * @return bool
  81. */
  82. private function processOrderCallback($data, $logDesc, $orderIdField = 'sf_order_id', $extraHandler = null)
  83. {
  84. Yii::info($logDesc . ': ' . json_encode($data, JSON_UNESCAPED_UNICODE), 'shunfeng-callback');
  85. if (empty($data[$orderIdField]) || !isset($data['order_status'])) {
  86. Yii::error($logDesc . '参数不完整: ' . json_encode($data, JSON_UNESCAPED_UNICODE), 'shunfeng-callback');
  87. return false;
  88. }
  89. $orderId = $data[$orderIdField];
  90. // 查找配送订单
  91. $deliveryOrder = $this->getDeliveryOrder($orderId);
  92. if (!$deliveryOrder) {
  93. Yii::error('顺丰配送订单不存在: ' . $orderIdField . '=' . $orderId, 'shunfeng-callback');
  94. return false;
  95. }
  96. $sendStatus = $this->convertOrderSendStatus($data['order_status']);
  97. $orderStatus = $this->convertOrderStatus($data['order_status']);
  98. if ($sendStatus === null) {
  99. Yii::error('顺丰订单状态转换失败: ' . $data['order_status'], 'shunfeng-callback');
  100. return false;
  101. }
  102. if($sendStatus == -1){
  103. noticeUtil::push('顺丰跑腿产生订单取消回调');
  104. }
  105. // 更新配送订单
  106. $deliveryOrder->orderStatus = $sendStatus;
  107. $deliveryOrder->save();
  108. // 更新主订单
  109. if (isset($deliveryOrder->ghsOrderId)) { // 批发
  110. util::checkRepeatCommit('ghs_pt_' . $deliveryOrder->ghsOrderId . '_' . $data['order_status'], 2);
  111. $order = OrderClass::getById($deliveryOrder->ghsOrderId, true, 'id,sendType,sendStatus,deliveryId,purchaseId,customId,status');
  112. if ($order) {
  113. if ($extraHandler) {
  114. call_user_func($extraHandler, $order, $sendStatus, true, $data);
  115. }
  116. $cg = PurchaseClass::getById($order->purchaseId, true, 'id,sendStatus');
  117. $cg->sendStatus = $sendStatus;
  118. $cg->save();
  119. $order->sendStatus = $sendStatus;
  120. $order->status = $orderStatus;
  121. $order->save();
  122. }
  123. } elseif (isset($deliveryOrder->hdOrderId)) { // 零售
  124. util::checkRepeatCommit('hd_pt_' . $deliveryOrder->hdOrderId . '_' . $data['order_status'], 2);
  125. $order = HdOrderClass::getById($deliveryOrder->hdOrderId, true, 'id,sendType,sendStatus,deliveryId,customId,status');
  126. if ($order) {
  127. if ($extraHandler) {
  128. call_user_func($extraHandler, $order, $sendStatus, false, $data);
  129. }
  130. $order->sendStatus = $sendStatus;
  131. $order->status = $orderStatus;
  132. $order->save();
  133. }
  134. }
  135. return true;
  136. }
  137. /**
  138. * 处理配送状态更改回调
  139. * 状态包括:10-配送员接单/改派;12-配送员到店;15-配送员配送中
  140. *
  141. * @param array $data 回调数据
  142. * @return bool 处理结果
  143. */
  144. private function handleRiderStatus($data)
  145. {
  146. return $this->processOrderCallback($data, '顺丰配送状态更改回调', 'sf_order_id');
  147. }
  148. /**
  149. * 处理订单完成回调
  150. * 订单状态:17-配送员点击完成
  151. *
  152. * @param array $data 回调数据
  153. * @return bool 处理结果
  154. */
  155. private function handleOrderComplete($data)
  156. {
  157. return $this->processOrderCallback($data, '顺丰订单完成回调', 'sf_order_id', function($order, $sendStatus, $isGhs, $data) {
  158. if ($isGhs && $sendStatus == 5) {
  159. $cg = PurchaseClass::getById($order->purchaseId, true, 'id,status,sendStatus');
  160. if($cg->status == 3){
  161. OrderClass::confirmReach($order, ['staffId' => 0, 'staffName' => '']);
  162. }else{
  163. Yii::warning('进行确认送达时,采购单状态不为3,无法进行确认送达。orderId='.$order->id);
  164. noticeUtil::push('进行确认送达时,采购单状态不为3,无法进行确认送达。orderId='.$order->id.', purchaseId='.$cg->id);
  165. }
  166. }
  167. });
  168. }
  169. /**
  170. * 处理顺丰原因取消回调
  171. * 订单状态:2-订单取消
  172. *
  173. * @param array $data 回调数据
  174. * @return bool 处理结果
  175. */
  176. private function handleSfCancel($data)
  177. {
  178. return $this->processOrderCallback($data, '顺丰取消订单回调', 'sf_order_id', function($order, $sendStatus, $isGhs, $data) {
  179. if(!in_array($order->sendStatus, [-1, -2]) && in_array($sendStatus, [-1, -2])) {
  180. $cancelCode = $data['cancel_code'];
  181. $event = $this->cancelFrom($sendStatus, $cancelCode);
  182. if($isGhs) {
  183. OrderClass::cancelOrderSend($order, ['staffId' => 0, 'staffName' => '']);
  184. GhsNotifyClass::ptErrorNotify($order->id, $event);
  185. }
  186. if(!$isGhs) {
  187. HdNotifyClass::ptErrorNotify($order->id, $event);
  188. }
  189. noticeUtil::push('处理顺丰原因取消回调 -- orderId='.$order->id);
  190. }
  191. });
  192. }
  193. /**
  194. * 处理订单异常回调
  195. * 订单状态:91-骑士上报异常
  196. *
  197. * @param array $data 回调数据
  198. * @return bool 处理结果
  199. */
  200. private function handleRiderException($data)
  201. {
  202. return $this->processOrderCallback($data, '顺丰订单异常回调', 'sf_order_id', function($order, $sendStatus, $isGhs, $data) {
  203. if(!in_array($order->sendStatus, [-1, -2]) && in_array($sendStatus, [-1, -2])){
  204. $exId = $data['ex_id'];
  205. $event = $this->cancelFrom($sendStatus, $exId);
  206. if ($isGhs) {
  207. OrderClass::cancelOrderSend($order, ['staffId' => 0, 'staffName' => '']);
  208. GhsNotifyClass::ptErrorNotify($order->id, $event);
  209. }
  210. if (!$isGhs) {
  211. HdNotifyClass::ptErrorNotify($order->id, $event);
  212. }
  213. noticeUtil::push('处理订单异常回调 -- orderId='.$order->id);
  214. }
  215. });
  216. }
  217. /**
  218. * 处理骑士撤单回调
  219. * 订单状态:22-配送员撤单
  220. *
  221. * @param array $data 回调数据
  222. * @return bool 处理结果
  223. */
  224. private function handleRiderRecall($data)
  225. {
  226. return $this->processOrderCallback($data, '顺丰骑士撤单回调', 'sf_order_id', function($order, $sendStatus, $isGhs, $data) {
  227. if (!in_array($order->sendStatus, [-1, -2]) && in_array($sendStatus, [-1, -2])) {
  228. $statusDesc = $data['status_desc'];
  229. if($isGhs){
  230. GhsNotifyClass::ptErrorNotify($order->id, $statusDesc);
  231. }
  232. if(!$isGhs){
  233. HdNotifyClass::ptErrorNotify($order->id, $statusDesc);
  234. }
  235. noticeUtil::push('处理骑士撤单回调 -- orderId='.$order->id);
  236. }
  237. });
  238. }
  239. /**
  240. * 处理顺丰授权成功回调
  241. *
  242. * @param array $data
  243. * @return bool
  244. */
  245. private function handleBindNotify($data)
  246. {
  247. $sign = Yii::$app->request->get('sign');
  248. Yii::info('顺丰授权状态回调(sign=' . ($sign ?? '') . '): ' . json_encode($data, JSON_UNESCAPED_UNICODE), 'shunfeng-callback');
  249. $mainId = isset($data['out_shop_id']) ? (int)$data['out_shop_id'] : 0;
  250. $shopId = isset($data['shop_id']) ? $data['shop_id'] : '';
  251. if ($shopId === '') {
  252. Yii::error('顺丰授权状态回调参数缺失: ' . json_encode($data, JSON_UNESCAPED_UNICODE), 'shunfeng-callback');
  253. return false;
  254. }
  255. $payload = [
  256. 'mainId' => $mainId,
  257. 'platform' => 'shunfeng',
  258. 'shopId' => $shopId,
  259. 'authType' => 'all_store',
  260. 'accessToken' => $data['access_token'] ?? '',
  261. 'refreshToken' => $data['refresh_token'] ?? '',
  262. 'expiresAt' => time() + (100 * 86400 * 365),
  263. ];
  264. $existing = DeliveryAuthTokenClass::getByCondition(
  265. ['mainId' => $mainId, 'platform' => 'shunfeng'],
  266. false,
  267. false,
  268. 'id'
  269. );
  270. if ($existing && isset($existing['id'])) {
  271. DeliveryAuthTokenClass::updateById($existing['id'], [
  272. 'shopId' => $payload['shopId'],
  273. 'authType' => $payload['authType'],
  274. 'accessToken' => $payload['accessToken'],
  275. 'refreshToken' => $payload['refreshToken'],
  276. 'expiresAt' => $payload['expiresAt'],
  277. ]);
  278. } else {
  279. DeliveryAuthTokenClass::add($payload);
  280. }
  281. return true;
  282. }
  283. /**
  284. * 处理顺丰取消授权回调
  285. *
  286. * @param array $data
  287. * @return bool
  288. */
  289. private function handleCancelBindNotify($data)
  290. {
  291. $sign = Yii::$app->request->get('sign');
  292. Yii::info('顺丰取消授权状态回调(sign=' . ($sign ?? '') . '): ' . json_encode($data, JSON_UNESCAPED_UNICODE), 'shunfeng-callback');
  293. $shopId = isset($data['shop_id']) ? $data['shop_id'] : '';
  294. if ($shopId === '') {
  295. Yii::error('顺丰授权状态回调参数缺失: ' . json_encode($data, JSON_UNESCAPED_UNICODE), 'shunfeng-callback');
  296. return false;
  297. }
  298. if (!empty($data['app_id'])) {
  299. $auth = new Auth();
  300. if ((string)$auth->getAppKey() !== (string)$data['app_id']) {
  301. Yii::warning('顺丰取消授权回调 app_id 不匹配: ' . json_encode($data, JSON_UNESCAPED_UNICODE), 'shunfeng-callback');
  302. return false;
  303. }
  304. }
  305. $condition = [
  306. 'platform' => 'shunfeng',
  307. 'shopId' => $shopId
  308. ];
  309. $deleted = DeliveryAuthTokenClass::deleteByCondition($condition);
  310. if ($deleted === 0) {
  311. Yii::warning('顺丰取消授权回调未删除任何记录: ' . json_encode($data, JSON_UNESCAPED_UNICODE), 'shunfeng-callback');
  312. }
  313. return true;
  314. }
  315. /**
  316. * 转换顺丰订单状态到系统配送状态
  317. *
  318. * 顺丰状态说明:
  319. * - 10: 配送员接单/配送员改派
  320. * - 12: 配送员到店
  321. * - 15: 配送员配送中
  322. * - 17: 配送员点击完成
  323. * - 2: 订单取消
  324. * - 22: 配送员撤单
  325. * - 91: 骑士上报异常
  326. *
  327. * 系统状态说明:
  328. * - 0: 订单生成
  329. * - 1: 系统已接单
  330. * - 2: 派单中
  331. * - 3: 待取货
  332. * - 4: 配送中
  333. * - 5: 已送达
  334. * - -1: 已取消
  335. * - -2: 异常
  336. * - 10: 改派中
  337. * - 20: 已分配骑手
  338. * - 30: 骑手已到店
  339. * - 40: 申请取消中
  340. * - 50: 客服介入处理中
  341. *
  342. * @param int $sfOrderStatus 顺丰订单状态
  343. * @return int|null 系统配送状态,null表示不需要更新主订单状态
  344. */
  345. private function convertOrderSendStatus($sfOrderStatus)
  346. {
  347. // 顺丰状态映射到系统配送状态
  348. $statusMap = [
  349. 10 => 20, // 配送员接单/改派 -> 已分配骑手
  350. 12 => 30, // 配送员到店 -> 骑手已到店
  351. 15 => 4, // 配送员配送中 -> 配送中
  352. 17 => 5, // 配送完成 -> 已送达
  353. 2 => -1, // 订单取消 -> 已取消
  354. 22 => 2, // 配送员撤单 -> 派单中(重新派单)
  355. 91 => -2, // 骑士上报异常 -> 异常
  356. ];
  357. return $statusMap[$sfOrderStatus] ?? null;
  358. }
  359. /**
  360. * 转换顺丰订单状态到系统订单状态
  361. *
  362. * @param int $sfOrderStatus 顺丰订单状态
  363. * @return int|null 系统订单状态,null表示不需要更新主订单状态
  364. */
  365. private function convertOrderStatus($sfOrderStatus)
  366. {
  367. // 顺丰状态映射到系统订单状态
  368. // 系统订单状态: 1待付款 2待配送 3配送中 4已完成 5已取消
  369. $statusMap = [
  370. 10 => 3, // 配送员接单/改派 -> 配送中
  371. 12 => 3, // 配送员到店 -> 配送中
  372. 15 => 3, // 配送员配送中 -> 配送中
  373. 17 => 4, // 配送完成 -> 已完成
  374. 2 => 2, // 订单取消 -> 待配送(配送的取消不等于订单的取消,由于 status 带有配送状态,所以改为:待配送)
  375. 22 => 3, // 配送员撤单 -> 配送中
  376. 91 => 3, // 骑士上报异常 -> 配送中
  377. ];
  378. return $statusMap[$sfOrderStatus] ?? null;
  379. }
  380. /**
  381. * 根据顺丰订单号查找配送订单
  382. *
  383. * @param string $orderId
  384. * @return object|null
  385. */
  386. private function getDeliveryOrder($orderId)
  387. {
  388. // 查找批发配送订单
  389. $deliveryOrder = GhsDeliveryOrderClass::getByCondition([
  390. 'deliveryId' => 'shunfeng',
  391. 'orderId' => $orderId
  392. ], true, 'id DESC');
  393. if ($deliveryOrder) {
  394. return $deliveryOrder;
  395. }
  396. // 查找零售配送订单
  397. return HdDeliveryOrderClass::getByCondition([
  398. 'deliveryId' => 'shunfeng',
  399. 'orderId' => $orderId
  400. ], true, 'id DESC');
  401. }
  402. private function cancelFrom($sendStatus, $cancelCode = 0)
  403. {
  404. if($sendStatus == -1){
  405. $reasons = [
  406. 100 => '误操作,抢错订单',
  407. 101 => '订单距离太远',
  408. 102 => '餐箱已满,无法配送',
  409. 103 => '物品过大无法配送',
  410. 104 => '联系不上寄件人',
  411. 105 => '寄方无法提供待配送物品(缺货/出餐慢/已配送等)',
  412. 106 => '寄方要求取消(暂时不需要寄件了/重复发单/信息有误)',
  413. 107 => '配送车辆故障',
  414. 108 => '其他,请注明原因',
  415. 303 => '骑士要求取消',
  416. 310 => '超出配送范围',
  417. 500 => '15分钟无人接单',
  418. 501 => '不兜底订单自动取消',
  419. 502 => '超期望送达8小时未完成',
  420. ];
  421. return $reasons[$cancelCode] ?? '未知';
  422. }
  423. if($sendStatus == -2){
  424. $exIds = [
  425. 1001 => '商家出货慢',
  426. 1007 => '更改取货地址',
  427. 2001 => '顾客电话无法接通',
  428. 2004 => '更改期望送达时间',
  429. 2005 => '顾客拒收',
  430. 2008 => '顾客不在家',
  431. 2009 => '更改送货地址',
  432. 2010 => '顾客拒绝实名认证',
  433. 2013 => '无法联系用户,退回寄件人',
  434. 3004 => '实名认证校验失败',
  435. 4001 => '配送地址错误',
  436. 4002 => '其他',
  437. 4003 => '托寄物丢失或损坏',
  438. ];
  439. return $exIds[$cancelCode] ?? '未知';
  440. }
  441. return '未知';
  442. }
  443. }