步步为营:Asp.Net 淘宝通用应用接口攻略

首先 阅读完这些文档

1、用户授权介绍:http://open.taobao.com/doc/detail.htm?id=105

2、参数解析验证签名介绍:http://open.taobao.com/doc/detail.htm?id=110

3、通过API获取数据:http://open.taobao.com/doc/detail.htm?id=111

4、示例SDK:http://open.taobao.com/doc/detail.htm?id=112

API测试工具:http://api.taobao.com/apitools/apiTools.htm    

错误码一览表: http://open.taobao.com/doc/detail.htm?id=114

/// <summary> 
/// 给TOP请求签名 API v2.0
/// </summary>
/// <param name="parameters">所有字符型的TOP请求参数</param>
/// <param name="secret">签名密钥</param>
/// <returns>签名</returns>
protected static string CreateSign(IDictionary<string, string> parameters, string secret)
{
parameters.Remove("sign");
IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
StringBuilder query = new StringBuilder(secret);
while (dem.MoveNext())
{
string key = dem.Current.Key;
string value = dem.Current.Value;
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
{
query.Append(key).Append(value);
}
}
query.Append(secret);
MD5 md5 = MD5.Create();
byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
StringBuilder result = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
string hex = bytes[i].ToString("X");
if (hex.Length == 1)
{
result.Append("0");
}
result.Append(hex);
}
return result.ToString();
}
/// <summary>
/// 组装普通文本请求参数。
/// </summary>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
protected static string PostData(IDictionary<string, string> parameters)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
postData.Append(Uri.EscapeDataString(value));
hasParam = true;
}
}
return postData.ToString();
}
/// <summary>
/// TOP API POST 请求
/// </summary>
/// <param name="url">请求容器URL</param>
/// <param name="appkey">AppKey</param>
/// <param name="appSecret">AppSecret</param>
/// <param name="method">API接口方法名</param>
/// <param name="session">调用私有的sessionkey</param>
/// <param name="param">请求参数</param>
/// <returns>返回字符串</returns>
public static string Post(string url, string appkey, string appSecret, string method, string session,
IDictionary<string, string> param,string format)
{
param.Add("app_key", appkey);
param.Add("method", method);
param.Add("session", session);
param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
param.Add("format", format);
param.Add("v", "2.0");
param.Add("sign_method", "md5");
param.Add("sign", CreateSign(param, appSecret));

string result = string.Empty;
byte[] postData = Encoding.UTF8.GetBytes(PostData(param));
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ServicePoint.Expect100Continue = false;
req.Method = "POST";
req.KeepAlive = true;
req.Timeout = 300000;
req.UserAgent = "Top4Net";
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
req.ContentLength = postData.Length;


Stream reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
reqStream.Close();

HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
Stream stream = null;
StreamReader reader = null;
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
result = reader.ReadToEnd();
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
return Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", "");;
}


/// <summary>
/// 验证回调地址的签名是否合法。
/// </summary>
/// <param name="callbackUrl">回调地址</param>
/// <param name="appSecret">应用密钥</param>
/// <returns>验证成功返回True,否则返回False</returns>
public static bool VerifyTopResponse(string callbackUrl, string appSecret)
{
Uri uri = new Uri(callbackUrl);

string query = uri.Query;
if (string.IsNullOrEmpty(query)) // 没有回调参数
{
return false;
}

query = query.Trim(new char[] { '?', ' ' });
if (query.Length == 0) // 没有回调参数
{
return false;
}

IDictionary<string, string> queryDict = new Dictionary<string, string>();
string[] queryParams = query.Split(new char[] { '&' });

if (queryParams != null && queryParams.Length > 0)
{
foreach (string queryParam in queryParams)
{
string[] oneParam = queryParam.Split(new char[] { '=' });
if (oneParam.Length >= 2)
{
queryDict.Add(oneParam[0], oneParam[1]);
}
}
}

StringBuilder result = new StringBuilder();
if (queryDict.ContainsKey("top_appkey")) result.Append(queryDict["top_appkey"]);
if (queryDict.ContainsKey("top_parameters")) result.Append(queryDict["top_parameters"]);
if (queryDict.ContainsKey("top_session")) result.Append(queryDict["top_session"]);
result.Append(appSecret);

byte[] bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(result.ToString()));
string sign = System.Convert.ToBase64String(bytes);

return queryDict.ContainsKey("top_sign") && Uri.EscapeDataString(sign) == queryDict["top_sign"];
}

/// <summary>
/// 验证回调地址的签名是否合法。
/// </summary>
/// <param name="topParams">TOP私有参数(未经Base64解密后的)</param>
/// <param name="topSession">TOP私有会话码</param>
/// <param name="topSign">TOP回调签名(经过URL反编码的)</param>
/// <param name="appKey">应用公钥</param>
/// <param name="appSecret">应用密钥</param>
/// <returns>验证成功返回True,否则返回False</returns>
public static bool VerifyTopResponse(string topParams, string topSession, string topSign, string appKey, string appSecret)
{
StringBuilder result = new StringBuilder();

System.Security.Cryptography.MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

result.Append(appKey).Append(topParams).Append(topSession).Append(appSecret);
byte[] bytes = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(result.ToString()));

return System.Convert.ToBase64String(bytes) == topSign;
}


/// <summary>
/// 解析回调地址中top_parameters中的值
/// </summary>
/// <param name="key">取值关键词</param>
/// <returns></returns>
public string GetParameters(string parameters, string key)
{
string ret = string.Empty;
try
{
string str = Base64ToString(parameters);
string[] param = str.Split('&');
for (int i = 0; i < param.Length; i++)
{
string[] info = param[i].Split('=');
if (info[0].ToLower() == key.ToLower())
{
ret = info[1];
break;
}
}
}
catch
{
//
}
return ret;
}


 

#region 测试taobao.user.get API 接口
public ActionResult tbuserget()
{
Shikee.Api.Model.Parameters paras = new Shikee.Api.Model.Parameters();
//userid = 110246;

IDictionary<string, string> parameters = new Dictionary<string, string>();
string sign = string.Empty;
//paras = Users.GetOpenTaobaoByUid(userid);
parameters.Add("fields", "user_id,uid,nick,sex,buyer_credit,seller_credit,location,created,last_visit,birthday,type,status,alipay_no,alipay_account,alipay_account,email,consumer_protection,alipay_bind");
parameters.Add("nick", "daisys1");

string xml = Shikee.Api.Util.Post("http://gw.api.taobao.com/router/rest", ConfigurationManager.AppSettings["taobao_appkey"].ToString(), ConfigurationManager.AppSettings["taobao_appsecret"].ToString(), "taobao.user.get", "", parameters, "xml");
//json = json.Replace("{\"user_get_response\":{\"user\":", "");
//json = json.Replace("}}", "");
//Shikee.Api.Model.User user = new JavaScriptSerializer().Deserialize<Shikee.Api.Model.User>(json);
return Content(xml);



}
#endregion
原文地址:https://www.cnblogs.com/79039535/p/2335556.html