当前位置:网站首页>Source code analysis of senparc.weixin.sample.mp
Source code analysis of senparc.weixin.sample.mp
2022-07-29 09:32:00 【Dotnet cross platform】
Senparc.Weixin.Sample.MP It is a sample of wechat official account .NET6 Source code , Project profile appsettings.json And the construction of wechat official account test environment : Wechat official account debugging and Natapp Environment building . Next, from the project structure , Project application and project source code 3 Explain from different angles .
One . From the perspective of project structure
The overall structure of the project code is as follows :
The key part is MessageHandlers Message processor section , Include message context 、 Message processor and event processor . After the project is started, the interface is :
Two . Application angle
1. The intuitive process of data flow
First of all, understand the wechat client 、 Wechat servers and third-party websites 3 The data flow relationship between , Let's introduce the process of data flow by taking the text sent by the user as an example :
Users send... Through wechat client OpenId
The wechat server sends the text to the third-party website . Of course, if there is no third-party website , That is to say, there is no secondary development of official account , Then the user will not get any response message
Third party websites process messages , For example, get the user's OpenId Etc
The third-party website returns the processed message to the wechat server
Wechat server forwards messages from third-party websites to wechat clients
In this way, the user will receive a message from the wechat client
The message types of wechat mainly include request messages and response messages , The request message is the message sent by the wechat server to the website , The response message is the message sent by the website to the wechat server . The specific request message and response message contain the following types :
2. Code process of data flow
(1) Official account message simulator
The input and output contents of official account message simulator are as follows :
URL: adopt Natapp Mapped domain names , namely http://fengling.nat300.top -> 127.0.0.1:8080.
Token、AppId and AESKey: Reference resources appsettings.json file .
type : Text 、 Location 、 picture 、 voice 、 video 、 Time push .
Content :OPENID. The text message processor processes the text .
(2)Post(PostModel postModel) Method
After the user sends a message , Wechat platform automatic Post A request to method public async TaskPost(PostModel postModel), And wait for a response XML:
In this method, you can customize MessageHandler To deal with :
var messageHandler = new CustomMessageHandler(await Request.GetRequestMemoryStreamAsync(), postModel, maxRecordCount);The real wechat processing method is :
public async Task ExecuteAsync(CancellationToken cancellationToken)(3)OnTextRequestAsync(RequestMessageText requestMessage) Method
This method can respond according to the input text , It can be matching keywords 、 Regular expressions 、 Don't reply , Or default response .
3、 ... and . Source angle
1.Program.cs Code
First of all Senparc.Weixin SDK Relevant codes of overall registration :
// To use local caching, you must add
builder.Services.AddMemoryCache();
// Senparc.Weixin register ( must )
builder.Services.AddSenparcWeixinServices(builder.Configuration);
...
var senparcWeixinSetting = app.Services.GetService<IOptions<SenparcWeixinSetting>>()!.Value;
// Enable wechat configuration ( must )
var registerService = app.UseSenparcWeixin(app.Environment,
null /* Not for null Coverage appsettings Medium SenpacSetting To configure */,
null /* Not for null Coverage appsettings Medium SenpacWeixinSetting To configure */,
register => { /*CO2NET Global configuration */ },
(register, weixinSetting) =>
{
// Register official account information ( It can be executed multiple times , Register multiple official account )
register.RegisterMpAccount(weixinSetting, "XXX official account ");
});
......
// Using official account MessageHandler middleware ( There is no need to create Controller)
app.UseMessageHandlerForMp("/WeixinAsync", CustomMessageHandler.GenerateMessageHandler, options =>
{
options.AccountSettingFunc = context => Senparc.Weixin.Config.SenparcWeixinSetting;
});(1)builder.Services.AddMemoryCache()
The framework supports memory caching 、Redis、Memcached And other caching strategies .
(2)builder.Services.AddSenparcWeixinServices(builder.Configuration)
Realization Senparc.Weixin Registration of .
(3)app.UseSenparcWeixin()
This method integrates CON2ET Global registration and Senparc.Weixin SDK Wechat registration process .
(4)app.UseMessageHandlerForMp
Use MessageHandler To configure , The asynchronous method will be used by default messageHandler.ExecuteAsync().
2.WeixinController.cs Code
(1)public ActionResult Get(PostModel postModel, string echostr)
This method is mainly used for wechat background address verification , It's not used at other times .
(2)public async Task<ActionResult> Post(PostModel postModel)
This method is to forward messages by wechat server [XML] To website , Wait for the website to process and return the message [XML] The process of sending to wechat server .
(3)messageHandler.OmitRepeatedMessage = true;
When the website cannot respond to the request of wechat server in time , Wechat server will continuously send multiple identical MsgId Message to the website , To prevent packet loss . This situation requires the use of MsgId De duplicate the news , Otherwise, the website will execute the same request many times .
It should be noted that , For multiple lines with the same MsgId Reply multiple times to the request message of , The client can only receive the response message corresponding to the last retransmission of the wechat server .
(4)messageHandler.DefaultMessageHandlerAsyncEvent = DefaultMessageHandlerAsyncEvent.SelfSynicMethod;
When the synchronization method is overridden , And the asynchronous method is not overridden , Try calling the synchronization method .
3.CustomMessageContext.cs Code
(1)CustomMessageContext
CustomMessageContext Is the context of the message , The writing method is basically fixed , You can use it by moving it directly . The message context is used to record the messages sent by a single user 、 Record of received messages , Even if different wechat official account send different messages at the same time , There will be no interference between the two , Because the context of the two is completely isolated .
(2)CustomMessageContext_MessageContextRemoved
When the context expires , The time triggered when it is removed . according to WeixinContext Algorithm in , The expired messages here will be cleared before the next request is executed after expiration .
4.CustomMessageHandler.cs Code
CustomMessageHandler and CustomMessageHandler_Events yes CustomMessageHandler Class 2 Partial classes , The former deals with non event type messages , For example, send text 、 Image, etc , The latter deals with event type messages , For example, click event 、 Subscription events ( Subscribe and unsubscribe ) etc. .
The request messages here are all ordinary messages :
5.CustomMessageHandler_Events.cs Code
All the request messages here are event push messages , Event push messages are divided into 3 Large type : Routine events [ Official account basic function return event ], Menu events [ Various types of official account menu return events ], Application events [ The application module returns an event ]:
reference :
[1]Senparc.Weixin.Sample.MP.sln:WeiXinMPSDK\Samples\MP\Senparc.Weixin.Sample.MP.sln
[2]Senparc.Weixin SDK Source code :https://github.com/JeffreySu/WeiXinMPSDK
[3]Senparc.Weixin.MP SDK Wechat public platform development course ( 23 ): stay .NET Core 2.0/3.0 Use in MessageHandler middleware :https://www.cnblogs.com/szw/p/Wechat-MessageHandler-Middleware.html
[4] Wechat development depth analysis : official account 、 Efficient development of small programs :http://book.weixin.senparc.com/BookHelper
[5] Wechat public platform interface debugging tool :https://mp.weixin.qq.com/debug
Artificial intelligence dry goods recommendation
Focus on technology sharing in the field of artificial intelligence
Game metauniverse
Focus on technology sharing in the game field
边栏推荐
- Commonly used DOS commands [gradually improved]
- 查看端口占用情况
- 【集中培训】HCIP-Cloud Computing 资源交流帖
- 网络安全(6)
- 23考研人撑住!考研第一波弃考高峰期已经到来!
- How to query express logistics and filter out no information doc No. to delete or copy
- 核酸扫码登记体验有感(如何提高OCR的文字正确识别率)
- Zhongang Mining: four steps for sustainable and healthy development of fluorite industry
- OpenCV入门基础学习
- Basic part 2 of flowable
猜你喜欢

Retinal Vessel Segmentation via a Semantics and Multi-Scale Aggregation Network

机器学习之分类模型评估指标及sklearn代码实现

How to change MySQL into Chinese
![[unity entry program] C # and unity - understand classes and objects](/img/bd/13cc90638c6e6ad4a45507b0ed2fb7.png)
[unity entry program] C # and unity - understand classes and objects

附录2-一些简单的练习
![[苹果开发者账号]06 转让开发者账号后,开发者年费自动续费问题](/img/a7/12fd63f16ebca81a3dd2d1b97847d1.png)
[苹果开发者账号]06 转让开发者账号后,开发者年费自动续费问题

先序遍历/后序遍历确定树的大致形态

First order traversal / second order traversal determines the approximate shape of the tree

不用Swagger,那我用啥?

分布式Session共享的4类技术方案,与优劣势比较
随机推荐
A structured random inactivation UNET for retinal vascular segmentation
Briefly describe the difference between heap and stack
[unity entry program] collection of common learning websites
Will the modified data be updated when it is the same as the original data?
Unity Xchart3.0基本用法快速上手
【BERT-多标签文本分类实战】之一——实战项目总览
redis可视化工具读取数据乱码问题解决
核酸扫码登记体验有感(如何提高OCR的文字正确识别率)
基于ArkUI eTS开发的坚果新闻(NutNews)
Floweable foundation Chapter 1
What kind of framework is friendly to developers?
Pyqt5 rapid development and practice 6.4 qboxlayout (box layout)
RTMP supports h265 streaming
mysql怎么换成中文
[performance optimization methodology series] III. core idea of performance optimization (2)
附录2-一些简单的练习
Redis series 3: highly available master-slave architecture
[苹果开发者账号]06 转让开发者账号后,开发者年费自动续费问题
Gao Zhiwei: data management enables the digital transformation of the transportation industry
Acwing game 59 [End]