惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Forbes - Security
Forbes - Security
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
SegmentFault 最新的问题
Y
Y Combinator Blog
Recorded Future
Recorded Future
博客园 - Franky
I
InfoQ
T
The Blog of Author Tim Ferriss
Recent Announcements
Recent Announcements
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
Cyberwarzone
Cyberwarzone
The Register - Security
The Register - Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
雷峰网
雷峰网
P
Palo Alto Networks Blog
G
GRAHAM CLULEY
Cloudbric
Cloudbric
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
MongoDB | Blog
MongoDB | Blog
F
Full Disclosure
Google DeepMind News
Google DeepMind News
Recent Commits to openclaw:main
Recent Commits to openclaw:main
C
Check Point Blog
爱范儿
爱范儿
The GitHub Blog
The GitHub Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
W
WeLiveSecurity
T
Threat Research - Cisco Blogs
U
Unit 42
N
Netflix TechBlog - Medium
The Cloudflare Blog
Spread Privacy
Spread Privacy
Microsoft Azure Blog
Microsoft Azure Blog
美团技术团队
T
Troy Hunt's Blog
Engineering at Meta
Engineering at Meta
H
Heimdal Security Blog
TaoSecurity Blog
TaoSecurity Blog
C
Cybersecurity and Infrastructure Security Agency CISA
T
Tenable Blog
B
Blog
S
Securelist
H
Hacker News: Front Page
Google Online Security Blog
Google Online Security Blog
G
Google Developers Blog

博客园 - baileyer

VisualSVN破解安装到VS2026 使用 SQL 中的递归查询(Recursive CTE)来实现1-50数字 git 忽略本地文件提交(VS) C# 自定义导出模板(NPOI) Abp vue项目找不到模块“./app.vue” MSSqlserver分割文件备份恢复 github的镜像下载加快clone下载速度 widows部署.NET Core 3.1项目到IIS问题 .net core/mvc获取特性 oracle instr 替代like查询 quartz3.0.7和topshelf4.2.1实现任务调度 VS2017同时生成.net core和.net framework两份代码 .net core Failed to load API definition 错误 vs 2017 调试中断问题 WinForm 校验只能输入数字英文字母退格键 NPOI导出excel C#通过反射获取相应的字段和值 activemq.bat 在window7 x64下启动(安装)报错解决方案 <asp:RadioButton> 选项判断
.net Core 2.2实现京东宙斯API采用OAuth授权方式调用
baileyer · 2019-09-03 · via 博客园 - baileyer

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();
        }
    }
}

一、Main运行入口代码

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();
        }
    }
}

二、创建JdHelper帮助类

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);
        }
    }
}

三、创建 JilJsonSerializer 帮助类

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; }
    }
}

四、创建接口 PopOrderSearch 对象

至此,OAuth授权方式调用实现完成,整个例子很简单,无非就是jil使用需要注意点,也可以使用Newtonsoft.Json 库,看自己个人习惯。