.NET微信公众号开发之公众号消息处理
程序员文章站
2024-02-20 08:56:34
一.前言
微信公众平台的消息处理还是比较完善的,有最基本的文本消息,到图文消息,到图片消息,语音消息,视频消息,音乐消息其基本原理都是一样的,只不过所pos...
一.前言
微信公众平台的消息处理还是比较完善的,有最基本的文本消息,到图文消息,到图片消息,语音消息,视频消息,音乐消息其基本原理都是一样的,只不过所post的xml数据有所差别,在处理消息之前,我们要认真阅读,官方给我们的文档:。首先我们从最基本的文本消息处理开始。
<xml> <tousername><![cdata[touser]]></tousername> <fromusername><![cdata[fromuser]]></fromusername> <createtime>12345678</createtime> <msgtype><![cdata[text]]></msgtype> <content><![cdata[你好]]></content> </xml>
我们可以看到这是消息处理的一个最基本的模式,有发送者,接受者,创建时间,类型,内容等等。
首先我们来创建一个消息处理的类,这个类用来捕获,所有的消息请求,根据不同的消息请求类型来处理不同的消息回复。
public class weixinservice { /// <summary> /// token /// </summary> private const string token = "finder"; /// <summary> /// 签名 /// </summary> private const string signature = "signature"; /// <summary> /// 时间戳 /// </summary> private const string timestamp = "timestamp"; /// <summary> /// 随机数 /// </summary> private const string nonce = "nonce"; /// <summary> /// 随机字符串 /// </summary> private const string echostr = "echostr"; /// <summary> /// /// </summary> private httprequest request { get; set; } /// <summary> /// 构造函数 /// </summary> /// <param name="request"></param> public weixinservice(httprequest request) { this.request = request; } /// <summary> /// 处理请求,产生响应 /// </summary> /// <returns></returns> public string response() { string method = request.httpmethod.toupper(); //验证签名 if (method == "get") { if (checksignature()) { return request.querystring[echostr]; } else { return "error"; } } //处理消息 if (method == "post") { return responsemsg(); } else { return "无法处理"; } } /// <summary> /// 处理请求 /// </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); //验证 if (new_signature == signature) { return true; } else { return false; } } }
在来看看我们的首先是如何捕获消息的。首页default.ashx的代码如下
public void processrequest(httpcontext context) { context.response.contenttype = "text/html"; string poststring = string.empty; if (httpcontext.current.request.httpmethod.toupper() == "post") { //由微信服务接收请求,具体处理请求 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(); } } }
从上面的代码中我们可以看到weixinservice.cs类中的消息相应至关重要。
/// <summary> /// 处理请求 /// </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是一个消息处理接口,其下面有eventhandler,texthandler处理类实现这个接口。代码如下
/// <summary> /// 处理接口 /// </summary> public interface ihandler { /// <summary> /// 处理请求 /// </summary> /// <returns></returns> string handlerequest(); }
eventhandler
class eventhandler : ihandler { /// <summary> /// 请求的xml /// </summary> private string requestxml { get; set; } /// <summary> /// 构造函数 /// </summary> /// <param name="requestxml"></param> public eventhandler(string requestxml) { this.requestxml = requestxml; } /// <summary> /// 处理请求 /// </summary> /// <returns></returns> public string handlerequest() { string response = string.empty; eventmessage em = eventmessage.loadfromxml(requestxml); if (em.event.equals("subscribe", stringcomparison.ordinalignorecase))//用来判断是不是首次关注 { pictextmessage tm = new pictextmessage();//我自己创建的一个图文消息处理类 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> /// 请求的xml /// </summary> private string requestxml { get; set; } /// <summary> /// 构造函数 /// </summary> /// <param name="requestxml">请求的xml</param> public texthandler(string requestxml) { this.requestxml = requestxml; } /// <summary> /// 处理请求 /// </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; //进行发送者、接收者转换 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"))//用来匹配用户输入的关键字 { response = "你的openid: "+openid; } else if (requestcontent.contains("token") || requestcontent.contains("access_token")) { response = "你的access_token: " + access_token; }else { response = "试试其他关键字吧。"; } return response; } }
handlerfactory
/// <summary> /// 处理器工厂类 /// </summary> public class handlerfactory { /// <summary> /// 创建处理器 /// </summary> /// <param name="requestxml">请求的xml</param> /// <returns>ihandler对象</returns> public static ihandler createhandler(string requestxml) { ihandler handler = null; if (!string.isnullorempty(requestxml)) { //解析数据 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; } }
在这里基本的一些类已经完成了,现在我们来完成,关注我们的微信公众号,我们就发送一条图文消息,同时输入我们的一些关键字,返回一些消息,比如输入id返回用户的openid等等。
二.pictextmessage
public class pictextmessage : message { /// <summary> /// 模板静态字段 /// </summary> private static string m_template; /// <summary> /// 默认构造函数 /// </summary> public pictextmessage() { this.msgtype = "news"; } /// <summary> /// 从xml数据加载文本消息 /// </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> /// 生成内容 /// </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[如有问题请致电400-6238-136或直接在微信留言,我们将第一时间为您服务!]]></description> <picurl><![cdata[http://www.baidu.com/youwei.jpg]]></picurl> <url><![cdata[http://www.baidu.com]]></url> </item> </articles> </xml> "; } }
最后我们的效果如下所示;
以上所述就是本文的全部内容了,希望大家能够喜欢
上一篇: 教你如何使用VS远程调试