Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop Wechat with C # to receive, process and decrypt Wechat Enterprise messages and events?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the C# development of Wechat how to achieve Wechat enterprise message and event reception processing and decryption operation, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

1. The setting of callback mode of Enterprise account

Like the official account, if Wechat Enterprise account needs to carry out secondary development, it also needs to set the corresponding callback parameters in the background, as shown in the following interface.

After setting up these and passing the check, we can send and receive messages on our Wechat application server.

At the message entry of the callback, we need to deal with POST data and ordinary GET data separately. GET data is the verification processing of Wechat itself, and POST data is the interactive operation of Wechat messages.

/ / Enterprise ID callback information API. An entrance to receive and process information in a unified manner. / public class corpapi: IHttpHandler {/ process the information of Enterprise / public void ProcessRequest (HttpContext context) {

Above we define a general application handler to process messages.

Then we separate different message types (POST, GET) and deal with them specifically.

If (HttpContext.Current.Request.HttpMethod.ToUpper () = "POST") {using (Stream stream = HttpContext.Current.Request.InputStream) {Byte [] postBytes = new Byte [stream.Length]; stream.Read (postBytes, 0, (Int32) stream.Length) PostString = Encoding.UTF8.GetString (postBytes);} if (! string.IsNullOrEmpty (postString)) {Execute (postString, accountInfo) }} else {Auth (accountInfo);} 2. Verification of Wechat callback messages

The following is Wechat's description of verifying URL for callback mode.

Verify the validity of URL

When you submit the above information, the enterprise ID will send a GET request to the entered URL. The GET request carries four parameters. The enterprise needs to do urldecode processing when obtaining the information, otherwise the verification will not be successful.

Parameter description: whether msg_signature Wechat encryption signature is required. Msg_signature combines the token entered by the enterprise, the timestamp and nonce parameters in the request, and the encrypted message body is timestamp timestamp is nonce random number is echostr encrypted random string, which is provided in msg_encrypt format. You need to decrypt and return echostr plaintext. After decryption, there are four fields: random, msg_len, msg and $CorpID. Msg is required for the first verification of echostr plaintext.

The enterprise verifies the request with the parameter msg_signature. If it is confirmed that the GET request comes from the enterprise account, the enterprise application decrypts the echostr parameter and returns the echostr plaintext as it is (no quotation marks are allowed), then the access verification takes effect and the callback mode can be enabled.

All subsequent callbacks to the enterprise will include the above parameters (except echostr) in the request URL, and the verification method is the same as that of the first verification URL.

According to the above instructions, we need to obtain these parameters, and then call the message handling function provided by Wechat for encryption and decryption processing.

In the Auth (accountInfo); operation of the verification URL, we can see that the core content is as follows, that is, the parameter information passed is obtained and handed over to the base class to process the signature content of the message.

# region specific processing logic string echoString = HttpContext.Current.Request.QueryString ["echoStr"]; string signature = HttpContext.Current.Request.QueryString ["msg_signature"]; / / msg_signature string timestamp = HttpContext.Current.Request.QueryString ["timestamp"] of the enterprise account; string nonce = HttpContext.Current.Request.QueryString ["nonce"] String decryptEchoString = "" If (new CorpBasicApi (). CheckSignature (token, signature, timestamp, nonce, corpId, encodingAESKey, echoString, ref decryptEchoString)) {if (! string.IsNullOrEmpty (decryptEchoString)) {HttpContext.Current.Response.Write (decryptEchoString) HttpContext.Current.Response.End ();}} # endregion

The verification code department is shown below.

/ verify Enterprise signature / signature content / / timestamp / / nonce Parameter / / Enterprise ID / / encryption key / / content string / / The returned string / public bool CheckSignature (string token String signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr) {WXBizMsgCrypt wxcpt = new WXBizMsgCrypt (token, encodingAESKey, corpId) Int result = wxcpt.VerifyURL (signature, timestamp, nonce, echostr, ref retEchostr); if (result! = 0) {LogTextHelper.Error ("ERR: VerifyURL fail, ret:" + result); return false;} return true;} 3, message processing of Enterprise account

As mentioned above, during the verification of URL by Wechat Enterprise account, there is another message processing process, that is, the Wechat server sends the message to our own application server for processing. Our application server needs to carry out regular reply processing in time after receiving the message.

That is, the following code logic.

If (HttpContext.Current.Request.HttpMethod.ToUpper () = "POST") {using (Stream stream = HttpContext.Current.Request.InputStream) {Byte [] postBytes = new Byte [stream.Length]; stream.Read (postBytes, 0, (Int32) stream.Length) PostString = Encoding.UTF8.GetString (postBytes);} if (! string.IsNullOrEmpty (postString)) {Execute (postString, accountInfo);}}

Similarly, when we respond to a message to the Wechat server, we also need to obtain the corresponding parameters, and then construct the information answer.

String echoString = HttpContext.Current.Request.QueryString ["echoStr"]; string signature = HttpContext.Current.Request.QueryString ["msg_signature"]; / / msg_signature string timestamp = HttpContext.Current.Request.QueryString ["timestamp"] of the enterprise; string nonce = HttpContext.Current.Request.QueryString ["nonce"]

Other parameter information comes from the configuration parameters of our enterprise account.

/ / get the configuration parameters and initialize the encryption and decryption function string CorpToken = accountInfo.Token; string AESKey = accountInfo.EncodingAESKey; string CorpId = accountInfo.CorpID

Then use the message encryption and decryption class provided by Wechat, you can successfully encrypt and decrypt the message. The specific operation code is shown below.

/ / initialize the message encryption and decryption class WXBizMsgCrypt wxcpt = new WXBizMsgCrypt (CorpToken, AESKey, CorpId) corresponding to Wechat according to the parameter information; / / parse the received ciphertext string sMsg = ""; / / the plaintext after parsing int flag = wxcpt.DecryptMsg (signature, timestamp, nonce, postStr, ref sMsg) If (flag = = 0) {/ / LogTextHelper.Info ("record decrypted data:"); / / LogTextHelper.Info (sMsg); / / record decrypted data CorpApiDispatch dispatch = new CorpApiDispatch (); string responseContent = dispatch.Execute (sMsg) / / encrypted and sent / / LogTextHelper.Info (responseContent); string encryptResponse = ""; timestamp = DateTime.Now.DateTimeToInt (). ToString (); wxcpt.EncryptMsg (responseContent, timestamp, nonce, ref encryptResponse, ref signature); HttpContext.Current.Response.ContentEncoding = Encoding.UTF8 HttpContext.Current.Response.Write (encryptResponse);} else {LogTextHelper.Info ("failed to decrypt message!") ;}

Finally, we just give the decrypted message to the corresponding wrapper class for unified processing.

CorpApiDispatch dispatch = new CorpApiDispatch (); string responseContent = dispatch.Execute (sMsg)

In this way, when we encapsulate the API on the enterprise number, we can only pay attention to the logic of how the message is answered, and don't care about the rest.

Thank you for reading this article carefully. I hope the article "how to receive, process and decrypt the messages and events of Wechat Enterprise in the development of Wechat by C#" shared by the editor is helpful to everyone. At the same time, I also hope that you will support it and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report