search
HomeBackend DevelopmentC#.Net Tutorialc# uses WeChat interface to develop WeChat portal application

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
From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C# .NET Interview Questions & Answers: Level Up Your ExpertiseC# .NET Interview Questions & Answers: Level Up Your ExpertiseApr 07, 2025 am 12:01 AM

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.