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

An example Analysis of the SDK process of Wechat Public platform

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

Share

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

Editor to share with you the Wechat public platform SDK process example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to understand it!

Service number description: to provide enterprises and organizations with more powerful business services and user management capabilities to help enterprises quickly achieve a new official account service platform.

.net SDK: Loogn.WeiXinSDK (net2.0 source code, the following code is only approximate, not quite correct, please download the source code yourself)

As I still use NOKIA-C5, have not used Wechat, the knowledge of Wechat is certainly not as much as you, but the company has demand, so I have to look at the interface document directly.

It is also interesting to find that a very useful function is that when a user sends a message to a public account, the program can automatically reply to the user according to the content sent by the user, such as sending a shipping order number to the public account of a logistics company.

The other party automatically replies to the logistics details of your waybill number, which feels pretty cool! For ease of explanation, first give the information of the applied public account:

The following figure shows the message flow in which the logistics details are viewed above (the number of the dotted line indicates the order of the process):

Wechat will send two types of messages to your URL:

One is the general message of the user, such as the waybill number sent by the user above.

The other is the user's behavior (that is, the events mentioned in the document), such as following your public account, scanning the QR code of the public account, clicking on your custom menu, etc.

Your URL can respond according to the type and content of the message received to achieve powerful business services, such as the logistics details returned above. Messages are all delivered in XML format, and what SDK does is convert XML into .NET objects to make it easy for you to write business logic. The frame class diagram of the message is shown as (Click to see the full diagram including subclasses):

First, there is a message base class, followed by received messages (RecEventBaseMsg) and replied messages (ReplyBaseMsg). As mentioned above, received messages can be divided into two categories, namely, general messages (RecBaseMsg) and event messages (EventBaseMsg). The types of messages received can be:

Not to mention other types, but when MsgType is Event, the message is a subclass of EventBaseMsg, and the MsgType of all subclasses of EventBaseMsg is Event, so the EventBaseMsg type has an EventType to distinguish different events. If you have read the interface document, you should know that its event type is not friendly to us to judge which event it is. Scanning the QR code event divides the user's attention and non-attention into two cases. When you have paid attention, EvenType is scan. EventType is subscribe when not followed, and the EventType that users follow the event is also subscribe, so a MyEventType is added to the SDK:

Now the process of the message is basically clear. The reply message calling SDK is as follows:

Using System.Web;using Loogn.WeiXinSDK;using Loogn.WeiXinSDK.Message;namespace WebTest {static string Token / Wechat-> Server configuration URL / public class WeiXinAPI: IHttpHandler {static string Token = "Token"; / / here is Token, not Access_Token public void ProcessRequest (HttpContext context) {context.Response.ContentType = "text/plain"; var signature = context.Request ["signature"] Var timestamp = context.Request ["timestamp"]; var nonce = context.Request ["nonce"] If (WeiXin.CheckSignature (signature, timestamp, nonce, Token)) / / Verification is a message sent to you by Wechat {/ / reply to the registered message and event handler, / / if you get a message or event that is useless for registration ReplyEmptyMsg.Instance is returned, that is, GetXML () is string.Empty, which meets the requirement of Wechat: var replyMsg = WeiXin.ReplyMsg () Var xml = replyMsg.GetXML (); / / WriteLog (xml); / / you can view the reply XML message context.Response.Write (xml) here;} else {context.Response.Write ("fuck you!") }} static WeiXinAPI () {WeiXin.ConfigGlobalCredential ("appid", "appSecret"); / / register a message handler. When the user sends "ABC", you reply "you say: ABC" WeiXin.RegisterMsgHandler ((msg) = > {return new ReplyTextMsg {Content = "you say:" + msg.Content / / FromUserName = msg.ToUserName, this is the default, no need to set it! / / ToUserName = msg.FromUserName. This is the default, and there is no need to set it! / / CreateTime = DateTime.Now.Ticks this is the default, no need to set it! };}); / / register an event handler that users follow, and when users follow your public account, you reply "Hello!" WeiXin.RegisterEventHandler ((msg) = > {return new ReplyTextMsg {Content = "Hello!"};}) / / you can continue to register messages and event handlers that interest you} public bool IsReusable {get {return false;}.

SDK contains the encapsulation of all interfaces except (OAuth3.0 web page authorization). The class name and method name are obvious. We will not demonstrate them one by one here. Interested friends can download dll for self-testing. This is a paid-for-authenticated interface diagram:

Let's talk about a few details of the implementation:

I. expired credentials (access_token)

"access_token is the only global ticket for the official account. Access_token is required when the official account calls each API. Normally, the access_token is valid for 7200 seconds. Repeated acquisition will invalidate the last acquired access_token. The official account can use AppID and AppSecret to call this API to obtain access_token. AppID and AppSecret can be obtained in the development mode (you need to have become a developer and the account has no abnormal status)."

According to the document, we can think of caching (it is impossible to use it every time! Caching code is very simple, mainly to be able to think of caching in this case, here is the incomplete code:

Access_token {; expires_in {; Dictionary creds = Dictionary TokenUrl = Credential GetCredential (appId, = (creds.TryGetValue (appId, (cred.add_time.AddSeconds (cred.expires_in -) 0) {return Util.JsonTo (json);} else {QRCodeTicket tk = new QRCodeTicket () Tk.error = Util.JsonTo (json); return tk;}

So after calling the interface with SDK, the resulting object can be easily judged:

Var qrcode = WeiXin.CreateQRCode (true, 23); if (qrcode.error = = null) {/ / returns an error. You can use qrcode.error to view the error message} else {/ / return correct, and you can operate qrcode.ticket}

III. Deserialization

The json returned by the Wechat API is sometimes not very direct for us to map to objects (the json format is too flexible! ), such as the json returned after the grouping is successfully created:

{"group": {"id": 107, "name": "test"}}

If you want to deserialize an object directly using json, the definition of the object's class might look like this:

Public class GroupInfo {public Group group {get; set;} public class Group {public int id {get; set;} public string name {get; set;}

When visiting, it will also be gp.group.name, so I say it's not very straightforward. The definition of the class we want must only look like the subclass above:

Public class GroupInfo {public int id {get; set;} public string name {get; set;}}

If the Wechat API returns something like this:

{"id": 107, "name": "test"}

It couldn't be better, but we can't change other people's code, so we have to figure it out ourselves.

1, to simple classes, 2 do not manually analyze json (such as regular), 3, do not want to define one more class, do you think of a good way? If there is any, you can reply to me, and I choose to use a dictionary to do the intermediate conversion.

Because almost all json formats can be deserialized into dictionaries (nested dictionaries, nested dictionary collections, etc.), for example, the json returned by Wechat above can be represented by the following types:

Dictionary

Json--- > dict--- > GroupInfo

Var dict = Util.JsonTo (json); var gi = new GroupInfo (); var gpdict = dict ["group"]; gi.id = Convert.ToInt32 (gpdict ["id"]); gi.name = gpdict ["name"] .ToString ()

IV. Optimization of message processing

"everything is simple for beauty", I am a programmer who likes simplicity very much. Still remember the first message (events belong to messages, here collectively referred to as messages) processing, I think it is very simple, which message needs to be processed to register the message handler. But this is not the case at the beginning. At the beginning, you have to manually determine the message type, like:

Using System.Web;using Loogn.WeiXinSDK;using Loogn.WeiXinSDK.Message;namespace WebTest {static string Token / Wechat-> Server configuration URL / public class WeiXinAPI: IHttpHandler {static string Token = "Token"; / / here is Token, not Access_Token public void ProcessRequest (HttpContext context) {context.Response.ContentType = "text/plain"; var signature = context.Request ["signature"] Var timestamp = context.Request ["timestamp"]; var nonce = context.Request ["nonce"] If (WeiXin.CheckSignature (signature, timestamp, nonce Token) / / verify that the message sent to you by Wechat {var replyMsg = WeiXin.ReplyMsg ((recEvtMsg) = > {switch (recEvtMsg.MsgType) {case MsgType.text: { Var msg = recEvtMsg as RecTextMsg / / to make a transition here, please return new ReplyTextMsg {Content = "you say:" + msg.Content} } case MsgType.Event: {var evtMsg = recEvtMsg as EventBaseMsg / / to switch to the basics of event messages here, please switch (evtMsg.MyEventType) {case MyEventType.Attend: var msg = evtMsg as EventAttendMsg / / this line of code is not required for this example, but other message contents need to be transformed. Please return new ReplyTextMsg {Content = "Hello!"} Default: break;} break } default: break;} return ReplyEmptyMsg.Instance; / / nested switch, and there are several per case, which is not elegant}; var xml = replyMsg.GetXML () / / WriteLog (xml); / / you can check the reply XML message context.Response.Write (xml);} else {context.Response.Write ("fuck you!") }} public bool IsReusable {get {return false;}

When making optimization, first try to see if you can do something on MsgType and MyEventType, such as passing in two parameters: MsgType and lamba when registering:

Public static void RegisterMsgHandler (MsgType type, Func handler) {/ / add handler}

This does work, but you still have to manually convert the type when you call SDK registration:

WeiXin.RegisterMsgHandler (MsgType.text, (recEvtMsg) = > msg = recEvtMsg ReplyTextMsg {Content = +

So can you write one for each subtype?

Public static void RegisterMsgHandler (MsgType type, Func handler) {/ / add handler} public static void RegisterMsgHandler (MsgType type, Func handler) {/ / add handler} /.

The definition is OK, let's take a look at the call:

/ can RegisterMsgHandler (MsgType.text, new Func ((msg) = > {return new ReplyTextMsg {Content = "you say:" + msg.Content};}); / / can RegisterMsgHandler (MsgType.text, new Func ((msg) = > {return new ReplyTextMsg {Content = "your picture:" + msg.PicUrl};}) / / Yes, note that the msg smart prompt here is RecTextMsg type RegisterMsgHandler (MsgType.text, (msg) = > {return new ReplyTextMsg {Content = "you say:" + msg.Content};}); / / Yes, note that the msg smart prompt is still RecTextMsg type, but using type inference, the runtime can determine that it is RecImageMsg, so you can RegisterMsgHandler (MsgType.text, (msg) = > {return new ReplyTextMsg {Content = "your picture:" + msg.PicUrl};})) / / No, note that the smart prompt of msg is still of type RecTextMsg, but there is no attribute of a specific subclass of msg in lamba body, so the type cannot be inferred, so call unknown RegisterMsgHandler (MsgType.text, (msg) = > {return new ReplyTextMsg {Content = "you sent a message"};})

As can be seen from the above call, if you want to call with this method, you can't use lamba expression at will. I don't want to! Finally, it's done with generics.

Public static void RegisterMsgHandler (Func handler) where TMsg: RecBaseMsg {var type = typeof (TMsg); var key = string.Empty; if (type = = typeof (RecTextMsg)) {key = MsgType.text.ToString ();} else if (type = = typeof (RecImageMsg)) {key = MsgType.image.ToString () } else if (type = = typeof (RecLinkMsg)) {key = MsgType.link.ToString ();} else if (type = = typeof (RecLocationMsg)) {key = MsgType.location.ToString () } else if (type = = typeof (RecVideoMsg)) {key = MsgType.video.ToString ();} else if (type = = typeof (RecVoiceMsg)) {key = MsgType.voice.ToString ();} else {return } m _ msgHandlers [key] = (Func) handler;}

With this transformation, we can register with concise lamba expressions as we did at the beginning.

The above is all the contents of the article "sample Analysis of the SDK process on Wechat Public platform". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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