You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
3.3 KiB

using Flurl;
using Flurl.Http;
using Flurl.Http.Configuration;
using Microsoft.Extensions.Options;
using SKIT.FlurlHttpClient;
using SKIT.FlurlHttpClient.Wechat.Api;
using Zncy.CloudCar.WeChat.Service.Options;
using IHttpClientFactory = System.Net.Http.IHttpClientFactory;
namespace Zncy.CloudCar.WeChat.Service.Services.HttpClients
{
public partial class WeChatApiHttpClientFactory : IWeChatApiHttpClientFactory
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly WeChatOptions _weChatOptions;
public WeChatApiHttpClientFactory(
IHttpClientFactory httpClientFactory,
IOptions<WeChatOptions> weChatOptions
)
{
_httpClientFactory = httpClientFactory;
_weChatOptions = weChatOptions.Value;
FlurlHttp.GlobalSettings.FlurlClientFactory = new DelegatingFlurlClientFactory(_httpClientFactory);
}
/// <summary>
/// 微信公众号请求
/// </summary>
/// <returns></returns>
public WechatApiClient CreateWeXinClient()
{
if (string.IsNullOrEmpty(_weChatOptions.WeiXinAppId) || string.IsNullOrEmpty(_weChatOptions.WeiXinAppSecret))
{
throw new Exception("未在配置项中找到微信公众号配置讯息。");
}
var wechatApiClient = new WechatApiClient(new WechatApiClientOptions()
{
AppId = _weChatOptions.WeiXinAppId,
AppSecret = _weChatOptions.WeiXinAppSecret
});
wechatApiClient.Configure(settings =>
{
settings.JsonSerializer = new FlurlNewtonsoftJsonSerializer();
});
return wechatApiClient;
}
/// <summary>
/// 微信小程序请求
/// </summary>
/// <returns></returns>
public WechatApiClient CreateWxOpenClient()
{
if (string.IsNullOrEmpty(_weChatOptions.WxOpenAppId) || string.IsNullOrEmpty(_weChatOptions.WxOpenAppSecret))
{
throw new Exception("未在配置项中找到微信小程序配置讯息。");
}
var wechatApiClient = new WechatApiClient(new WechatApiClientOptions()
{
AppId = _weChatOptions.WxOpenAppId,
AppSecret = _weChatOptions.WxOpenAppSecret
});
wechatApiClient.Configure(settings =>
{
settings.JsonSerializer = new FlurlNewtonsoftJsonSerializer();
});
return wechatApiClient;
}
}
public partial class WeChatApiHttpClientFactory
{
internal class DelegatingFlurlClientFactory : IFlurlClientFactory
{
private readonly IHttpClientFactory _httpClientFactory;
public DelegatingFlurlClientFactory(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
}
public void Dispose()
{
// Do Nothing
}
public IFlurlClient Get(Url url)
{
return new FlurlClient(_httpClientFactory.CreateClient(url.ToUri().Host));
}
}
}
}