docs: 提供微信公众平台模块的示例项目

This commit is contained in:
Fu Diwei
2021-07-27 18:37:11 +08:00
parent 0fd94ea541
commit b62867de8d
18 changed files with 616 additions and 7 deletions

View File

@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SKIT.FlurlHttpClient.Wechat.Api.Sample_Net5.Services.HttpClients
{
public interface IWechatApiHttpClientFactory
{
WechatApiClient Create(string appId);
}
}

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Flurl;
using Flurl.Http;
using Flurl.Http.Configuration;
using Microsoft.Extensions.Options;
namespace SKIT.FlurlHttpClient.Wechat.Api.Sample_Net5.Services.HttpClients.Implements
{
partial class WechatApiHttpClientFactory : IWechatApiHttpClientFactory
{
private readonly System.Net.Http.IHttpClientFactory _httpClientFactory;
private readonly Options.WechatOptions _wechatOptions;
public WechatApiHttpClientFactory(
System.Net.Http.IHttpClientFactory httpClientFactory,
IOptions<Options.WechatOptions> wechatOptions)
{
_httpClientFactory = httpClientFactory;
_wechatOptions = wechatOptions.Value;
}
public WechatApiClient Create(string appId)
{
var wechatAccount = _wechatOptions.Accounts?.FirstOrDefault(e => string.Equals(appId, e.AppId));
if (wechatAccount == null)
throw new Exception("未在配置项中找到该 AppId 对应的微信账号。");
FlurlHttp.GlobalSettings.FlurlClientFactory = new DelegatingFlurlClientFactory(_httpClientFactory);
return new WechatApiClient(new WechatApiClientOptions()
{
AppId = wechatAccount.AppId,
AppSecret = wechatAccount.AppSecret
});
}
}
partial class WechatApiHttpClientFactory
{
internal class DelegatingFlurlClientFactory : IFlurlClientFactory
{
private readonly System.Net.Http.IHttpClientFactory _httpClientFactory;
public DelegatingFlurlClientFactory(System.Net.Http.IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
}
public IFlurlClient Get(Url url)
{
return new FlurlClient(_httpClientFactory.CreateClient(url.ToUri().Host));
}
public void Dispose()
{
// Do Nothing
}
}
}
}