Huolala.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. <?php
  2. namespace common\components\delivery\platform\huolala;
  3. use common\components\delivery\helpers\HttpClient;
  4. use common\components\delivery\helpers\SignHelper;
  5. use Yii;
  6. class Huolala
  7. {
  8. protected $baseUrl;
  9. protected $appSecret;
  10. protected $appKey;
  11. protected $accessToken;
  12. protected $apiVersion = '1.0';
  13. protected $isSandbox;
  14. /**
  15. * @var string 订单消息回调地址
  16. */
  17. protected $notifyUrl;
  18. const CITY_VEHICLE_CACHE_TTL = 86400; // 1 day
  19. const CITY_VEHICLE_CACHE_KEY_PATTERN = 'huolala-city-vehicle:%d_%s';
  20. public function __construct($accessToken='')
  21. {
  22. if (getenv('YII_ENV') == 'production') {
  23. $cfg = [
  24. 'base_url' => 'https://openapi.huolala.cn/v1',
  25. 'app_key' => 'gBhmCdWtX7hi7qnljduk0yK21XgQg8w3',
  26. 'secret' => 'bARxI68FFHpEXAcCQ23fxVQyxtJ9RONU',
  27. 'notify_url' => Yii::$app->params['ghsHost'].'/delivery/huolala-callback',
  28. ];
  29. $this->isSandbox = false;
  30. } else {
  31. $cfg = [
  32. 'base_url' => 'https://openapi-pre.huolala.cn/v1',
  33. 'app_key' => '8S2uZQrWwM1mkG2Cj576PsMiNIe25UNT',
  34. 'secret' => 'olzor07UgmUWaagahNGQAKQKXRtvhK8j',
  35. 'notify_url' => Yii::$app->params['ghsHost'].'/delivery/huolala-callback',
  36. ];
  37. $this->isSandbox = true;
  38. }
  39. $this->baseUrl = $cfg['base_url'];
  40. $this->appSecret = $cfg['secret'];
  41. $this->appKey = $cfg['app_key'];
  42. $this->accessToken = $accessToken;
  43. $this->notifyUrl = $cfg['notify_url'];
  44. }
  45. /**
  46. * 获取城市可选车型信息
  47. *
  48. * 通过此接口可获取城市可选车型信息,包括车型详情、计价规则、车型附加要求和额外需求等
  49. *
  50. * @param int $cityId 城市ID
  51. * @param bool $forceRefresh 是否强制刷新缓存
  52. * @return array|null 包含城市车型信息的响应数据
  53. */
  54. public function getCityVehicleList($cityId, $forceRefresh = false)
  55. {
  56. // 参数验证
  57. if (empty($cityId) || !is_numeric($cityId)) {
  58. return null;
  59. }
  60. $cityId = (int)$cityId;
  61. $env = $this->isSandbox ? 'dev' : 'production'; // 避免切环境后,使用了不同环境的缓存数据
  62. $cacheKey = sprintf(self::CITY_VEHICLE_CACHE_KEY_PATTERN, $cityId, $env);
  63. $redis = Yii::$app->has('redis') ? Yii::$app->redis : null;
  64. if ($redis !== null) {
  65. if ($forceRefresh) {
  66. $redis->executeCommand('DEL', [$cacheKey]);
  67. } else {
  68. $cached = $redis->executeCommand('GET', [$cacheKey]);
  69. if ($cached !== false && $cached !== null) {
  70. $decoded = json_decode($cached, true);
  71. if (is_array($decoded)) {
  72. return $decoded;
  73. }
  74. }
  75. }
  76. }
  77. // 构建请求参数,发送请求
  78. $payload = $this->buildRequestPayload('u-city-info', ['city_id' => $cityId]);
  79. $resp = HttpClient::post($this->baseUrl, $payload);
  80. // 处理响应
  81. if (isset($resp['ret']) && $resp['ret'] == 0 && isset($resp['data'])) {
  82. $data = $resp['data'];
  83. // 提取车型列表
  84. $vehicleList = [];
  85. if (!empty($data['vehicle_list']) && is_array($data['vehicle_list'])) {
  86. foreach ($data['vehicle_list'] as $vehicle) {
  87. // 处理超里程价格分段
  88. $exceedSegmentPrice = [];
  89. if (!empty($vehicle['price_text_item']['exceed_segment_price'])
  90. && is_array($vehicle['price_text_item']['exceed_segment_price'])) {
  91. foreach ($vehicle['price_text_item']['exceed_segment_price'] as $segment) {
  92. $exceedSegmentPrice[] = [
  93. 'start_exdistancekm' => $segment['start_exdistancekm'] ?? 0,
  94. 'end_exdistancekm' => $segment['end_exdistancekm'] ?? 0,
  95. 'price_extra_fen' => $segment['price_extra_fen'] ?? 0,
  96. ];
  97. }
  98. }
  99. // 处理车型附加要求
  100. $vehicleStdItem = [];
  101. if (!empty($vehicle['vehicle_std_item']) && is_array($vehicle['vehicle_std_item'])) {
  102. foreach ($vehicle['vehicle_std_item'] as $std) {
  103. $vehicleStdItem[] = [
  104. 'name' => $std['name'] ?? '',
  105. 'desc' => $std['desc'] ?? '',
  106. 'price_fen' => $std['price_fen'] ?? 0,
  107. ];
  108. }
  109. }
  110. $vehicleList[] = [
  111. 'order_vehicle_id' => $vehicle['order_vehicle_id'] ?? 0,
  112. 'vehicle_name' => $vehicle['vehicle_name'] ?? '',
  113. 'img_url_high_light' => $vehicle['img_url_high_light'] ?? '',
  114. 'vehicle_volume' => $vehicle['vehicle_volume'] ?? '',
  115. 'vehicle_weight' => $vehicle['vehicle_weight'] ?? '',
  116. 'vehicle_size' => $vehicle['vehicle_size'] ?? '',
  117. 'standard_order_vehicle_id' => $vehicle['standard_order_vehicle_id'] ?? 0,
  118. 'text_desc' => $vehicle['text_desc'] ?? '',
  119. 'vehicle_attr' => $vehicle['vehicle_attr'] ?? 0,
  120. 'price_text_item' => [
  121. 'base_distancekm' => $vehicle['price_text_item']['base_distancekm'] ?? 0,
  122. 'base_price_fen' => $vehicle['price_text_item']['base_price_fen'] ?? 0,
  123. 'exceed_segment_price' => $exceedSegmentPrice,
  124. ],
  125. 'vehicle_std_item' => $vehicleStdItem,
  126. ];
  127. }
  128. }
  129. // 处理城市额外需求列表
  130. $specReqItem = [];
  131. if (!empty($data['spec_req_item']) && is_array($data['spec_req_item'])) {
  132. foreach ($data['spec_req_item'] as $specReq) {
  133. $specReqItem[] = [
  134. 'type' => (int)($specReq['type'] ?? 0),
  135. 'name' => $specReq['name'] ?? '',
  136. 'desc' => $specReq['desc'] ?? '',
  137. 'price_type' => (int)($specReq['price_type'] ?? 0),
  138. 'price_value_fen' => (int)($specReq['price_value_fen'] ?? 0),
  139. ];
  140. }
  141. }
  142. $result = [
  143. 'city_id' => $data['city_id'],
  144. 'name' => $data['name'],
  145. 'name_en' => $data['name_en'],
  146. 'city_info_revision' => $data['city_info_revision'],
  147. 'vehicle_list' => $vehicleList,
  148. 'spec_req_item' => $specReqItem,
  149. ];
  150. if ($redis !== null) {
  151. $redis->executeCommand('SETEX', [
  152. $cacheKey,
  153. self::CITY_VEHICLE_CACHE_TTL,
  154. json_encode($result, JSON_UNESCAPED_UNICODE)
  155. ]);
  156. }
  157. return $result;
  158. }
  159. return null;
  160. }
  161. /**
  162. * 获取可选取消原因
  163. *
  164. * 通过此接口可获取可选择的取消原因,包括主原因和子原因
  165. *
  166. * @param array $data 业务参数(当前接口无必需参数,可传空数组)
  167. * @return array|null 包含取消原因列表的响应数据
  168. */
  169. public function getCancelReasonList($data)
  170. {
  171. // 构建请求参数(无业务数据)
  172. $payload = $this->buildRequestPayload('u-order-cancelReason', []);
  173. // 发送请求
  174. $resp = HttpClient::post($this->baseUrl, $payload);
  175. // 处理响应
  176. if (isset($resp['ret']) && $resp['ret'] == 0 && isset($resp['data'])) {
  177. $respData = $resp['data'];
  178. // 提取取消原因列表
  179. $reasonList = [];
  180. if (!empty($respData['reason']) && is_array($respData['reason'])) {
  181. foreach ($respData['reason'] as $reason) {
  182. if (!empty($reason['sub_reason']) && is_array($reason['sub_reason'])) {
  183. foreach ($reason['sub_reason'] as $subReason) {
  184. $reasonList[] = [
  185. 'order_cancel_code' => (int)($subReason['id'] ?? 0),
  186. 'order_cancel_desc' => $subReason['name'] ?? '',
  187. ];
  188. }
  189. }
  190. }
  191. }
  192. return [
  193. 'code' => 0,
  194. 'data' => [
  195. 'reasonList' => $reasonList,
  196. ]
  197. ];
  198. }
  199. return [
  200. 'code' => $resp['ret'] ?? -1,
  201. 'msg' => $resp['msg'] ?? 'Unknown error',
  202. 'data' => null
  203. ];
  204. }
  205. /**
  206. * 构建API请求参数
  207. *
  208. * 根据货拉拉API规范构建完整的请求参数,包括签名
  209. *
  210. * @param string $apiMethod API方法名
  211. * @param array $apiData 业务参数
  212. * @param string|null $accessToken 用户授权令牌(可选)
  213. * @return array 完整的请求参数
  214. */
  215. protected function buildRequestPayload($apiMethod, $apiData = [], $accessToken = null)
  216. {
  217. // 生成随机数(nonce_str)
  218. $nonceStr = $this->generateNonceStr();
  219. // 构建系统级参数
  220. $payload = [
  221. 'api_method' => $apiMethod,
  222. 'api_version' => $this->apiVersion,
  223. 'app_key' => $this->appKey,
  224. 'timestamp' => time(),
  225. 'nonce_str' => $nonceStr,
  226. ];
  227. // 如果提供了访问令牌,加入参数
  228. if (!empty($accessToken)) {
  229. $payload['access_token'] = $accessToken;
  230. }
  231. // 业务数据作为 JSON 字符串
  232. // 注意:如果不加 JSON_UNESCAPED_SLASHES,PHP 会把 / 编码成 \/
  233. // 而很多第三方(包括货拉拉)在服务端是按未转义的 / 参与签名的,
  234. // 一旦字段里有 URL(如 notify_url),双方签名串就会不一致。
  235. // 因此这里显式关闭斜杠转义,保证本地和对端采用一致的 JSON 形式参与签名。
  236. $payload['api_data'] = json_encode($apiData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  237. // 计算签名
  238. $signature = $this->generateSignature($payload);
  239. $payload['signature'] = $signature;
  240. return $payload;
  241. }
  242. /**
  243. * 生成签名
  244. *
  245. * 复用 SignHelper 的通用签名算法
  246. * 货拉拉要求32位小写MD5签名,而 SignHelper 返回大写,所以需要转为小写
  247. *
  248. * @param array $params 待签名参数(不包括signature)
  249. * @return string 签名值(32位小写)
  250. */
  251. protected function generateSignature($params)
  252. {
  253. // 使用 SignHelper 的通用签名算法
  254. $sign = SignHelper::makeSign($params, $this->appSecret);
  255. // 货拉拉 API 要求32位小写,转换为小写
  256. return strtolower($sign);
  257. }
  258. public function generateSignatureWithoutAppSecret($params)
  259. {
  260. $sign = SignHelper::makeSign($params, '');
  261. return strtolower($sign);
  262. }
  263. /**
  264. * 生成随机数字符串
  265. *
  266. * @param int $length 长度
  267. * @return string 随机字符串
  268. */
  269. protected function generateNonceStr($length = 16)
  270. {
  271. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  272. $str = '';
  273. for ($i = 0; $i < $length; $i++) {
  274. $str .= $chars[random_int(0, strlen($chars) - 1)];
  275. }
  276. return $str;
  277. }
  278. public function getIsSandbox()
  279. {
  280. return $this->isSandbox;
  281. }
  282. }