1.在Web專案中執行Install-Package Aquarius.Weixin
或dotnet add package Aquarius.Weixin
安裝Nuget包,建議使用最新版本以防止各種問題
2、在Startup.cs 中加入Aquarius.Weixin.Core.Configuration.DependencyInjection
引用
3、 ConfigurationServices
配置
方式一:
在ConfigurationServices
中加入Aquarius.Weixin:
services.AddAquariusWeixin(opt =>
{
opt.BaseSetting = new BaseSettings()
{
Debug = true,//调试模式
IsRepetValid = false,//是否启用消息重复验证
AppId = "appid",//appId
AppSecret = "appsecret",//appSecret
Token = "token",//token
EncodingAESKey = "asekey",//AES Key,用于消息加密
ApiKey = "apikey",//商户Api key
CertPass = "certpass",//商户p12密码
CertRoot = "certroot",//商户p12证书密码
MchId = "mchid"//商户Id
};
opt.CacheType = CacheType.InMemory;//缓存模式,支持InMemory和Redis,此处采用InMemory
opt.MsgMiddlewareType = MessageMiddlewareType.Plain;//消息中间件模式,支持Plain(明文)和Cipher(密文),此处采用明文
});
方式二:
新增設定檔AquariusWeixinOptions.json
新增如下配置:
{
"CacheType": "InMemory",
"MsgMiddlewareType": "Plain",
"BaseSetting": {
"Debug": true,
"IsRepetValid": false,
"AppId": "appid",
"AppSecret": "appsecret",
"Token": "token",
"EncodingAESKey": "asekey",
"ApiKey": "apikey",
"CertPass": "certpass",
"CertRoot": "certroot",
"MchId": "mchid"
}
}
並在ConfigurationServices
中加入Aquarius.Weixin:
var options = new ConfigurationBuilder()
.AddJsonFile("AquariusWeixinOptions.json")
.Build();
services.AddAquariusWeixin(options);
或直接在ConfigurationServices
中新增:
services.AddAquariusWeixin(opt =>
{
opt.BaseSetting = new BaseSettings()
{
Debug = true,
IsRepetValid = false,
AppId = "your appid",
AppSecret = "your appsecret",
Token = "token",
//其他配置
};
opt.CacheType = CacheType.InMemory;
opt.MsgMiddlewareType = MessageMiddlewareType.Plain;
});
快速使用可以指設定BaseSetting 中的Debug(建议为true)
、 IsRepetValid(建议为false)
、 AppId
、 AppSecret
、 Token
以及CacheType
設定為InMemory
, MsgMiddlewareType
設定為Plain
,其他不進行設定或設定為空白
4.使用範例WeixinController.cs
(1)網頁授權
public IActionResult Authorization(string code)
{
//通过code获取openId
var openId = _authorizationContainer.GetOpenId(code);
//通过openId获取userInfo
var userInfo = _authorizationContainer.GetUserInfo(openId, Language.zh_CN);
return Content($"your openId is {openId}, your nickname is {userInfo.nickname}");
}
網頁授權回呼連結的Action 必須接收一個code
參數或在程式碼中從request 取code
(2)選單創建
public IActionResult CreateMenu()
{
//创建菜单对象
var menu = new Menu()
{
button = new List<IButton>()
{
new SingleClickButton("按钮1")
{
key = "Button1"
},
new SubButton("二级菜单")
{
sub_button = new List<SingleButton>()
{
new SingleClickButton("按钮2")
{
key = "按钮2"
},
new SingleViewButton("网页")
{
url = "http://yourdomain.com"
}
}
}
}
};
//获取AccessToken
var accessToken = _accessTokenContainer.GetAccessToken();
//创建菜单
var result = _menuInterfaceCaller.CreateMenu(accessToken, menu.ToJson());
return Content(result);
}
建立選單樣式如下:
(3)訊息管理
public async Task<IActionResult> Index(string signature, string timestamp, string nonce, string echostr, string encrypt_type, string msg_signature)
{
try
{
if(!string.IsNullOrEmpty(echostr))
{
//服务器认证
if (_verifyer.VerifySignature(signature, timestamp, nonce, _baseSettings.Token))
{
return Content(echostr);
}
else
{
return Content("success");
}
}
else
{
//消息接收
using (var sr = new StreamReader(Request.Body))
{
string data = await sr.ReadToEndAsync();
_logger.LogInformation(data);
//接收消息中间处理
data = _messageMiddleware.ReceiveMessageMiddle(signature, msg_signature, timestamp, nonce, data);
//解析消息
IMessage message = MessageParser.ParseMessage(data);
//处理消息,生成回复
string reply = _processer.ProcessMessage(message);
//回复消息中间处理
reply = _messageMiddleware.ReplyMessageMiddle(reply);
return Content(reply);
}
}
}
catch(Exception ex)
{
_logger.LogError("Error", ex);
return Content("success");
}
}
將上述程式碼的Action 配置為伺服器鏈接,注意:該訊息接收代碼為建議模式,不建議增刪
程式碼中預設的所有訊息處理為返回success
即不進行任何處理,需要編寫一個訊息處理類別來進行實際的訊息處理,以下以點擊選單按鈕返回文字為例
新建ClickEventReplyTextHandler
類別,程式碼如下:
public class ClickEventReplyTextHandler : IClickEvtMessageHandler
{
private readonly IMessageReply<TextMessage> _messageReply;
public ClickEventReplyTextHandler(IMessageReply<TextMessage> messageReply)
{
_messageReply = messageReply;
}
public string Handle(ClickEvtMessage message)
{
var textMessage = new TextMessage(message)
{
CreateTime = UtilityHelper.GetTimeStamp(),
Content = $"你点击了{message.EventKey}按钮"
};
return _messageReply.CreateXml(textMessage);
}
}
① ClickEventReplyTextHandler
所實作的介面IClickEvtMessageHandler
即為要重寫的訊息類型處理接口,本例為點擊事件訊息處理。
② _messageReplay
欄位的類型為泛型IMessageReply<T>
類型,類型T
即為要傳回的訊息類型,此範例傳回文字訊息(TextMessage)
以上兩點,此範例即對點擊事件訊息進行處理並傳回文字訊息
最後在ConfigureServices
方法中的AddAquariusWeixin
之後加入
services.AddScoped<IClickEvtMessageHandler, ClickEventReplyTextHandler>();
即完成點擊按鈕返回文字訊息
支付教學不包含在Quick Start 中,後續將會更新詳細教學
有問題請提Issue 或與我聯繫
微信:wdcdavyc(請備註:Github)。