获取临时token
//获取临时token function get_token(){ $url1='https://sts.aliyuncs.com'; $array=[ 'Action'=>'AssumeRole', 'SignatureVersion'=>'1.0', 'Version'=>'2015-04-01', 'RoleArn'=>ROLE_ARN, //阿里云角色名称 'RoleSessionName'=>ROLE_SESSION_NAME, //阿里云获取 'Format'=>'JSON', 'Timestamp'=>date('Y-m-dTH:i:s', time() - date('Z')), 'AccessKeyId'=>ACCESSKEYID, //阿里云accesskeyid 'SignatureMethod'=>'HMAC-SHA1', 'SignatureNonce'=>substr(md5(rand(1, 99999999)), rand(1, 9), 14) ]; $get_sign=get_sign($array,'GET');//获取sign签名 get_sign方法在下方↓ $array['Signature']=$get_sign['hmac']; //计算完签名之后,将签名放入请求数组 $uri = http_build_query($array); $url = 'https://sts.aliyuncs.com/?'.$uri; $data=curl_get($url); // 请求方式与获取sign签名一致 get $data=json_decode($data,true); return $data??''; }
计算签名sign:
//获取sign
function get_sign($params,$mothod='GET'){
//获取签名
ksort($params); //字典化排序
$stringToSign=strtoupper($mothod).'&'.percentEncode('/').'&'; //precentEncode规范化请求字符串↓
$tmp = "";
foreach ($params as $key => $val) {
$tmp.='&'.percentEncode($key).'='.percentEncode($val);
}
$tmp=trim($tmp,'&');
$stringToSign = $stringToSign.percentEncode($tmp);
$key=ACCESS_KEY_SECRET.'&'; //阿里云accesskeysecret
$hmac=base64_encode(hash_hmac("sha1",$stringToSign,$key,true));//hash_hmac — 使用 HMAC 方法生成带有密钥的哈希值
return ['hmac'=>$hmac,'stringToSign'=>$stringToSign];
}
规范化请求字符串
//规范化请求字符串 function percentEncode($value = null) { $en = urlencode($value); $en = str_replace("+","%20",$en); $en = str_replace("*","%2A",$en); $en = str_replace("%7E","~",$en); return $en; }