Home Backend Development C#.Net Tutorial c# uses WeChat interface to develop WeChat portal application

c# uses WeChat interface to develop WeChat portal application

Jan 17, 2017 am 10:58 AM

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(); //微信接入的测试
            }
        }
Copy after login

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"];
Copy after login

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();
                }
            }
        }
Copy after login

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;
            }
        }
Copy after login

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 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)

How to use various symbols in C language How to use various symbols in C language Apr 03, 2025 pm 04:48 PM

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

What is the role of char in C strings What is the role of char in C strings Apr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

How to handle special characters in C language How to handle special characters in C language Apr 03, 2025 pm 03:18 PM

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

The difference between char and wchar_t in C language The difference between char and wchar_t in C language Apr 03, 2025 pm 03:09 PM

In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

How to convert char in C language How to convert char in C language Apr 03, 2025 pm 03:21 PM

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

How to use char array in C language How to use char array in C language Apr 03, 2025 pm 03:24 PM

The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

See all articles