和微信用户的沟通少不了,总觉得看起来微信凯发网娱乐官网下载官网后台管理中的会话回复消息有点呆板,所以我这里就自定义了一个会话管理功能,最终效果图如下:
因为我试使用富文本文件ckeditor来进行编写,你看到稳中可能会有
字段,后台获取数据内容时,替换为空字符即可:如下string txtcontent = this.txtmessage.value.tostring().replace("", ""); stringbuilder sb = new stringbuilder(); sb.append(txtcontent.replace("
\r\n", ""));
在我个人理解,做会话管理,无非就是将用户对话信息(用户发过来的数据,发给用户的数据)存入数据库,根据用户的数据时间和回复用户数据的时间来和当天系统的时间做对比,如果大于多少分钟或者多少个小时就不可以再主动和用户对话,就算我这里是根据微信凯发网娱乐官网下载官网48小时来进行限制的,超过48小时禁用控件,如下图:
废话少说,上代码:需要用到的两个类,数据库也要创建和类相同的名字(至少我试这么做的)
////// 微信会话记录类,用户存储会话记录列表 /// public class weixinkefuinfo { public int uid { get; set; }//编号 public string useropenid { get; set; }//用户的openid public string usercontent { get; set; }//用户内容 public string createrdate { get; set; }//创建时间 } ////// 与微信用户会话的消息记录类 /// public class wxmessageinfo { public int msgid { get; set; }//消息id public string fromuser { get; set; }//发送用户 public string touser { get; set; }//接收用户 public string content { get; set; }//发送内容 public string fasongdate { get; set; }//发送时间 public string uid { get; set; }//会话用户的uid,微信会话记录类外键 } ////// 发送文本。。。。。。。。。。。。。还记得这个方法吗?就是根据用户发送过来的消息类型进行判断后,如果是文本就回复发送此方法内的内容 /// /// private void sendtextcase(requestxml requestxml) { weixinkefuservice wkfs = new weixinkefuservice();//自己写的服务类 //根据openid查询数据库会话记录是否存在 weixinkefuinfo wkfinfoinfo = wkfs.getweixinkefuinfobyopenid(requestxml.fromusername.tostring()); if (wkfinfoinfo != null) { //如果存在直接保存消息记录 wxmessageservice wms = new wxmessageservice(); wxmessageinfo wminfo = new wxmessageinfo(); wminfo.fromuser = requestxml.fromusername.tostring(); wminfo.touser = "我"; wminfo.content = requestxml.content.tostring(); wminfo.fasongdate = system.datetime.now.tostring("yyyy/mm/dd hh:mm:ss"); wminfo.uid = wkfinfoinfo.uid.tostring(); wms.addwxmessageinfo(wminfo); } else { //如果不存在新建会话记录 weixinkefuinfo wkfinfo = new weixinkefuinfo(); wkfinfo.useropenid = requestxml.fromusername.tostring(); wkfinfo.usercontent = requestxml.content.tostring(); wkfinfo.createrdate = system.datetime.now.tostring("yyyy/mm/dd hh:mm:ss"); wkfs.addweixinkefuinfo(wkfinfo); string responsecontent = formattextxml(requestxml.fromusername, requestxml.tousername, "正在接入.请稍候....."); httpcontext.current.response.contenttype = "text/xml"; httpcontext.current.response.contentencoding = encoding.utf8; httpcontext.current.response.write(responsecontent); httpcontext.current.response.end(); } }
以上代码实现了数据库的插入,那么取出来,显示的页面,核心代码:weixinsessionlist.aspx,前台代码如下:
<%@ page language="c#" autoeventwireup="true" codebehind="weixinsessionlist.aspx.cs" inherits="dqwebsite.administrator.weixinsessionlist" %>
weixinsessionlist.aspx.cs后台代码如下:
pageddatasource pds = new pageddatasource(); protected void page_load(object sender, eventargs e) { if (!page.ispostback) { bindgustbooklist(); this.databind(); usersinfo user = session["users"] as usersinfo; if (user != null && user.rolsid == 1) { this.btndelete.enabled = true; } else { this.btndelete.enabled = false; } } } private void bindgustbooklist() { weixinkefuservice wkf = new weixinkefuservice(); listwkflists = wkf.getallweixinkefuinfolist(); //if (this.ddlstate.selectedvalue.equals("1")) //{ // lists = gbs.getallgustbooklistbystate(); //} //else if (this.ddlstate.selectedvalue.equals("2")) //{ // lists = gbs.getallgustbooklistbystate2(); //} //else //{ // lists = gbs.getallgustbooklist(); //} pds.datasource = wkflists; pds.allowpaging = true; pds.pagesize = 20;//每页显示为20条 int currentpage; if (!string.isnullorwhitespace(this.txtpageindex.text.tostring().trim())) { currentpage = convert.toint32(this.txtpageindex.text.tostring().trim()); } else if (request.querystring["page"] != null) { currentpage = convert.toint32(request.querystring["page"]); } else { currentpage = 1; } pds.currentpageindex = currentpage - 1;//当前页的索引就等于当前页码-1; if (!pds.isfirstpage) { //request.currentexecutionfilepath 为当前请求的虚拟路径 this.lnktop.navigateurl = request.currentexecutionfilepath "?page=" convert.tostring(currentpage - 1); this.lnkfist.enabled = this.lnktop.enabled = true; this.lnknext.enabled = this.lnklast.enabled = true; } else { this.lnkfist.enabled = this.lnktop.enabled = false; this.lnknext.enabled = this.lnklast.enabled = true; this.lnkfist.attributes.add("style", "color:#ced9df;"); this.lnktop.attributes.add("style", "color:#ced9df;"); this.lnknext.attributes.remove("style"); this.lnklast.attributes.remove("style"); } if (!pds.islastpage) { //request.currentexecutionfilepath 为当前请求的虚拟路径 this.lnknext.navigateurl = request.currentexecutionfilepath "?page=" convert.tostring(currentpage 1); this.lnkfist.enabled = this.lnktop.enabled = true; this.lnknext.enabled = this.lnklast.enabled = true; } else { this.lnknext.enabled = this.lnklast.enabled = false; this.lnkfist.enabled = this.lnktop.enabled = true; this.lnknext.attributes.add("style", "color:#ced9df;"); this.lnklast.attributes.add("style", "color:#ced9df;"); this.lnkfist.attributes.remove("style"); this.lnktop.attributes.remove("style"); } this.lnkfist.navigateurl = request.currentexecutionfilepath "?page=" convert.tostring(1);//跳转至凯发网娱乐凯发网娱乐官网下载官网下载首页 this.lnklast.navigateurl = request.currentexecutionfilepath "?page=" convert.tostring(pds.pagecount);//跳转至末页 this.repeatergustbooklist.datasource = pds; this.repeatergustbooklist.databind(); this.lbcountdata.text = wkflists.count.tostring(); this.lbpageindex.text = (pds.currentpageindex 1).tostring(); this.lbpagesize.text = "每页" pds.pagesize.tostring() "条记录"; this.lbcountpage.text = pds.pagecount.tostring(); this.txtpageindex.text = (pds.currentpageindex 1).tostring(); if (int.parse(wkflists.count.tostring()) <= int.parse(pds.pagesize.tostring())) { this.lnkfist.visible = this.lnktop.visible = this.lnknext.visible = this.lnklast.visible = this.txtpageindex.visible = this.linkbtntopage.visible = false; } else { this.lnkfist.visible = this.lnktop.visible = this.lnknext.visible = this.lnklast.visible = this.txtpageindex.visible = this.linkbtntopage.visible = true; } } /// /// 删除选中 /// /// /// protected void btndelete_click(object sender, eventargs e) { boolean bools = false; foreach (repeateritem di in this.repeatergustbooklist.items) { checkbox checkin = (checkbox)di.findcontrol("checkin"); if (checkin.checked) { bools = true; label lbgustno = di.findcontrol("lbuid") as label; weixinkefuservice wkf = new weixinkefuservice(); int num = wkf.deleteweixinkefuinfo(int.parse(lbgustno.text.tostring())); if (num > 0) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('删除成功!');location='weixinsessionlist.aspx'", true); } else { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('删除失败!');location='weixinsessionlist.aspx'", true); } } } if (!bools) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('未选中删除项!');location='weixinsessionlist.aspx'", true); } } ////// 全选全不选 /// /// /// protected void checkall_checkedchanged(object sender, eventargs e) { checkbox checkall = (checkbox)sender; foreach (repeateritem d in this.repeatergustbooklist.items) { checkbox checkin = (checkbox)d.findcontrol("checkin"); checkin.checked = checkall.checked; } } protected void linkbtnlook_click(object sender, eventargs e) { bindgustbooklist(); } ////// 绑定事件 /// /// /// protected void repeatergustbooklist_itemdatabound(object sender, repeateritemeventargs e) { if (e.item.itemtype == listitemtype.header) { checkbox checkall = e.item.findcontrol("checkall") as checkbox; checkall.autopostback = true; } if (e.item.itemtype == listitemtype.item || e.item.itemtype == listitemtype.alternatingitem) { weixinkefuinfo wkf = e.item.dataitem as weixinkefuinfo; label lbuid = e.item.findcontrol("lbuid") as label; lbuid.text = wkf.uid.tostring(); wxmessageservice wms = new wxmessageservice(); wxmessageinfo wminfo = wms.gettoplastfasongdatebyuid(lbuid.text.tostring()); if(wminfo!=null&&!string.isnullorwhitespace(wminfo.fasongdate.tostring())) { label lblastdate = e.item.findcontrol("lblastdate") as label; lblastdate.text = wminfo.fasongdate.tostring(); datetime datesystemss = datetime.parse(system.datetime.now.tostring()); datetime lastloingdatess = datetime.parse(lblastdate.text.tostring()); timespan ts11 = new timespan(datesystemss.ticks); timespan ts22 = new timespan(lastloingdatess.ticks); timespan ts33 = ts11.subtract(ts22).duration(); label lbstate = e.item.findcontrol("lbstate") as label; string chaoshifenzhong = ts33.totalminutes.tostring(); if (double.parse(chaoshifenzhong) <=10) { lbstate.text = "会话中"; lbstate.attributes.add("style","color:red;"); } else { lbstate.text = "已结束"; } label lbchaoshi = e.item.findcontrol("lbchaoshi") as label; datetime datesystem = datetime.parse(system.datetime.now.tostring()); datetime lastloingdate = datetime.parse(lblastdate.text.tostring()); timespan ts1 = new timespan(datesystem.ticks); timespan ts2 = new timespan(lastloingdate.ticks); timespan ts3 = ts1.subtract(ts2).duration(); lbchaoshi.text = ts3.days.tostring() "天" ts3.hours.tostring() "小时" ts3.minutes.tostring() "分钟"; } //////根据用户的openid获取用户昵称 //weixinserver wxs = new weixinserver(); /////从缓存读取accesstoken //string access_token = cache["access_token"] as string; //if (access_token == null) //{ // //如果为空,重新获取 // access_token = wxs.getaccesstoken(); // //设置缓存的数据7000秒后过期 // cache.insert("access_token", access_token, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); //} //string access_tokento = access_token.substring(17, access_token.length - 37); //string jsonres = ""; //jsonres = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" access_tokento "&openid=" wkf.useropenid; //httpwebrequest myrequest = (httpwebrequest)webrequest.create(jsonres); //myrequest.method = "get"; //httpwebresponse myresponse = (httpwebresponse)myrequest.getresponse(); //streamreader reader = new streamreader(myresponse.getresponsestream(), encoding.utf8); //string content = reader.readtoend(); //reader.close(); ////使用前需药引用newtonsoft.json.dll文件 //jobject jsonobj = jobject.parse(content); //label lbnikename = e.item.findcontrol("lbnikename") as label; //label lbsex = e.item.findcontrol("lbsex") as label; //lbnikename.text = jsonobj["nickname"].tostring(); //if (jsonobj["sex"].tostring().equals("1")) //{ // lbsex.text = "男"; //} //else //{ // lbsex.text = "女"; //} } } ////// 输入页码提交跳转 /// /// /// protected void linkbtntopage_click(object sender, eventargs e) { if (string.isnullorwhitespace(this.txtpageindex.text.tostring().trim())) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('页码不能为空!')", true); this.txtpageindex.focus(); return; } if (isnum(this.txtpageindex.text.tostring().trim())) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('页码数只能输入数字!')", true); this.txtpageindex.focus(); this.txtpageindex.text = this.lbpageindex.text.tostring(); return; } if (int.parse(this.txtpageindex.text.tostring().trim()) > int.parse(this.lbcountpage.text.tostring().trim())) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('所输页数不能大于总页数!')", true); this.txtpageindex.focus(); this.txtpageindex.text = this.lbpageindex.text.tostring(); return; } bindgustbooklist(); } ////// 判断是否是数字 /// /// ///public static bool isnum(string text) // { for (int i = 0; i < text.length; i ) { if (!char.isnumber(text, i)) { return true; //输入的不是数字 } } return false; //否则是数字 }
此代码已包含,后台分页功能,仔细研究下,即可使用.
点击开启会话的页面:messagewindow.aspx如下:
<%@ page language="c#" autoeventwireup="true" validaterequest="false" codebehind="messagewindow.aspx.cs" inherits="dqwebsite.administrator.messagewindow" %>
messagewindow.aspx.cs的核心代码如下:
protected void page_load(object sender, eventargs e) { if(!page.ispostback) { if(request.querystring["id"]!=null) { weixinkefuservice wkfs = new weixinkefuservice(); weixinkefuinfo wkfinfo = wkfs.getweixinkefuinfobyid(int.parse(request.querystring["id"].tostring())); this.lbduihuamsg.text = wkfinfo.useropenid.tostring(); this.lbduihua1.text = "正在于"; this.lbduihua2.text = "对话中......."; wxmessageservice wms = new wxmessageservice(); wxmessageinfo wminfo = wms.gettoplastfasongdatebyuid(wkfinfo.uid.tostring()); if (wminfo != null) { datetime datesystemss = datetime.parse(system.datetime.now.tostring()); datetime lastloingdatess = datetime.parse(wminfo.fasongdate.tostring()); timespan ts11 = new timespan(datesystemss.ticks); timespan ts22 = new timespan(lastloingdatess.ticks); timespan ts33 = ts11.subtract(ts22).duration(); string chaodays = ts33.totaldays.tostring(); if (double.parse(chaodays) >=2) { this.linkbtnsubsend.enabled = false; this.errmsg.innertext = "会话已结束!超过48小时不能主动推送信息给该用户!"; this.lbduihua1.text = "已经于"; this.lbduihua2.text = "失去连接.....除非该用户主动会话才能重新建立连接!"; this.txtmessage.attributes.add("readonly","true"); } } bindmsglist(); this.databind(); } } } private void bindmsglist() { string id = request.querystring["id"].tostring(); wxmessageservice wms = new wxmessageservice(); listwmlist = wms.getallmessagelist(id); if(wmlist.count>0) { this.repeatermessagelist.datasource = wmlist; this.repeatermessagelist.databind(); } } protected void timetick_tick(object sender, eventargs e) { bindmsglist(); } /// /// 推送消息到用户 /// /// /// protected void linkbtnsubsend_click(object sender, eventargs e) { if(string.isnullorwhitespace(this.txtmessage.value.tostring().trim())) { this.errmsg.innertext = "发送的内容不能为空!"; this.txtmessage.focus(); return; } if (this.txtmessage.value.tostring().length < 5 || this.txtmessage.value.tostring().length > 200) { this.errmsg.innertext = "发送内容应在5-200个字符之间!"; this.txtmessage.focus(); return; } //如果存在直接保存消息记录 wxmessageservice wms = new wxmessageservice(); wxmessageinfo wminfo = new wxmessageinfo(); wminfo.fromuser = "我"; wminfo.touser = this.lbduihuamsg.text.tostring(); wminfo.content = this.txtmessage.value.tostring().trim(); wminfo.fasongdate = system.datetime.now.tostring("yyyy/mm/dd hh:mm:ss"); wminfo.uid = request.querystring["id"].tostring(); wms.addwxmessageinfo(wminfo); weixinserver wxs = new weixinserver(); string res = ""; ///从缓存读取accesstoken string access_token = cache["access_token"] as string; if(access_token==null) { //如果为空,重新获取 access_token = wxs.getaccesstoken(); //设置缓存的数据7000秒后过期 cache.insert("access_token", access_token, null, datetime.now.addseconds(7000), system.web.caching.cache.noslidingexpiration); } string access_tokento = access_token.substring(17, access_token.length - 37); string txtcontent = this.txtmessage.value.tostring().replace("", ""); stringbuilder sb = new stringbuilder(); sb.append(txtcontent.replace("
\r\n", "")); string posturl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" access_tokento; string postdata = "{"touser":"" this.lbduihuamsg.text.tostring() "","msgtype":"text","text":{"content":"" sb.tostring() ""}}"; res = wxs.getpage(posturl, postdata); //使用前需药引用newtonsoft.json.dll文件 jobject jsonobj = jobject.parse(res); ///获取返回结果的正确|true|false string isright = jsonobj["errcode"].tostring();//0 string istrueorfalse = jsonobj["errmsg"].tostring();//ok if (isright.equals("0") && istrueorfalse.equals("ok")) { this.errmsg.innertext = "消息推送成功!消息已送达微信用户!"; this.txtmessage.value = ""; } else { this.errmsg.innertext = "消息推送失败!消息已保存至数据库!"; } } protected void repeatermessagelist_itemdatabound(object sender, repeateritemeventargs e) { if (e.item.itemtype == listitemtype.item || e.item.itemtype == listitemtype.alternatingitem) { wxmessageinfo wminfo = e.item.dataitem as wxmessageinfo; image imagelaba = e.item.findcontrol("imagelaba") as image; label lbfromuser = e.item.findcontrol("lbfromuser") as label; lbfromuser.text = wminfo.fromuser.tostring(); if (wminfo.fromuser.tostring().equals("我")) { imagelaba.imageurl = "images/fa.gif"; } else { imagelaba.imageurl = "images/shou.gif"; } } }
本文已被整理到了《asp.net微信开发教程汇总》,欢迎大家学习阅读。
以上就是会话管理功能的全部核心代码,仅供参考,希望对大家的学习有所帮助。