一、接口申请
通过聚合https://www.juhe.cn/docs/api/id/43自助申请开通接口权限。
二、通过PHP发起快递查询
class JuheExpress
{
private $apiKey = '**************'; // 在聚合申请到的快递查询接口请求Key
private $apiHost = 'Https://v.juhe.cn/exp';
public function getCompanys()
{
// 组装请求完整URL
$requestApiUrl = $this->apiHost . '/com?key=' . $this->apiKey;
// 发起网络请求聚合
$requestResponseContent = $this->juheHttpRequest($requestApiUrl);
// 解析结果
$requestResult = JSON_decode($requestResponseContent, true);
if (!$requestResult) {
// 请求异常,可能网络异常等原因,根据自身逻辑修改
echo "请求异常";
return false;
} else {
$requestStatusCode = $requestResult['error_code'];
if ($requestStatusCode === 0) {
// 请求成功,根据自身逻辑修改
$companys = $requestResult['result'];
return $companys;
} else {
// 请求失败,根据自身逻辑修改
echo $requestResult['error_code'] . ':' . $requestResult['reason'];
return false;
}
}
}
public function getResult()
{
$apiUrl = $this->apiHost . '/index';
$requestParams = [
'key' => $this->apiKey,
'com' => 'yd', // 需要查询的快递公司编号
'no' => '4312453259458', // 需要查询的快递单号
'senderPhone' => '',
'receiverPhone' => ''
];
// 发起网络请求聚合
$requestResponseContent = $this->juheHttpRequest($apiUrl, $requestParams, 1);
// 解析结果
$requestResult = json_decode($requestResponseContent, true);
if (!$requestResult) {
// 请求异常,可能网络异常等原因,根据自身逻辑修改
echo "请求异常";
return false;
} else {
$requestStatusCode = $requestResult['error_code'];
if ($requestStatusCode === 0) {
// 请求成功,根据自身逻辑修改
$companys = $requestResult['result'];
return $companys;
} else {
// 请求失败,根据自身逻辑修改
echo $requestResult['error_code'] . ':' . $requestResult['reason'];
return false;
}
}
}
private function juheHttpRequest($url, $params = false, $ispost = 0)
{
// $httpInfo = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (windows NT 10.0; WOW64) AppleWEBKit/537.36 (Khtml, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 12);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($ispost) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_URL, $url);
} else {
if ($params) {
if (is_array($params)) {
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
} else {
curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
}
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
$response = curl_exec($ch);
if ($response === false) {
// echo "cURL Error: ".curl_error($ch);
return false;
}
// $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
curl_close($ch);
return $response;
}
}
$juheExpress = new JuheExpress();
$companys = $juheExpress->getCompanys();
print_r($companys);
$results = $juheExpress->getResult();
print_r($results);