LogisticSFService.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. <?php
  2. namespace App\Services;
  3. use App\Exceptions\WarningException;
  4. use App\OrderPackage;
  5. use Exception;
  6. use Illuminate\Http\Client\Response;
  7. use Illuminate\Support\Carbon;
  8. use Illuminate\Support\Facades\Http;
  9. class LogisticSFService
  10. {
  11. /**
  12. * 顺丰字段与数据库字段的映射关心
  13. * @var string[]
  14. */
  15. protected $protected_switch = [
  16. 'logistic_number' => 'mailno',
  17. 'transfer_status' => 'remark',
  18. 'received_at' => 'accept_time',
  19. ];
  20. /**
  21. * 获取顺丰快递揽收数据
  22. * @param array $logisticNums [logisticNums]快递单号数组
  23. * @return array 快递揽收信息数组
  24. * @throws Exception 未知的丰桥opCode
  25. */
  26. public function get(array $logisticNums): array
  27. {
  28. // 将$logisticNums以10个位单位进行分割,返回二维数组
  29. $logisticNums_size_10 = array_chunk($logisticNums, config('api_logistic.SF.max_size', 10));
  30. // 遍历二维数组批量查询顺丰接口
  31. //将查询到的结果整合到一起,更新order_packages.received_at
  32. $result = [];
  33. foreach ($logisticNums_size_10 as $numbers) {
  34. $numbersStr = implode(',', $numbers);
  35. $result_10 = $this->getResultFromSF(config('api_logistic.SF.head'), $numbersStr, config('api_logistic.SF.check_word'), config('api_logistic.SF.url'));
  36. $result = array_merge($result, $result_10);
  37. }
  38. return $result;
  39. }
  40. /**
  41. * @param string $head 客户号
  42. * @param string $numbers 快递单号字符串,多个以','分隔
  43. * @param string $checkWord 客户秘钥
  44. * @param string $url 顺丰接口地址
  45. * @return array
  46. * @throws Exception 未知的丰桥opCode
  47. */
  48. public function getResultFromSF(string $head, string $numbers, string $checkWord, string $url): array
  49. {
  50. $responseBody = get_object_vars(simplexml_load_string($this->sendHttpToSF($head, $numbers, $checkWord, $url))->Body)['RouteResponse'];
  51. $result = [];
  52. if (is_array($responseBody)) {//SF返回多个单号的查询结果
  53. $result = $this->transformSFMoreToArr($responseBody, $result);
  54. } else {
  55. $result[] = $this->transformSFOneToArr(get_object_vars($responseBody), []);
  56. }
  57. return $result;
  58. }
  59. /**
  60. * 构建顺丰xml请求体
  61. * @param string $head
  62. * @param string $number
  63. * @return string
  64. */
  65. private function buildXmlStr(string $head, string $number): string
  66. {
  67. return <<<xml
  68. <?xml version="1.0" encoding="utf-8" ?>
  69. <Request service='RouteService' lang='zh-CN'>
  70. <Head>$head</Head>
  71. <Body>
  72. <RouteRequest
  73. tracking_number="{$number}" tracking_type='1' method_type='1'
  74. />
  75. </Body>
  76. </Request>
  77. xml;
  78. }
  79. /**
  80. * 将单个单号的顺丰数据转换为数组
  81. * @param array $routeResponse
  82. * @param array $data
  83. * @return array
  84. * @throws Exception
  85. */
  86. public function transformSFOneToArr(array $routeResponse, array $data): array
  87. {
  88. $data['logistic_number'] = $routeResponse['@attributes'][$this->protected_switch['logistic_number']];
  89. try {
  90. $lastRoute = get_object_vars($routeResponse['Route'][count($routeResponse['Route']) - 1])['@attributes'];//获取最新的路由信息
  91. $data = $this->switchOpCodeToStatus($lastRoute, $data);
  92. $data['transfer_status'] = $this->transformRoutes($routeResponse['Route']);
  93. if (!array_key_exists('exception', $data)) {//当顺丰返回异常时,不需要再根据时间判断是否异常,直接用顺丰的异常就好
  94. $data = $this->setExceptionType($data, $lastRoute['accept_time']);
  95. }
  96. //如果没有发现额外的异常,且查询到物流轨迹,将异常置为无
  97. if (!array_key_exists('exception', $data)
  98. && !array_key_exists('exception_type', $data)
  99. && array_key_exists('transfer_status', $data)
  100. ) {
  101. $data['exception_type'] = '无';
  102. $data['exception'] = '否';
  103. }
  104. } catch (Exception $e) {
  105. throw new WarningException("单号没有查询到快递路由信息','LogisticSFService->transformSFOneToArr->{$data['logistic_number']}");
  106. } finally {
  107. return $data;
  108. }
  109. }
  110. /**
  111. * 转换快递路由信息
  112. * @param $routs 快递路由
  113. * @return array
  114. */
  115. public function transformRoutes($routs): array
  116. {
  117. $result = [];
  118. if (!is_array($routs)) {
  119. $routs = [$routs];
  120. }
  121. foreach ($routs as $route) {
  122. $route = get_object_vars($route)['@attributes'];
  123. $data['accept_time'] = $route['accept_time'];
  124. $data['accept_address'] = $route['accept_address'];
  125. $data['remark'] = $route['remark'];
  126. $result[] = $data;
  127. }
  128. return $result;
  129. }
  130. /**
  131. * 将最新路由信息转换为数组
  132. * @param array $lastRoute
  133. * @param array $data
  134. * @return array
  135. * @throws Exception
  136. */
  137. public function switchOpCodeToStatus(array $lastRoute, array $data): array
  138. {
  139. try {
  140. switch ($lastRoute['opcode']) {
  141. case 123:
  142. case 130:
  143. case 3036:
  144. case 31:
  145. case 30:
  146. case 36:
  147. $data['status'] = '在途';
  148. break;
  149. case 33:
  150. $data['status'] = '派送异常';
  151. $data['exception_type'] = '派件异常';
  152. $data['exception'] = '是';
  153. break;
  154. case 204:
  155. case 44:
  156. $data['status'] = '派送中';
  157. break;
  158. case 50:
  159. $data['status'] = '已揽收';
  160. break;
  161. case 607:
  162. case 8000:
  163. case 80:
  164. $data['status'] = '已收件';
  165. $data['received_at'] = $lastRoute[$this->protected_switch['received_at']];
  166. break;
  167. case 648:
  168. case 99:
  169. $data['status'] = '返回中';
  170. break;
  171. case 70:
  172. $data['status'] = '无';
  173. $data['exception'] = '是';
  174. $data['exception_type'] = '其他';
  175. break;
  176. default:
  177. throw new WarningException("未知的丰桥状态码: {$lastRoute['opcode']}->{json_encode($lastRoute)}");
  178. }
  179. } catch (WarningException $e) {
  180. $data['status'] = '其他异常';
  181. } finally {
  182. return $data;
  183. }
  184. }
  185. /**
  186. * @param string $head
  187. * @param string $numbers
  188. * @param string $checkWord
  189. * @param string $url
  190. * @return Response
  191. * @throws Exception
  192. */
  193. public function sendHttpToSF(string $head, string $numbers, string $checkWord, string $url): Response
  194. {
  195. $xml = $this->buildXmlStr($head, $numbers);
  196. $checkingJson = $xml . $checkWord;
  197. $verifyCode = base64_encode(md5($checkingJson, true));
  198. try {
  199. $response = Http::withHeaders(['Content-Type' => 'text/xml'])->get($url, ['xml' => $xml, 'verifyCode' => $verifyCode]);
  200. } catch (Exception $e) {
  201. throw new WarningException("HTTP请求顺丰接口异常->{$e->getMessage()}");
  202. }
  203. return $response;
  204. }
  205. /**
  206. * 将多个顺丰的单号转换为数组
  207. * @param array $responseBody
  208. * @param array $result
  209. * @return array
  210. * @throws Exception
  211. */
  212. public function transformSFMoreToArr(array $responseBody, array $result): array
  213. {
  214. foreach ($responseBody as $routeResponse) {
  215. $result[] = $this->transformSFOneToArr(get_object_vars($routeResponse), []);
  216. }
  217. return $result;
  218. }
  219. /**
  220. * @param array $data
  221. * @param $lastRouteDate
  222. * @return array
  223. */
  224. private function setExceptionType(array $data, $lastRouteDate = null): array
  225. {
  226. $logistic_number = $data['logistic_number'];
  227. /** @var OrderPackage $orderPackage */
  228. $orderPackage = OrderPackage::query()->with('order')->where('logistic_number', $logistic_number)->first();
  229. $delivered_duration = now()->diffInHours(Carbon::parse($orderPackage['sent_at']));
  230. $last_routed_duration = now()->diffInHours(Carbon::parse($lastRouteDate));
  231. $VALID_HOURS = 4;
  232. $SHORT_RESPONSE_HOURS = 24;
  233. $LONG_RESPONSE_HOURS = (function ($province) {
  234. switch ($province) {
  235. case '浙江省':
  236. case '江苏省':
  237. case '上海':
  238. case '安徽省':
  239. return 72;
  240. case '北京':
  241. case '天津':
  242. case '江西省':
  243. case '湖北省':
  244. case '湖南省':
  245. case '广东省':
  246. case '福建省':
  247. case '山东省':
  248. case '河北省':
  249. case '河南省':
  250. case '山西省':
  251. case '四川省':
  252. case '陕西省':
  253. case '重庆':
  254. case '广西壮族自治区':
  255. case '贵州省':
  256. case '云南省':
  257. case '海南省':
  258. case '吉林省':
  259. case '黑龙江省':
  260. case '辽宁省':
  261. return 120;
  262. case '青海省':
  263. case '宁夏回族自治区':
  264. case '甘肃省':
  265. case '内蒙古自治区':
  266. case '新疆维吾尔自治区':
  267. case '西藏自治区':
  268. return 168;
  269. default:
  270. break;
  271. }
  272. })($orderPackage->order->province);
  273. $SENDING_RESPONSE_HOURS = 48;
  274. $IS_ROUTED = 1; //0000 0001 有路由信息
  275. $IS_IN_VALID_TIME = 2; //0000 0010 大于4小时
  276. $IS_WEIGHED = 4; //0000 0100 称重过
  277. $IS_RECEIVED = 8; //0000 1000 已经收货
  278. $IS_SENDING = 16; //0001 0000 正在派送
  279. $IS_SHORT_NO_RESPONSE = 32; //0010 0000 中转异常
  280. $IS_LONG_NO_RESPONSE = 64; //0010 0000 疑似丢件
  281. $IS_SENDING_NO_RESPONSE = 128; //0010 0000 派送异常
  282. $conclusion = (function () use (
  283. $data, $delivered_duration, $last_routed_duration,
  284. $VALID_HOURS, $IS_ROUTED, $IS_IN_VALID_TIME, $IS_WEIGHED, $IS_RECEIVED, $IS_SENDING, $IS_SHORT_NO_RESPONSE, $IS_LONG_NO_RESPONSE, $IS_SENDING_NO_RESPONSE,
  285. $SHORT_RESPONSE_HOURS, $LONG_RESPONSE_HOURS, $SENDING_RESPONSE_HOURS,
  286. $orderPackage
  287. ) {
  288. $conclusion = 0;
  289. $conclusion |= !empty($data['transfer_status']) ? $IS_ROUTED : 0;
  290. $conclusion |= ($delivered_duration > $VALID_HOURS) ? $IS_IN_VALID_TIME : 0;
  291. $conclusion |= ($orderPackage->weighed_at) ? $IS_WEIGHED : 0;
  292. $conclusion |= ($data['status'] == '已收件') ? $IS_RECEIVED : 0;
  293. $conclusion |= ($data['status'] == '派送中') ? $IS_SENDING : 0;//
  294. $conclusion |= ($last_routed_duration > $SHORT_RESPONSE_HOURS && $last_routed_duration < $LONG_RESPONSE_HOURS) ? $IS_SHORT_NO_RESPONSE : 0;
  295. $conclusion |= ($last_routed_duration > $LONG_RESPONSE_HOURS) ? $IS_LONG_NO_RESPONSE : 0;
  296. $conclusion |= ($last_routed_duration > $SENDING_RESPONSE_HOURS && $data['status'] == '派送中') ? $IS_SENDING_NO_RESPONSE : 0;
  297. return $conclusion;
  298. })();
  299. switch ($conclusion) {
  300. case $IS_IN_VALID_TIME:
  301. $data['exception_type'] = '疑似库内丢件';
  302. break;
  303. case $IS_IN_VALID_TIME | $IS_WEIGHED:
  304. $data['exception_type'] = '揽件异常';
  305. break;
  306. case $IS_ROUTED | $IS_IN_VALID_TIME | $IS_SHORT_NO_RESPONSE:
  307. case $IS_ROUTED | $IS_IN_VALID_TIME | $IS_SHORT_NO_RESPONSE | $IS_WEIGHED:
  308. $data['exception_type'] = '中转异常';
  309. break;
  310. case $IS_ROUTED | $IS_IN_VALID_TIME | $IS_LONG_NO_RESPONSE:
  311. case $IS_ROUTED | $IS_IN_VALID_TIME | $IS_LONG_NO_RESPONSE | $IS_WEIGHED:
  312. $data['exception_type'] = '疑似丢件';
  313. break;
  314. default:
  315. break;
  316. }
  317. if($conclusion
  318. ==($conclusion | $IS_ROUTED | $IS_IN_VALID_TIME | $IS_SENDING | $IS_SENDING_NO_RESPONSE)){
  319. $data['exception_type'] = '派件异常';
  320. }
  321. switch ($conclusion) {
  322. case $IS_IN_VALID_TIME:
  323. case $IS_IN_VALID_TIME | $IS_WEIGHED:
  324. case $IS_ROUTED | $IS_SHORT_NO_RESPONSE:
  325. case $IS_LONG_NO_RESPONSE:
  326. $data['exception'] = '是';
  327. break;
  328. default:
  329. break;
  330. }
  331. return $data;
  332. }
  333. }