1, an overview of the

In the process of interaction between wechat users and public accounts, some operations of users will make the wechat server notify the developer of the server address set in the developer center through event push, so that the developer can obtain the information. Some event notifications allow developers to reply to users after they occur, while others do not

As we mentioned in the last wechat C# series 6, message management-ordinary message acceptance and processing, wechat messages can be roughly divided into two types, one is ordinary messages including text, voice, pictures, etc., and the other is the event type to be discussed in this paper. Including: follow/unfollow events, scan qr code events with parameters, report geo-location events, user-defined menu-related events, etc., this article explains one by one. Because too much partial content is easy to cause reading fatigue, we will explain the processing of customized menu-related events in the next chapter.

The message here refers to the traditional wechat public platform message exchange. After a wechat user sends a message to the official account, the official account replies the message to the wechat user. Includes the following types:

  1. Subscribe /unsubscribe events: SUBSCRIBE /unsubscribe
  2. Scanning a TWO-DIMENSIONAL code with parameters: Scan
  3. Report the location event: location
  4. Custom menu events
  5. Click the menu to pull the event push
  6. Event push when clicking the menu jump link

This article focuses on the first three.

2. Implementation method

The Senparc.Weixin framework is used to quickly handle all kinds of receive event push, the implementation is very simple, a custom inheritance of MessageHandler class, rewrite these types of methods. Note that DefaultResponseMessage must be overridden to return unprocessed message types (it can also be used for default messages, such as help messages); All of the original OnXX abstract methods have been changed to virtual methods, so you don’t have to rewrite each one. If not overridden, the result in the DefaultResponseMessage method is returned by default.

Custom message handling classes:

public partial class CustomMessageHandler : MessageHandler<MessageContext<IRequestMessageBase, IResponseMessageBase>> { public CustomMessageHandler(Stream inputStream, int maxRecordCount = 0) : base(inputStream, null, maxRecordCount) { WeixinContext.ExpireMinutes = 3; } public override void OnExecuting () {/ / testing MessageContext StorageData if (CurrentMessageContext. StorageData = = null) { CurrentMessageContext.StorageData = 0; } base.OnExecuting(); } public override void OnExecuted() { base.OnExecuted(); CurrentMessageContext.StorageData = ((int)CurrentMessageContext.StorageData) + 1; }}Copy the code

Once you have defined the event handling classes, override the events that receive the event push mentioned above. We can override these types in MessageHandler to handle our business, or we can override only some types that are needed, and we can not override the types that are not needed, just define a unified DefaultResponseMessage

Public override iResponsemessBase DefaultResponseMessage(IRequestMessageBase requestMessage) {// All unprocessed messages are returned by default  var responseMessage = this.CreateResponseMessage<ResponseMessageText>(); Responsemessage. Content = "This message is from DefaultResponseMessage." ; return responseMessage; }Copy the code

The importance of the message to the weight

As we mentioned in the last article, the wechat server will disconnect the connection if it receives no response within 5 seconds and re-initiate the request, retry it three times in total. In this way, we simulate such a scenario: when users follow wechat accounts, the current user information is obtained, and then the information is written into the database, similar to website registration. Suppose we need to deal with complex business logic in this concern event. Such as award points, write user log, assigned user groups, and so on need to perform a series of logic, or network environment is more complex, there is no guarantee that 5 seconds response to the current user’s operation, what if when the operation is not yet complete, WeChat server to our server push again the attention of the same event, we will carry out our the logic again, This may cause duplicate data to appear in the database. I would like to say that I thought so too, but the real operating environment and our debugging environment are still not the same, until I found a lot of duplicate user information in the database, I realized the importance of message deduplication.) .

There is a difference between a normal message and an event message. Normal messages use msGID, while event messages use FromUserName + CreateTime.

4. Follow/unfollow events

When users follow or unfollow an official account, wechat will push this event to the URL filled in by the developer. It is convenient for developers to send welcome messages to users or unbind accounts.

If the server can not guarantee processing and reply within five seconds, you can directly reply to the empty string, wechat server will not do anything about this, and will not initiate a retry.

Examples of following or unfollowing event-push XML packets:

<xml> <ToUserName><! [CDATA[toUser]]></ToUserName> <FromUserName><! [CDATA[FromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><! [CDATA[event]]></MsgType> <Event><! [CDATA[subscribe]]></Event> </xml>Copy the code

Parameter Description:

Parameter Description ToUserName developer wechat id FromUserName Sender account (an OpenID) CreateTime Message creation time (integer) MsgType Message type, event event type, Subscribe, unsubscribeCopy the code

4.1 Concerned Events

To pay attention to events, we just need to rewrite the OnEvent_SubscribeRequest event code. We return a text message as follows:

/// </summary> // </returns> public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage) { var responseMessage = CreateResponseMessage<ResponseMessageNews>(); The foreach (var model in messageList) {responseMessage. Articles. Add (new Article () {Title = "countries, the public", Description = "Welcome to guosi software public account, more content steady official website, thank you!" , PicUrl = "http://www.rdiframework.net/WeiXin.png", Url = "http://www.rdiframework.net/" }); } return responseMessage; }Copy the code

In the above concerned event, the user concerned public number will automatically execute the above event code, we can do related business processing in the event code, such as binding user group, increase the user to the local and so on. And push a welcome message back to the user’s phone.

4.2 Unfollowing Events

Unsubscribe events are similar to follow events, except that the event becomes unsubscribe. Unsubscribe event – The main meaning of unsubscribe is to delete the OpenID binding that has been recorded in the website application in time, eliminate redundant data, and pay attention to the situation of user loss.

To unsubscribe from events, we just need to rewrite the OnEvent_UnsubscribeRequest event code. We return a text message as follows:

/// <summary> /// unsubscribe/unfollow // // The significance of the unsubscribe event is to delete the OpenID binding recorded in the website application in time and eliminate redundant data. And keep an eye on churn. /// </summary> /// <returns></returns> public override IResponseMessageBase OnEvent_UnsubscribeRequest(RequestMessageEvent_Unsubscribe requestMessage) { int returnValue = RDIFrameworkService.Instance.WeixinBasicService.UserUnsubscribeByOpenId(Id,requestMessage.FromUserName); / / var responseMessage = base. CreateResponseMessage < ResponseMessageText > (); Responsemessage. Content = "return "; return responseMessage; }Copy the code

The above code is automatically executed when the user unfollows the public account. You can see that we have a line of code for the business logic executed when the user unfollows, while returning a text message. The actual user has unfollowed, and the returned message can not be returned to the user’s mobile phone.

5. Scan the QR code with parameters

When a user scans a TWO-DIMENSIONAL code with scene values, the following two events may be pushed:

  1. If the user has not followed the public account, the user can follow the public account, after following wechat will push the event with the scene value to the developer.
  2. If the user has followed the public account, wechat will push the scanning event with scene value to the developer.

5.1 Interface Presentation and Implementation

The first one has been described above, but the second one is only described here.

Examples of push XML packets:

<xml> <ToUserName><! [CDATA[toUser]]></ToUserName> <FromUserName><! [CDATA[FromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><! [CDATA[event]]></MsgType> <Event><! [CDATA[SCAN]]></Event> <EventKey><! [CDATA[SCENE_VALUE]]></EventKey> <Ticket><! [CDATA[TICKET]]></Ticket> </xml>Copy the code

Parameter Description:

Parameter Description ToUserName developer wechat id FromUserName Sender account (an OpenID) CreateTime Message creation time (integer) MsgType Message type, event event type, SCAN EventKey EventKey value, which is a 32-bit unsigned integer, that is, the qr code when the qr code is created. Scene_id Ticket Ticket of the qr code, which can be exchanged for a qr code pictureCopy the code

For the generation of qr codes with parameters we will be specifically introduced in later articles, here we understand a concept of this. In order to meet the needs of user channel promotion analysis and user account binding and other scenarios, the public platform provides an interface for generating qr codes with parameters. The interface can be used to obtain multiple TWO-DIMENSIONAL codes with different scene values. After the user scans, the public account can receive event push. For details, please refer to the official technical document: Generate the TWO-DIMENSIONAL code with parameters

There are currently two types of QR codes:

1, temporary two-dimensional code, there is an expiration time, the longest can be set to 30 days after the two-dimensional code generation (that is, 2592000 seconds) after the expiration, but can generate more. Temporary QR codes are used in service scenarios that do not require permanent storage of QR codes, such as account binding

2, permanent TWO-DIMENSIONAL code, is no expiration time, but the number is small (currently up to 100,000). The permanent QR code applies to account binding and user source statistics.

To scan the two-dimensional code event with parameters, we only need to rewrite the OnEvent_ScanRequest event code. We return a text message as follows.

Public override IResponseMessageBase OnEvent_ScanRequest(RequestMessageEvent_Scan requestMessage) responseMessage = CreateResponseMessage<ResponseMessageText>(); responseMessage.Content = responseMessage.Content ?? String. Format(" Welcome to guos software, enter by scanning the QR code, scene value: {0}", requestMessage.eventKey); return responseMessage; }Copy the code

In the code above, after the user scans the TWO-DIMENSIONAL code with scene value to enter the public account, we return a prompt text message. This is a very useful function, often used to promote, can do different business according to different TWO-DIMENSIONAL code scene value, such as statistical attention to every fan from where to do channel promotion analysis, but the focus is the same public number.

5.2 Generate the purpose of qr code with parameters

What is the use of the TWO-DIMENSIONAL code generated by wechat public number with parameters?

  1. Can distinguish the source of fans, just need to generate different two-dimensional code with parameters, put these two-dimensional codes into each channel, fans through these channels two-dimensional code can distinguish the source of fans, micro help background channel fans list has the number of fans and details;
  2. Fans through the scanning channel TWO-DIMENSIONAL code to pay attention to the public number, will label groups, such as fans scan store A, B two-dimensional code in the wechat public number later user management can be viewed to store A/B two-dimensional code under the name of the details of the fans and groups;
  3. Can generate a number of different channels of TWO-DIMENSIONAL code configuration of different marketing activities, set up different attention to reply information, so that fans understand the motivation of the activity for the first time, whether interested in participating in and so on;
  4. We can use the two-dimensional code generation function of channels to follow the public account of wechat before receiving payment and indirectly analyze the follow-up consumption of fans.
  5. Assessment of promotion staff to complete the task of progress, such as to promote the name to generate more than the same TWO-DIMENSIONAL code, assigned to different promoters, each promoters attracted many fans to pay attention to the public number, micro help background can be one detail;
  6. Two-dimensional code with parameters is also called channel two-dimensional code or scene two-dimensional code, the number of survival is limited, and is permanent two-dimensional code. When the number is used up, you can delete some unused TWO-DIMENSIONAL code release, secondary use.

6. Report geolocation events

After the user agrees to report the location, the user will report the location when entering the session of the public account, or report the location every 5 seconds after entering the session. The public account can modify the above Settings in the public platform website. When the location is reported, wechat will push the reported location event to the URL filled in by the developer. To obtain the user’s address and location, it is necessary to enable the function of reporting location in the developer center of wechat public platform. After enabling this function, the option whether to allow reporting location will pop up when the user enters the public account for the first time. If you choose to allow, wechat will report the user’s location to the URL filled in by your developer center in XML form every time the user enters the public account session.

** Note: ** user location is passively obtained and will be reported only after the user agrees. Wechat public platform development cannot actively obtain user location.

Examples of push XML packets:

<xml> <ToUserName><! [CDATA[toUser]]></ToUserName> <FromUserName><! [CDATA[fromUser]]></FromUserName> <CreateTime>123456789</CreateTime> <MsgType><! [CDATA[event]]></MsgType> <Event><! [CDATA [LOCATION]] > < / Event > < Latitude > 23.137466 < / Latitude > < Longitude > 113.352425 < / Longitude > The < Precision > 119.385040 < / Precision > > < / XMLCopy the code

Parameter Description:

Parameter Description ToUserName developer wechat id FromUserName Sender account (an OpenID) CreateTime Message creation time (integer) MsgType Message type, event event type, Longitude Precision Longitude Precision of geographical LOCATIONCopy the code

The OnEvent_LocationRequest event code needs to be rewritten to report the location event.

public override IResponseMessageBase OnEvent_LocationRequest(RequestMessageEvent_Location requestMessage) { Var responseMessage = CreateResponseMessage<ResponseMessageText>(); Responsemessage.content = "God loves you!" ; return responseMessage; // You can also return null (note the issue of null when writing logs)}Copy the code

Reporting geographical location is very useful. It can be used to obtain city code by dimension and longitude, call weather Api, and monitor the location of employees for wechat attendance. In wechat operation, user location or we carry out marketing planning, advertising campaigns, user precision marketing is an important basis.

Refer to the article

Wechat public platform technical document – official

Senparc.Weixin SDK + official website example source code

RDIFramework.NET – Based. NET rapid information system development framework – series directory

RDIFramework.NET ━.NET Rapid information system development framework ━ Workflow components

RDIFramework.NET SOA solution (distributed as Windows services, WinForm and IIS) – distributed applications

RDIFramework.NET code generator new V3.5 release – major upgrade


Over the years, thanks to supporters and users of the RDIFramework.NET framework, you can find out more at the following address.

RDIFramework.NET official website: www.rdiframework.net/

RDIFramework.NET official blog: blog.rdiframework.net/

At the same time need to explain, all technical articles in the future to the official website prevail, welcome everyone to collect!

RDIFramework.NET framework has been developed by a professional team for a long time, and is always updated and upgraded. Please feel free to use it!

Please follow the official wechat account of RDIFramework.net (wechat id: Guosisoft) to keep abreast of the latest developments.

Scan the QR code for immediate attention