LogisticSFService.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. $orderPackageReceivedSyncService = app('OrderPackageReceivedSyncService');
  95. $exceptionData = $orderPackageReceivedSyncService->setExceptionType($data, array_key_exists('accept_time',$lastRoute) ? $lastRoute['accept_time'] : null);
  96. $data['exception_type'] = $exceptionData['exception_type'];
  97. $data['exception'] = $exceptionData['exception'];
  98. }
  99. //如果没有发现额外的异常,且查询到物流轨迹,将异常置为无
  100. if (!array_key_exists('exception', $data)
  101. && !array_key_exists('exception_type', $data)
  102. && array_key_exists('transfer_status', $data)
  103. ) {
  104. $data['exception_type'] = '无';
  105. $data['exception'] = '否';
  106. }
  107. } catch (Exception $e) {
  108. throw new WarningException("单号没有查询到快递路由信息','LogisticSFService->transformSFOneToArr->{$data['logistic_number']}");
  109. } finally {
  110. $data['routes_length'] = array_key_exists('transfer_status', $data) ? count($data['transfer_status']) : 0;
  111. return $data;
  112. }
  113. }
  114. /**
  115. * 转换快递路由信息
  116. * @param $routs 快递路由
  117. * @return array
  118. */
  119. public function transformRoutes($routs): array
  120. {
  121. $result = [];
  122. if (!is_array($routs)) {
  123. $routs = [$routs];
  124. }
  125. foreach ($routs as $route) {
  126. $route = get_object_vars($route)['@attributes'];
  127. $data['accept_time'] = $route['accept_time'];
  128. $data['accept_address'] = $route['accept_address'];
  129. $data['remark'] = $route['remark'];
  130. $result[] = $data;
  131. }
  132. return $result;
  133. }
  134. /**
  135. * 将最新路由信息转换为数组
  136. * @param array $lastRoute
  137. * @param array $data
  138. * @return array
  139. * @throws Exception
  140. */
  141. public function switchOpCodeToStatus(array $lastRoute, array $data): array
  142. {
  143. try {
  144. switch ($lastRoute['opcode']) {
  145. case 123:
  146. case 130:
  147. case 3036:
  148. case 31:
  149. case 30:
  150. case 36:
  151. $data['status'] = '在途';
  152. break;
  153. case 33:
  154. $data['status'] = '派送异常';
  155. $data['exception_type'] = '派件异常';
  156. $data['exception'] = '是';
  157. break;
  158. case 204:
  159. case 44:
  160. $data['status'] = '派送中';
  161. break;
  162. case 50:
  163. $data['status'] = '已揽收';
  164. break;
  165. case 607:
  166. case 8000:
  167. case 80:
  168. $data['status'] = '已收件';
  169. $data['received_at'] = $lastRoute[$this->protected_switch['received_at']];
  170. break;
  171. case 648:
  172. case 99:
  173. $data['status'] = '返回中';
  174. break;
  175. case 70:
  176. $data['status'] = '无';
  177. $data['exception'] = '是';
  178. $data['exception_type'] = '其他';
  179. break;
  180. default:
  181. throw new WarningException("未知的丰桥状态码: {$lastRoute['opcode']}->{json_encode($lastRoute)}");
  182. }
  183. } catch (WarningException $e) {
  184. $data['status'] = '其他异常';
  185. } finally {
  186. return $data;
  187. }
  188. }
  189. /**
  190. * @param string $head
  191. * @param string $numbers
  192. * @param string $checkWord
  193. * @param string $url
  194. * @return Response
  195. * @throws Exception
  196. */
  197. public function sendHttpToSF(string $head, string $numbers, string $checkWord, string $url): Response
  198. {
  199. $xml = $this->buildXmlStr($head, $numbers);
  200. $checkingJson = $xml . $checkWord;
  201. $verifyCode = base64_encode(md5($checkingJson, true));
  202. try {
  203. $response = Http::withHeaders(['Content-Type' => 'text/xml'])->get($url, ['xml' => $xml, 'verifyCode' => $verifyCode]);
  204. } catch (Exception $e) {
  205. throw new WarningException("HTTP请求顺丰接口异常->{$e->getMessage()}");
  206. }
  207. return $response;
  208. }
  209. /**
  210. * 将多个顺丰的单号转换为数组
  211. * @param array $responseBody
  212. * @param array $result
  213. * @return array
  214. * @throws Exception
  215. */
  216. public function transformSFMoreToArr(array $responseBody, array $result): array
  217. {
  218. foreach ($responseBody as $routeResponse) {
  219. $result[] = $this->transformSFOneToArr(get_object_vars($routeResponse), []);
  220. }
  221. return $result;
  222. }
  223. }