阿里巴巴开放平台Oauth2.0协议获取access_token
原创
©著作权归作者所有:来自51CTO博客作者廖圣平_的原创作品,请联系作者获取转载授权,否则将追究法律责任
如果对Oauth2不太熟,有时间的话可以去学习一下之前写的一篇
Oauth2.0 oauth2-server-php的使用Demo,怎么连接redis/可实现thinkphp5/yii/Laravel中使用
阿里巴巴composer 包:
阿里巴巴开放平台SDK
一、获取Code
//获取的code有效时间2分钟
public function getCode(){
#拼接获取Code的URL
$url='http://gw.api.alibaba.com/openapi';
$appKey='';
$appSecret ='';
#回调URL
$redirectUrl = 'http://127.0.0.1/auth.php';
#生成签名
$code_arr = array(
'client_id' => $appKey,
'redirect_uri' => $redirectUrl,
'site' => '1688'
);
ksort($code_arr);
$sign_str = '';
foreach ($code_arr as $key=>$val){
$sign_str .= $key . $val;
}
$code_sign = strtoupper(bin2hex(hash_hmac("sha1", $sign_str, $appSecret, true)));
$get_code_url = 'http://gw.api.alibaba.com/auth/authorize.htm?client_id='.$appKey.'&site=aliexpress&redirect_uri='.$redirectUrl.'&_aop_signature='.$code_sign;
$get_code_url;
}
二、拿Code 换access_token
public function gettoken(){
#根据code获取refresh_token、access_token
$url = 'http://gw.api.alibaba.com/openapi';
$appKey = '';
$appSecret ='';
$redirectUrl = 'http://http://127.0.0.1/auth.php';
#此处code即为上面的方法getCode取得的code值
$code='';
#拼接获取token的Url
$getTokenUrl='https://gw.api.alibaba.com/openapi/http/1/system.oauth2/getToken/'.$appKey;
$data='grant_type=authorization_code&need_refresh_token=true&client_id='.$appKey.'&client_secret='.$appSecret.'&redirect_uri='.$redirectUrl.'&code='.$code;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $getTokenUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
curl_close($ch);
#打印出返回结果
print_r(json_decode($result));
exit;
}
和我做朋友?
廖圣平博客整理
参考:www.04007.cn