首页 > 编程语言 >【.NetCore】结合MasaDcc实现动态配置小程序消息模板并进行推送消息

【.NetCore】结合MasaDcc实现动态配置小程序消息模板并进行推送消息

时间:2023-05-26 09:45:47浏览次数:33  
标签:MiniProgramConfig await NetCore MasaDcc messageBodyString item var 推送 public

仅适用于更换小程序模板(属于换汤不换药)。可实现多环境对应不同的小程序模板

一.配置文件格式

  "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

相关文章

  • 基于.NetCore开源的Windows的GIF录屏工具
    推荐一个Github上Start超过20K的超火、好用的屏幕截图转换为GIF动图开源项目。项目简介这是基于.NetCore+WPF开发的、开源项目,可将屏幕截图转为GIF动画。它的核心功能是能够简单、快速地截取整个屏幕或者选定区域,并将其转为GIF动画,还支持自定义GIF动画效果、字幕、背......
  • xiaofeng.NET系列之 netcore c#快速导出数据CSV格式 winfrom wpf
    一个导出buttonnuget搜索 usingXiaoFeng.IO;usingXiaoFeng; privatevoidbutton1_Click(objectsender,EventArgse){varsavedlg=newFolderBrowserDialog(){Description="选择保存的路径",......
  • MobTech MobPush|ChatGPT辅助消息推送,实现文案千人千版
    消息推送的千人千面困境为了吸引用户的注意力,增加用户的活跃度和留存率,提升应用的流量和收入,手机应用程序往往希望千人千面地向用户推送通知,即根据用户的特征和需求,为每个用户推送合适的消息内容,以有针对性地获得用户的关注。目前,消息推送通过智能标签能力已经可以实现用户画像千人......
  • 2..NetCore部署Linux环境搭建
    1.查考链接 https://www.cnblogs.com/wugh8726254/p/15231372.html2.https://zhuanlan.zhihu.com/p/3447148063.https://blog.csdn.net/qq_39173779/article/details/1295077924.https://blog.csdn.net/SIXGODrr/article/details/1253723385.https://zhuanlan.zhihu.com/p/59......
  • 使用git推送gihub方法使用教程
    目的:使用git推送代码至github仓库,且创立分支。 一.安装(步骤1)安装git客户端github是服务端,要想在自己电脑上使用git我们还需要一个git客户端,windows用户请下载 http://msysgit.github.com/二.在本地创建sshkey(步骤2)1.使用gitbash建立连接 $ssh-keygen-trsa-C"y......
  • 微信⼩程序开发消息推送配置教程
    微信⼩程序开发消息推送配置这⼀块⽹上都是PHP居多,由于⽤egg.js写了⼀套验证⽅法。第⼀步:填写服务器配置登录微信⼩程序官⽹后,在⼩程序官⽹的“设置-消息服务器”页⾯,管理员扫码启⽤消息服务,填写服务器地址(URL)、Token和EncodingAESKey。URL是开发者⽤来接收微信消息和事件的接......
  • 【fastweixin框架教程6】微信企业号给关注的用户主动发送推送消息
     下面这个类我对fastweixin框架的简单封装调用,大家可以参考,如果需要QYAPIConfigExt和MainServernSupport,请参考本教程以前几篇文章  如需测试,需要去微信企业号官网申请试用账号。其中发送文本消息和图文消息都是没有问题。  我们知道,企业号主要......
  • ABP模块签入GitLab后自动打包并推送到ProGet
    #1、添加一个名为下划线的解决方案文件夹#2、把解决方案根目录下的几个必要的文件添加到上述文件夹下#3、修改NuGet.Config,添加私有NuGet服务器的网址,并配置用户名和密码:ABPSuite模板生成的NuGet.Config是这样的:添加一行自己服务器的配置,另外有对应的节点设置用户名和密码:#4、......
  • 记一次将 .netcore 项目用 IIS 进程调试
    环境:win10,VisualStudio2022 在.netframework年代,我们都习惯用iis进程调试代码。因为用F5调试代码效率太低下。现在.netcore时代,这种好习惯可不能丢。简单记录一下,我的操作过程。 1.首先用IIS挂载网站,看能不能把发布的好的网站跑起来2.其次用IIS增加网站,......
  • 使用增强版 singleflight 合并事件推送,效果炸裂!
    hello,大家好啊,我是小楼。最近在工作中对Go的singleflight包做了下增强,解决了一个性能问题,这里记录下,希望对你也有所帮助。singleflight是什么singleflight直接翻译为”单(次)飞(行)“,它是对同一种请求的抑制,保证同一时刻相同的请求只有一个在执行,且在它执行期间的相同请求都......