Home WeChat Applet WeChat Development Take you to analyze WeChat development from the source code

Take you to analyze WeChat development from the source code

May 05, 2017 am 10:49 AM

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

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

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

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

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

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.

1

2

3

4

5

6

7

switch (msgType)

{                case "text":

        {

        }                case "event":

        {

        }                default:                    return Tools.GetReturn("error");

}

Copy after login

 e, all the codes are here:

1

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

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

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

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tutorial on updating curl version under Linux! Tutorial on updating curl version under Linux! Mar 07, 2024 am 08:30 AM

To update the curl version under Linux, you can follow the steps below: Check the current curl version: First, you need to determine the curl version installed in the current system. Open a terminal and execute the following command: curl --version This command will display the current curl version information. Confirm available curl version: Before updating curl, you need to confirm the latest version available. You can visit curl's official website (curl.haxx.se) or related software sources to find the latest version of curl. Download the curl source code: Using curl or a browser, download the source code file for the curl version of your choice (usually .tar.gz or .tar.bz2

Linux kernel source code storage path analysis Linux kernel source code storage path analysis Mar 14, 2024 am 11:45 AM

The Linux kernel is an open source operating system kernel whose source code is stored in a dedicated code repository. In this article, we will analyze the storage path of the Linux kernel source code in detail, and use specific code examples to help readers better understand. 1. Linux kernel source code storage path The Linux kernel source code is stored in a Git repository called linux, which is hosted at [https://github.com/torvalds/linux](http

How to view java source code How to view java source code Dec 27, 2023 pm 04:41 PM

View steps: 1. Find the installation directory or view online; 2. Unzip the source code; 3. Use a text editor or integrated development environment; 4. Navigate and view the source code. Detailed introduction: 1. Find the installation directory or view online: If JDK is installed, you can find the Java source code in the JDK installation directory. In the JDK installation directory, there is usually a src.zip or similar compressed file, which contains the source code of the Java core class library; it is also possible to view the Java source code online, etc.

How to view Tomcat source code How to view Tomcat source code Jan 25, 2024 pm 01:56 PM

Steps to view the Tomcat source code: 1. Download the Tomcat source code; 2. Import the Tomcat source code in IDEA; 3. View the source code; 4. Understand the working principle of Tomcat; 5. Participate in the community and contribute; 6. Precautions; 7. Continuously learn and update; 8. Use tools and plug-ins. Detailed introduction: 1. To download the Tomcat source code, you first need to obtain the source code of Tomcat. You can download the source code package from the official website of Apache Tomcat, etc.

What is the suffix of java source code? What is the suffix of java source code? Dec 27, 2023 pm 04:31 PM

In Java, the suffix for source code files is usually .java. When writing a Java program, a source code file with a .java suffix is ​​created, which contains the Java source code. For example, a simple Java source code file could be named MyClass.java, where MyClass is the name of the class and .java is the suffix of the file.

PHP WeChat development: How to implement message encryption and decryption PHP WeChat development: How to implement message encryption and decryption May 13, 2023 am 11:40 AM

PHP is an open source scripting language that is widely used in web development and server-side programming, especially in WeChat development. Today, more and more companies and developers are starting to use PHP for WeChat development because it has become a truly easy-to-learn and easy-to-use development language. In WeChat development, message encryption and decryption are a very important issue because they involve data security. For messages without encryption and decryption methods, hackers can easily obtain the data, posing a threat to users.

An in-depth exploration of the Linux kernel source code distribution An in-depth exploration of the Linux kernel source code distribution Mar 15, 2024 am 10:21 AM

This is a 1500-word article that explores the Linux kernel source code distribution in depth. Due to limited space, we will focus on the organizational structure of the Linux kernel source code and provide some specific code examples to help readers better understand. The Linux kernel is an open source operating system kernel whose source code is hosted on GitHub. The entire Linux kernel source code distribution is very large, containing hundreds of thousands of lines of code, involving multiple different subsystems and modules. To gain a deeper understanding of the Linux kernel source code

How can you understand the design principles and goals behind the latest PHP code specification by reading its source code? How can you understand the design principles and goals behind the latest PHP code specification by reading its source code? Sep 05, 2023 pm 02:46 PM

How can you understand the design principles and goals behind the latest PHP code specification by reading its source code? Introduction: When writing high-quality PHP code, it is very important to follow certain coding standards. Through code specifications, the readability, maintainability and scalability of the code can be improved. For the PHP language, there is a widely adopted code specification, namely PSR (PHPStandardsRecommendations). This article will introduce how to read the source code of the latest PHP code specification

See all articles