| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318 |
- <?php
- namespace common\components\delivery\platform\huolala;
- use common\components\delivery\helpers\HttpClient;
- use common\components\delivery\helpers\SignHelper;
- use Yii;
- class Huolala
- {
- protected $baseUrl;
- protected $appSecret;
- protected $appKey;
- protected $accessToken;
- protected $apiVersion = '1.0';
- protected $isSandbox;
- /**
- * @var string 订单消息回调地址
- */
- protected $notifyUrl;
- const CITY_VEHICLE_CACHE_TTL = 86400; // 1 day
- const CITY_VEHICLE_CACHE_KEY_PATTERN = 'huolala-city-vehicle:%d_%s';
- public function __construct($accessToken='')
- {
- if (getenv('YII_ENV') == 'production') {
- $cfg = [
- 'base_url' => 'https://openapi.huolala.cn/v1',
- 'app_key' => 'gBhmCdWtX7hi7qnljduk0yK21XgQg8w3',
- 'secret' => 'bARxI68FFHpEXAcCQ23fxVQyxtJ9RONU',
- 'notify_url' => Yii::$app->params['ghsHost'].'/delivery/huolala-callback',
- ];
- $this->isSandbox = false;
- } else {
- $cfg = [
- 'base_url' => 'https://openapi-pre.huolala.cn/v1',
- 'app_key' => '8S2uZQrWwM1mkG2Cj576PsMiNIe25UNT',
- 'secret' => 'olzor07UgmUWaagahNGQAKQKXRtvhK8j',
- 'notify_url' => Yii::$app->params['ghsHost'].'/delivery/huolala-callback',
- ];
- $this->isSandbox = true;
- }
- $this->baseUrl = $cfg['base_url'];
- $this->appSecret = $cfg['secret'];
- $this->appKey = $cfg['app_key'];
- $this->accessToken = $accessToken;
- $this->notifyUrl = $cfg['notify_url'];
- }
- /**
- * 获取城市可选车型信息
- *
- * 通过此接口可获取城市可选车型信息,包括车型详情、计价规则、车型附加要求和额外需求等
- *
- * @param int $cityId 城市ID
- * @param bool $forceRefresh 是否强制刷新缓存
- * @return array|null 包含城市车型信息的响应数据
- */
- public function getCityVehicleList($cityId, $forceRefresh = false)
- {
- // 参数验证
- if (empty($cityId) || !is_numeric($cityId)) {
- return null;
- }
- $cityId = (int)$cityId;
- $env = $this->isSandbox ? 'dev' : 'production'; // 避免切环境后,使用了不同环境的缓存数据
- $cacheKey = sprintf(self::CITY_VEHICLE_CACHE_KEY_PATTERN, $cityId, $env);
- $redis = Yii::$app->has('redis') ? Yii::$app->redis : null;
- if ($redis !== null) {
- if ($forceRefresh) {
- $redis->executeCommand('DEL', [$cacheKey]);
- } else {
- $cached = $redis->executeCommand('GET', [$cacheKey]);
- if ($cached !== false && $cached !== null) {
- $decoded = json_decode($cached, true);
- if (is_array($decoded)) {
- return $decoded;
- }
- }
- }
- }
- // 构建请求参数,发送请求
- $payload = $this->buildRequestPayload('u-city-info', ['city_id' => $cityId]);
- $resp = HttpClient::post($this->baseUrl, $payload);
- // 处理响应
- if (isset($resp['ret']) && $resp['ret'] == 0 && isset($resp['data'])) {
- $data = $resp['data'];
- // 提取车型列表
- $vehicleList = [];
- if (!empty($data['vehicle_list']) && is_array($data['vehicle_list'])) {
- foreach ($data['vehicle_list'] as $vehicle) {
- // 处理超里程价格分段
- $exceedSegmentPrice = [];
- if (!empty($vehicle['price_text_item']['exceed_segment_price'])
- && is_array($vehicle['price_text_item']['exceed_segment_price'])) {
- foreach ($vehicle['price_text_item']['exceed_segment_price'] as $segment) {
- $exceedSegmentPrice[] = [
- 'start_exdistancekm' => $segment['start_exdistancekm'] ?? 0,
- 'end_exdistancekm' => $segment['end_exdistancekm'] ?? 0,
- 'price_extra_fen' => $segment['price_extra_fen'] ?? 0,
- ];
- }
- }
- // 处理车型附加要求
- $vehicleStdItem = [];
- if (!empty($vehicle['vehicle_std_item']) && is_array($vehicle['vehicle_std_item'])) {
- foreach ($vehicle['vehicle_std_item'] as $std) {
- $vehicleStdItem[] = [
- 'name' => $std['name'] ?? '',
- 'desc' => $std['desc'] ?? '',
- 'price_fen' => $std['price_fen'] ?? 0,
- ];
- }
- }
- $vehicleList[] = [
- 'order_vehicle_id' => $vehicle['order_vehicle_id'] ?? 0,
- 'vehicle_name' => $vehicle['vehicle_name'] ?? '',
- 'img_url_high_light' => $vehicle['img_url_high_light'] ?? '',
- 'vehicle_volume' => $vehicle['vehicle_volume'] ?? '',
- 'vehicle_weight' => $vehicle['vehicle_weight'] ?? '',
- 'vehicle_size' => $vehicle['vehicle_size'] ?? '',
- 'standard_order_vehicle_id' => $vehicle['standard_order_vehicle_id'] ?? 0,
- 'text_desc' => $vehicle['text_desc'] ?? '',
- 'vehicle_attr' => $vehicle['vehicle_attr'] ?? 0,
- 'price_text_item' => [
- 'base_distancekm' => $vehicle['price_text_item']['base_distancekm'] ?? 0,
- 'base_price_fen' => $vehicle['price_text_item']['base_price_fen'] ?? 0,
- 'exceed_segment_price' => $exceedSegmentPrice,
- ],
- 'vehicle_std_item' => $vehicleStdItem,
- ];
- }
- }
- // 处理城市额外需求列表
- $specReqItem = [];
- if (!empty($data['spec_req_item']) && is_array($data['spec_req_item'])) {
- foreach ($data['spec_req_item'] as $specReq) {
- $specReqItem[] = [
- 'type' => (int)($specReq['type'] ?? 0),
- 'name' => $specReq['name'] ?? '',
- 'desc' => $specReq['desc'] ?? '',
- 'price_type' => (int)($specReq['price_type'] ?? 0),
- 'price_value_fen' => (int)($specReq['price_value_fen'] ?? 0),
- ];
- }
- }
- $result = [
- 'city_id' => $data['city_id'],
- 'name' => $data['name'],
- 'name_en' => $data['name_en'],
- 'city_info_revision' => $data['city_info_revision'],
- 'vehicle_list' => $vehicleList,
- 'spec_req_item' => $specReqItem,
- ];
- if ($redis !== null) {
- $redis->executeCommand('SETEX', [
- $cacheKey,
- self::CITY_VEHICLE_CACHE_TTL,
- json_encode($result, JSON_UNESCAPED_UNICODE)
- ]);
- }
- return $result;
- }
- return null;
- }
- /**
- * 获取可选取消原因
- *
- * 通过此接口可获取可选择的取消原因,包括主原因和子原因
- *
- * @param array $data 业务参数(当前接口无必需参数,可传空数组)
- * @return array|null 包含取消原因列表的响应数据
- */
- public function getCancelReasonList($data)
- {
- // 构建请求参数(无业务数据)
- $payload = $this->buildRequestPayload('u-order-cancelReason', []);
- // 发送请求
- $resp = HttpClient::post($this->baseUrl, $payload);
- // 处理响应
- if (isset($resp['ret']) && $resp['ret'] == 0 && isset($resp['data'])) {
- $respData = $resp['data'];
- // 提取取消原因列表
- $reasonList = [];
- if (!empty($respData['reason']) && is_array($respData['reason'])) {
- foreach ($respData['reason'] as $reason) {
- if (!empty($reason['sub_reason']) && is_array($reason['sub_reason'])) {
- foreach ($reason['sub_reason'] as $subReason) {
- $reasonList[] = [
- 'order_cancel_code' => (int)($subReason['id'] ?? 0),
- 'order_cancel_desc' => $subReason['name'] ?? '',
- ];
- }
- }
- }
- }
- return [
- 'code' => 0,
- 'data' => [
- 'reasonList' => $reasonList,
- ]
- ];
- }
- return [
- 'code' => $resp['ret'] ?? -1,
- 'msg' => $resp['msg'] ?? 'Unknown error',
- 'data' => null
- ];
- }
- /**
- * 构建API请求参数
- *
- * 根据货拉拉API规范构建完整的请求参数,包括签名
- *
- * @param string $apiMethod API方法名
- * @param array $apiData 业务参数
- * @param string|null $accessToken 用户授权令牌(可选)
- * @return array 完整的请求参数
- */
- protected function buildRequestPayload($apiMethod, $apiData = [], $accessToken = null)
- {
- // 生成随机数(nonce_str)
- $nonceStr = $this->generateNonceStr();
- // 构建系统级参数
- $payload = [
- 'api_method' => $apiMethod,
- 'api_version' => $this->apiVersion,
- 'app_key' => $this->appKey,
- 'timestamp' => time(),
- 'nonce_str' => $nonceStr,
- ];
- // 如果提供了访问令牌,加入参数
- if (!empty($accessToken)) {
- $payload['access_token'] = $accessToken;
- }
- // 业务数据作为 JSON 字符串
- // 注意:如果不加 JSON_UNESCAPED_SLASHES,PHP 会把 / 编码成 \/
- // 而很多第三方(包括货拉拉)在服务端是按未转义的 / 参与签名的,
- // 一旦字段里有 URL(如 notify_url),双方签名串就会不一致。
- // 因此这里显式关闭斜杠转义,保证本地和对端采用一致的 JSON 形式参与签名。
- $payload['api_data'] = json_encode($apiData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
- // 计算签名
- $signature = $this->generateSignature($payload);
- $payload['signature'] = $signature;
- return $payload;
- }
- /**
- * 生成签名
- *
- * 复用 SignHelper 的通用签名算法
- * 货拉拉要求32位小写MD5签名,而 SignHelper 返回大写,所以需要转为小写
- *
- * @param array $params 待签名参数(不包括signature)
- * @return string 签名值(32位小写)
- */
- protected function generateSignature($params)
- {
- // 使用 SignHelper 的通用签名算法
- $sign = SignHelper::makeSign($params, $this->appSecret);
- // 货拉拉 API 要求32位小写,转换为小写
- return strtolower($sign);
- }
- public function generateSignatureWithoutAppSecret($params)
- {
- $sign = SignHelper::makeSign($params, '');
- return strtolower($sign);
- }
- /**
- * 生成随机数字符串
- *
- * @param int $length 长度
- * @return string 随机字符串
- */
- protected function generateNonceStr($length = 16)
- {
- $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
- $str = '';
- for ($i = 0; $i < $length; $i++) {
- $str .= $chars[random_int(0, strlen($chars) - 1)];
- }
- return $str;
- }
- public function getIsSandbox()
- {
- return $this->isSandbox;
- }
- }
|