博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
步步为营:Asp.Net 淘宝通用应用接口攻略
阅读量:6259 次
发布时间:2019-06-22

本文共 6927 字,大约阅读时间需要 23 分钟。

首先 阅读完这些文档

1、用户授权介绍:

2、参数解析验证签名介绍:

3、通过API获取数据:

4、示例SDK:

API测试工具:    

错误码一览表:

 

///  /// 给TOP请求签名 API v2.0 ///  /// 所有字符型的TOP请求参数 /// 签名密钥 /// 
签名
protected static string CreateSign(IDictionary
parameters, string secret) {
parameters.Remove("sign"); IDictionary
sortedParams = new SortedDictionary
(parameters); IEnumerator
> 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(); } ///
/// 组装普通文本请求参数。 /// ///
Key-Value形式请求参数字典 ///
URL编码后的请求数据
protected static string PostData(IDictionary
parameters) { StringBuilder postData = new StringBuilder(); bool hasParam = false; IEnumerator
> 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(); } ///
/// TOP API POST 请求 /// ///
请求容器URL ///
AppKey ///
AppSecret ///
API接口方法名 ///
调用私有的sessionkey ///
请求参数 ///
返回字符串
public static string Post(string url, string appkey, string appSecret, string method, string session, IDictionary
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]", "");; } ///
/// 验证回调地址的签名是否合法。 /// ///
回调地址 ///
应用密钥 ///
验证成功返回True,否则返回False
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
queryDict = new Dictionary
(); 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"]; } ///
/// 验证回调地址的签名是否合法。 /// ///
TOP私有参数(未经Base64解密后的) ///
TOP私有会话码 ///
TOP回调签名(经过URL反编码的) ///
应用公钥 ///
应用密钥 ///
验证成功返回True,否则返回False
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; } ///
/// 解析回调地址中top_parameters中的值 /// ///
取值关键词 ///
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
parameters = new Dictionary
(); 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
(json); return Content(xml); } #endregion

 

 

转载于:https://www.cnblogs.com/79039535/archive/2012/02/02/2335556.html

你可能感兴趣的文章
SpringMVC那点事
查看>>
大话nbu三(配置media server存储)
查看>>
【嵌入式】内存管理,虚拟存储
查看>>
Linux多线程实践(2) --线程基本API
查看>>
从BaseActivity与BaseFragment的封装谈起
查看>>
Java Web开发相关连接
查看>>
虚拟机内存中数据细节
查看>>
ZigBee Silicon Labs/Ember EFR32MG/EM357 1.1 总体框架
查看>>
信号结构类的时间开销对比
查看>>
在Ubuntu上部署开源博客系统Blog_mini
查看>>
内部类知识
查看>>
使用 kubeadm 创建一个 kubernetes 集群
查看>>
MYSQL主从同步故障
查看>>
nginx 代理http配置实例
查看>>
阿里巴巴12位科学家发布2018年科技趋势预测
查看>>
开放的即时通信协议Jabber
查看>>
Django 的生命周期
查看>>
菜鸟也玩DNS之配置DNS的MX记录
查看>>
实战操作主机角色转移之清除宕机DC的元数据(三)
查看>>
MySQL实现序列(Sequence)效果以及在Mybatis中如何使用这种策略
查看>>