/// <summary> /// 向需要AccessToken的API发送消息的公共方法 /// </summary> /// <param name="accessToken">这里的AccessToken是通用接口的AccessToken,非OAuth的。如果不需要,可以为null,此时urlFormat不要提供{0}参数</param> /// <param name="urlFormat">用accessToken参数填充{0}</param> /// <param name="data">如果是Get方式,可以为null</param> /// <param name="sendType"></param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <param name="checkValidationResult">验证服务器证书回调自动验证</param> /// <param name="jsonSetting"></param> /// <returns></returns> public static T Send <T>(string accessToken, string urlFormat, object data, CommonJsonSendType sendType = CommonJsonSendType.POST, int timeOut = CO2NET.Config.TIME_OUT, bool checkValidationResult = false, JsonSetting jsonSetting = null) { //TODO:此方法可以设定一个日志记录开关 try { var url = string.IsNullOrEmpty(accessToken) ? urlFormat : string.Format(urlFormat, accessToken.AsUrlData()); switch (sendType) { case CommonJsonSendType.GET: return(Get.GetJson <T>(url, afterReturnText: getFailAction)); case CommonJsonSendType.POST: var jsonString = SerializerHelper.GetJsonString(data, jsonSetting); using (MemoryStream ms = new MemoryStream()) { var bytes = Encoding.UTF8.GetBytes(jsonString); ms.Write(bytes, 0, bytes.Length); ms.Seek(0, SeekOrigin.Begin); WeixinTrace.SendApiPostDataLog(url, jsonString); //记录Post的Json数据 //PostGetJson方法中将使用WeixinTrace记录结果 return(Post.PostGetJson <T>(url, null, ms, timeOut: timeOut, afterReturnText: postFailAction, checkValidationResult: checkValidationResult)); } //TODO:对于特定的错误类型自动进行一次重试,如40001(目前的问题是同样40001会出现在不同的情况下面) default: throw new ArgumentOutOfRangeException("sendType"); } } catch (ErrorJsonResultException ex) { ex.Url = urlFormat; throw; } }
public static JsApiReturnJson JsApi(IServiceProvider serviceProvider, JsApiRequestData data, int timeOut = Config.TIME_OUT) { var url = ReurnPayApiUrl("https://api.mch.weixin.qq.com/{0}v3/pay/transactions/jsapi"); var jsonString = SerializerHelper.GetJsonString(data, null); using (MemoryStream ms = new MemoryStream()) { var bytes = Encoding.UTF8.GetBytes(jsonString); ms.Write(bytes, 0, bytes.Length); ms.Seek(0, SeekOrigin.Begin); WeixinTrace.SendApiPostDataLog(url, jsonString);//记录Post的Json数据 //PostGetJson方法中将使用WeixinTrace记录结果 return(Post.PostGetJson <JsApiReturnJson>(serviceProvider, url, null, ms, timeOut: timeOut, afterReturnText: null, checkValidationResult: false)); } }
/// <summary> /// 向需要AccessToken的API发送消息的公共方法 /// </summary> /// <param name="accessToken">这里的AccessToken是通用接口的AccessToken,非OAuth的。如果不需要,可以为null,此时urlFormat不要提供{0}参数</param> /// <param name="urlFormat"></param> /// <param name="data">如果是Get方式,可以为null。在POST方式中将被转为JSON字符串提交</param> /// <param name="sendType">发送类型,POST或GET,默认为POST</param> /// <param name="timeOut">代理请求超时时间(毫秒)</param> /// <param name="checkValidationResult">验证服务器证书回调自动验证</param> /// <param name="jsonSetting">JSON字符串生成设置</param> /// <returns></returns> public static async Task <T> SendAsync <T>(string accessToken, string urlFormat, object data, CommonJsonSendType sendType = CommonJsonSendType.POST, int timeOut = CO2NET.Config.TIME_OUT, bool checkValidationResult = false, JsonSetting jsonSetting = null) { try { var url = string.IsNullOrEmpty(accessToken) ? urlFormat : string.Format(urlFormat, accessToken.AsUrlData()); switch (sendType) { case CommonJsonSendType.GET: return(await Get.GetJsonAsync <T>(CommonDI.CommonSP, url, afterReturnText : getFailAction).ConfigureAwait(false)); case CommonJsonSendType.POST: var jsonString = SerializerHelper.GetJsonString(data, jsonSetting); using (MemoryStream ms = new MemoryStream()) { var bytes = Encoding.UTF8.GetBytes(jsonString); await ms.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); ms.Seek(0, SeekOrigin.Begin); WeixinTrace.SendApiPostDataLog(url, jsonString); //记录Post的Json数据 //PostGetJson方法中将使用WeixinTrace记录结果 return(await Post.PostGetJsonAsync <T>(CommonDI.CommonSP, url, null, ms, timeOut : timeOut, afterReturnText : postFailAction, checkValidationResult : checkValidationResult).ConfigureAwait(false)); } default: throw new ArgumentOutOfRangeException("sendType"); } } catch (ErrorJsonResultException ex) { ex.Url = urlFormat; throw; } }
/// <summary> /// 获取 HttpResponseMessage 对象 /// </summary> /// <param name="url"></param> /// <param name="data">如果为 GET 请求,此参数可为 null</param> /// <param name="timeOut"></param> /// <param name="requestMethod"></param> /// <param name="checkDataNotNull">非 GET 请求情况下,是否强制检查 data 参数不能为 null,默认为 true</param> /// <returns></returns> public async Task <HttpResponseMessage> GetHttpResponseMessageAsync(string url, object data, int timeOut = Config.TIME_OUT, ApiRequestMethod requestMethod = ApiRequestMethod.POST, bool checkDataNotNull = true) { try { //var co2netHttpClient = CO2NET.HttpUtility.RequestUtility.HttpPost_Common_NetCore(serviceProvider, url, out var hc, contentType: "application/json"); ////设置参数 //var mchid = _tenpayV3Setting.TenPayV3_MchId; //var ser_no = _tenpayV3Setting.TenPayV3_SerialNumber; //var privateKey = _tenpayV3Setting.TenPayV3_PrivateKey; ////使用微信支付参数,配置 HttpHandler //TenPayHttpHandler httpHandler = new(mchid, ser_no, privateKey); //TODO:此处重构使用ISenparcWeixinSettingForTenpayV3 TenPayHttpHandler httpHandler = new(_tenpayV3Setting); //创建 HttpClient HttpClient client = new HttpClient(httpHandler); //设置超时时间 client.Timeout = TimeSpan.FromMilliseconds(timeOut); //设置 HTTP 请求头 SetHeader(client); HttpResponseMessage responseMessage = null; switch (requestMethod) { case ApiRequestMethod.GET: responseMessage = await client.GetAsync(url); WeixinTrace.Log(url); //记录Get的Json数据 break; case ApiRequestMethod.POST: case ApiRequestMethod.PUT: case ApiRequestMethod.PATCH: //检查是否为空 if (checkDataNotNull) { _ = data ?? throw new ArgumentNullException($"{nameof(data)} 不能为 null!"); } //设置请求 Json 字符串 //var jsonString = SerializerHelper.GetJsonString(data, new CO2NET.Helpers.Serializers.JsonSetting(true)); string jsonString = data != null ? data.ToJson(false, new Newtonsoft.Json.JsonSerializerSettings() { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }) : ""; WeixinTrace.SendApiPostDataLog(url, jsonString); //记录Post的Json数据 //设置 HttpContent var hc = new StringContent(jsonString, Encoding.UTF8, mediaType: "application/json"); //获取响应结果 responseMessage = requestMethod switch { ApiRequestMethod.POST => await client.PostAsync(url, hc), ApiRequestMethod.PUT => await client.PutAsync(url, hc), ApiRequestMethod.PATCH => await client.PatchAsync(url, hc), _ => throw new ArgumentOutOfRangeException(nameof(requestMethod)) }; break; default: throw new ArgumentOutOfRangeException(nameof(requestMethod)); } return(responseMessage); } catch (Exception) { throw; } }
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); } }