调用淘宝API 有三个参数,Appkey , AppSecret,SessionKey ,前面两个参数可以在开放平台找到,后面的sessionKey 要通过授权得到。那我们今天来讲讲如何获取SessionKey(淘宝API 令牌)
获取令牌分下面两步
//1) 通过用户授权获取授权码Code;
// (获取授权码 :https://oauth.taobao.com/authorize; 沙箱访问 https://oauth.tbsandbox.com/authorize;)
//2) 通过授权码获取Access ToKen令牌
// (获取令牌:https://oauth.taobao.com/token; 沙箱访问 https://oauth.tbsandbox.com/token";)
//获取code
private void GetCode()
{
string url = "https://oauth.tbsandbox.com/authorize"; //沙箱测试环境
string client_id = AppKey;
string redirect_uri = "http://localhost:1200/Default.aspx";//回调地址
string response_type = "code";
string state = "13";
string view = "web";
url += ("?client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&response_type=" + response_type + "&state=" + state + "&view=" + view);
Response.Redirect(url);
}
//获取Access ToKen令牌方法
protected void GetAccessToKen(string code)
{
string url = "https://oauth.tbsandbox.com/token"; //沙箱环境
#region 参数整合
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("client_id", AppKey);
param.Add("client_secret", AppSecret);
param.Add("code", code);
param.Add("grant_type", "authorization_code");
param.Add("redirect_uri", "http://localhost:1200/Default.aspx");
param.Add("state", "13");
param.Add("view", "web");
#endregion
string content = ChuangXiang.Net.Common.TaoBaoAPI.DoPost(url, param);
List = Newtonsoft.Json.JsonConvert.DeserializeObject<Token>(content);
}
public class Token
{
public string w2_expires_in { get; set; }
public string taobao_user_id { get; set; }
public string taobao_user_nick { get; set; }
public string w1_expires_in { get; set; }
public string re_expires_in { get; set; }
public string r2_expires_in { get; set; }
public string expires_in { get; set; }
public string token_type { get; set; }
public string refresh_token { get; set; }
public string access_token { get; set; }
public string r1_expires_in { get; set; }
}