


.NET WeChat development public account message processing code example
Apr 25, 2017 am 11:25 AM1. Foreword
The message processing of the WeChat public platform is relatively complete, including the most basic text messages, graphic messages, picture messages, voice messages, video messages, and music messages. The basic principles are the same, but the XML data posted is different. Before processing the message, we must carefully read the official document given to us: mp.weixin.qq.com/wiki/14/89b871b5466b19b3efa4ada8e577d45e.html . First we start with the most basic text message processing.
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[你好]]></Content> </xml>
We can see that this is the most basic pattern of message processing, with sender, receiver, creation time, type, content, etc.
First we create a message processing class. This class is used to capture all message requests and process different message replies according to different message request types.
public class WeiXinService { /// <summary> /// TOKEN /// </summary> private const string TOKEN = "finder"; /// <summary> /// 簽名 /// </summary> private const string SIGNATURE = "signature"; /// <summary> /// 時(shí)間戳 /// </summary> private const string TIMESTAMP = "timestamp"; /// <summary> /// 隨機(jī)數(shù) /// </summary> private const string NONCE = "nonce"; /// <summary> /// 隨機(jī)字符串 /// </summary> private const string ECHOSTR = "echostr"; /// <summary> /// /// </summary> private HttpRequest Request { get; set; } /// <summary> /// 構(gòu)造函數(shù) /// </summary> /// <param name="request"></param> public WeiXinService(HttpRequest request) { this.Request = request; } /// <summary> /// 處理請(qǐng)求,產(chǎn)生響應(yīng) /// </summary> /// <returns></returns> public string Response() { string method = Request.HttpMethod.ToUpper(); //驗(yàn)證簽名 if (method == "GET") { if (CheckSignature()) { return Request.QueryString[ECHOSTR]; } else { return "error"; } } //處理消息 if (method == "POST") { return ResponseMsg(); } else { return "無法處理"; } } /// <summary> /// 處理請(qǐng)求 /// </summary> /// <returns></returns> private string ResponseMsg() { string requestXml = CommonWeiXin.ReadRequest(this.Request); IHandler handler = HandlerFactory.CreateHandler(requestXml); if (handler != null) { return handler.HandleRequest(); } return string.Empty; } /// <summary> /// 檢查簽名 /// </summary> /// <param name="request"></param> /// <returns></returns> private bool CheckSignature() { string signature = Request.QueryString[SIGNATURE]; string timestamp = Request.QueryString[TIMESTAMP]; string nonce = Request.QueryString[NONCE]; List<string> list = new List<string>(); list.Add(TOKEN); list.Add(timestamp); list.Add(nonce); //排序 list.Sort(); //拼串 string input = string.Empty; foreach (var item in list) { input += item; } //加密 string new_signature = SecurityUtility.SHA1Encrypt(input); //驗(yàn)證 if (new_signature == signature) { return true; } else { return false; } } }
Let’s take a look at how we capture the message first. The code of Default.ashx on the homepage is as follows
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string postString = string.Empty; if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST") { //由微信服務(wù)接收請(qǐng)求,具體處理請(qǐng)求 WeiXinService wxService = new WeiXinService(context.Request); string responseMsg = wxService.Response(); context.Response.Clear(); context.Response.Charset = "UTF-8"; context.Response.Write(responseMsg); context.Response.End(); } else { string token = "wei2414201"; if (string.IsNullOrEmpty(token)) { return; } 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 (!string.IsNullOrEmpty(echoString)) { HttpContext.Current.Response.Write(echoString); HttpContext.Current.Response.End(); } } }
From the above code we can see that the messages in the WeiXinService.cs class are very important.
/// <summary> /// 處理請(qǐng)求 /// </summary> /// <returns></returns> private string ResponseMsg() { string requestXml = CommonWeiXin.ReadRequest(this.Request); IHandler handler = HandlerFactory.CreateHandler(requestXml); if (handler != null) { return handler.HandleRequest(); } return string.Empty; }
IHandler is a message processing interface, under which there is EventHandler, and the TextHandler processing class implements this interface. The code is as follows
/// <summary> /// 處理接口 /// </summary> public interface IHandler { /// <summary> /// 處理請(qǐng)求 /// </summary> /// <returns></returns> string HandleRequest(); }
EventHandler
class EventHandler : IHandler { /// <summary> /// 請(qǐng)求的xml /// </summary> private string RequestXml { get; set; } /// <summary> /// 構(gòu)造函數(shù) /// </summary> /// <param name="requestXml"></param> public EventHandler(string requestXml) { this.RequestXml = requestXml; } /// <summary> /// 處理請(qǐng)求 /// </summary> /// <returns></returns> public string HandleRequest() { string response = string.Empty; EventMessage em = EventMessage.LoadFromXml(RequestXml); if (em.Event.Equals("subscribe", StringComparison.OrdinalIgnoreCase))//用來判斷是不是首次關(guān)注 { PicTextMessage tm = new PicTextMessage();//我自己創(chuàng)建的一個(gè)圖文消息處理類 tm.ToUserName = em.FromUserName; tm.FromUserName = em.ToUserName; tm.CreateTime = CommonWeiXin.GetNowTime(); response = tm.GenerateContent(); } return response; } }
TextHandler
/// <summary> /// 文本信息處理類 /// </summary> public class TextHandler : IHandler { string openid { get; set; } string access_token { get; set; } /// <summary> /// 請(qǐng)求的XML /// </summary> private string RequestXml { get; set; } /// <summary> /// 構(gòu)造函數(shù) /// </summary> /// <param name="requestXml">請(qǐng)求的xml</param> public TextHandler(string requestXml) { this.RequestXml = requestXml; } /// <summary> /// 處理請(qǐng)求 /// </summary> /// <returns></returns> public string HandleRequest() { string response = string.Empty; TextMessage tm = TextMessage.LoadFromXml(RequestXml); string content = tm.Content.Trim(); if (string.IsNullOrEmpty(content)) { response = "您什么都沒輸入,沒法幫您啊。"; } else { string username = System.Configuration.ConfigurationManager.AppSettings["weixinid"].ToString(); AccessToken token = AccessToken.Get(username); access_token = token.access_token; openid = tm.FromUserName; response = HandleOther(content); } tm.Content = response; //進(jìn)行發(fā)送者、接收者轉(zhuǎn)換 string temp = tm.ToUserName; tm.ToUserName = tm.FromUserName; tm.FromUserName = temp; response = tm.GenerateContent(); return response; } /// <summary> /// 處理其他消息 /// </summary> /// <param name="tm"></param> /// <returns></returns> private string HandleOther(string requestContent) { string response = string.Empty; if (requestContent.Contains("你好") || requestContent.Contains("您好")) { response = "您也好~"; }else if (requestContent.Contains("openid") || requestContent.Contains("id") || requestContent.Contains("ID"))//用來匹配用戶輸入的關(guān)鍵字 { response = "你的Openid: "+openid; } else if (requestContent.Contains("token") || requestContent.Contains("access_token")) { response = "你的access_token: " + access_token; }else { response = "試試其他關(guān)鍵字吧。"; } return response; } }
HandlerFactory
/// <summary> /// 處理器工廠類 /// </summary> public class HandlerFactory { /// <summary> /// 創(chuàng)建處理器 /// </summary> /// <param name="requestXml">請(qǐng)求的xml</param> /// <returns>IHandler對(duì)象</returns> public static IHandler CreateHandler(string requestXml) { IHandler handler = null; if (!string.IsNullOrEmpty(requestXml)) { //解析數(shù)據(jù) XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(requestXml); XmlNode node = doc.SelectSingleNode("/xml/MsgType"); if (node != null) { XmlCDataSection section = node.FirstChild as XmlCDataSection; if (section != null) { string msgType = section.Value; switch (msgType) { case "text": handler = new TextHandler(requestXml); break; case "event": handler = new EventHandler(requestXml); break; } } } } return handler; } }
Some basic classes here have been completed, now let’s complete it, follow us WeChat official account, we will send a graphic message, enter some of our keywords, and return some messages, such as entering the id to return the user's openid, etc.
二.PicTextMessage
public class PicTextMessage : Message { /// <summary> /// 模板靜態(tài)字段 /// </summary> private static string m_Template; /// <summary> /// 默認(rèn)構(gòu)造函數(shù) /// </summary> public PicTextMessage() { this.MsgType = "news"; } /// <summary> /// 從xml數(shù)據(jù)加載文本消息 /// </summary> /// <param name="xml"></param> public static PicTextMessage LoadFromXml(string xml) { PicTextMessage tm = null; if (!string.IsNullOrEmpty(xml)) { XElement element = XElement.Parse(xml); if (element != null) { tm = new PicTextMessage(); tm.FromUserName = element.Element(CommonWeiXin.FROM_USERNAME).Value; tm.ToUserName = element.Element(CommonWeiXin.TO_USERNAME).Value; tm.CreateTime = element.Element(CommonWeiXin.CREATE_TIME).Value; } } return tm; } /// <summary> /// 模板 /// </summary> public override string Template { get { if (string.IsNullOrEmpty(m_Template)) { LoadTemplate(); } return m_Template; } } /// <summary> /// 生成內(nèi)容 /// </summary> /// <returns></returns> public override string GenerateContent() { this.CreateTime = CommonWeiXin.GetNowTime(); string str= string.Format(this.Template, this.ToUserName, this.FromUserName, this.CreateTime); return str; } /// <summary> /// 加載模板 /// </summary> private static void LoadTemplate() { m_Template= @"<xml> <ToUserName><![CDATA[{0}]]></ToUserName> <FromUserName><![CDATA[{1}]]></FromUserName> <CreateTime>{2}</CreateTime> <MsgType><![CDATA[news]]></MsgType> <ArticleCount>1</ArticleCount> <Articles> <item> <Title><![CDATA[有位停車歡迎你!]]></Title> <Description><![CDATA[如有問題請(qǐng)致電400-6238-136或直接在微信留言,我們將第一時(shí)間為您服務(wù)!]]></Description> <PicUrl><![CDATA[http://www.baidu.com/youwei.jpg]]></PicUrl> <Url><![CDATA[http://www.baidu.com]]></Url> </item> </Articles> </xml> "; } }
Finally our effect is as follows;
The above is the detailed content of .NET WeChat development public account message processing code example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

Android development is a busy and exciting job, and choosing a suitable Linux distribution for development is particularly important. Among the many Linux distributions, which one is most suitable for Android development? This article will explore this issue from several aspects and give specific code examples. First, let’s take a look at several currently popular Linux distributions: Ubuntu, Fedora, Debian, CentOS, etc. They all have their own advantages and characteristics.

VSCode is a powerful, flexible, and easy-to-extend open source code editor that is widely favored by developers. It supports many programming languages ??and frameworks to meet different project needs. However, the advantages of VSCode may be different for different frameworks. This article will discuss the applicability of VSCode in the development of different frameworks and provide specific code examples. 1.ReactReact is a popular JavaScript library used for building user interfaces. When developing projects using React,

1. The Origin of .NETCore When talking about .NETCore, we must not mention its predecessor .NET. Java was in the limelight at that time, and Microsoft also favored Java. The Java virtual machine on the Windows platform was developed by Microsoft based on JVM standards. It is said to be the best performance Java virtual machine at that time. However, Microsoft has its own little abacus, trying to bundle Java with the Windows platform and add some Windows-specific features. Sun's dissatisfaction with this led to a breakdown of the relationship between the two parties, and Microsoft then launched .NET. .NET has borrowed many features of Java since its inception and gradually surpassed Java in language features and form development. Java in version 1.6
