.net Core 2.2实现京东宙斯API采用OAuth授权方式调用
1.实现对接京东接口,这里主要是写了采用Oauth授权的方式调用。
2.VS2017 使用了.net core 2.2 控制台程序,json库使用 jil(这个比较轻量级,加载数据较快,但也需要注意有小坑),使用了自动排序的 SortedDictionary
3.该例子通过创建实体的方式,实例化实体,入参。
4.安装jil 可以通过nuget程序包管理器控制台:install-package jil 就会自动安装啦
5.这里只要填入 appSecret,app_key,access_token 对应值,即可。
using System; using System.Collections.Generic; using System.Xml; namespace JdServices { internal class Program { private static void Main(string[] args) { /* * 以 jingdong.pop.order.search 方法为例 * */ SortedDictionary<string, string> param = new SortedDictionary<string, string>(); JilJsonSerializer serializer = new JilJsonSerializer(); PopOrderSearch popOrder = new PopOrderSearch() { optional_fields = @"vender_id,order_id,pay_type,order_total_price,freight_price,seller_discount,order_payment,delivery_type,order_state,order_state_remark,invoice_info,order_remark,order_start_time,order_end_time,consignee_info,item_info_list", order_state = "WAIT_SELLER_STOCK_OUT", page = "1", page_size = "20", start_date = "2019-09-01 00:00:00", end_date = "2019-09-01 18:00:00", }; var jdApi = "https://api.jd.com/routerjson"; var appSecret = ""; var app_key = ""; var access_token = ""; //参数 param.Add("app_key", app_key); param.Add("access_token", access_token); param.Add("format", "json"); param.Add("v", "2.0"); param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); param.Add("method", "jingdong.pop.order.search"); param.Add("360buy_param_json", serializer.ToJson<PopOrderSearch>(popOrder)); //生成签名 string sign = JdServices.JdHelper.GetSign(param, appSecret); param.Add("sign", sign); //生成请求URL var resultUrl = JdHelper.BuildGetUrl(jdApi, param); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; namespace JdServices { public static class JdHelper { /// <summary> /// 获取签名 /// </summary> /// <param name="parameters">组成签名的参数</param> /// <param name="appSecret">secret</param> /// <param name="accessToken">token</param> /// <returns></returns> public static string GetSign(SortedDictionary<string, string> parameters, string appSecret, string accessToken = "") { //参数排序 var str = new StringBuilder(); foreach (var kv in parameters) { if (!string.IsNullOrWhiteSpace(kv.Key) && !string.IsNullOrWhiteSpace(kv.Value)) { str.Append(kv.Key).Append(kv.Value); } } // 使用MD5加密转大写 var result = EncryptMD5(str + appSecret).ToUpper(); return result; } ///<summary> /// 给一个字符串进行MD5加密 ///</summary> ///<param name="strText">待加密字符串</param> ///<returns>加密后的字符串</returns> public static string EncryptMD5(string strText) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(strText)); return string.Join("", hashBytes.Select(i => i.ToString("x2"))); } /// <summary> /// 生成请求连接地址. /// </summary> /// <param name="url"></param> /// <param name="param"></param> /// <returns></returns> public static string BuildGetUrl(string url, SortedDictionary<string, string> param) { var strMsg = new StringBuilder(); foreach (var (key, value) in param) { strMsg.AppendFormat(@"&{0}={1}", key, value); } //?. 是C#6.0的语法,叫Null-Conditional Operator(null条件运算符) // 我们经常需要判断对象是否为null(不判断就会报异常System.NullReferenceException之类的信息) if (url?.IndexOf("?") != -1) { url += "&" + strMsg; } else { url += "?" + strMsg; } return url.ToString(); } } }
using Jil; using System; using System.Collections.Generic; using System.Text; namespace JdServices { public class JilJsonSerializer { private readonly Encoding _encoding; public JilJsonSerializer(bool isCamelCase = false) : this(new Options(prettyPrint: true, excludeNulls: false, jsonp: false, dateFormat: DateTimeFormat.ISO8601, includeInherited: true, serializationNameFormat: isCamelCase ? SerializationNameFormat.CamelCase : SerializationNameFormat.Verbatim, unspecifiedDateTimeKindBehavior: UnspecifiedDateTimeKindBehavior.IsUTC)) { _encoding = Encoding.UTF8; } private JilJsonSerializer(Options options) { if (options == null) throw new ArgumentNullException(nameof(options)); JSON.SetDefaultOptions(options); } public byte[] Serialize(Type type, object obj) { var jsonString = JSON.Serialize(obj); return _encoding.GetBytes(jsonString); } public byte[] Serialize<T>(T t) { var s = JSON.Serialize(t); return _encoding.GetBytes(s); } public object Deserialize(Type type, byte[] serializedObject) { var jsonString = _encoding.GetString(serializedObject); return JSON.Deserialize(jsonString, type); } public T Deserialize<T>(byte[] serializedObject) { return JSON.Deserialize<T>(_encoding.GetString(serializedObject)); } public string ToJson<T>(T t) { var bytes = Serialize(t); return _encoding.GetString(bytes); } public T ToObject<T>(string json) { return JSON.Deserialize<T>(json); } } }
using System.Collections.Generic; using System.Text; namespace JdServices { /// <summary> /// jingdong.pop.order.search接口参数实体 /// </summary> public class PopOrderSearch { public string end_date { get; set; } public string optional_fields { get; set; } public string order_state { get; set; } public string page { get; set; } public string page_size { get; set; } public string start_date { get; set; } } }
至此,OAuth授权方式调用实现完成,整个例子很简单,无非就是jil使用需要注意点,也可以使用Newtonsoft.Json 库,看自己个人习惯。