zhaojs
2023-09-15 fc13938ff90213060532d99a600dea4a84456885
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Jayrock.Json.Conversion;
using YouZanSDKStandard.Api.Request;
using YouZanSDK.Setting;
using CommonUtil.Web;
using CommonUtil;
 
namespace YouZanSDKStandard.Api
{
    public class YouZanClient
    {
        /// <summary>
        /// 调用接口
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static T Execute<T>(IRequest<T> request) where T : YouZanResponse
        {
            return Execute<T>(request, string.Empty);
        }
 
 
        /// <summary>
        /// 调用接口
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <param name="SessionKey"></param>
        /// <returns></returns>
        public static T Execute<T>(IRequest<T> request, string SessionKey) where T : YouZanResponse
        {
            T t = null;
 
            #region 检验参数
            request.Validate();
            #endregion
 
 
            //接口参数
            IDictionary<string, object> dict = request.GetParameters();
            //Dictionary<string, object> dict = new Dictionary<string, object>();
            //foreach (var dic in dictionary)
            //{
            //    dict.Add(dic.Key, dic.Value);
            //}
            string reStr = "";
            YouZanResponse rspBase = null;
            try
            {
                string apiUrl = YouZanSetting.GetApiUrl(request.GetApiName(), request.GetApiVersion(), SessionKey);
                //reStr = PostJson(apiUrl, dict);
                reStr = new WebUtil().DoPostWithJson(apiUrl, dict, null);
                //if (!reStr.Contains("true"))
                //    LogTextHelper.WriteLine("有赞接口返回错误信息", reStr);
 
                try
                {
                    //rspBase = JsonConvert.Import(typeof(YouZanResponse), reStr) as YouZanResponse;
                    rspBase = JSONUtil.JsonToObject<YouZanResponse>(reStr);
                }
                catch (Exception e)
                {
                    LogTextHelper.WriteLine("有赞接口转换错误", reStr);
                }
 
                if (rspBase != null)
                {
                    if (rspBase.success)
                    {
                        try
                        {
                            reStr = request.ResponseJsonPrefix(reStr);
                           // t = JsonConvert.Import(typeof(T), reStr) as T;
                           t= JSONUtil.JsonToObject<T>(reStr);
                        }
                        catch (Exception ex)
                        {
                            LogTextHelper.WriteLine("有赞接口转换错误1", reStr);
                            rspBase = new YouZanResponse
                            {
                                code = 500,
                                success = false,
                                message = "接口调用异常" + ex.ToString() + "接口返回:" + reStr,
                            };
 
                            t = (T)rspBase;
                        }
                    }
                    else
                    {
                        reStr = request.ResponseJsonPrefix(reStr);
                        t = JSONUtil.JsonToObject<T>(reStr);
                    }
                }
                else
                {
                    rspBase = new YouZanResponse
                    {
                        code = 500,
                        success = false,
                        message = "接口调用异常接口返回:" + reStr,
                    };
 
                    t = (T)rspBase;
                }
            }
            catch (Exception ex)
            {
                rspBase = new YouZanResponse
                {
                    code = 500,
                    success = false,
                    message = "接口调用异常" + ex.ToString() + "接口返回:" + reStr,
                };
 
                t = (T)rspBase;
            }
            if (t == null)
            {
                rspBase = new YouZanResponse
                {
                    code = 500,
                    success = false,
                    message = "接口调用异常接口返回:" + reStr,
                };
 
                t = (T)rspBase;
            }
 
            return t;
            #region 旧sdk废弃
            /*
            //youzan.items.get 长度16
            int num = apiName.LastIndexOf(".");//num=12
            string text = apiName.Substring(0, num);//text="youzan.items"
            string text2 = apiName.Substring(num + 1, apiName.Length - (num + 1));//text2="get"
            string postUrl = YouZanSetting.OfficialCallUrl + "/" + text + "/3.1.0/" + text2;
            string postPar = "?access_token=" + SessionKey;
            if (dictionary.Count > 0)
            {
                foreach (var item in dictionary )
                {
                    postPar += "&" + item.Key + "=" + item.Value;
                }
            }
         //   string reStr = postMethod(postUrl, postPar, false);
            Auth auth = new Token(SessionKey);
            YZClient yzClient = new DefaultYZClient(auth);
            string reStr="" ;
            switch (apiName)
            {
                case "youzan.scrm.customer.search": reStr = yzClient.Invoke(apiName, "3.1.0", "Post", dict, null); ; break;
                case "youzan.trades.sold.outer.get": reStr = yzClient.Invoke(apiName, "3.0.0", "get", dict, null); ; break;
                case "youzan.trades.sold.get": reStr = yzClient.Invoke(apiName, "4.0.0", "get", dict, null); ; break;
            }
            YouZanResponse rspBase;
            try
            {
                rspBase = JsonConvert.Import(typeof(YouZanResponse), reStr) as YouZanResponse;
 
                if (rspBase != null)
                {
                    if (rspBase.error_response != null)
                    {
                        rspBase.IsError = true;
                    }
 
 
 
 
                    #region 返回值处理
                    if (rspBase.IsError)
                    {
                        t = (T) rspBase;
                    }
                    else
                    {
                        #region Response对象处理
                        try
                        {
                            reStr = request.ResponseJsonPrefix(reStr);
                            t = JsonConvert.Import(typeof(T), reStr) as T;
                        }
                        catch(Exception ex)
                        {
                            string exStr = ex.ToString();
                        }
                        #endregion
                    }
                    #endregion
 
                }
                else
                {
                    rspBase = new YouZanResponse
                    {
                        IsError = true,
                        error_response = {msg = "接口调用异常"}
                    };
                    t = (T)rspBase;
                }
            }
            catch (Exception ex)
            {
                rspBase = new YouZanResponse
                {
                    IsError = true,
                    error_response = { msg = "接口调用异常" }
                };
                t = (T) rspBase;
            }
            return t;
            */
            #endregion
        }
 
 
 
 
 
        /// <summary>
        /// post调用求情
        /// </summary>
        /// <param name="postUrl">请求地址</param>
        /// <param name="pars">请求参数</param>
        /// <param name="isLogin"></param>
        /// <returns></returns>
        private static string postMethod(string postUrl, string pars, bool isLogin = false)
        {
            byte[] postData = System.Text.Encoding.UTF8.GetBytes(pars);
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(postUrl);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "post";
            request.Timeout = 5000;
            request.ContentLength = postData.Length;
 
            System.IO.Stream requestStream = request.GetRequestStream();
            requestStream.Write(postData, 0, postData.Length);
            requestStream.Close();
 
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
 
            var ecoding = isLogin ? Encoding.Default : Encoding.UTF8;
 
            System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), ecoding);
 
            string str = sr.ReadToEnd();//读取获取到的参数
            sr.Close();
            response.Close();
            return str;
 
        }
 
        /// <summary>
        /// PostJson请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postObj"></param>
        /// <returns></returns>
        public static string PostJson(string url, object postObj)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            var postData = Jayrock.Json.Conversion.JsonConvert.ExportToString(postObj);
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(postData);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                return result;
            }
        }
 
        public static string PostJsonSpecial(string url, string postData)
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
 
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(postData);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = streamReader.ReadToEnd();
                return result;
            }
        }
 
    }
}