コード例 #1
0
        public async Task <T> SendAsync <T>(string url, object data, int timeOut = Senparc.Weixin.Config.TIME_OUT, ApiRequestMethod requestMethod = ApiRequestMethod.POST, bool checkSign = true, Func <T> createDefaultInstance = null)
            where T : ReturnJsonBase       /*, new()*/
        {
            T          result = null;
            HttpMethod method = GetHttpMethod(requestMethod);

            try
            {
                var request = new HttpRequestMessage(method, url);

                //设置超时时间
                _client.Timeout = TimeSpan.FromMilliseconds(timeOut);

                //设置请求 Json 字符串
                string jsonString = data != null
                    ? data.ToJson(false, new Newtonsoft.Json.JsonSerializerSettings()
                {
                    NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
                })
                    : "";

                WeixinTrace.SendApiPostDataLog(url, jsonString); //记录Post的Json数据
                request.Content = new StringContent(jsonString, Encoding.UTF8, mediaType: "application/json");

                // 进行签名
                var authorization = await GenerateAuthorizationHeader(request);

                request.Headers.Add("Authorization", $"WECHATPAY2-{_signer.GetAlgorithm()} {authorization}");

                // 发送请求
                var responseMessage = await _client.SendAsync(request);

                //获取响应结果
                string content = await responseMessage.Content.ReadAsStringAsync();//TODO:如果不正确也要返回详情

#if DEBUG
                Console.WriteLine("Content:" + content + ",,Headers:" + responseMessage.Headers.ToString());
#endif

                //检查响应代码
                TenPayApiResultCode resutlCode = TenPayApiResultCode.TryGetCode(responseMessage.StatusCode, content);

                if (resutlCode.Success)
                {
                    result = content.GetObject <T>();

                    if (checkSign)
                    {
                        result.VerifySignSuccess = await VerifyResponseMessage(responseMessage, content);
                    }
                }
                else
                {
                    result = createDefaultInstance?.Invoke() ?? GetInstance <T>(true);
                    resutlCode.Additional = content;
                }
                result.ResultCode = resutlCode;

                return(result);
            }
            catch (Exception ex)
            {
                SenparcTrace.BaseExceptionLog(ex);
                result = createDefaultInstance?.Invoke() ?? GetInstance <T>(false);
                if (result != null)
                {
                    result.ResultCode = new() { ErrorMessage = ex.Message };
                }

                return(result);
            }
        }