Sparkdo.Weixin.Service
3.0.0-preview.1
dotnet add package Sparkdo.Weixin.Service --version 3.0.0-preview.1
NuGet\Install-Package Sparkdo.Weixin.Service -Version 3.0.0-preview.1
<PackageReference Include="Sparkdo.Weixin.Service" Version="3.0.0-preview.1" />
<PackageVersion Include="Sparkdo.Weixin.Service" Version="3.0.0-preview.1" />
<PackageReference Include="Sparkdo.Weixin.Service" />
paket add Sparkdo.Weixin.Service --version 3.0.0-preview.1
#r "nuget: Sparkdo.Weixin.Service, 3.0.0-preview.1"
#:package Sparkdo.Weixin.Service@3.0.0-preview.1
#addin nuget:?package=Sparkdo.Weixin.Service&version=3.0.0-preview.1&prerelease
#tool nuget:?package=Sparkdo.Weixin.Service&version=3.0.0-preview.1&prerelease
Sparkdo.Weixin.Service
微信服务号产品域包:服务号配置(WeixinServiceOptions)+ 模板消息发送(Message.SendTemplateMessageRequest)+ 两个把 Options 钉成服务号的请求基类。
它与 Sparkdo.Weixin 共用同一套凭据 SPI、命名 HttpClient 与池化 UTF-8 管线;本包只把"身份类型"换掉,把"服务号才有"的一小段协议补上。
三条硬承诺:
- 模板消息的 wire 契约逐字固定:
POST /cgi-bin/message/template/send?access_token=…,请求体六段(touser/template_id/url/miniprogram/data/client_msg_id)由源生成 resolver 产出,测试按整串 URL 与逐字段断言。 msgid两种形态都吃:微信不同网关/版本把它写成 JSON 数字或字符串,包内转换器统一读成string,两种都有用例。- 零反射、AOT 就绪、可编译期扩展:路由与 JSON 契约都在本包编译内闭合;新增服务号接口就照本包的写法派生。
目录
- 为什么这个包这么小
- 快速开始
- 接线:本包没有 Add 方法
- WeixinServiceOptions
- 两个基类怎么选
- 模板消息逐项
- 端点表
- 新增一个服务号端点
- 典型用法配方
- 失败语义与错误信息
- JSON 契约与 AOT
- 常见坑
- 非目标
- 工程与验证
为什么这个包这么小
服务号的开放接口面很大(客服消息、群发、素材、标签、菜单、用户管理),本包只交付模板消息一条 + 可扩展的基类,其余刻意留白(port-analysis §4.3:移植保持源库覆盖面)。所以对本包的正确期待是:
- 要发模板消息 → 直接用。
- 要发别的 → 照新增一个服务号端点派生,基类与 JSON context 都给你留好了位置。
- 要"整套服务号 SDK" → 本包不是;先读核心包与订阅号包的覆盖面表,判断自己维护端点的成本。
快速开始
using Microsoft.Extensions.DependencyInjection;
using Sparkdo.Json;
using Sparkdo.Mediation;
using Sparkdo.Mediation.DependencyInjection;
using Sparkdo.Weixin.DependencyInjection;
using Sparkdo.Weixin.Service;
using Sparkdo.Weixin.Service.Requests;
var services = new ServiceCollection();
services.AddLogging();
services.AddSparkdoMediation();
services.AddSparkdoJson();
services.AddSparkdoWeixin(); // Access Token 存储 + 命名 HttpClient
services.Configure<WeixinServiceOptions>(o =>
{
o.AppId = configuration["Weixin:Service:AppId"]!;
o.Secret = configuration["Weixin:Service:Secret"]!;
});
await using var provider = services.BuildServiceProvider();
using var scope = provider.CreateScope();
var sender = scope.ServiceProvider.GetRequiredService<ISender>();
var model = new Message.SendTemplateMessageModel
{
ToUser = "OPENID",
TemplateId = "TEMPLATE_ID",
Url = "https://example.com/order/1",
MiniProgram = new Message.MiniProgram
{
AppId = "wxMINIAPPID",
PagePath = "pages/order/index?order=1",
},
Data = new Dictionary<string, Dictionary<string, string>>
{
["first"] = new() { ["value"] = "您好,订单已发货" },
["keyword1"] = new() { ["value"] = "ORDER-0001", ["color"] = "#FF0000" },
["remark"] = new() { ["value"] = "点击详情查看物流" },
},
ClientMsgId = "ORDER-0001-shipped", // 十分钟内防重复发送
};
var response = await sender.SendAsync(Message.ToSendTemplateMessage(model));
if (!response.Succeed())
{
// response.ErrCode / response.ErrMsg;40164 = IP 白名单,43101/45009 等见核心包错误码表
throw WeixinException.FromResponse("发送模板消息", response);
}
Console.WriteLine(response.MsgId); // "1234567890"(数字形态也被读成字符串)
成功时响应是 {"errcode":0,"errmsg":"ok","msgid":…},注意本包的 SendTemplateMessageResponse 没有覆写 ErrCode 缺省值——缺省仍是基类的 -1,也就是"响应没带 errcode 就判失败"(fail-closed)。真实微信一定带,代理/桩把它抹掉时会判失败,这是预期。
接线:本包没有 Add 方法
刻意如此(子包不提供 Add*)。本包需要的全部基础设施都来自 AddSparkdoWeixin():
| 需要的 | 从哪来 |
|---|---|
IAccessTokenStore(模板消息的 access_token) |
AddSparkdoWeixin() |
命名 HttpClient "Sparkdo.Weixin" |
AddSparkdoWeixin()(不是支付那个名字) |
IOptions<WeixinServiceOptions> |
宿主自己 services.Configure<WeixinServiceOptions>(…) |
| 派发与序列化 | AddSparkdoMediation() + AddSparkdoJson() |
服务号与公众号的 Options 是两份独立配置(WeixinServiceOptions 只是 WeixinOptions 的空派生类,换一个 DI 身份):
services.AddSparkdoWeixin(o => { o.AppId = officialAppId; o.Secret = officialSecret; }); // 核心包那一套
services.Configure<WeixinServiceOptions>(o => { o.AppId = serviceAppId; o.Secret = serviceSecret; });
但凭据缓存按 AppId 分键(键形如 Weixin:AppId-{AppId}:AccessToken,不含包名):两份 Options 若填同一个 AppId 会共用同一个 token——那是微信侧的事实(token 按 AppId 发),不是串台。
WeixinServiceOptions
public class WeixinServiceOptions : WeixinOptions { }——零新增成员。可用能力全在基类:
| 成员 | 缺省 | 说明 |
|---|---|---|
AppId |
string.Empty |
必填;缺失时 WeixinException("WeixinServiceOptions.AppId 未配置。")(消息里是实际类型名) |
Secret |
string.Empty |
模板消息不需要它(token 由存储负责),但存储刷新 token 时要——所以事实上的必填点在凭据侧 |
BaseAddress |
null → https://api.weixin.qq.com |
测试替身/反向代理入口;必须绝对 http/https,路径部分会被丢弃 |
UseStableAccessToken |
true |
只影响默认凭据存储刷新走哪条 token 端点 |
EnsureValid() / RequireSecret() / ResolveBaseAddress() |
— | 发送前由请求基类调 EnsureValid() |
两个基类怎么选
| 你要的 | 派生 | 说明 |
|---|---|---|
只有查询串、无请求体(GET 或空体 POST) |
ServiceRequest<TResponse> |
构造重载:(options) 与 ()(DI 解析) |
| 带 JSON 请求体 | ServiceRequest<TModel, TResponse> |
构造重载:(model) / (model, options);序列化、ResolveModel 钩子都继承核心包 |
| 响应就用通用错误码 | TResponse = WeixinResponse |
WeixinResponse 已由核心包登记进 JSON context,不必再声明 |
两者的唯一作用是把 TOptions 钉成 WeixinServiceOptions,因此请求管线(Method / Path / RequiresAccessToken / BuildRequestUriAsync / BuildContentAsync / OnRequestMessage / Response)与核心包完全一致——细节见核心包自述的一次发送。
命名注记:源库把这两个基类叫 HttpRequest<TResponse>,与 Sparkdo.Mediation.Http.HttpRequest<> 冲突(派生类里必须 global:: 限定才写得出来),移植后更名为 ServiceRequest<>;响应基类同理从 HttpResponse 更名为 WeixinResponse。
模板消息逐项
Message.SendTemplateMessageModel(可变 POCO,属性逐字对应 wire 键):
| 属性 | JSON 键 | 类型/缺省 | 事实 |
|---|---|---|---|
ToUser |
touser |
string(默认 default!,实际须自己填) |
接收者 OpenID |
TemplateId |
template_id |
string |
模板 ID |
Url |
url |
string? |
点击跳转链接;与 MiniProgram 可同时给(小程序优先) |
MiniProgram |
miniprogram |
Message.MiniProgram? |
两个字段 appid / pagepath(都可空) |
Data |
data |
Dictionary<string, Dictionary<string, string>>(默认 []) |
外层键 = 模板字段名,内层键 = value / color |
ClientMsgId |
client_msg_id |
string? |
十分钟内防重复发送的客户端消息 ID |
[Required] 标注只是文档(port-analysis §3.4:DataAnnotations 不在运行时校验)。库里唯一真正的 fail-fast 是"模型或 Options 传 null 抛 ArgumentNullException"(基类)。填漏字段不会被客户端拦住,会原样发给微信由其报错。
响应 Message.SendTemplateMessageResponse:
| 属性 | JSON 键 | 说明 |
|---|---|---|
MsgId |
msgid |
string;数字形态(1234567890)与字符串形态("abc")都读成字符串;响应未携带该字段时保持初值 string.Empty |
ErrCode / ErrMsg |
errcode / errmsg |
来自基类,ErrCode 缺省 -1(缺字段即判失败) |
data 的 color 是可选的样式键——它和 value 都塞在同一个 Dictionary<string,string> 里,所以写 ["color"] = "#FF0000" 是合法用法(上面例子里的 keyword1 就带了颜色)。
端点表
| 请求 / 工厂 | 方法 + 路径 | 凭据 | 请求体 | 响应 |
|---|---|---|---|---|
Message.SendTemplateMessageRequest<br>Message.ToSendTemplateMessage(model)<br>Message.ToSendTemplateMessage(options, model) |
POST /cgi-bin/message/template/send?access_token=… |
Access Token(查询串,由核心包存储提供) | 上表六段 | SendTemplateMessageResponse(errcode/errmsg/msgid) |
实测的 wire 形状(ServicePackageTests 逐条断言):Method == POST、AbsolutePath == "/cgi-bin/message/template/send"、Query == "?access_token={token}"、Content-Type 含 application/json,请求体逐字段(含 miniprogram.appid/pagepath 与 data.first.value 的嵌套形状)。
新增一个服务号端点
在
Requests/下建Xxx.YyyRequest.cs,public static partial class Xxx内定义请求 + 模型 + 响应。派生
ServiceRequest<TResponse>或ServiceRequest<TModel, TResponse>;覆写Path与必要的Method/RequiresAccessToken。查询参数在BuildQueryAsync里数据化声明,基类自动拼进 URI(access token 自动置首、值自动转义)——不要重抄Path字面量,也不要覆写BuildRequestUriAsync(只有绝对地址等特殊 URI 才需要):protected override ValueTask<(string Name, string? Value)[]> BuildQueryAsync( WeixinServiceOptions options, CancellationToken cancellationToken) => ValueTask.FromResult(new (string Name, string? Value)[] { ("lang", "zh_CN"), });无查询参数的端点连
BuildQueryAsync都不用覆写。把新的模型/响应类型登记进
SparkdoWeixinServiceJsonContext的[JsonSerializable]块(它是sealed,只能改这个文件不能派生)。补两个
ToYyy工厂重载(省略 Options / 显式 Options)。加一条 wire 用例(方法、完整
PathAndQuery、Content-Type、请求体逐字段),并更新ApiBaselines/Sparkdo.Weixin.Service.approved.txt。
响应类型如果是通用错误码,直接用 WeixinResponse(已登记,不要再往服务号 context 里登记一次——同 name 内的重复声明会被生成器拦下)。
典型用法配方
1. 复用请求实例(显式 Options)
var options = new WeixinServiceOptions { AppId = serviceAppId, Secret = serviceSecret };
var request = Message.ToSendTemplateMessage(options, model);
await sender.SendAsync(request); // 身份构造期冻结,可安全复用、跨线程共享
await sender.SendAsync(request);
省略 Options 的那条工厂恒用容器里那一套服务号凭据;多服务号场景请显式传(同核心包配方 9)。
2. 幂等:用 client_msg_id 挡住十分钟内的重复投递
model.ClientMsgId = $"{orderId}-{eventType}"; // 同一事件重投时 ID 相同
await sender.SendAsync(Message.ToSendTemplateMessage(model), ct);
client_msg_id 只在十分钟内去重,且只对相同 OpenID + 相同模板生效(微信侧规则)。它是"防手滑重发"的兜底,不是业务幂等键。
3. 模板消息 + 小程序跳转
MiniProgram = new Message.MiniProgram
{
AppId = "wxMINIAPPID",
PagePath = $"pages/order/index?orderId={orderId}",
},
服务号模板消息跳小程序要求两账号已关联;未关联时微信报错,本包原样透传 errcode/errmsg。
4. 批量发送:自己控并发
await Parallel.ForEachAsync(openIds, new ParallelOptions { MaxDegreeOfParallelism = 8 },
async (openId, ct) =>
{
// 每个请求一份模型:模型是可变 POCO,不要在并发里共享并改写同一个实例
var perUser = new Message.SendTemplateMessageModel
{
ToUser = openId,
TemplateId = templateId,
Data = Data(),
ClientMsgId = $"{orderId}-{openId}",
};
await sender.SendAsync(Message.ToSendTemplateMessage(perUser), ct);
});
库里没有限流、没有退避、没有失败重试(非目标)。模板消息接口有频控,把并发打高只会换来 45009。模型是可变 POCO,一个请求配一个模型实例,不要在并发里共享并改写同一个模型。
5. 离网测试
照抄测试工程里的三个替身(StubHttpMessageHandler / StubHttpClientFactory / HttpResponses,都不随包发布),或者更省事:services.AddSingleton<IHttpClientFactory>(…) 返回带桩 handler 的 client,让 /cgi-bin/stable_token 与 /cgi-bin/message/template/send 分别响应。
6. 把模板消息接到支付回调
支付通知的处理在 Payment 包;两条链路是两个独立命名 client、两套独立 Options(WeixinServiceOptions vs WeixinPaymentOptions),在一个订阅者里串起来即可:
public sealed class NotifyBuyer(ISender sender, IOptions<WeixinServiceOptions> serviceOptions)
: INotificationHandler<Payment.Notifies.TransactionsNotifyResponse>
{
public async ValueTask HandleAsync(Payment.Notifies.TransactionsNotifyResponse n, CancellationToken ct)
{
await sender.SendAsync(Message.ToSendTemplateMessage(serviceOptions.Value, new Message.SendTemplateMessageModel
{
ToUser = n.Payer.OpenId,
TemplateId = paidTemplateId,
Data = new Dictionary<string, Dictionary<string, string>>
{
["first"] = new() { ["value"] = $"已支付 {n.Amount.Total / 100m:0.##} 元" },
},
ClientMsgId = $"paid-{n.OutTradeNo}",
}), ct);
}
}
失败语义与错误信息
| 层 | 判据 | 表现 |
|---|---|---|
| HTTP 层 | 非 2xx 且正文 errcode == 0 |
MarkHttpFailure 把 ErrCode 改写为状态码,ErrMsg ??= "HTTP request failed with status code {code}." |
| 业务层 | errcode != 0 |
Succeed() == false;EnsureSucceed("发送模板消息") 抛 WeixinException,消息 {操作}失败:errcode={c}, errmsg={m}。 |
| 形状层 | 正文缺 errcode |
ErrCode == -1 → 判失败(fail-closed) |
| 凭据层 | token 刷新失败 | 获取微信 AccessToken失败:errcode=…, errmsg=…。(核心包存储抛) |
| 配置层 | Options 未配 | WeixinServiceOptions.AppId 未配置。 |
| 空正文 + 2xx | — | new SendTemplateMessageResponse() → ErrCode == -1(本包类型没覆写)→ 判失败。这条与核心包的 AccessToken.Response 相反,别类推 |
WeixinException.ErrCode/.ErrMsg 是结构化字段,别从消息里正则取。
JSON 契约与 AOT
| 机制 | 本包 |
|---|---|
| Context | [SparkdoJsonContext("Sparkdo.Weixin.Service")],登记 3 个类型(SendTemplateMessageModel、SendTemplateMessageResponse、MiniProgram),sealed partial |
| 命名隔离 | 独立 name 避免与其它微信包在同一 CLR 类型上跨 name 歧义(JsonSerializerTypeAmbiguousException) |
| 键名 | 100% 由 [JsonPropertyName] 逐字钉住;无命名策略 |
| 转换器 | StringOrInt64JsonConverter(internal,不对外提供,只服务 msgid 的双形态) |
| 路由 | 1 条 HTTP 回退在本包编译内闭合 |
| AOT | IsAotCompatible + IsTrimmable + 三套分析器常开,Release 零警告 |
常见坑
ErrCode缺省是 -1(本包响应类型没覆写):桩/代理省略errcode时判失败。真实微信返回errcode:0。MsgId是string:1234567890这种数字形态已被读成"1234567890",别long.Parse再比。字段缺失时是string.Empty(不是 null)。Data是两层字典:外层键必须是模板里声明的字段名,内层键是value(必填)与color(可选)。写成["first"] = "文本"编译不过就是提示你这个形状。[Required]不校验:ToUser/TemplateId/Data/ClientMsgId漏填不会被客户端拦,会原样发给微信。ClientMsgId声明为string?但带[Required]:不设就发"client_msg_id":null。请显式给值。- 本包没有 DI 扩展:漏
AddSparkdoWeixin()的表现是第一次发送时IOptions<WeixinServiceOptions>或ISender解析失败;漏Configure<WeixinServiceOptions>是WeixinServiceOptions.AppId 未配置。 AddSparkdoWeixin(o => …)配的是核心 Options,不影响服务号那一套。- 命名 client 是
"Sparkdo.Weixin"(公众平台那条链路),不是"Sparkdo.Weixin.Payment"。 SparkdoWeixinServiceJsonContext是sealed:新增 wire 类型只能改那个文件,不能在自己程序集里派生它。Message这个类名容易和别处冲突:与System.Net.Http.HttpRequestMessage/System.Messaging或自家Message命名类型同框时请起别名(测试里的写法是using ServiceMessage = Sparkdo.Weixin.Service.Requests.Message;)。- 模板消息 ≠ 订阅消息:小程序那条走
Sparkdo.Weixin.MiniProgram(/cgi-bin/message/subscribe/send),路径与模型都不同。 - 库里没有限流/重试:批量发送请自己控并发并处理
45009。
非目标
- 不交付客服消息、群发(mass send)、素材管理、图文、菜单、标签、用户管理、模板列表/行业设置等其它服务号接口。
- 不做消息加解密(
aes_msg、URL 校验signature/echostr)。 - 不做
Add*接线、不做 named/keyed Options、不做多服务号注册表。 - 不做模板 ID 的校验、字段名对齐、内容审核、变量长度限制。
- 不做发送队列、重试、退避、限流、失败落库与补偿。
- 不做送达统计(
msgid只回给你,微信的送达回调由宿主接收)。
工程与验证
| 工程 | 职责 | 打包 |
|---|---|---|
| Sparkdo.Weixin.Service.csproj | 本包:Options、两个基类、模板消息、JSON context | Sparkdo.Weixin.Service(只依赖核心包) |
| ../test/Sparkdo.Weixin.E2E.Tests | ServicePackageTests 4 项 wire 断言(请求形状 + msgid 数字/字符串/缺失三态)+ SubPackagePublicApiApprovalTests 的 Service 基线 1 项 |
不打包 |
# 域全量测试(Release 全绿,构建 0 警告)
dotnet test src/weixin/Sparkdo.Weixin.slnx -c Release
# 只跑服务号相关断言
dotnet test src/weixin/test/Sparkdo.Weixin.E2E.Tests -c Release --filter "FullyQualifiedName~ServicePackageTests"
# 打包并核对包内自述与 XML 文档随包
dotnet pack src/weixin/src/Sparkdo.Weixin.Service -c Release -o artifacts/feed
unzip -l artifacts/feed/Sparkdo.Weixin.Service.1.0.0.nupkg | grep -E "README|\.xml"
相邻文档:产品域自述 · 核心包自述 · MiniProgram 包自述 · Payment 包自述 · Subscription 包自述
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- Microsoft.Extensions.Caching.Abstractions (>= 10.0.8)
- Microsoft.Extensions.Configuration (>= 10.0.8)
- Microsoft.Extensions.Configuration.Abstractions (>= 10.0.8)
- Microsoft.Extensions.DependencyInjection (>= 10.0.8)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.8)
- Microsoft.Extensions.Http (>= 10.0.8)
- Microsoft.Extensions.Logging (>= 10.0.8)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.8)
- Microsoft.Extensions.Options (>= 10.0.8)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 10.0.8)
- Microsoft.Extensions.Primitives (>= 10.0.8)
- Sparkdo.Weixin (>= 3.0.0-preview.1)
-
net11.0
- Microsoft.Extensions.Configuration (>= 10.0.8)
- Microsoft.Extensions.DependencyInjection (>= 10.0.8)
- Microsoft.Extensions.Http (>= 10.0.8)
- Microsoft.Extensions.Logging (>= 10.0.8)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 10.0.8)
- Sparkdo.Weixin (>= 3.0.0-preview.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 3.0.0-preview.1 | 72 | 10/30/2026 |
| 1.0.4-preview.3 | 108 | 6/8/2026 |
| 1.0.4-preview.2 | 95 | 6/7/2026 |
| 1.0.4-preview.1 | 95 | 6/7/2026 |
| 1.0.3 | 174 | 6/6/2026 |
| 1.0.3-preview.1 | 94 | 5/17/2026 |
| 1.0.2 | 154 | 4/27/2026 |
| 1.0.2-preview.5 | 99 | 4/15/2026 |
| 1.0.2-preview.4 | 113 | 2/8/2026 |
| 1.0.2-preview.3 | 111 | 2/1/2026 |
| 1.0.2-preview.2 | 102 | 1/31/2026 |
| 1.0.2-preview.1 | 217 | 12/4/2025 |
| 1.0.1 | 274 | 11/27/2025 |
| 1.0.0 | 253 | 11/25/2025 |
| 1.0.0-preview.5 | 167 | 10/24/2025 |
| 1.0.0-preview.4 | 166 | 10/3/2025 |
| 1.0.0-preview.2 | 204 | 10/2/2025 |
| 1.0.0-preview.1 | 196 | 10/2/2025 |