发送微信模板消息步骤如下:
- 首先要申请微信公众号,并申请消息模板,审核通过后才可使用
- 在
appsettings.json
中设置框架微信配置信息如下:
{
"Weixin": {
"GZHId": "公众ID(可空,绑定公众号才用到)",
"AppId": "公众号开发的AppId,通过微信公众平台获取",
"AppSecret": "公众号开发的密钥,通过微信公众平台获取",
"RedirectUri": "公众号请求地址(可空,绑定公众号才用到)"
},
}
- 后台业务逻辑调用发送模板消息,示例如下:
class YourBizService
{
//XXX通知
public static async Task SendXXXNoticeAsync(this Database db, XXXInfo info)
{
var weixin = await db.GetWeixinAsync(info.WeixinUser.Id);
if (weixin == null || string.IsNullOrWhiteSpace(weixin.OpenId))
return;
var info = new WeixinTemplateInfo
{
BizId = model.Id,
BizName = $"XXX通知-{info.WeixinUser.Name}"
};
info.Template = new TemplateInfo
{
ToUser = weixin.OpenId,
TemplateId = "微信模板消息ID(微信公众号平台上获取)",
Url = "点击模板消息跳转的连接",
Data = new
{
thing12 = TemplateData.Create(info.Field1),
thing3 = TemplateData.Create(info.Field2),
const26 = TemplateData.Create("XXXX状态"),
thing27 = TemplateData.Create(db.User.Name),
time28 = TemplateData.Create($"{DateTime.Now:yyyy-MM-dd HH:mm}")
}
};
var result = await db.SendTemplateMessageAsync(info);
Console.WriteLine($"XXX通知已发送给{model.WeixinUser.Name}-{result.IsValid}-{result.Message}");
}
}