Home  >  Article  >  Backend Development  >  c# uses WeChat interface to develop WeChat portal application

c# uses WeChat interface to develop WeChat portal application

高洛峰
高洛峰Original
2017-01-17 10:58:231271browse

WeChat applications are in full swing, and many companies hope to get on the information express. This is a business opportunity and a technical direction. Therefore, researching and learning about WeChat-related development when you have time has become one of the important things in daily plans. One. This series of articles hopes to comprehensively introduce the relevant development process and related experience summary of WeChat from a step-by-step perspective, hoping to give everyone an understanding of the relevant development process. This essay mainly focuses on the preliminary preparation of the WeChat development process and the introduction of some initial work.

In the week before writing this article, I mainly referred to some introductory articles and related interface instructions of the WeChat public platform, combined with C# code development, to sort out my company's portal interface and implement WeChat The preliminary user interaction and information display work of the work account. As the work further develops, more and more functions may be added, and I hope to expand the WeChat interface from an application perspective, so as to realize my technical exploration and understanding of the WeChat interface. .

1. WeChat account

To develop and use WeChat’s platform API, you need to register on WeChat’s public platform (https://mp.weixin.qq.com/) and have a Service account or subscription account. Service account is mainly for enterprises and organizations. Subscription account is mainly for organizations and individuals. There are certain differences between them. You can apply for the corresponding account according to different needs.

In order to use some advanced interfaces, you may need to have a service account and advanced authentication. In the account registration process, you need to download an application form, print it and stamp it with the official seal. In addition, the applicant needs to take a photo with the ID card (a bit weird, haha), and then upload it to the server for review. Generally, the approval can be obtained quickly.

I applied for a service account in the name of the company. After the account is registered, your relevant information will be displayed on the main interface. In addition, a QR code will be applied for you. Scan the QR code to enter the company's account. WeChat follows the confirmation dialog box, which is very convenient. The following is the QR code of my company account after I applied, which can be scanned directly.

c# uses WeChat interface to develop WeChat portal application

2. WeChat menu definition

WeChat has two ways of menu definition, one is the editing mode and the other is the development mode. The two interact with each other. Exclusion, that is to say, once we adopt the development mode, we cannot use the editing mode, and vice versa. The menu under editing can actually be managed, but WeChat does not support it, which makes me feel very unhappy.

Under normal circumstances, if we have just applied for a WeChat number, we can use the edit menu to test it and edit some menus according to the instructions. Although WeChat says it will be updated within 24 hours, it is usually updated very quickly, maybe within a minute or two at the fastest, which feels good.

To use developer mode, you need to place a page link on the server according to the requirements of WeChat. If you use C# to develop, you can use the naming method of ***.ashx and use the general processing program of Asp.NET That’s it, no need to use a normal page.

Using the development mode menu, that is, you can call the WeChat API to create the menu. For calling the WeChat API (WeChat has many APIs that can be called), we need to know the importance of several parameters. So when the development mode is turned on, these parameters will be listed for you, as shown below.

c# uses WeChat interface to develop WeChat portal application

3. Link processing to access WeChat

As mentioned above, when you apply for development mode to make menu or other API calls, you need to pass it smoothly The test of accessing WeChat is to confirm that the link you filled in exists and can successfully pass WeChat's callback test. WeChat provides an example of PHP page processing. If we develop it in C#, we can search and we will get the answer. My processing method is as follows.

Create a general processing program, and then add a processing logic to its processing page. If it is non-POST content, it means the Get test performed by WeChat. You need to add some processing logic and give it to your Just transfer the content back. If it is in POST mode, it is the WeChat server's request operation for the interface message, which will be introduced later.

/// <summary>
    /// 微信接口。统一接收并处理信息的入口。
    /// </summary>
    public class wxapi : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string postString = string.Empty;
            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);
                }
            }
            else
            {
                Auth(); //微信接入的测试
            }
        }

Generally speaking, in the Auth function, the relevant parameters are obtained, and then processed and returned to the WeChat server.

string token = "****";//你申请的时候填写的Token
string echoString = HttpContext.Current.Request.QueryString["echoStr"];
string signature = HttpContext.Current.Request.QueryString["signature"];
string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
string nonce = HttpContext.Current.Request.QueryString["nonce"];

The complete Author function code is as follows, in which I further extracted the business logic into a new class to facilitate the management of business logic.

/// <summary>
        /// 成为开发者的第一步,验证并相应服务器的数据
        /// </summary>
        private void Auth()
        {
            string token = ConfigurationManager.AppSettings["WeixinToken"];//从配置文件获取Token
            if (string.IsNullOrEmpty(token))
            {
                LogTextHelper.Error(string.Format("WeixinToken 配置项没有配置!"));
            }
            string echoString = HttpContext.Current.Request.QueryString["echoStr"];
            string signature = HttpContext.Current.Request.QueryString["signature"];
            string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
            string nonce = HttpContext.Current.Request.QueryString["nonce"];
            if (new BasicApi().CheckSignature(token, signature, timestamp, nonce))
            {
                if (!string.IsNullOrEmpty(echoString))
                {
                    HttpContext.Current.Response.Write(echoString);
                    HttpContext.Current.Response.End();
                }
            }
        }

The code for signing and returning the WeChat parameter CheckSignature is as follows

/// <summary>
        /// 验证微信签名
        /// </summary>
        public bool CheckSignature(string token, string signature, string timestamp, string nonce)
        {
            string[] ArrTmp = { token, timestamp, nonce };
            Array.Sort(ArrTmp);
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

4. Use the development method to create the menu


Once you successfully pass WeChat's authentication, it will allow you to call its API in development mode and create your menu at will.

To create a menu, you can enter its API processing interface through the following location.

c# uses WeChat interface to develop WeChat portal application

After entering, you will find that WeChat has divided the processing of many messages into different categories.

c# uses WeChat interface to develop WeChat portal application

For more c# related articles using WeChat interface to develop WeChat portal applications, please pay attention to the PHP Chinese website!

Statement:
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