heyuntao
2023-05-05 cc09b6fe6ffac34a4eeeb26d313b187713cae0de
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
using AlibabaSDK.Setting;
using CommonUtil;
using CommonUtil.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using CommonUtil;
using System.Web;
 
 
namespace AlibabaSDK.Api
{
    public class AliabaClient
    {
        /// <summary>
        /// 执行TOP公开API请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <param name="appKey"></param>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        public static T Execute<T>(IAlibabaApiRequest<T> request, string sessionKey) where T : AlibabaApiResponse
        {
            T t = null;
            try
            {
                // request.Validate();
                string Method = request.GetApiName();
                string PostUrl = AlibabaApiSet.G1OfficialUrl;
                string appKey = AlibabaApiSet.AppKey;
                string secretKey = AlibabaApiSet.SecretKey;
                long timeStamp = ExtendUtil.EncodeUnixMillisecond(DateTime.Now);
                //系统级参数
                string baseUrl = $"{Method}/{appKey}";
                PostUrl += $"{baseUrl}";
                //获取应用级参数
                Dictionary<string, object> paramers = request.GetParameters();
                paramers.Add("access_token", sessionKey);
                //计算sign
                string sign = GetSign(baseUrl, paramers);
                //paramers.Add("_aop_timestamp", timeStamp.ToString());
                paramers.Add("_aop_signature", sign);
                string paramStr = string.Empty;
                foreach (var pa in paramers)
                {
                    paramStr += paramStr.IsNullOrEmpty() ? $"?" : "&";
                    Type ty = pa.Value.GetType();
                    if ("string,long,int,douber,decimal".Contains(ty.Name.ToLower()))
                    {
                        paramStr += $"{ pa.Key}={ pa.Value}";
                    }
                    else
                    {
                        paramStr += $"{ pa.Key}={ JSONUtil.ObjectToJson(pa.Value).ToUrlEncode()}";
                    }
                }
                IDictionary<string, object> postDic = JSONUtil.JsonToObject<IDictionary<string, object>>(JsonConvert.SerializeObject(paramers));
                //Post请求数据
                PostUrl += paramStr;
 
                //string responseStr = new WebUtil().DoPost(PostUrl, text, null);
                string responseStr = Post(PostUrl);
                if (responseStr.IsNullOrEmpty())
                {
                    return null;
                }
                t = JsonConvert.DeserializeObject<T>(responseStr);
                t.Body = responseStr;
            }
            catch (Exception exe)
            {
                LogUtil.Error(exe.ToString(), "1688sdk错误");
                t = request.ErrorObj() as T;
                if (t != null)
                {
                    t.ErrorMsg = exe.Message;
                    t.ErrorCode = "-32606";
                }
                t.Body = "";
            }
            return t;
        }
 
        //urlPath: 基础url部分,格式为protocol/apiVersion/namespace/apiName/appKey,如 json/1/system/currentTime/1;如果为客户端授权时此参数置为空串""
        //paramDic: 请求参数,即queryString + request body 中的所有参数
        private static string GetSign(string urlPath, Dictionary<string, object> paramDic)
        {
            if (urlPath.StartsWith("/"))
            {
                urlPath = urlPath.Substring(1, urlPath.Length - 1);
            }
            byte[] signatureKey = Encoding.UTF8.GetBytes(AlibabaApiSet.SignKey);//此处用自己的签名密钥
            List<string> list = new List<string>();
            foreach (KeyValuePair<string, object> kv in paramDic)
            {
 
                Type ty = kv.Value.GetType();
                if ("string,long,int,douber,decimal".Contains(ty.Name.ToLower()))
                {
                    list.Add(kv.Key + kv.Value.ToString());
                }
                else
                {
                    list.Add(kv.Key + JSONUtil.ObjectToJson(kv.Value));
                }
            }
            list.Sort();
            string tmp = urlPath;
            foreach (string kvstr in list)
            {
                tmp = tmp + kvstr;
            }
 
            //HMAC-SHA1
            HMACSHA1 hmacsha1 = new HMACSHA1(signatureKey);
            byte[] hashBytes = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(tmp));
            byte[] hash = hmacsha1.Hash;
            //TO HEX
            return BitConverter.ToString(hashBytes).Replace("-", "").ToUpper();
        }
 
        public static string Post(string Url)
        {
            string strURL = Url;
            //创建一个HTTP请求  
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            //Post请求方式  
            request.Method = "POST";
            //内容类型
            //  request.ContentType = "application/x-www-form-urlencoded";
 
            //设置参数,并进行URL编码 
 
            //  string paraUrlCoded = jsonParas;//System.Web.HttpUtility.UrlEncode(jsonParas);   
 
            byte[] payload;
            //将Json字符串转化为字节  
            //  payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
            //设置请求的ContentLength   
            // request.ContentLength = payload.Length;
            //发送请求,获得请求流 
 
            Stream writer;
            try
            {
                writer = request.GetRequestStream();//获取用于写入请求数据的Stream对象
            }
            catch (Exception)
            {
                writer = null;
                Console.Write("连接服务器失败!");
            }
            //将请求参数写入流
            // writer.Write(null, 0, 0);
            writer.Close();//关闭请求流
                           // String strValue = "";//strValue为http响应所返回的字符流
            HttpWebResponse response;
            try
            {
                //获得响应流
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
            }
            Stream s = response.GetResponseStream();
            //  Stream postData = Request.InputStream;
            StreamReader sRead = new StreamReader(s);
            string postContent = sRead.ReadToEnd();
            sRead.Close();
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine($"服务端返回信息:{postContent},时间:{DateTime.Now.ToString()}");
 
 
            return postContent;//返回Json数据
        }
    }
}