当前位置:Gxlcms > asp.net > asp.net微信开发(自定义会话管理)

asp.net微信开发(自定义会话管理)

时间:2021-07-01 10:21:17 帮助过:14人阅读

和微信用户的沟通少不了,总觉得看起来微信官网后台管理中的会话回复消息有点呆板,所以我这里就自定义了一个会话管理功能,最终效果图如下:

因为我试使用富文本文件CKEDITOR来进行编写,你看到稳中可能会有<P></p>字段,后台获取数据内容时,替换为空字符即可:如下

  1. string txtcontent = this.txtMessage.Value.ToString().Replace("<p>", "");
  2. StringBuilder sb = new StringBuilder();
  3. sb.Append(txtcontent.Replace("</p>\r\n", ""));

在我个人理解,做会话管理,无非就是将用户对话信息(用户发过来的数据,发给用户的数据)存入数据库,根据用户的数据时间和回复用户数据的时间来和当天系统的时间做对比,如果大于多少分钟或者多少个小时就不可以再主动和用户对话,就算我这里是根据微信官网48小时来进行限制的,超过48小时禁用控件,如下图:


废话少说,上代码:需要用到的两个类,数据库也要创建和类相同的名字(至少我试这么做的)
 

  1. /// <summary>
  2. /// 微信会话记录类,用户存储会话记录列表
  3. /// </summary>
  4. public class WeixinKeFuInfo
  5. {
  6. public int UId { get; set; }//编号
  7. public string UserOpenId { get; set; }//用户的OpenID
  8. public string UserContent { get; set; }//用户内容
  9. public string CreaterDate { get; set; }//创建时间
  10. }
  11. /// <summary>
  12. /// 与微信用户会话的消息记录类
  13. /// </summary>
  14. public class WxMessageInfo
  15. {
  16. public int msgId { get; set; }//消息ID
  17. public string FromUser { get; set; }//发送用户
  18. public string ToUser { get; set; }//接收用户
  19. public string Content { get; set; }//发送内容
  20. public string FaSongDate { get; set; }//发送时间
  21. public string UId { get; set; }//会话用户的UId,微信会话记录类外键
  22. }
  23. /// <summary>
  24. /// 发送文本。。。。。。。。。。。。。还记得这个方法吗?就是根据用户发送过来的消息类型进行判断后,如果是文本就回复发送此方法内的内容
  25. /// </summary>
  26. /// <param name="requestXML"></param>
  27. private void SendTextCase(RequestXML requestXML)
  28. {
  29.       WeixinKeFuService wkfs = new WeixinKeFuService();//自己写的服务类
  30. //根据openId查询数据库会话记录是否存在
  31. WeixinKeFuInfo wkfinfoinfo = wkfs.GetWeixinKeFuInfoByOpenId(requestXML.FromUserName.ToString());
  32. if (wkfinfoinfo != null)
  33. {
  34. //如果存在直接保存消息记录
  35. WxMessageService wms = new WxMessageService();
  36. WxMessageInfo wminfo = new WxMessageInfo();
  37. wminfo.FromUser = requestXML.FromUserName.ToString();
  38. wminfo.ToUser = "我";
  39. wminfo.Content = requestXML.Content.ToString();
  40. wminfo.FaSongDate = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
  41. wminfo.UId = wkfinfoinfo.UId.ToString();
  42. wms.AddWxMessageInfo(wminfo);
  43. }
  44. else
  45. {
  46. //如果不存在新建会话记录
  47. WeixinKeFuInfo wkfinfo = new WeixinKeFuInfo();
  48. wkfinfo.UserOpenId = requestXML.FromUserName.ToString();
  49. wkfinfo.UserContent = requestXML.Content.ToString();
  50. wkfinfo.CreaterDate = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
  51. wkfs.AddWeixinKeFuInfo(wkfinfo);
  52. string responseContent = FormatTextXML(requestXML.FromUserName, requestXML.ToUserName, "正在接入.请稍候.....");
  53. HttpContext.Current.Response.ContentType = "text/xml";
  54. HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
  55. HttpContext.Current.Response.Write(responseContent);
  56. HttpContext.Current.Response.End();
  57. }
  58.   }

以上代码实现了数据库的插入,那么取出来,显示的页面,核心代码:WeiXinSessionList.aspx,前台代码如下:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WeiXinSessionList.aspx.cs" Inherits="DQWebSite.Administrator.WeiXinSessionList" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head id="Head1" runat="server">
  5. <title></title>
  6. <meta http-equiv="refresh" content="60; url=WeiXinSessionList.aspx" />
  7. <link href="css/style.css" rel="Stylesheet" type="text/css" />
  8. <style type="text/css">
  9. .tablestyle { width:1124px; margin:10px auto 10px auto; border:1px solid #ecd9df; text-align:center;
  10. }
  11. th { height:35px;background-image:url('images/th.gif'); background-repeat:repeat-x;
  12. }
  13. tr { height:30px;
  14. }
  15. td {
  16. border-left:1px dotted #a7b5bc;
  17. }
  18. .trcolor { background-color:#ecd9df;
  19. }
  20. tr:hover { cursor:pointer;
  21. }
  22. #FenPage { width:1124px; height:25px; line-height:25px; text-align:center; margin:20px auto 20px auto;
  23. }
  24. .linka { color:#0094ff; cursor:pointer;
  25. }
  26. .fenyebtn {width:60px; height:25px; border:1px solid #ced9df; border-radius:5px; text-align:center; line-height:25px; float:right;
  27. }
  28. .fenyebtn2 { width:60px; height:25px; border:1px solid #ced9df; border-radius:5px; text-align:center; line-height:25px;margin-left:10px;float:right;
  29. }
  30. .toPageIndex { width:60px;height:25px; background-image:url('images/inputbg.gif'); margin-left:10px; background-repeat:repeat-x;border-top:solid 1px #a7b5bc; border-left:solid 1px #a7b5bc; border-right:solid 1px #ced9df; border-bottom:solid 1px #ced9df; text-align:center; float:right;
  31. }
  32. .gotoPagebtn { width:60px; height:25px; border:1px solid #ced9df; border-radius:5px; text-align:center; line-height:25px;margin-left:10px;float:right; background-color:#ced9df;
  33. }
  34. .deletebtn {float:left;width:100px; color:#000; height:25px; background-color:#ced9df; border:1px solid #ced9df; border-radius:5px; text-align:center;
  35. }
  36. #BtnDeleteSelected:hover { cursor:pointer;
  37. }
  38. .publishHuoDong {background-color:#ced9df; border:1px solid #ced9df; border-radius:5px;text-align:center; width:100px; color:#000; height:25px; line-height:25px; float:left;
  39. }
  40. a { color:#08a5e0;
  41. }
  42. .droplist { background-image:url('images/inputbg.gif'); background-repeat:repeat-x; width:120px; height:25px; border:1px solid #ced9df;
  43. }
  44. </style>
  45. <script type="text/javascript">
  46. function EditRoster(piciNumber) {
  47. var url = 'MessageWindow.aspx?id=' + piciNumber; //转向网页的地址;
  48. var name = 'add'; //网页名称,可为空;
  49. var iWidth = 850; //弹出窗口的宽度;
  50. var iHeight = 600; //弹出窗口的高度;
  51. //获得窗口的垂直位置
  52. var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
  53. //获得窗口的水平位置
  54. var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
  55. window.open(url, name, 'height=' + iHeight + ',,innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no');
  56. }
  57. </script>
  58. </head>
  59. <body style="background-image:url('images/ygbg.png'); background-repeat:repeat;">
  60. <form id="form1" runat="server">
  61. <div class="place">
  62. <span>位置:</span>
  63. <ul class="placeul">
  64. <li><a href="WelCome.aspx" target="rightFrame">首页</a></li>
  65. <li>微信管理</li>
  66. <li>德桥员工服务中心--会话管理</li>
  67. </ul>
  68. </div>
  69. <div>
  70. <div style="width:1124px;margin:10px auto 0px 20px;">
  71. <font style="color:red;"> 根据微信公众平台规定,用户主送发起会话后,48小时之内可与该用户进行无限次会话,超过48小时不能主动会话。</font>
  72. </div>
  73. <asp:ScriptManager ID="ScriptManager1" runat="server">
  74. </asp:ScriptManager>
  75. <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  76. <ContentTemplate>
  77. <table class="tablestyle">
  78. <asp:Repeater ID="RepeaterGustBookList" runat="server" OnItemDataBound="RepeaterGustBookList_ItemDataBound">
  79. <HeaderTemplate>
  80. <tr>
  81. <th style="width:50px;"><asp:CheckBox ID="CheckAll" runat="server"
  82. oncheckedchanged="CheckAll_CheckedChanged" /><br /></th>
  83. <th style="width:105px;">openId</th>
  84. <%-- <th style="width:150px;">昵称</th>
  85. <th style="width:50px;">性别</th>--%>
  86. <th style="width:200px;">初始内容</th>
  87. <th style="width:100px;">接入时间</th>
  88. <th style="width:100px;">近期会话</th>
  89. <th style="width:80px;">会话状态</th>
  90. <th style="width:150px;">已过时间</th>
  91. <th style="width:100px;">会话操作</th>
  92. </tr>
  93. </HeaderTemplate>
  94. <ItemTemplate>
  95. <tr style='%#(Container.ItemIndex%2==0)?"#fff":"#ced9ff"%>' >
  96. <td><asp:CheckBox ID="CheckIn" runat="server" /></td>
  97. <td><asp:Label ID="lbUId" runat="server" Visible="false" Text="Label"></asp:Label>
  98. <%# Eval("UserOpenId")%>
  99. </td>
  100. <%-- <td><asp:Label ID="lbNikeName" runat="server" Text="未知"></asp:Label></td>
  101. <td><asp:Label ID="lbSex" runat="server" Text="未知"></asp:Label></td>--%>
  102. <td><%# (Eval("UserContent").ToString().Length>10)?Eval("UserContent").ToString().Substring(0,10)+"..":Eval("UserContent") %></td>
  103. <td><%# Eval("CreaterDate")%></td>
  104. <td><asp:Label ID="lblastDate" runat="server" Text="未知"></asp:Label></td>
  105. <td><asp:Label ID="lbState" runat="server" Text="未知"></asp:Label></td>
  106. <td><asp:Label ID="lbChaoshi" runat="server" Text="未知"></asp:Label></td>
  107. <td><a onclick="EditRoster(<%# Eval("UId") %>);">启动会话</a>
  108. <%-- <asp:HyperLink ID="HyperLinkNewSession" runat="server">新建</asp:HyperLink> --%>
  109. </td>
  110. </tr>
  111. </ItemTemplate>
  112. </asp:Repeater>
  113. </table>
  114. <div id="FenPage">
  115. <asp:LinkButton ID="LinkBtnToPage" CssClass="gotoPagebtn" runat="server" OnClick="LinkBtnToPage_Click">确定</asp:LinkButton>
  116. <asp:TextBox ID="txtPageIndex" CssClass="toPageIndex" runat="server"></asp:TextBox>
  117. <asp:HyperLink ID="lnkLast" runat="server"><span class="fenyebtn2">>>|</span></asp:HyperLink>
  118. <asp:HyperLink ID="lnkNext" runat="server"><span class="fenyebtn2">></span></asp:HyperLink>
  119. <asp:HyperLink ID="lnkTop" runat="server"><span class="fenyebtn2"><</span></asp:HyperLink>
  120. <asp:HyperLink ID="lnkFist" runat="server"><span class="fenyebtn">|<<</span></asp:HyperLink>
  121. <asp:Button ID="BtnDelete" runat="server" Text="删除选中项" CssClass="deletebtn"
  122. BackColor="ButtonFace" onclick="BtnDelete_Click" />
  123. <span style="float:left;margin-left:20px;">当前第</span>
  124. <span style="float:left; color:red;"><asp:Label ID="lbPageIndex" runat="server" Text=""></asp:Label></span>
  125. <span style="float:left;margin-left:5px;">页/</span>
  126. <span style="float:left;margin-left:5px;">共</span>
  127. <span style="float:left;color:red;"><asp:Label ID="lbCountPage" runat="server" Text=""></asp:Label></span>
  128. <span style="float:left;margin-left:5px;">页</span>
  129. <span style="float:left;margin-left:10px;"><asp:Label ID="lbPageSize" runat="server" Text=""></asp:Label></span>
  130. <span style="float:left;margin-left:10px;">共搜索到 </span>
  131. <span style="float:left;margin-left:5px; color:red;"><asp:Label ID="lbCountData" runat="server" Text=""></asp:Label></span>
  132. <span style="float:left;margin-left:5px;">条记录.</span>
  133. </div>
  134. </ContentTemplate>
  135. </asp:UpdatePanel>
  136. </div>
  137. </form>
  138. </body>
  139. </html>

WeiXinSessionList.aspx.cs后台代码如下:

  1. PagedDataSource pds = new PagedDataSource();
  2. protected void Page_Load(object sender, EventArgs e)
  3. {
  4. if (!Page.IsPostBack)
  5. {
  6. BindGustBookList();
  7. this.DataBind();
  8. UsersInfo user = Session["Users"] as UsersInfo;
  9. if (user != null && user.RolsId == 1)
  10. {
  11. this.BtnDelete.Enabled = true;
  12. }
  13. else
  14. {
  15. this.BtnDelete.Enabled = false;
  16. }
  17. }
  18. }
  19. private void BindGustBookList()
  20. {
  21. WeixinKeFuService wkf = new WeixinKeFuService();
  22. List<WeixinKeFuInfo> wkflists = wkf.GetAllWeixinKeFuInfoList();
  23. //if (this.DDLState.SelectedValue.Equals("1"))
  24. //{
  25. // lists = gbs.GetAllGustBookListByState();
  26. //}
  27. //else if (this.DDLState.SelectedValue.Equals("2"))
  28. //{
  29. // lists = gbs.GetAllGustBookListByState2();
  30. //}
  31. //else
  32. //{
  33. // lists = gbs.GetAllGustBookList();
  34. //}
  35. pds.DataSource = wkflists;
  36. pds.AllowPaging = true;
  37. pds.PageSize = 20;//每页显示为20条
  38. int CurrentPage;
  39. if (!String.IsNullOrWhiteSpace(this.txtPageIndex.Text.ToString().Trim()))
  40. {
  41. CurrentPage = Convert.ToInt32(this.txtPageIndex.Text.ToString().Trim());
  42. }
  43. else if (Request.QueryString["Page"] != null)
  44. {
  45. CurrentPage = Convert.ToInt32(Request.QueryString["Page"]);
  46. }
  47. else
  48. {
  49. CurrentPage = 1;
  50. }
  51. pds.CurrentPageIndex = CurrentPage - 1;//当前页的索引就等于当前页码-1;
  52. if (!pds.IsFirstPage)
  53. {
  54. //Request.CurrentExecutionFilePath 为当前请求的虚拟路径
  55. this.lnkTop.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(CurrentPage - 1);
  56. this.lnkFist.Enabled = this.lnkTop.Enabled = true;
  57. this.lnkNext.Enabled = this.lnkLast.Enabled = true;
  58. }
  59. else
  60. {
  61. this.lnkFist.Enabled = this.lnkTop.Enabled = false;
  62. this.lnkNext.Enabled = this.lnkLast.Enabled = true;
  63. this.lnkFist.Attributes.Add("style", "color:#ced9df;");
  64. this.lnkTop.Attributes.Add("style", "color:#ced9df;");
  65. this.lnkNext.Attributes.Remove("style");
  66. this.lnkLast.Attributes.Remove("style");
  67. }
  68. if (!pds.IsLastPage)
  69. {
  70. //Request.CurrentExecutionFilePath 为当前请求的虚拟路径
  71. this.lnkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(CurrentPage + 1);
  72. this.lnkFist.Enabled = this.lnkTop.Enabled = true;
  73. this.lnkNext.Enabled = this.lnkLast.Enabled = true;
  74. }
  75. else
  76. {
  77. this.lnkNext.Enabled = this.lnkLast.Enabled = false;
  78. this.lnkFist.Enabled = this.lnkTop.Enabled = true;
  79. this.lnkNext.Attributes.Add("style", "color:#ced9df;");
  80. this.lnkLast.Attributes.Add("style", "color:#ced9df;");
  81. this.lnkFist.Attributes.Remove("style");
  82. this.lnkTop.Attributes.Remove("style");
  83. }
  84. this.lnkFist.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(1);//跳转至首页
  85. this.lnkLast.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(pds.PageCount);//跳转至末页
  86. this.RepeaterGustBookList.DataSource = pds;
  87. this.RepeaterGustBookList.DataBind();
  88. this.lbCountData.Text = wkflists.Count.ToString();
  89. this.lbPageIndex.Text = (pds.CurrentPageIndex + 1).ToString();
  90. this.lbPageSize.Text = "每页" + pds.PageSize.ToString() + "条记录";
  91. this.lbCountPage.Text = pds.PageCount.ToString();
  92. this.txtPageIndex.Text = (pds.CurrentPageIndex + 1).ToString();
  93. if (int.Parse(wkflists.Count.ToString()) <= int.Parse(pds.PageSize.ToString()))
  94. {
  95. this.lnkFist.Visible = this.lnkTop.Visible = this.lnkNext.Visible = this.lnkLast.Visible = this.txtPageIndex.Visible = this.LinkBtnToPage.Visible = false;
  96. }
  97. else
  98. {
  99. this.lnkFist.Visible = this.lnkTop.Visible = this.lnkNext.Visible = this.lnkLast.Visible = this.txtPageIndex.Visible = this.LinkBtnToPage.Visible = true;
  100. }
  101. }
  102. /// <summary>
  103. /// 删除选中
  104. /// </summary>
  105. /// <param name="sender"></param>
  106. /// <param name="e"></param>
  107. protected void BtnDelete_Click(object sender, EventArgs e)
  108. {
  109. Boolean bools = false;
  110. foreach (RepeaterItem di in this.RepeaterGustBookList.Items)
  111. {
  112. CheckBox checkIn = (CheckBox)di.FindControl("CheckIn");
  113. if (checkIn.Checked)
  114. {
  115. bools = true;
  116. Label lbGustNo = di.FindControl("lbUId") as Label;
  117. WeixinKeFuService wkf = new WeixinKeFuService();
  118. int num = wkf.DeleteWeixinKeFuInfo(int.Parse(lbGustNo.Text.ToString()));
  119. if (num > 0)
  120. {
  121. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('删除成功!');location='WeiXinSessionList.aspx'", true);
  122. }
  123. else
  124. {
  125. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('删除失败!');location='WeiXinSessionList.aspx'", true);
  126. }
  127. }
  128. }
  129. if (!bools)
  130. {
  131. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('未选中删除项!');location='WeiXinSessionList.aspx'", true);
  132. }
  133. }
  134. /// <summary>
  135. /// 全选全不选
  136. /// </summary>
  137. /// <param name="sender"></param>
  138. /// <param name="e"></param>
  139. protected void CheckAll_CheckedChanged(object sender, EventArgs e)
  140. {
  141. CheckBox checkAll = (CheckBox)sender;
  142. foreach (RepeaterItem d in this.RepeaterGustBookList.Items)
  143. {
  144. CheckBox checkIn = (CheckBox)d.FindControl("CheckIn");
  145. checkIn.Checked = checkAll.Checked;
  146. }
  147. }
  148. protected void LinkBtnLook_Click(object sender, EventArgs e)
  149. {
  150. BindGustBookList();
  151. }
  152. /// <summary>
  153. /// 绑定事件
  154. /// </summary>
  155. /// <param name="sender"></param>
  156. /// <param name="e"></param>
  157. protected void RepeaterGustBookList_ItemDataBound(object sender, RepeaterItemEventArgs e)
  158. {
  159. if (e.Item.ItemType == ListItemType.Header)
  160. {
  161. CheckBox checkAll = e.Item.FindControl("CheckAll") as CheckBox;
  162. checkAll.AutoPostBack = true;
  163. }
  164. if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  165. {
  166. WeixinKeFuInfo wkf = e.Item.DataItem as WeixinKeFuInfo;
  167. Label lbUId = e.Item.FindControl("lbUId") as Label;
  168. lbUId.Text = wkf.UId.ToString();
  169. WxMessageService wms = new WxMessageService();
  170. WxMessageInfo wminfo = wms.GetTopLastFaSongDateByUId(lbUId.Text.ToString());
  171. if(wminfo!=null&&!String.IsNullOrWhiteSpace(wminfo.FaSongDate.ToString()))
  172. {
  173. Label lblastDate = e.Item.FindControl("lblastDate") as Label;
  174. lblastDate.Text = wminfo.FaSongDate.ToString();
  175. DateTime datesystemss = DateTime.Parse(System.DateTime.Now.ToString());
  176. DateTime lastLoingDatess = DateTime.Parse(lblastDate.Text.ToString());
  177. TimeSpan ts11 = new TimeSpan(datesystemss.Ticks);
  178. TimeSpan ts22 = new TimeSpan(lastLoingDatess.Ticks);
  179. TimeSpan ts33 = ts11.Subtract(ts22).Duration();
  180. Label lbState = e.Item.FindControl("lbState") as Label;
  181. string chaoshifenzhong = ts33.TotalMinutes.ToString();
  182. if (double.Parse(chaoshifenzhong) <=10)
  183. {
  184. lbState.Text = "会话中";
  185. lbState.Attributes.Add("style","color:red;");
  186. }
  187. else
  188. {
  189. lbState.Text = "已结束";
  190. }
  191. Label lbChaoshi = e.Item.FindControl("lbChaoshi") as Label;
  192. DateTime datesystem = DateTime.Parse(System.DateTime.Now.ToString());
  193. DateTime lastLoingDate = DateTime.Parse(lblastDate.Text.ToString());
  194. TimeSpan ts1 = new TimeSpan(datesystem.Ticks);
  195. TimeSpan ts2 = new TimeSpan(lastLoingDate.Ticks);
  196. TimeSpan ts3 = ts1.Subtract(ts2).Duration();
  197. lbChaoshi.Text = ts3.Days.ToString() + "天" + ts3.Hours.ToString() + "小时" + ts3.Minutes.ToString() + "分钟";
  198. }
  199. //////根据用户的openId获取用户昵称
  200. //WeiXinServer wxs = new WeiXinServer();
  201. /////从缓存读取accesstoken
  202. //string Access_token = Cache["Access_token"] as string;
  203. //if (Access_token == null)
  204. //{
  205. // //如果为空,重新获取
  206. // Access_token = wxs.GetAccessToken();
  207. // //设置缓存的数据7000秒后过期
  208. // Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
  209. //}
  210. //string Access_tokento = Access_token.Substring(17, Access_token.Length - 37);
  211. //string jsonres = "";
  212. //jsonres = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + Access_tokento + "&openid=" + wkf.UserOpenId;
  213. //HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(jsonres);
  214. //myRequest.Method = "GET";
  215. //HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
  216. //StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
  217. //string content = reader.ReadToEnd();
  218. //reader.Close();
  219. ////使用前需药引用Newtonsoft.json.dll文件
  220. //JObject jsonObj = JObject.Parse(content);
  221. //Label lbNikeName = e.Item.FindControl("lbNikeName") as Label;
  222. //Label lbSex = e.Item.FindControl("lbSex") as Label;
  223. //lbNikeName.Text = jsonObj["nickname"].ToString();
  224. //if (jsonObj["sex"].ToString().Equals("1"))
  225. //{
  226. // lbSex.Text = "男";
  227. //}
  228. //else
  229. //{
  230. // lbSex.Text = "女";
  231. //}
  232. }
  233. }
  234. /// <summary>
  235. /// 输入页码提交跳转
  236. /// </summary>
  237. /// <param name="sender"></param>
  238. /// <param name="e"></param>
  239. protected void LinkBtnToPage_Click(object sender, EventArgs e)
  240. {
  241. if (String.IsNullOrWhiteSpace(this.txtPageIndex.Text.ToString().Trim()))
  242. {
  243. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('页码不能为空!')", true);
  244. this.txtPageIndex.Focus();
  245. return;
  246. }
  247. if (IsNum(this.txtPageIndex.Text.ToString().Trim()))
  248. {
  249. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('页码数只能输入数字!')", true);
  250. this.txtPageIndex.Focus();
  251. this.txtPageIndex.Text = this.lbPageIndex.Text.ToString();
  252. return;
  253. }
  254. if (int.Parse(this.txtPageIndex.Text.ToString().Trim()) > int.Parse(this.lbCountPage.Text.ToString().Trim()))
  255. {
  256. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('所输页数不能大于总页数!')", true);
  257. this.txtPageIndex.Focus();
  258. this.txtPageIndex.Text = this.lbPageIndex.Text.ToString();
  259. return;
  260. }
  261. BindGustBookList();
  262. }
  263. /// <summary>
  264. /// 判断是否是数字
  265. /// </summary>
  266. /// <param name="text"></param>
  267. /// <returns></returns>
  268. public static bool IsNum(string text) //
  269. {
  270. for (int i = 0; i < text.Length; i++)
  271. {
  272. if (!Char.IsNumber(text, i))
  273. {
  274. return true; //输入的不是数字
  275. }
  276. }
  277. return false; //否则是数字
  278. }

此代码已包含,后台分页功能,仔细研究下,即可使用.
点击开启会话的页面:MessageWindow.aspx如下:

  1. <%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false" CodeBehind="MessageWindow.aspx.cs" Inherits="DQWebSite.Administrator.MessageWindow" %>
  2. <!DOCTYPE html>
  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  6. <title></title>
  7. <style type="text/css">
  8. .messagestyle { width:100%; height:60px; margin-top:10px;
  9. }
  10. #LinkBtnSubSend { float:left;
  11. }
  12. /*.weixiao{ float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:0px 0px; width:30px; height:28px;
  13. }
  14. .piezui { float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-31px -0px; width:30px; height:28px;
  15. }
  16. .hanxiao {float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-0px -62px; width:30px; height:28px;
  17. }
  18. .zhuakuang {float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-218px -62px; width:28px; height:28px;
  19. }
  20. .shuai {float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-248px -62px; width:28px; height:28px;
  21. }
  22. .yiwen {float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-126px -62px; width:28px; height:28px;
  23. }
  24. .liuhan {float:left; background-image:url('images/qqbiaoqing.jpg'); background-repeat:no-repeat; background-position:-404px -30px; width:28px; height:28px;
  25. }*/
  26. a:hover { cursor:pointer;
  27. }
  28. .LinkBtnSubSend { margin-top:5px;
  29. }
  30. </style>
  31. <script type="text/javascript">
  32. function LessThan(oTextArea) {
  33. //获得textarea的maxlength属性
  34. var num = oTextArea.getAttribute("maxlength") - oTextArea.value.length;
  35. document.getElementById("errmsg").innerHTML = "还可输入的字符数:" + num;
  36. //返回文本框字符个数是否符号要求的boolean值
  37. return oTextArea.value.length < oTextArea.getAttribute("maxlength");
  38. }
  39. </script>
  40. <script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
  41. <script src="../ckeditor_4.5.4_full2/ckeditor/ckeditor.js"></script>
  42. </head>
  43. <body>
  44. <form id="form1" runat="server">
  45. <div style="height:30px; text-align:left;"> <asp:Label ID="lbduihua1" runat="server" Text="Label"></asp:Label> <span style="color:red;"><asp:Label ID="lbduihuamsg" runat="server" Text="Label"></asp:Label></span> <asp:Label ID="lbduihua2" runat="server" Text="Label"></asp:Label></div>
  46. <div style="height:200px; width:100%; border:2px groove #ced9df; border-top-left-radius:5px; border-top-right-radius:5px; overflow-y:auto;background-image:url('images/ygbg.png'); background-repeat:repeat;">
  47. <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
  48. <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  49. <ContentTemplate>
  50. <ul>
  51. <asp:Repeater ID="RepeaterMessageList" runat="server" OnItemDataBound="RepeaterMessageList_ItemDataBound" >
  52. <ItemTemplate>
  53. <li><span style="color:red;">
  54. <asp:Label ID="lbFromUser" runat="server" Text="Label"></asp:Label> </span>对<span style="color:red;"><%# Eval("ToUser") %></span>说:
  55. <asp:Image ID="Imagelaba" runat="server" />
  56. <br />
  57. <%# Eval("Content") %> [<%# Eval("FaSongDate") %>]<br />
  58. </li>
  59. </ItemTemplate>
  60. </asp:Repeater>
  61. </ul>
  62. <asp:Timer ID="timeTick" runat="server" Interval="200" OnTick="timeTick_Tick"></asp:Timer>
  63. </ContentTemplate>
  64. </asp:UpdatePanel>
  65. </div>
  66. <textarea id="txtMessage" name="txtMessage" runat="server" class="ckeditor messagestyle" maxlength="200" onkeypress="return LessThan(this);" onchange="return LessThan(this);"></textarea>
  67. <script type="text/javascript">CKEDITOR.replace('<%=txtMessage.ClientID.Replace("_","$") %>');</script>
  68. <div style="height:35px; line-height:35px;">
  69. <asp:LinkButton ID="LinkBtnSubSend" CssClass="LinkBtnSubSend" runat="server" OnClick="LinkBtnSubSend_Click"><div style="background-image:url('images/buttonbg.png'); width:111px; height:35px; line-height:35px; font-weight:bold; text-align:center; float:left; color:#fff;">发送</div></asp:LinkButton>
  70. <span id="errmsg" style="color:red;" runat="server" >该推送功能直接将信息推送到对方用户微信,谨慎发言</span>
  71. </div>
  72. </form>
  73. </body>
  74. </html>

MessageWindow.aspx.cs的核心代码如下:

  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if(!Page.IsPostBack)
  4. {
  5. if(Request.QueryString["id"]!=null)
  6. {
  7. WeixinKeFuService wkfs = new WeixinKeFuService();
  8. WeixinKeFuInfo wkfinfo = wkfs.GetWeixinKeFuInfoByid(int.Parse(Request.QueryString["id"].ToString()));
  9. this.lbduihuamsg.Text = wkfinfo.UserOpenId.ToString();
  10. this.lbduihua1.Text = "正在于";
  11. this.lbduihua2.Text = "对话中.......";
  12. WxMessageService wms = new WxMessageService();
  13. WxMessageInfo wminfo = wms.GetTopLastFaSongDateByUId(wkfinfo.UId.ToString());
  14. if (wminfo != null)
  15. {
  16. DateTime datesystemss = DateTime.Parse(System.DateTime.Now.ToString());
  17. DateTime lastLoingDatess = DateTime.Parse(wminfo.FaSongDate.ToString());
  18. TimeSpan ts11 = new TimeSpan(datesystemss.Ticks);
  19. TimeSpan ts22 = new TimeSpan(lastLoingDatess.Ticks);
  20. TimeSpan ts33 = ts11.Subtract(ts22).Duration();
  21. string chaodays = ts33.TotalDays.ToString();
  22. if (double.Parse(chaodays) >=2)
  23. {
  24. this.LinkBtnSubSend.Enabled = false;
  25. this.errmsg.InnerText = "会话已结束!超过48小时不能主动推送信息给该用户!";
  26. this.lbduihua1.Text = "已经于";
  27. this.lbduihua2.Text = "失去连接.....除非该用户主动会话才能重新建立连接!";
  28. this.txtMessage.Attributes.Add("readonly","true");
  29. }
  30. }
  31. BindMsgList();
  32. this.DataBind();
  33. }
  34. }
  35. }
  36. private void BindMsgList()
  37. {
  38. string id = Request.QueryString["id"].ToString();
  39. WxMessageService wms = new WxMessageService();
  40. List<WxMessageInfo> wmlist = wms.GetAllMessageList(id);
  41. if(wmlist.Count>0)
  42. {
  43. this.RepeaterMessageList.DataSource = wmlist;
  44. this.RepeaterMessageList.DataBind();
  45. }
  46. }
  47. protected void timeTick_Tick(object sender, EventArgs e)
  48. {
  49. BindMsgList();
  50. }
  51. /// <summary>
  52. /// 推送消息到用户
  53. /// </summary>
  54. /// <param name="sender"></param>
  55. /// <param name="e"></param>
  56. protected void LinkBtnSubSend_Click(object sender, EventArgs e)
  57. {
  58. if(String.IsNullOrWhiteSpace(this.txtMessage.Value.ToString().Trim()))
  59. {
  60. this.errmsg.InnerText = "发送的内容不能为空!";
  61. this.txtMessage.Focus();
  62. return;
  63. }
  64. if (this.txtMessage.Value.ToString().Length < 5 || this.txtMessage.Value.ToString().Length > 200)
  65. {
  66. this.errmsg.InnerText = "发送内容应在5-200个字符之间!";
  67. this.txtMessage.Focus();
  68. return;
  69. }
  70. //如果存在直接保存消息记录
  71. WxMessageService wms = new WxMessageService();
  72. WxMessageInfo wminfo = new WxMessageInfo();
  73. wminfo.FromUser = "我";
  74. wminfo.ToUser = this.lbduihuamsg.Text.ToString();
  75. wminfo.Content = this.txtMessage.Value.ToString().Trim();
  76. wminfo.FaSongDate = System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
  77. wminfo.UId = Request.QueryString["id"].ToString();
  78. wms.AddWxMessageInfo(wminfo);
  79. WeiXinServer wxs = new WeiXinServer();
  80. string res = "";
  81. ///从缓存读取accesstoken
  82. string Access_token = Cache["Access_token"] as string;
  83. if(Access_token==null)
  84. {
  85. //如果为空,重新获取
  86. Access_token = wxs.GetAccessToken();
  87. //设置缓存的数据7000秒后过期
  88. Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
  89. }
  90. string Access_tokento = Access_token.Substring(17, Access_token.Length - 37);
  91. string txtcontent = this.txtMessage.Value.ToString().Replace("<p>", "");
  92. StringBuilder sb = new StringBuilder();
  93. sb.Append(txtcontent.Replace("</p>\r\n", ""));
  94. string posturl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_tokento;
  95. string postData = "{\"touser\":\"" + this.lbduihuamsg.Text.ToString() + "\",\"msgtype\":\"text\",\"text\":{\"content\":\"" + sb.ToString() + "\"}}";
  96. res = wxs.GetPage(posturl, postData);
  97. //使用前需药引用Newtonsoft.json.dll文件
  98. JObject jsonObj = JObject.Parse(res);
  99. ///获取返回结果的正确|true|false
  100. string isright = jsonObj["errcode"].ToString();//0
  101. string istrueorfalse = jsonObj["errmsg"].ToString();//ok
  102. if (isright.Equals("0") && istrueorfalse.Equals("ok"))
  103. {
  104. this.errmsg.InnerText = "消息推送成功!消息已送达微信用户!";
  105. this.txtMessage.Value = "";
  106. }
  107. else
  108. {
  109. this.errmsg.InnerText = "消息推送失败!消息已保存至数据库!";
  110. }
  111. }
  112. protected void RepeaterMessageList_ItemDataBound(object sender, RepeaterItemEventArgs e)
  113. {
  114. if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  115. {
  116. WxMessageInfo wminfo = e.Item.DataItem as WxMessageInfo;
  117. Image Imagelaba = e.Item.FindControl("Imagelaba") as Image;
  118. Label lbFromUser = e.Item.FindControl("lbFromUser") as Label;
  119. lbFromUser.Text = wminfo.FromUser.ToString();
  120. if (wminfo.FromUser.ToString().Equals("我"))
  121. {
  122. Imagelaba.ImageUrl = "images/fa.gif";
  123. }
  124. else
  125. {
  126. Imagelaba.ImageUrl = "images/shou.gif";
  127. }
  128. }
  129. }

本文已被整理到了《ASP.NET微信开发教程汇总》,欢迎大家学习阅读。

以上就是会话管理功能的全部核心代码,仅供参考,希望对大家的学习有所帮助。

人气教程排行