AliyunExpressService.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. return $this->appCode;
  37. if (empty($this->appCode)) {
  38. return false;
  39. }
  40. $params = ['no' => $no];
  41. if (!empty($type)) {
  42. $params['type'] = $type;
  43. }
  44. $url = $this->api . '?' . http_build_query($params);
  45. $ch = curl_init();
  46. curl_setopt_array($ch, [
  47. CURLOPT_URL => $url,
  48. CURLOPT_RETURNTRANSFER => true,
  49. CURLOPT_HTTPHEADER => [
  50. 'Authorization: APPCODE ' . $this->appCode,
  51. ],
  52. CURLOPT_TIMEOUT => 30,
  53. CURLOPT_SSL_VERIFYPEER => false,
  54. ]);
  55. $result = curl_exec($ch);
  56. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  57. curl_close($ch);
  58. if ($httpCode !== 200) {
  59. return false;
  60. }
  61. return json_decode($result, true) ?: false;
  62. }
  63. /**
  64. * 物流状态码转中文
  65. * @param int $status
  66. * @return string
  67. */
  68. public function getStatusText(int $status): string
  69. {
  70. $map = [
  71. 0 => '在途',
  72. 1 => '揽收',
  73. 2 => '疑难',
  74. 3 => '签收',
  75. 4 => '退签',
  76. 5 => '派件',
  77. 6 => '退回',
  78. 7 => '转单',
  79. 10 => '待清关',
  80. 11 => '清关中',
  81. 12 => '已清关',
  82. 13 => '清关异常',
  83. 14 => '收件人拒签',
  84. ];
  85. return $map[$status] ?? '未知';
  86. }
  87. }