博客 (2)

本文使用 ASP.NET 6 版本 Senparc.Weixin.Sample.MP 示例项目改造。


第一步 注册多公众号

方法一:打开 appsettings.json 文件,在 SenparcWeixinSetting 节点内添加数组节点 Items,该对象类型同 SenparcWeixinSetting。

//Senparc.Weixin SDK 设置
"SenparcWeixinSetting": {
  "IsDebug": true,
  "Token": "",
  "EncodingAESKey": "",
  "WeixinAppId": "",
  "WeixinAppSecret": "",
  "Items": [
    {
      "IsDebug": true,
      "Token": "a",
      "EncodingAESKey": "a",
      "WeixinAppId": "a",
      "WeixinAppSecret": "a"
    },
    {
      "IsDebug": true,
      "Token": "b",
      "EncodingAESKey": "b",
      "WeixinAppId": "b",
      "WeixinAppSecret": "b"
    }
  ]
}

方法二:修改 Program.cs 文件,在 UseSenparcWeixin 方法中注册多个公众号信息。

var registerService = app.UseSenparcWeixin(app.Environment,
    null /* 不为 null 则覆盖 appsettings  中的 SenparcSetting 配置*/,
    null /* 不为 null 则覆盖 appsettings  中的 SenparcWeixinSetting 配置*/,
    register => { /* CO2NET 全局配置 */ },
    (register, weixinSetting) =>
    {
        //注册公众号信息(可以执行多次,注册多个公众号)
        //register.RegisterMpAccount(weixinSetting, "【盛派网络小助手】公众号");
        foreach (var mp in 从数据库或配置文件中获取的公众号列表)
        {
            register.RegisterMpAccount(new SenparcWeixinSetting
            {
                //IsDebug = true,
                WeixinAppId = mp.AppId,
                WeixinAppSecret = mp.AppSecret,
                Token = mp.Token,
                EncodingAESKey = mp.EncodingAeskey,
            }, mp.Name);
        }
    });

完成后,我们可以从 Config.SenparcWeixinSetting.Items 获取这些信息。


第二步 接入验证与消息处理

打开 WeixinController 控制器,将构造函数改写为:

public WeixinController(IHttpContextAccessor httpContextAccessor)
{
    AppId = httpContextAccessor.HttpContext!.Request.Query["appId"];
    var MpSetting = Services.MPService.MpSettingByAppId(AppId);
    Token = MpSetting.Token;
    EncodingAESKey = MpSetting.EncodingAESKey;
}

示例中 Services.MPService.MpSettingByAppId() 方法实现从 Config.SenparcWeixinSetting.Items 返回指定 appId 的公众号信息。

为使 IHttpContextAccessor 注入生效,打开 Program.cs,在行

builder.Services.AddControllersWithViews();

下方插入

builder.Services.AddHttpContextAccessor();

这样,我们就可以在构造函数中直接获取地址栏中的 appId 参数,找到对应的公众号进行消息处理。


第三步 消息自动回复中的 AppId

打开 CustomMessageHandler.cs,将 

private string appId = Config.SenparcWeixinSetting.MpSetting.WeixinAppId;
private string appSecret = Config.SenparcWeixinSetting.MpSetting.WeixinAppSecret;

替换为:

private string appId = null!;
private string appSecret = null!;

并在构造函数中插入

appId = postModel.AppId;
appSecret = Services.MPService.MpSettingByAppId(postModel.AppId).WeixinAppSecret;

这样,本页中使用的 appId / appSecret 会从 postModel 中获取,而非默认公众号。postModel 已在 WeixinController 中赋值当前的 appId。

改造后,我们可以在 OnTextRequestAsync() 等处理消息的方法中可以判断 appId 来处理不同的消息。


第四步 其它功能和接口

其它功能和接口均可用指定的 AppId 和对应的 AppSecret 进行调用。

xoyozo 2 年前
1,868

打开 appsettings.json,添加一项配置(如下方示例中的“SiteOptions”项)

image.png

* 注意,如需配置开发环境与生产环境不同的值,可单独在 appsettings.Development.json 文件中配置不同项,格式层次须一致;


C# 中习惯用强类型的方式来操作对象,那么在项目根目录添加类(类名以 SiteOptions为例),格式与 appsettings.json 中保持一致:

public class SiteOptions
{
    public ERPOptions ERP { get; set; }
    public WeixinOpenOptions WeixinOpen { get; set; }
    public WeixinMPOptions WeixinMP { get; set; }
    public SMSOptions SMS { get; set; }
    public AliyunOSSOptions AliyunOSS { get; set; }

    /// <summary>
    /// 单个文件上传的最大大小(MB)
    /// </summary>
    public int MaxSizeOfSigleFile_MB { get; set; }

    /// <summary>
    /// 单个文件上传的最大大小(字节)
    /// </summary>
    public int MaxSizeOfSigleFile_B => MaxSizeOfSigleFile_MB * 1024 * 1024;

    public class ERPOptions
    {
        public int ChannelId { get; set; }
        public string AppKey { get; set; }
    }
    public class WeixinOpenOptions
    {
        public string AppId { get; set; }
        public string AppSecret { get; set; }
    }
    public class WeixinMPOptions
    {
        public string AppId { get; set; }
        public string AppSecret { get; set; }
    }
    public class SMSOptions
    {
        public string AppKey { get; set; }
    }
    public class AliyunOSSOptions
    {
        public string Endpoint { get; set; }
        public string AccessKeyId { get; set; }
        public string AccessKeySecret { get; set; }
        public string BucketName { get; set; }

        /// <summary>
        /// 格式://域名/
        /// </summary>
        public string CdnUrl { get; set; }
    }
}


在 Startup 中注入 IConfiguration,并在 ConfigureServices() 方法中添加服务(注意使用 GetSection() 映射到自命名的“SiteOptions”项)

image.png


在控制器中使用

在控制器类中键入“ctor”,并按两次 Tab 键,创建构造函数

image.png

在构造函数中注入“IOptions”,并在 Action 中使用

using Microsoft.Extensions.Options;

public class TestController : Controller
{
    private readonly IOptions<SiteOptions> options;

    public TestController(IOptions<SiteOptions> options)
    {
        this.options = options;
    }

    public IActionResult Index()
    {
        return View(options.Value.ERP.ChannelId.ToString());
    }
}


在视图中使用

@using Microsoft.Extensions.Options
@inject IOptions<SiteOptions> options

@options.Value.ERP.ChannelId


xoyozo 5 年前
2,712