AliyunExpressService.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\services;
  4. use app\model\api\Sys;
  5. /**
  6. * 阿里云物流查询服务
  7. */
  8. class AliyunExpressService
  9. {
  10. /**
  11. * 阿里云物流查询API
  12. * @var string
  13. */
  14. protected $api = 'https://wuliu.market.alicloudapi.com/kdi';
  15. /**
  16. * AppCode
  17. * @var string
  18. */
  19. protected $appCode;
  20. /**
  21. * 构造方法
  22. */
  23. public function __construct()
  24. {
  25. $sys = Sys::find(1);
  26. $this->appCode = $sys ? (string)($sys->system_express_app_code ?? '') : '';
  27. }
  28. /**
  29. * 查询物流信息
  30. * @param string $no 快递单号
  31. * @param string $type 快递公司编码(可选,阿里云接口可自动识别)
  32. * @return array|false
  33. */
  34. public function query(string $no, string $type = '')
  35. {
  36. if (empty($this->appCode)) {
  37. return false;
  38. }
  39. $params = ['no' => $no];
  40. if (!empty($type)) {
  41. $params['type'] = $type;
  42. }
  43. $url = $this->api . '?' . http_build_query($params);
  44. $ch = curl_init();
  45. curl_setopt_array($ch, [
  46. CURLOPT_URL => $url,
  47. CURLOPT_RETURNTRANSFER => true,
  48. CURLOPT_HTTPHEADER => [
  49. 'Authorization: APPCODE ' . $this->appCode,
  50. ],
  51. CURLOPT_TIMEOUT => 30,
  52. CURLOPT_SSL_VERIFYPEER => false,
  53. ]);
  54. $result = curl_exec($ch);
  55. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  56. curl_close($ch);
  57. if ($httpCode !== 200) {
  58. return false;
  59. }
  60. return json_decode($result, true) ?: false;
  61. }
  62. /**
  63. * 物流状态码转中文
  64. * @param int $status
  65. * @return string
  66. */
  67. public function getStatusText(int $status): string
  68. {
  69. $map = [
  70. 0 => '在途',
  71. 1 => '揽收',
  72. 2 => '疑难',
  73. 3 => '签收',
  74. 4 => '退签',
  75. 5 => '派件',
  76. 6 => '退回',
  77. 7 => '转单',
  78. 10 => '待清关',
  79. 11 => '清关中',
  80. 12 => '已清关',
  81. 13 => '清关异常',
  82. 14 => '收件人拒签',
  83. ];
  84. return $map[$status] ?? '未知';
  85. }
  86. }