C # development portal and application (21)-receiving, processing, and decryption of enterprise numbers and events,
In the previous article, I wrote "C # development portal and application (19)-sending of enterprise numbers (text, images, files, voices, videos, text messages, etc) this section describes how to send a message about the Enterprise ID. The official website specifically states that the message does not need to be encrypted. However, on the Callback Server, that is, on the server of our website, the sent messages are encrypted. We need to call the class library to decrypt messages and events, due to the incomplete official examples, I found a lot of time and finally successfully decrypted various messages and events. This document describes how to receive, process, and decrypt enterprise numbers and events.
1. Set the enterprise number callback Mode
Like the public account, if the enterprise account requires secondary development, you also need to set the corresponding callback parameters in the background, as shown in the following interface.
After these settings are complete, we can send and receive messages on our application server.
At the entrance of the callback message, we need to separate the POST data from the common GET data. The GET data is verified and the POST data is the interactive operation of the message.
/// <Summary> /// interface for enterprise number callback information. Portal for receiving and processing information in a unified manner. /// </Summary> public class corpapi: IHttpHandler {// <summary> // process the enterprise ID information /// </summary> /// <param name = "context"> </param> public void ProcessRequest (HttpContext context) {
We have defined a general application processing program to process messages.
Then we separate different message types (POST and GET methods) for targeted processing.
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 callback messages
The following describes the URL verification for the callback mode.
Verify URL Validity
When you submit the preceding information, the enterprise ID sends a GET request to the URL filled in. The GET request carries four parameters,Enterprises need to perform urldecode processing when obtainingOtherwise, the verification fails.
Parameters |
Description |
Required |
Msg_signature |
Encrypted Signature. msg_signature combines the token entered by the enterprise, timestamp, nonce parameter in the request, and encrypted message body. |
Yes |
Timestamp |
Timestamp |
Yes |
Nonce |
Random Number |
Yes |
Echostr |
The encrypted random string, which is provided in msg_encrypt format. The echostr plaintext needs to be decrypted and returned. After decryption, there are four fields: random, msg_len, msg, and $ CorpID. msg is the echostr plaintext. |
REQUIRED for the first verification |
The Enterprise verifies the request through the msg_signature parameter. If you confirm that the GET request comes from the enterprise numberThe Enterprise Application decrypts the echostr parameter and returns the echostr plaintext (no quotation marks are allowed)To enable the callback mode.
The preceding parameters (except echostr) will be included in the request URL for future callback. The verification method is the same as the first verification URL.
According to the preceding instructions, we need to obtain these parameters and then call the provided message processing function for encryption and decryption.
In the authentication URL's Auth (accountInfo); operation, we can see that the core content is as follows, is to get the passed parameter information, then, it is 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 of the enterprise number. current. request. queryString ["timestamp"]; string nonce = HttpContext. current. request. queryString ["nonce"]; string decryptEchoString = ""; if (new CorpBasicApi (). checkSignature (token, sig Nature, 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 as follows.
/// <Summary> /// verify the enterprise ID signature /// </summary> /// <param name = "token"> Token of the enterprise ID configuration </param> // /<param name = "signature"> signature content </param> // <param name = "timestamp"> timestamp </param> // <param name =" nonce "> nonce parameter </param> // <param name =" corpId "> enterprise ID </param> // <param name =" encodingAESKey "> encryption key </param> /// <param name = "echostr"> content string </param> /// <param name = "retEchostr"> returned string </param> // /<returns> </returns> p Ublic bool CheckSignature (string token, string signature, string timestamp, string nonce, string corpId, string encodingAESKey, string echostr, ref string retEchostr) {symbol wxcpt = new symbol (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 numbers
As described above, there is another message processing process in the URL verification process of the enterprise number, that is, the process in which the server sends the message to our own application server for processing, our application server must promptly perform regular reply processing 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 server, we also need to obtain the corresponding parameters and then construct the information to answer.
String echoString = HttpContext. current. request. queryString ["echoStr"]; string signature = HttpContext. current. request. queryString ["msg_signature"]; // msg_signature string timestamp = HttpContext of the enterprise number. current. request. queryString ["timestamp"]; string nonce = HttpContext. current. request. queryString ["nonce"];
Some other parameter information comes from the configuration parameters of our enterprise account.
// Obtain the configuration parameters and initialize string CorpToken = accountInfo. Token for the encryption and decryption function; string AESKey = accountInfo. EncodingAESKey; string CorpId = accountInfo. CorpID;
Then, you can use the provided message encryption and decryption class to smoothly encrypt and decrypt the message. The specific operation code is as follows.
// Initialize the corresponding message encryption and decryption class WXBizMsgCrypt wxcpt = new WXBizMsgCrypt (CorpToken, AESKey, CorpId) based on the parameter information ); // parse the received ciphertext string sMsg = ""; // The parsed plaintext int flag = wxcpt. decryptMsg (signature, timestamp, nonce, postStr, ref sMsg); if (flag = 0) {// LogTextHelper. info ("record decrypted data:"); // LogTextHelper. info (sMsg); // record the 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 ("An error occurred while decrypting the message! ");}
Finally, we can pass the decrypted message to the corresponding encapsulation class for unified processing.
CorpApiDispatch dispatch = new CorpApiDispatch(); string responseContent = dispatch.Execute(sMsg);
In this way, we can encapsulate the enterprise account API by simply focusing on the logic of how the message responds.
If you are interested in this series of C # development portals and applications, you can follow my other articles as follows:
C # development portal and application (20)-menu management of enterprise number
C # development portal and application (19)-sending of enterprise numbers (text, images, files, voice, video, text messages, etc)
C # development portal and application (18)-member management for enterprise address book management and development
C # development portal and application (17)-department management for enterprise address book management and development
C # development portal and application (16)-enterprise number configuration and use
C # development portal and application (15)-added the scan, image sending, and geographic location functions in the menu
C # development portal and application (14)-use redirection in the menu to obtain user data
C # development portal and application (13)-use geographic location Extension
C # development portal and application (12)-use voice processing
C # development portal and application (11)-menu presentation
C # development portal and application (10) -- synchronize user group information in the management system
C # development portal and application (9)-portal menu management and submission to server
C # development portal and application (8)-portal application management system function Introduction
C # development portal and application (7)-Multi-customer service functions and development integration
C # development portal and application (6)-portal menu management operations
C # development portal and application (5) -- User Group Information Management
C # development portal and application (4) -- Focus on the user list and detailed information management
C # development portal and application (3) -- Response to text messages and text messages
C # development portal and application (2) -- Message Processing and response
C # development portal and application (1) -- getting started with Interfaces