今天做一个访问阿里云api刷新缓存的功能,开始想找sdk的,但是没找到,只有一个个方法找,其实改好了发现也不是难的。
### 请求参数
function setParameter($specialParameter){
$time = date('Y-m-d H:i:s', time()-8*60*60);//北京时间转换为UTC时间
$var = strtr($time, ' ', 'T');
$Timestamp = $var . 'Z';
$signature_nonce = '';
for($i =0 ; $i < 14; $i++){
$signature_nonce .= mt_rand(0,9);
}
$publicParameter = array(
'Format' => 'JSON',
'Version' => '2014-11-11',
'SignatureMethod' => 'HMAC-SHA1',
'TimeStamp' => $Timestamp,
'SignatureVersion' => '1.0',
'SignatureNonce' => $signature_nonce,
'ObjectType' => 'File'
);
$parameter = array_merge($publicParameter, $specialParameter);
return $parameter;
}
将参数排序并添加$signature
function getStringToSign($parameter,$access_key_secret){
ksort($parameter);
foreach($parameter as $key => $value){
$str[] = rawurlencode($key). "=" .rawurlencode($value);
}
$ss = "";
if(!empty($str)){
for($i=0; $i<count($str); $i++){
if(!isset($str[$i+1])){
$ss .= $str[$i];
}else{
$ss .= $str[$i]."&";
}
}
}
$StringToSign = "GET" . "&" . rawurlencode("/") . "&" . rawurlencode($ss);
$signature = base64_encode(hash_hmac("sha1", $StringToSign, $access_key_secret."&", true));
$url = "https://cdn.aliyuncs.com/?" . $ss . "&Signature=" . $signature;
return $url;
}
curl访问
function curl_get($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_HEADER, 0); // 不要http header 加快效率
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
调用函数
function describeCdnService( $url_show, $action = 'RefreshObjectCaches' ){
$access_key_id = ACCESS_ID;
$access_key_secret = ACCESS_SECRET;
if(empty($access_key_id) || empty($access_key_secret)){
$message = array(
'status' => 'failed',
'reason' => 'Access key Id or access key secret is invalid',
);
return json_encode($message);
}
$specialParameter = array(
'AccessKeyId' => $access_key_id,
'Action' => $action,
'ObjectPath' => $url_show,
);
$parameter = setParameter( $specialParameter );
$url = getStringToSign( $parameter, $access_key_secret );
$ret = curl_get( $url );
return $ret;
}
最后这个函数就是项目要调用的,此方法调用上面的三个方法
$url = DT_URL.'sell/show-'. $itemid .'.html';
describeCdnService( $url );
大功告成