search
HomeBackend DevelopmentC#.Net TutorialDetailed explanation of asp.net implementation of WeChat public account interface development method

This article is mainly a detailed explanationasp.netImplementing WeChat public accountInterfaceDevelopment method, interested friends can refer to it

Speaking of WeChat public accounts, everyone is familiar with it. Using this platform can add a new highlight to the website or system. Let’s go directly to the topic. Be sure to read the official API carefully before using it. document.
Method implemented using .net:
//WeChat interface address page code:


weixin _wx = new weixin(); 
string postStr = ""; 
if (Request.HttpMethod.ToLower() == "post") 
{ 
Stream s = System.Web.HttpContext.Current.Request.InputStream; 
byte[] b = new byte[s.Length]; 
s.Read(b, 0, (int)s.Length); 
postStr = Encoding.UTF8.GetString(b); 
if (!string.IsNullOrEmpty(postStr)) //请求处理 
{ 
_wx.Handle(postStr); 
} 
} 
else 
{ 
_wx.Auth(); 
}

Specific Processing class


/// <summary> 
/// 微信公众平台操作类 
/// </summary> 
public class weixin 
{ 
private string Token = "my_weixin_token"; //换成自己的token 
public void Auth() 
{ 
string echoStr = System.Web.HttpContext.Current.Request.QueryString["echoStr"]; 
if (CheckSignature()) //校验签名是否正确 
{ 
if (!string.IsNullOrEmpty(echoStr)) 
{ 
System.Web.HttpContext.Current.Response.Write(echoStr); //返回原值表示校验成功 
System.Web.HttpContext.Current.Response.End(); 
} 
} 
} 
 
 
public void Handle(string postStr) 
{ 
//封装请求类 
XmlDocument doc = new XmlDocument(); 
doc.LoadXml(postStr); 
XmlElement rootElement = doc.DocumentElement; 
//MsgType 
XmlNode MsgType = rootElement.SelectSingleNode("MsgType"); 
//接收的值--->接收消息类(也称为消息推送) 
RequestXML requestXML = new RequestXML(); 
requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText; 
requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText; 
requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText; 
requestXML.MsgType = MsgType.InnerText; 
 
//根据不同的类型进行不同的处理 
switch (requestXML.MsgType) 
{ 
case "text": //文本消息 
requestXML.Content = rootElement.SelectSingleNode("Content").InnerText; 
break; 
case "image": //图片 
requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText; 
break; 
case "location": //位置 
requestXML.Location_X = rootElement.SelectSingleNode("Location_X").InnerText; 
requestXML.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText; 
requestXML.Scale = rootElement.SelectSingleNode("Scale").InnerText; 
requestXML.Label = rootElement.SelectSingleNode("Label").InnerText; 
break; 
case "link": //链接 
break; 
case "event": //事件推送 支持V4.5+ 
break; 
} 
 
//消息回复 
ResponseMsg(requestXML); 
} 
 
 
/// <summary> 
/// 验证微信签名 
/// * 将token、timestamp、nonce三个参数进行字典序排序 
/// * 将三个参数字符串拼接成一个字符串进行sha1加密 
/// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。 
/// </summary> 
/// <returns></returns> 
private bool CheckSignature() 
{ 
string signature = System.Web.HttpContext.Current.Request.QueryString["signature"]; 
string timestamp = System.Web.HttpContext.Current.Request.QueryString["timestamp"]; 
string nonce = System.Web.HttpContext.Current.Request.QueryString["nonce"]; 
//加密/校验流程: 
//1. 将token、timestamp、nonce三个参数进行字典序排序 
string[] ArrTmp = { Token, timestamp, nonce }; 
Array.Sort(ArrTmp);//字典排序 
//2.将三个参数字符串拼接成一个字符串进行sha1加密 
string tmpStr = string.Join("", ArrTmp); 
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1"); 
tmpStr = tmpStr.ToLower(); 
//3.开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。 
if (tmpStr == signature) 
{ 
return true; 
} 
else 
{ 
return false; 
} 
} 
 
/// <summary> 
/// 消息回复(微信信息返回) 
/// </summary> 
/// <param name="requestXML">The request XML.</param> 
private void ResponseMsg(RequestXML requestXML) 
{ 
try 
{ 
string resxml = ""; 
//主要是调用数据库进行关键词匹配自动回复内容,可以根据自己的业务情况编写。 
//1.通常有,没有匹配任何指令时,返回帮助信息 
AutoResponse mi = new AutoResponse(requestXML.Content, requestXML.FromUserName); 
 
switch (requestXML.MsgType) 
{ 
case "text": 
//在这里执行一系列操作,从而实现自动回复内容. 
string _reMsg = mi.GetReMsg(); 
if (mi.msgType == 1) 
{ 
resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[news]]></MsgType><Content><![CDATA[]]></Content><ArticleCount>2</ArticleCount><Articles>"; 
resxml += mi.GetRePic(requestXML.FromUserName); 
resxml += "</Articles><FuncFlag>1</FuncFlag></xml>"; 
} 
else 
{ 
resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + _reMsg + "]]></Content><FuncFlag>1</FuncFlag></xml>"; 
} 
break; 
case "location": 
string city = GetMapInfo(requestXML.Location_X, requestXML.Location_Y); 
if (city == "0") 
{ 
resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[好啦,我们知道您的位置啦。您可以:" + mi.GetDefault() + "]]></Content><FuncFlag>1</FuncFlag></xml>"; 
} 
else 
{ 
resxml = "<xml><ToUserName><![CDATA[" + requestXML.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + requestXML.ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[好啦,我们知道您的位置啦。您可以:" + mi.GetDefault() + "]]></Content><FuncFlag>1</FuncFlag></xml>"; 
} 
break; 
case "image": 
//图文混合的消息 具体格式请见官方API“回复图文消息” 
break; 
} 
 
System.Web.HttpContext.Current.Response.Write(resxml); 
WriteToDB(requestXML, resxml, mi.pid); 
} 
catch (Exception ex) 
{ 
//WriteTxt("异常:" + ex.Message + "Struck:" + ex.StackTrace.ToString()); 
//wx_logs.MyInsert("异常:" + ex.Message + "Struck:" + ex.StackTrace.ToString()); 
} 
} 
 
 
/// <summary> 
/// unix时间转换为datetime 
/// </summary> 
/// <param name="timeStamp"></param> 
/// <returns></returns> 
private DateTime UnixTimeToTime(string timeStamp) 
{ 
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); 
long lTime = long.Parse(timeStamp + "0000000"); 
TimeSpan toNow = new TimeSpan(lTime); 
return dtStart.Add(toNow); 
} 
 
 
/// <summary> 
/// datetime转换为unixtime 
/// </summary> 
/// <param name="time"></param> 
/// <returns></returns> 
private int ConvertDateTimeInt(System.DateTime time) 
{ 
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); 
return (int)(time - startTime).TotalSeconds; 
} 
 
 
/// <summary> 
/// 调用百度地图,返回坐标信息 
/// </summary> 
/// <param name="y">经度</param> 
/// <param name="x">纬度</param> 
/// <returns></returns> 
public string GetMapInfo(string x, string y) 
{ 
try 
{ 
string res = string.Empty; 
string parame = string.Empty; 
string url = "http://maps.googleapis.com/maps/api/geocode/xml"; 
 
parame = "latlng=" + x + "," + y + "&language=zh-CN&sensor=false";//此key为个人申请 
res = webRequestPost(url, parame); 
 
XmlDocument doc = new XmlDocument(); 
doc.LoadXml(res); 
 
XmlElement rootElement = doc.DocumentElement; 
string Status = rootElement.SelectSingleNode("status").InnerText; 
 
if (Status == "OK") 
{ 
//仅获取城市 
XmlNodeList xmlResults = rootElement.SelectSingleNode("/GeocodeResponse").ChildNodes; 
for (int i = 0; i < xmlResults.Count; i++) 
{ 
XmlNode childNode = xmlResults[i]; 
if (childNode.Name == "status") { 
continue; 
} 
string city = "0"; 
for (int w = 0; w < childNode.ChildNodes.Count; w++) 
{ 
for (int q = 0; q < childNode.ChildNodes[w].ChildNodes.Count; q++) 
{ 
XmlNode childeTwo = childNode.ChildNodes[w].ChildNodes[q]; 
if (childeTwo.Name == "long_name") 
{ 
city = childeTwo.InnerText; 
} 
else if (childeTwo.InnerText == "locality") 
{ 
return city; 
} 
} 
} 
return city; 
} 
} 
} 
catch (Exception ex) 
{ 
//WriteTxt("map异常:" + ex.Message.ToString() + "Struck:" + ex.StackTrace.ToString()); 
return "0"; 
} 
return "0"; 
} 
 
 
/// <summary> 
/// Post 提交调用抓取 
/// </summary> 
/// <param name="url">提交地址</param> 
/// <param name="param">参数</param> 
/// <returns>string</returns> 
public string webRequestPost(string url, string param) 
{ 
byte[] bs = System.Text.Encoding.UTF8.GetBytes(param); 
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + "?" + param); 
req.Method = "Post"; 
req.Timeout = 120 * 1000; 
req.ContentType = "application/x-www-form-urlencoded;"; 
req.ContentLength = bs.Length; 
 
using (Stream reqStream = req.GetRequestStream()) 
{ 
reqStream.Write(bs, 0, bs.Length); 
reqStream.Flush(); 
} 
 
using (WebResponse wr = req.GetResponse()) 
{ 
//在这里对接收到的页面内容进行处理 
Stream strm = wr.GetResponseStream(); 
StreamReader sr = new StreamReader(strm, System.Text.Encoding.UTF8); 
 
string line; 
System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
while ((line = sr.ReadLine()) != null) 
{ 
sb.Append(line + System.Environment.NewLine); 
} 
sr.Close(); 
strm.Close(); 
return sb.ToString(); 
} 
} 
 
/// <summary> 
/// 将本次交互信息保存至数据库中 
/// </summary> 
/// <param name="requestXML"></param> 
/// <param name="_xml"></param> 
/// <param name="_pid"></param> 
private void WriteToDB(RequestXML requestXML, string _xml, int _pid) 
{ 
WeiXinMsg wx = new WeiXinMsg(); 
wx.FromUserName = requestXML.FromUserName; 
wx.ToUserName = requestXML.ToUserName; 
wx.MsgType = requestXML.MsgType; 
wx.Msg = requestXML.Content; 
wx.Creatime = requestXML.CreateTime; 
wx.Location_X = requestXML.Location_X; 
wx.Location_Y = requestXML.Location_Y; 
wx.Label = requestXML.Label; 
wx.Scale = requestXML.Scale; 
wx.PicUrl = requestXML.PicUrl; 
wx.reply = _xml; 
wx.pid = _pid; 
try 
{ 
wx.Add(); 
} 
catch (Exception ex) 
{ 
//wx_logs.MyInsert(ex.Message); 
//ex.message; 
} 
} 
}

Response classMODEL


 #region 微信请求类 RequestXML 
/// <summary> 
/// 微信请求类 
/// </summary> 
public class RequestXML 
{ 
private string toUserName = ""; 
/// <summary> 
/// 消息接收方微信号,一般为公众平台账号微信号 
/// </summary> 
public string ToUserName 
{ 
get { return toUserName; } 
set { toUserName = value; } 
} 
 
private string fromUserName = ""; 
/// <summary> 
/// 消息发送方微信号 
/// </summary> 
public string FromUserName 
{ 
get { return fromUserName; } 
set { fromUserName = value; } 
} 
 
private string createTime = ""; 
/// <summary> 
/// 创建时间 
/// </summary> 
public string CreateTime 
{ 
get { return createTime; } 
set { createTime = value; } 
} 
 
private string msgType = ""; 
/// <summary> 
/// 信息类型 地理位置:location,文本消息:text,消息类型:image 
/// </summary> 
public string MsgType 
{ 
get { return msgType; } 
set { msgType = value; } 
} 
 
private string content = ""; 
/// <summary> 
/// 信息内容 
/// </summary> 
public string Content 
{ 
get { return content; } 
set { content = value; } 
} 
 
private string location_X = ""; 
/// <summary> 
/// 地理位置纬度 
/// </summary> 
public string Location_X 
{ 
get { return location_X; } 
set { location_X = value; } 
} 
 
private string location_Y = ""; 
/// <summary> 
/// 地理位置经度 
/// </summary> 
public string Location_Y 
{ 
get { return location_Y; } 
set { location_Y = value; } 
} 
 
private string scale = ""; 
/// <summary> 
/// 地图缩放大小 
/// </summary> 
public string Scale 
{ 
get { return scale; } 
set { scale = value; } 
} 
 
private string label = ""; 
/// <summary> 
/// 地理位置信息 
/// </summary> 
public string Label 
{ 
get { return label; } 
set { label = value; } 
} 
 
private string picUrl = ""; 
/// <summary> 
/// 图片链接,开发者可以用HTTP GET获取 
/// </summary> 
public string PicUrl 
{ 
get { return picUrl; } 
set { picUrl = value; } 
} 
} 
#endregion

By reading this article, everyone will have a rough idea of ​​how .net implements the development of the WeChat public account interface. I hope this article will be helpful to everyone's learning.

The above is the detailed content of Detailed explanation of asp.net implementation of WeChat public account interface development method. For more information, please follow other related articles on 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
Beyond the Hype: Assessing the Current Role of C# .NETBeyond the Hype: Assessing the Current Role of C# .NETApr 30, 2025 am 12:06 AM

C#.NET is a powerful development platform that combines the advantages of the C# language and .NET framework. 1) It is widely used in enterprise applications, web development, game development and mobile application development. 2) C# code is compiled into an intermediate language and is executed by the .NET runtime environment, supporting garbage collection, type safety and LINQ queries. 3) Examples of usage include basic console output and advanced LINQ queries. 4) Common errors such as empty references and type conversion errors can be solved through debuggers and logging. 5) Performance optimization suggestions include asynchronous programming and optimization of LINQ queries. 6) Despite the competition, C#.NET maintains its important position through continuous innovation.

The Future of C# .NET: Trends and OpportunitiesThe Future of C# .NET: Trends and OpportunitiesApr 29, 2025 am 12:02 AM

The future trends of C#.NET are mainly focused on three aspects: cloud computing, microservices, AI and machine learning integration, and cross-platform development. 1) Cloud computing and microservices: C#.NET optimizes cloud environment performance through the Azure platform and supports the construction of an efficient microservice architecture. 2) Integration of AI and machine learning: With the help of the ML.NET library, C# developers can embed machine learning models in their applications to promote the development of intelligent applications. 3) Cross-platform development: Through .NETCore and .NET5, C# applications can run on Windows, Linux and macOS, expanding the deployment scope.

C# .NET Development Today: Trends and Best PracticesC# .NET Development Today: Trends and Best PracticesApr 28, 2025 am 12:25 AM

The latest developments and best practices in C#.NET development include: 1. Asynchronous programming improves application responsiveness, and simplifies non-blocking code using async and await keywords; 2. LINQ provides powerful query functions, efficiently manipulating data through delayed execution and expression trees; 3. Performance optimization suggestions include using asynchronous programming, optimizing LINQ queries, rationally managing memory, improving code readability and maintenance, and writing unit tests.

C# .NET: Building Applications with the .NET EcosystemC# .NET: Building Applications with the .NET EcosystemApr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

C# as a Versatile .NET Language: Applications and ExamplesC# as a Versatile .NET Language: Applications and ExamplesApr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

C# .NET for Web, Desktop, and Mobile DevelopmentC# .NET for Web, Desktop, and Mobile DevelopmentApr 25, 2025 am 12:01 AM

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

C# .NET Ecosystem: Frameworks, Libraries, and ToolsC# .NET Ecosystem: Frameworks, Libraries, and ToolsApr 24, 2025 am 12:02 AM

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

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

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.