1. Execute Install-Package Aquarius.Weixin
or dotnet add package Aquarius.Weixin
in the Web project to install the Nuget package. It is recommended to use the latest version to prevent various problems.
2. Add Aquarius.Weixin.Core.Configuration.DependencyInjection
reference in Startup.cs
3. ConfigurationServices
configuration
Method one:
Add Aquarius.Weixin in ConfigurationServices
:
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(密文),此处采用明文
});
Method two:
Add the configuration file AquariusWeixinOptions.json
and add the following configuration:
{
"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"
}
}
And add Aquarius.Weixin in ConfigurationServices
:
var options = new ConfigurationBuilder()
.AddJsonFile("AquariusWeixinOptions.json")
.Build();
services.AddAquariusWeixin(options);
Or add it directly in 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;
});
Quick use can refer to setting Debug(建议为true)
, IsRepetValid(建议为false)
, AppId
, AppSecret
, Token
and CacheType
in BaseSetting to InMemory
, MsgMiddlewareType
to Plain
, and other configurations are not configured or are empty
4. Use example WeixinController.cs
(1) Web page authorization
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}");
}
The Action of the web page authorization callback link must receive a code
parameter or get the code from the request in the code.
(2) Menu creation
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);
}
Create the menu style as follows:
(3) Message management
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");
}
}
Configure the Action of the above code as a server link. Note: The message receiving code is in recommended mode, and additions and deletions are not recommended.
The default message processing in the code is to return success
that is, no processing is performed. You need to write a message processing class to perform actual message processing. The following is an example of clicking the menu button to return text.
Create a new ClickEventReplyTextHandler
class with the following code:
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);
}
}
① The interface IClickEvtMessageHandler
implemented by ClickEventReplyTextHandler
is the message type processing interface to be rewritten. This example is click event message processing.
② The type of the _messageReplay
field is the generic IMessageReply<T>
type, and the type T
is the message type to be returned. This example returns a text message (TextMessage)
Based on the above two points, this example processes the click event message and returns the text message
Finally, add it after AddAquariusWeixin
in the ConfigureServices
method
services.AddScoped<IClickEvtMessageHandler, ClickEventReplyTextHandler>();
Click the button to return to the text message
The payment tutorial is not included in Quick Start. Detailed tutorials will be updated later.
If you have any questions, please raise an Issue or contact me
WeChat: wdcdavyc (please note: Github).