仅适用于更换小程序模板(属于换汤不换药)。可实现多环境对应不同的小程序模板
一.配置文件格式
"MiniProgramConfig": { "Token": "r8Z6weJVCb0", "EncodingAESKey": "MhemkNp9DZXqe24A", "AppId": "wxff9df85f87", "AppSecret": "a63351ef63f573a9a70b4c4" },"DccOptions": { "ManageServiceAddress": "http://localhost:8890", "RedisOptions": { "Servers": [ { "Host": "10.175.27.202", "Port": 30260 } ], "DefaultDatabase": 1, "Password": "sis" }, "Environment": "Staging", "ConfigObjectSecret": "masastack.com" },
二.使用Dcc配置消息模板
Program.cs引用服务
builder.Services.AddMasaConfiguration(configurationBuilder => { configurationBuilder.UseDcc(); });
{"template_id":"nA6B4euE6wM-mc0k9isdfqGX6CzaMPdd4vGSkuoPdZk","touser":"{openid}","page":"/subpackges/my/charterbusiness/payreminder","data":{"thing1":{"value":"{title}"},"character_string6":{"value":"{leaseNo}"},"amount3":{"value":"{amount}"},"time4":{"value":"{time}"},"thing7":{"value":"{contactName}"}}}
三.Controller
public class WeChatController : BaseController { private IEventBus _eventBus;
/// <summary> /// 构造函数 /// </summary> public WeChatController(IEventBus eventBus) { _eventBus = eventBus; }
#region 集成事件 /// <summary> /// 小程序缴费通知 /// </summary> /// <param name="integrationEvent"></param> /// <returns></returns> [HttpPost] [Topic("pubsub", nameof(SendLeasePayReminderMessageIntegrationEvent))] public async Task SendLeasePayReminderMessageAsync(SendLeasePayReminderMessageIntegrationEvent integrationEvent) { await _eventBus.PublishAsync(new SendLeasePayReminderMessageCommand(integrationEvent.Request)); } #endregion }
三.Application应用层
public class AppletMessageCommandHandlers { private readonly IEstateAccountRepository _accountRepository; private readonly IMasaConfiguration _configuration; public AppletMessageCommandHandlers(IEstateAccountRepository accountRepository, IMasaConfiguration configuration) { _accountRepository = accountRepository; _configuration = configuration; } /// <summary> /// 缴费提醒 /// </summary> /// <returns></returns> [EventHandler] public async Task SeedLeasePayReminderMessageAsync(SendLeasePayReminderMessageCommand command) {
if (command.Request.Count == 0)
{
return;
}
var messageBodyString = _configuration.ConfigurationApi.GetDefault().GetValue<string>("小程序缴费提醒"); if (string.IsNullOrWhiteSpace(messageBodyString)) { return; } var request = command.Request; var mobiles = request.Select(item => item.Mobile).Distinct(); var accounts = await _accountRepository.GetListAsync(item => mobiles.Contains(item.Mobile)); foreach ( var item in request) { var account = accounts.FirstOrDefault(account => account.Mobile == item.Mobile); if (account != null) { messageBodyString = messageBodyString.Replace("{openid}", account.OpenId);//"oYydZpJmgeQmo" messageBodyString = messageBodyString.Replace("{title}", item.Title);//"" messageBodyString = messageBodyString.Replace("{leaseNo}", item.LeaseNo);//"456465" messageBodyString = messageBodyString.Replace("{amount}", item.Amount.ToString());//"33.00" messageBodyString = messageBodyString.Replace("{time}", item.Time);//DateTime.Now.ToString() messageBodyString = messageBodyString.Replace("{contactName}", item.ContactName);//"宋梦辉" var result = await AppletMessageService.SenMessages(messageBodyString); Console.WriteLine(result); } } } }
//Command命令
public record class SendLeasePayReminderMessageCommand : Command { public List<SendLeasePayReminderMessageRequest> Request { get; set; } public SendLeasePayReminderMessageCommand(List<SendLeasePayReminderMessageRequest> request) { Request = request; } }
2.核心推送代码
public static class AppletMessageService { private static readonly MiniProgramConfigModel MiniProgramConfig; static AppletMessageService() { MiniProgramConfig = AppSettings.GetModel<MiniProgramConfigModel>(WeChatConst.MiniProgramConfigName); if (MiniProgramConfig == null) { throw new ArgumentNullException(nameof(MiniProgramConfig)); } } /// <summary> /// 获取微信AccessToken /// </summary> /// <returns></returns> public static async Task<string> GetAccessToken() { var appid = MiniProgramConfig.AppId; var secret = MiniProgramConfig.AppSecret; var url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}"; using (var client = new HttpClient()) { HttpResponseMessage response = await client.GetAsync(url); var readAsString = await response.Content.ReadAsStringAsync(); var res = JsonConvert.DeserializeObject<dynamic>(readAsString); return res.access_token ?? string.Empty; } } /// <summary> /// 发送通知 /// <param name="body">body</param> /// </summary> public static async Task<string> SenMessages(object body) { var accessToken = await GetAccessToken(); var url = $"https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={accessToken}"; using (var client = new HttpClient()) { var content = new StringContent(body is String ? (string)body : JsonConvert.SerializeObject(body)); content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"); var response = await client.PostAsync(url, content); var readAsString = await response.Content.ReadAsStringAsync(); var res = JsonConvert.DeserializeObject<dynamic>(readAsString); if (res.errcode == "0") { return "ok"; } else { return res.errmsg; } } } }
标签:MiniProgramConfig,await,NetCore,MasaDcc,messageBodyString,item,var,推送,public From: https://www.cnblogs.com/duia/p/17433848.html