淘宝客网站API有一个授权过程,有两种方式取得sessionkey,
取得授权返回值的URL为:
https://oauth.taobao.com/authorize?response_type=token&client_id=25016850&redirect_uri=你的回调地址&state=附加参数&view=web
关键点是response_type参数,它有两种主要值:
如上例,那么它会跳到你的回调地址,如下:
http://wsd.591hufu.com/apiback.php#access_token=新的sessionkey值&token_type=Bearer&expires_in=86400&refresh_token=新的token值&re_expires_in=2592000&r1_expires_in=86400&r2_expires_in=86400&taobao_open_uid=......
这时从锚中直接取得新的sessionkey,也就是上面的access_token值。
不过这种方式不推荐
即这样:
https://oauth.taobao.com/authorize?response_type=code&client_id=25016850&redirect_uri=你的回调地址&state=附加参数&view=web
这样用户授权后,会返回
http://wsd.591hufu.com/apiback.php?code=Vrq123sdfewDs43gBMEtq1GyORw1283192&state=4109
然后,使用这个code值,去换取新的sessionkey,换取有两种方法:
$req = new TopAuthTokenCreateRequest; $req->setCode("aQwoNxMdYDdDCnWpLpxDSUKP810656"); $req->setUuid("abc"); $resp = $c->execute($req);
这个仅支持HTTPS调用,否则返回这样的错:
Invalid method:taobao.top.auth.token.create 仅支持https调用
把相关必要的参数POST到网址 https://oauth.taobao.com/token 即可。
代码如下
$url = 'https://oauth.taobao.com/token'; $postfields= array('grant_type'=>'authorization_code', 'client_id'=>'123123123', 'client_secret'=>'a2sdf123132bcd12332sd122', 'code'=>'aQwoNxMdYDdDCnWpLpxDSUKP810656', 'redirect_uri'=>'http://wsd.591hufu.com/apiback.php'); $post_data = ''; foreach($postfields as $key=>$value){ $post_data .="$key=".urlencode($value)."&"; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); //指定post数据 curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data,0,-1)); //添加变量 $output = curl_exec($ch); $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //正确时返回200 curl_close($ch); echo "\n===============\n"; var_dump($output);
如果错误,会返回:
{
"error_description": "application callback can not match the redirect_uri",
"error": "invalid_client"
}
如果正确,则返回:
{"w1_expires_in":86400,"refresh_token_valid_time":1536728553620,"taobao_user_nick":"淘宝昵称","re_expires_in":2592000,"expire_time":1534222953620,"token_type":"Bearer","access_token":"新的sessionkey","taobao_open_uid":"DFEpFpIHAGshHDE21Eu7-Kl5","w1_valid":1534222953620,"refresh_token":"700122323.....","w2_expires_in":1800,"w2_valid":1534138353620,"r1_expires_in":86400,....}