C#.net 微信公众账号接口开发
程序员文章站
2023-12-18 13:49:28
微信越来越火,微信公众平台成为开发成新宠,本文用c#.net开发微信公众信号接口。
微信接口地址代码:
weixin _wx = new weixin();...
微信越来越火,微信公众平台成为开发成新宠,本文用c#.net开发微信公众信号接口。
微信接口地址代码:
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(); } 微信处理类: public class weixin { private string token = "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; 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; if (requestxml.msgtype == "text") { requestxml.content = rootelement.selectsinglenode("content").innertext; } else if (requestxml.msgtype == "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; } else if (requestxml.msgtype == "image") { requestxml.picurl = rootelement.selectsinglenode("picurl").innertext; } //回复消息 responsemsg(requestxml); } /// <summary> /// 验证微信签名 /// </summary> /// * 将token、timestamp、nonce三个参数进行字典序排序 /// * 将三个参数字符串拼接成一个字符串进行sha1加密 /// * 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。 /// <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"]; 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; } } /// <summary> /// 回复消息(微信信息返回) /// </summary> /// <param name="weixinxml"></param> private void responsemsg(requestxml requestxml) { try { string resxml = ""; mijiya mi = new mijiya(requestxml.content,requestxml.fromusername); if (requestxml.msgtype == "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>"; } } else if (requestxml.msgtype == "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>"; } } else if (requestxml.msgtype == "image") { 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>"; //返回10以内条 //int size = 10; //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>" + size + "</articlecount><articles>"; //list<string> list = new list<string>(); ////假如有20条查询的返回结果 //for (int i = 0; i < 20; i++) //{ // list.add("1"); //} //string[] piclist = new string[] { "/abstract_pencil_scribble_background_vector_main.jpg", "/balloon_tree.jpg", "/bloom.jpg", "/colorful_flowers.jpg", "/colorful_summer_flower.jpg", "/fall.jpg", "/fall_tree.jpg", "/growing_flowers.jpg", "/shoes_illustration.jpg", "/splashed_tree.jpg" }; //for (int i = 0; i < size && i < list.count; i++) //{ // resxml += "<item><title><![cdata[沈阳-黑龙江]]></title><description><![cdata[元旦特价:¥300 市场价:¥400]]></description><picurl><![cdata[" + "http://www.hougelou.com" + piclist[i] + "]]></picurl><url><![cdata[http://www.hougelou.com]]></url></item>"; //} //resxml += "</articles><funcflag>1</funcflag></xml>"; } else if (wx_tmsg.getmsgcount(requestxml.fromusername) == 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.getfirst() + "]]></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>"; } //writetxt(resxml); 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(); } } private void writetodb(requestxml requestxml,string _xml,int _pid) { wx_tmsg wx = new wx_tmsg(); wx.addnew(); 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.update(); } catch (exception ex) { wx_logs.myinsert(ex.message); //ex.message; } } } //微信请求类 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; } } }
说明: 其中用到的mijiya类,主要是调用数据库进行关键词匹配自动回复内容,可以根据自己的业务情况编写。