Take you to analyze WeChat development from the source code

Y2J
Release: 2017-05-05 10:49:29
Original
1789 people have browsed it

In the past two days, the project needed to open an interface on WeChat, so I studied it. The process was very difficult, but the results were ideal. Now I will introduce what needs to be paid attention to in WeChat development.

1, account problem

/* First of all, you have to choose the public platform (the open platform seems to be for application integration, I haven’t studied this carefully. If anyone knows, please let me know.) On the public platform, we need to register an account. There are two types of accounts, personal type and corporate type. Among them, personal type can only apply for a subscription number, while corporate type Only then can you get a service account. Subscription accounts can only be done manually or by configuring some keywords. Service accounts can deploy some smart stuff. Advanced development permissions are required only for service accounts. So if you are an individual and want to target Reply to messages sent by users with different content, then go to sleep. */

Anyone who is engaged in development knows the meaning of the above paragraph. Yes, I commented it. When I logged in to the subscription account today, I found that the subscription account also has advanced functions. Maybe I didn’t have them at that time. Pass the review, OK, it does not hinder the sharing below.

2, development mode

It’s very simple. When you get your service account, you will find that there are There is an advanced function (there is no advanced function option in the subscription account), and you can choose which method to activate it later. Currently only one can be started for development and editing.

3, Configuration Server

The WeChat interface has only one URL, and any data is connected to you through this URL The server needs to use this interface to connect (GET or POST). The following will talk about two places where it is used.

4, Verify server

After filling in your server URL, WeChat will bring several parameters to access your URL. You only need to return specific data. For specific methods, you can also check this link: http://mp.weixin.qq.com/wiki/index.php?title=%E6%8E%A5%E5%85%A5 %E6%8C%87%E5%8D%97

There are some PHP codes in the connection for reference. I will post my code below. I have taken many detours here, so I try my best. Post it in full

 1         /// <summary> 2         /// 验证微信签名 3         /// </summary> 4         /// <param name="sigNature">微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。</param> 5         /// <param name="timestamp">时间戳</param> 6         /// <param name="nonce">随机数</param> 7         /// <param name="echoStr">随机字符串</param> 8         /// <returns>开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。</returns> 9         [System.Web.Http.AcceptVerbs("GET")]10         [System.Web.Http.ActionName("Api")]11         [ApiExplorerSettings(IgnoreApi = false)]12         public HttpResponseMessage CheckSignature(string sigNature, string timestamp, string nonce, string echoStr)13         {14             var content =15                    string.Format("SigNature:{0}\nTimestamp:{1}\nNonce:{2}\nEchoStr:{3}",16                                  sigNature, timestamp, nonce, echoStr);17             logger.Debug(content);    // 此处的log你可以删掉18 19             var list = new string[] { timestamp, nonce, TOKEN };20             Array.Sort(list);21             var tmpArr = string.Join("", list);22             var tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpArr, "SHA1").ToLower();23 24             if (tmpStr == sigNature && !string.IsNullOrEmpty(echoStr))     //根据微信的验证规则做判断25                 return Tools.GetReturn(echoStr);26 27             return Tools.GetReturn("error");28         }
Copy after login

The reason why I wrote the GetReturn function is because MVC encapsulates my results. Every time I return a string, it A pair of quotation marks will be added to the outer layer, and WeChat is still stupid enough not to recognize it. . . . This function is mainly to remove the MVC encapsulation for me

1      public static HttpResponseMessage GetReturn(string message)2         {3             return new HttpResponseMessage4                 {5                     Content = new StringContent(message, Encoding.UTF8, "text/html")6                 };7         }
Copy after login

The CheckSignature above is a GET interface, which is mainly used to verify the WeChat service.

Of course, if you carefully study what WeChat said, you can also find that when When you receive echoStr, it's OK to just return it without going through extra verification steps.

5, message receiving interface

I only focused on one function, when user

sends message Sometimes I want to reply to user messages, and it’s OK to only focus on text messages (in fact, the principles of other types of messages are similar).

We need to pay attention to a few points here:

a. The ActionName of this interface is the same as the interface verified above. In this way, they use the same URL when accessed from the outside. The method is just different.

1         [System.Web.Http.AcceptVerbs("POST")]2         [System.Web.Http.ActionName("Api")]3         [ApiExplorerSettings(IgnoreApi = false)]4         public HttpResponseMessage ReceiveMessage()
Copy after login

 b, I have been researching this method of obtaining message content for a long time before I found it, and it took a lot of effort.

1   var message = Request.Content.ReadAsStringAsync().Result;
Copy after login

c. He POSTed a lot of

variables in this interface. I used regular expressions to get them for him.

1             var toUserName = GetItemValue(message, ToUserNameReg);2             var fromUserName = GetItemValue(message, FromUserNameReg);3             var createTime = GetItemValue(message, CreateTimeReg);4             var msgType = GetItemValue(message, MsgTypeReg);5             var content = GetItemValue(message, ContentReg);6             var msgId = GetItemValue(message, MsgIdReg);7             var eventStr = GetItemValue(message, EventReg);8             var eventKey = GetItemValue(message, EventKeyReg);
Copy after login

d. I only pay attention to two types of them.

Event: event and text, the event is worthy of attention and unfollowing, and it is necessary to express gratitude when paying attention; for the text sent, I need to find the content of the reply.

            switch (msgType)
            {                case "text":
                    {
                    }                case "event":
                    {
                    }                default:                    return Tools.GetReturn("error");
            }
Copy after login

 e, all the codes are here:

1         private static readonly Regex ToUserNameReg = new Regex(@"(?<=<ToUserName><!\[CDATA\[).*?(?=\]\]></ToUserName>)", RegexOptions.Compiled);2         private static readonly Regex FromUserNameReg = new Regex(@"(?<=<FromUserName><!\[CDATA\[).*?(?=\]\]></FromUserName>)", RegexOptions.Compiled);3         private static readonly Regex CreateTimeReg = new Regex(@"(?<=<CreateTime>)\d*?(?=</CreateTime>)", RegexOptions.Compiled);4         private static readonly Regex MsgTypeReg = new Regex(@"(?<=<MsgType><!\[CDATA\[).*?(?=\]\]></MsgType>)", RegexOptions.Compiled);5         private static readonly Regex ContentReg = new Regex(@"(?<=<Content><!\[CDATA\[).*?(?=\]\]></Content>)", RegexOptions.Compiled);6         private static readonly Regex MsgIdReg = new Regex(@"(?<=<MsgId>)\d*?(?=</MsgId>)", RegexOptions.Compiled);7         private static readonly Regex EventReg = new Regex(@"(?<=<Event><!\[CDATA\[).*?(?=\]\]></Event>)", RegexOptions.Compiled);8         private static readonly Regex EventKeyReg = new Regex(@"(?<=<EventKey><!\[CDATA\[).*?(?=\]\]></EventKey>)", RegexOptions.Compiled);
Copy after login
 1      /// <summary> 2         /// 接受微信消息,如果需要反馈,则调用回复接口进行答复 3         /// </summary> 4         /// <param name="ToUserName">开发者微信号</param> 5         /// <param name="FromUserName">发送方帐号(一个OpenID)</param> 6         /// <param name="CreateTime">消息创建时间 (整型)</param> 7         /// <param name="MsgType">text</param> 8         /// <param name="Content">文本消息内容</param> 9         /// <param name="MsgId">消息id,64位整型</param>10         /// <returns>successful or not</returns>11         [System.Web.Http.AcceptVerbs("POST")]12         [System.Web.Http.ActionName("Api")]13         [ApiExplorerSettings(IgnoreApi = false)]14         public HttpResponseMessage ReceiveMessage()15         {16             var message = Request.Content.ReadAsStringAsync().Result;17 18             var toUserName = GetItemValue(message, ToUserNameReg);19             var fromUserName = GetItemValue(message, FromUserNameReg);20             var createTime = GetItemValue(message, CreateTimeReg);21             var msgType = GetItemValue(message, MsgTypeReg);22             var content = GetItemValue(message, ContentReg);23             var msgId = GetItemValue(message, MsgIdReg);24             var eventStr = GetItemValue(message, EventReg);25             var eventKey = GetItemValue(message, EventKeyReg);26 27             var logStr = string.Format("Message:{8}\n\nToUserName:{0}\nFromUserName:{1}\nCreateTime:{2}\nMsgType:{3}\nContent:{4}\nMsgId:{5}\nEvent:{6}\nEventKey:{7}",28                         toUserName, fromUserName, createTime, msgType, content, msgId, eventStr, eventKey, message);29             logger.Debug(logStr);30 31             switch (msgType)32             {33                 case "text":34                     {35                         var returnMessage = Tools.GetCategory(content);  // 这块是获取反馈信息的方法,你的和我的应该不一样,所以这块你得修改一下。36                         var sendMessage = GetSendMessage(fromUserName, returnMessage, toUserName);37                         logger.Debug("MsgId:" + msgId + Environment.NewLine + sendMessage);38 39                         return Tools.GetReturn(sendMessage);        // 这个函数在上面已经贴出来了,在这块就不在贴了40                     }41                 case "event":42                     {43                         if (eventStr == "subscribe")      // 关注事件44                         {45                             var returnMessage = "欢迎关注**账号 [微笑]";46                             var sendMessage = GetSendMessage(fromUserName, returnMessage, toUserName);47                             return Tools.GetReturn(sendMessage);48                         }49                         return Tools.GetReturn("error");50                     }51                 default:52                     return Tools.GetReturn("error");53             }54         }
Copy after login
 1      /// <summary> 2         /// 获取消息体中正则所能匹配到的内容 3         /// </summary> 4         /// <param name="message">消息内容</param> 5         /// <param name="regex">正则</param> 6         /// <returns>返回正则匹配的所有内容</returns> 7         [ApiExplorerSettings(IgnoreApi = true)] 8         private string GetItemValue(string message, Regex regex) 9         {10             if(regex.IsMatch(message))11                 return regex.Match(message).Value;12             return "";13         }
Copy after login
 1 /// <summary> 2         /// 发送被动响应消息 3         /// </summary> 4         /// <param name="ToUserName">接收方帐号(收到的OpenID)</param> 5         /// <param name="Content">回复的消息内容(换行:在content中能够换行,微信客户端就支持换行显示)</param> 6         /// <param name="FromUserName">开发者微信号</param> 7         /// <param name="CreateTime">消息创建时间 (整型)</param> 8         /// <param name="MsgType">text</param> 9         /// <returns></returns>10         [System.Web.Http.AcceptVerbs("POST")]11         [System.Web.Http.ActionName("GetSendMessage")]12         [ApiExplorerSettings(IgnoreApi = false)]13         public string GetSendMessage(string ToUserName, string Content, string FromUserName = Developer,14                                      string MsgType = "text")15         {16             var createTime = Tools.ConvertDateTimeToInt(DateTime.Now);17 18             return19                 string.Format(@"<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[{3}]]></MsgType><Content><![CDATA[{4}]]></Content></xml>", ToUserName, FromUserName, createTime, MsgType, Content);20         }
Copy after login
[Related recommendations]

1.

WeChat public account platform source code download

2.

Xiaozhu CMS Life Tong O2O system v2.0 exclusive version download

The above is the detailed content of Take you to analyze WeChat development from the source code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template