首先 阅读完这些文档
1、用户授权介绍:
2、参数解析验证签名介绍:
3、通过API获取数据:
4、示例SDK:
API测试工具:
错误码一览表:
////// 给TOP请求签名 API v2.0 /// /// 所有字符型的TOP请求参数 /// 签名密钥 ///签名 protected static string CreateSign(IDictionaryparameters, 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(IDictionaryparameters) { 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, IDictionaryparam,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; } IDictionaryqueryDict = 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; IDictionaryparameters = 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