using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Flurl.Http;
using Flurl.Http.Configuration;
namespace SKIT.FlurlHttpClient.Wechat.Api
{
///
/// 一个微信 API HTTP 客户端。
///
public class WechatApiClient : WechatClientBase
{
///
/// 获取当前客户端使用的微信 AppId。
///
public string WechatAppId { get; }
///
/// 获取当前客户端使用的微信 AppSecret。
///
internal string WechatAppSecret { get; }
///
/// 获取当前客户端使用的即时配送公司帐号 AppKey(用于即使配送相关接口的请求签名)。
///
internal string? WechatImmeDeliveryAppKey { get; }
///
/// 获取当前客户端使用的即时配送公司帐号 AppSecret(用于即使配送相关接口的请求签名)。
///
internal string? WechatImmeDeliveryAppSecret { get; }
///
/// 获取或设置米大师平台 AppKey(用于虚拟支付相关接口的请求签名)。
///
internal string? WechatMidasAppKey { get; }
///
/// 获取当前客户端使用的 JSON 序列化器。
///
internal ISerializer FlurlJsonSerializer
{
get { return FlurlClient.Settings?.JsonSerializer ?? new FlurlNewtonsoftJsonSerializer(); }
}
///
/// 用指定的配置项初始化 类的新实例。
///
/// 配置项。
public WechatApiClient(WechatApiClientOptions options)
: base()
{
if (options == null) throw new ArgumentNullException(nameof(options));
WechatAppId = options.AppId;
WechatAppSecret = options.AppSecret;
WechatImmeDeliveryAppKey = options.ImmeDeliveryAppKey;
WechatImmeDeliveryAppSecret = options.ImmeDeliveryAppSecret;
WechatMidasAppKey = options.MidasAppKey;
FlurlClient.BaseUrl = options.Endpoints ?? WechatApiEndpoints.DEFAULT;
FlurlClient.WithTimeout(TimeSpan.FromMilliseconds(options.Timeout));
}
///
/// 用指定的微信 AppId 和微信 AppSecret 初始化 类的新实例。
///
/// 微信 AppId。
/// 微信 AppSecret。
public WechatApiClient(string appId, string appSecret)
: this(new WechatApiClientOptions() { AppId = appId, AppSecret = appSecret })
{
}
///
/// 异步发起请求。
///
///
///
///
///
///
public async Task SendRequestAsync(IFlurlRequest flurlRequest, HttpContent? content = null, CancellationToken cancellationToken = default)
where T : WechatApiResponse, new()
{
try
{
using IFlurlResponse flurlResponse = await base.SendRequestAsync(flurlRequest, content, cancellationToken).ConfigureAwait(false);
return await GetResposneAsync(flurlResponse).ConfigureAwait(false);
}
catch (FlurlHttpException ex)
{
throw new WechatApiException(ex.Message, ex);
}
}
///
/// 异步发起请求。
///
///
///
///
///
///
public async Task SendRequestWithJsonAsync(IFlurlRequest flurlRequest, object? data = null, CancellationToken cancellationToken = default)
where T : WechatApiResponse, new()
{
try
{
using IFlurlResponse flurlResponse = await base.SendRequestWithJsonAsync(flurlRequest, data, cancellationToken).ConfigureAwait(false);
return await GetResposneAsync(flurlResponse).ConfigureAwait(false);
}
catch (FlurlHttpException ex)
{
throw new WechatApiException(ex.Message, ex);
}
}
private async Task GetResposneAsync(IFlurlResponse flurlResponse)
where T : WechatApiResponse, new()
{
string contentType = flurlResponse.Headers.GetAll("Content-Type").FirstOrDefault() ?? string.Empty;
bool contentTypeIsNotJson =
(flurlResponse.StatusCode != (int)HttpStatusCode.OK) ||
(!contentType.StartsWith("application/json") && !contentType.StartsWith("text/json") && !contentType.StartsWith("text/plain"));
T result = contentTypeIsNotJson ? new T() : await flurlResponse.GetJsonAsync().ConfigureAwait(false);
result.RawStatus = flurlResponse.StatusCode;
result.RawHeaders = new ReadOnlyDictionary(
flurlResponse.Headers
.GroupBy(e => e.Name)
.ToDictionary(
k => k.Key,
v => string.Join(", ", v.Select(e => e.Value))
)
);
result.RawBytes = await flurlResponse.ResponseMessage.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
return result;
}
}
}