当前位置:Gxlcms > asp.net > asp.net微信开发(高级群发图文)

asp.net微信开发(高级群发图文)

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

上一篇介绍了如何群发文本消息,本篇将介绍如何群发图文信息,上传图文信息所需的素材,界面如下:

我们先看从素材库中获取图文素材的代码,界面:

素材列表,我是使用的repeater控件,

前台代码如下:

  1. <!--弹出选择素材窗口-->
  2. <div id="shownewgroup">
  3. <div class="closeLogin" style="height:40px; background-color:#ddd9ff; line-height:40px;"><span style="float:left; color:#000; font-size:14px; text-indent:5px;">选择素材</span>
  4. <span style="float:left;margin-left:20px;"><a href="WxNewTuWen.aspx" style="color:red;" onclick="hrefurl();" class="hrefurl">新建图文素材</a></span>
  5. <a class="closeloginpage"><img src="images/close1.png" alt="" /></a>  </div>
  6. <div style="height:455px; width:100%;">
  7. <asp:UpdatePanel ID="UpdatePanel2" runat="server">
  8. <ContentTemplate>
  9. <div style="width:100%; height:35px; margin:10px;"><asp:LinkButton ID="LinkBtnSelect" runat="server" OnClick="LinkBtnSelect_Click" ><div style="background-image:url('images/buttonbg.png'); width:111px; height:35px; float:left; line-height:35px; font-weight:bold; text-align:center;color:#fff;">确认选择</div></asp:LinkButton>
  10. <span style="float:left;margin-left:20px;"><asp:LinkButton ID="LinkbtnRefresh" CssClass="LinkbtnRefresh" runat="server" OnClick="LinkbtnRefresh_Click"><div style="background-image:url('images/buttonbg.png'); width:111px; height:35px; line-height:35px; font-weight:bold; text-align:center;color:#fff;">刷新</div></asp:LinkButton></span>
  11. <span style="float:left;margin-left:20px;"><asp:LinkButton ID="LinkBtnDelete" CssClass="LinkbtnRefresh" runat="server" OnClick="LinkBtnDelete_Click"><div style="background-image:url('images/buttonbg.png'); width:111px; height:35px; line-height:35px; font-weight:bold; text-align:center;color:#fff;">删除素材</div></asp:LinkButton></span>
  12. </div>
  13. <div style="word-wrap:break-word;" id="lbnewssucai" runat="server">
  14. <asp:Repeater ID="Repeatersucailist" runat="server" OnItemDataBound="Repeatersucailist_ItemDataBound">
  15. <ItemTemplate>
  16. <table style="width:100%; border-top:1px solid #edc9df; border-collapse:collapse; font-size:12px;" >
  17. <tr>
  18. <td style="width:100px;"><asp:Image ID="ImageUrl" CssClass="fenmianstyle2" runat="server" /></td>
  19. <td style="text-align:left; width:470px; ">
  20. <asp:Repeater ID="Repeatersucailist2" runat="server">
  21. <ItemTemplate>
  22. <ul style="margin:0px;padding:0px;">
  23. <li><%# Eval("title") %></li>
  24. </ul>
  25. </ItemTemplate>
  26. </asp:Repeater>
  27. </td>
  28. <td style="width:130px;">
  29. <asp:Label ID="lbUpate_time" runat="server" Text="Label"></asp:Label>
  30. </td>
  31. <td style="width:50px; text-align:center;">
  32. <asp:CheckBox ID="CheckIn" runat="server" />
  33. <asp:Label ID="lbmedia_id" runat="server" Visible="false" Text=""></asp:Label>
  34. </td>
  35. </tr>
  36. </table>
  37. </ItemTemplate>
  38. </asp:Repeater>
  39. <div style="font-size:14px; height:30px; line-height:30px; text-indent:10px; border-top:1px solid #ced9df;">
  40. <span style="float:left;">本类型素材总数量为:</span><span style="float:left; color:red;"><asp:Label ID="lbtotal_count" runat="server" Text="0"></asp:Label></span>  
  41. <span style="float:left; margin-left:20px;">本次获取的素材数量为:</span><span style="float:left; color:red;"><asp:Label ID="lbitem_count" runat="server" Text="0"></asp:Label></span>
  42. </div>
  43. </div>
  44. </ContentTemplate>
  45. </asp:UpdatePanel>
  46. </div>
  47. </div>
  48. <div id="shownewgroupzhezhaoceng"></div>

后台代码如下:

  1. /// <summary>
  2. /// 绑定图文素材列表
  3. /// </summary>
  4. private void BindNewsSucaiList()
  5. {
  6. WeiXinServer wxs = new WeiXinServer();
  7. string res = "";
  8. ///从缓存读取accesstoken
  9. string Access_token = Cache["Access_token"] as string;
  10. if (Access_token == null)
  11. {
  12. //如果为空,重新获取
  13. Access_token = wxs.GetAccessToken();
  14. //设置缓存的数据7000秒后过期
  15. Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
  16. }
  17. string Access_tokento = Access_token.Substring(17, Access_token.Length - 37);
  18. string posturl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + Access_tokento;
  19. //POST数据例子: POST数据例子:{"type":TYPE,"offset":OFFSET,"count":COUNT}
  20. string postData = "{\"type\":\"news\",\"offset\":\"0\",\"count\":\"20\"}";
  21. res = wxs.GetPage(posturl, postData);
  22. //使用前需要引用Newtonsoft.json.dll文件
  23. JObject jsonObj = JObject.Parse(res);
  24. int groupsnum = jsonObj["item"].Count();
  25. List<WxNewsSucaiIteminfo> newssucaiitemlist = new List<WxNewsSucaiIteminfo>();
  26. List<WxNewsSuCaiItemlistinfo> WxNewsSuCaiItemlist = new List<WxNewsSuCaiItemlistinfo>();
  27. for (int i = 0; i < groupsnum; i++)
  28. {
  29. WxNewsSucaiIteminfo newssucaiitem = new WxNewsSucaiIteminfo();
  30. newssucaiitem.media_id = jsonObj["item"][i]["media_id"].ToString();
  31. newssucaiitem.update_time = jsonObj["item"][i]["update_time"].ToString();
  32. newssucaiitem.total_count = jsonObj["total_count"].ToString();
  33. newssucaiitem.item_count = jsonObj["item_count"].ToString();
  34. newssucaiitemlist.Add(newssucaiitem);
  35. int news_itemcount = jsonObj["item"][i]["content"]["news_item"].Count();
  36. if (news_itemcount > 0)
  37. {
  38. for (int j = 0; j < news_itemcount; j++)
  39. {
  40. WxNewsSuCaiItemlistinfo wnscilinfo = new WxNewsSuCaiItemlistinfo();
  41. wnscilinfo.title = jsonObj["item"][i]["content"]["news_item"][j]["title"].ToString();
  42. wnscilinfo.thumb_media_id = jsonObj["item"][i]["content"]["news_item"][j]["thumb_media_id"].ToString();
  43. wnscilinfo.show_cover_pic = int.Parse(jsonObj["item"][i]["content"]["news_item"][j]["show_cover_pic"].ToString());
  44. wnscilinfo.author = jsonObj["item"][i]["content"]["news_item"][j]["author"].ToString();
  45. wnscilinfo.digest = jsonObj["item"][i]["content"]["news_item"][j]["digest"].ToString();
  46. wnscilinfo.content = jsonObj["item"][i]["content"]["news_item"][j]["content"].ToString();
  47. wnscilinfo.url = jsonObj["item"][i]["content"]["news_item"][j]["url"].ToString();
  48. wnscilinfo.content_source_url = jsonObj["item"][i]["content"]["news_item"][j]["content_source_url"].ToString();
  49. wnscilinfo.media_id = newssucaiitem.media_id.ToString();
  50. WxNewsSuCaiItemlist.Add(wnscilinfo);
  51. }
  52. }
  53. }
  54. Session["WxNewsSuCaiItemlist"] = WxNewsSuCaiItemlist;
  55. this.Repeatersucailist.DataSource = newssucaiitemlist;
  56. this.Repeatersucailist.DataBind();
  57. }

再来看看,新建单图文信息界面:

新建单图文上传封面,删除封面的代码如下:

  1. /// <summary>
  2. ///
  3. /// </summary>上传图片文件
  4. /// <param name="sender"></param>
  5. /// <param name="e"></param>
  6. protected void LinkBtnFileUploadImg_Click(object sender, EventArgs e)
  7. {
  8. if (this.FileUploadImg.HasFile)
  9. {
  10. string fileContentType = FileUploadImg.PostedFile.ContentType;
  11. if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/png" || fileContentType == "image/x-png" || fileContentType == "image/jpeg"
  12. || fileContentType == "image/pjpeg")
  13. {
  14. int fileSize = this.FileUploadImg.PostedFile.ContentLength;
  15. if (fileSize <=2097152)
  16. {
  17. string fileName = this.FileUploadImg.PostedFile.FileName;
  18. // 客户端文件路径
  19. string filepath = FileUploadImg.PostedFile.FileName; //得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg
  20. //string filepath = FileUpload1.FileName; //得到上传的文件名20022775_m.jpg
  21. string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg
  22. string serverpath = Server.MapPath("~/WeiXinImg/") + filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg
  23. this.ImgTuWen.ImageUrl = "~/WeiXinImg/" + FileUploadImg.FileName;
  24. this.ImgTuWen2.Visible = true;
  25. this.ImgTuWen2.ImageUrl = "~/WeiXinImg/" + FileUploadImg.FileName;
  26. this.FileUploadImg.PostedFile.SaveAs(serverpath);//将上传的文件另存为
  27. this.LinkBtnDeleteImg.Visible = true;
  28. Session["fileNameimg"] = this.FileUploadImg.PostedFile.FileName;
  29. //上传临时图片素材至微信服务器,3天后微信服务器会自动删除
  30. WeiXinServer wxs = new WeiXinServer();
  31. ///从缓存读取accesstoken
  32. string Access_token = Cache["Access_token"] as string;
  33. if (Access_token == null)
  34. {
  35. //如果为空,重新获取
  36. Access_token = wxs.GetAccessToken();
  37. //设置缓存的数据7000秒后过期
  38. Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
  39. }
  40. string Access_tokento = Access_token.Substring(17, Access_token.Length - 37);
  41. //WebClient wx_upload = new WebClient();
  42. //wx_upload.Credentials = CredentialCache.DefaultCredentials;
  43. string url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", Access_tokento, "image");
  44. string result = HttpUploadFile(url, serverpath);
  45. if (result.Contains("media_id"))
  46. {
  47. //使用前需要引用Newtonsoft.json.dll文件
  48. JObject jsonObj = JObject.Parse(result);
  49. Session["imgmedia_id"] = jsonObj["media_id"].ToString();
  50. }
  51. Response.Write("<script>alert('上传图片成功!')</script>");
  52. }
  53. else
  54. {
  55. Response.Write("<script>alert('上传文件不能大于2M!')</script>");
  56. }
  57. }
  58. else
  59. {
  60. Response.Write("<script>alert('只支持BMP,GIF,PNG,JPG格式的图片!')</script>");
  61. }
  62. }
  63. else
  64. {
  65. Response.Write("<script>alert('请选择图片!')</script>");
  66. }
  67. }
  68. /// <summary>
  69. /// Http上传文件
  70. /// </summary>
  71. public static string HttpUploadFile(string url, string path)
  72. {
  73. // 设置参数
  74. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  75. CookieContainer cookieContainer = new CookieContainer();
  76. request.CookieContainer = cookieContainer;
  77. request.AllowAutoRedirect = true;
  78. request.Method = "POST";
  79. string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
  80. request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
  81. byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
  82. byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
  83. int pos = path.LastIndexOf("\\");
  84. string fileName = path.Substring(pos + 1);
  85. //请求头部信息
  86. StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
  87. byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
  88. FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
  89. byte[] bArr = new byte[fs.Length];
  90. fs.Read(bArr, 0, bArr.Length);
  91. fs.Close();
  92. Stream postStream = request.GetRequestStream();
  93. postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
  94. postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
  95. postStream.Write(bArr, 0, bArr.Length);
  96. postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
  97. postStream.Close();
  98. //发送请求并获取相应回应数据
  99. HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  100. //直到request.GetResponse()程序才开始向目标网页发送Post请求
  101. Stream instream = response.GetResponseStream();
  102. StreamReader sr = new StreamReader(instream, Encoding.UTF8);
  103. //返回结果网页(html)代码
  104. string content = sr.ReadToEnd();
  105. return content;
  106. }
  107. /// <summary>
  108. /// 删除图片
  109. /// </summary>
  110. /// <param name="sender"></param>
  111. /// <param name="e"></param>
  112. protected void LinkBtnDeleteImg_Click(object sender, EventArgs e)
  113. {
  114. string filename = Session["fileNameimg"].ToString();
  115. if (!string.IsNullOrEmpty(filename))//确保picPath有值并且不为空。
  116. {
  117. string serverpath = Server.MapPath("~/WeiXinImg/") + filename;//取得文件在服务器上保存的位置C:\Inetpub\wwwroot\WebSite1\images\20022775_m.jpg
  118. if (File.Exists(serverpath))
  119. {
  120. try
  121. {
  122. File.Delete(serverpath);
  123. this.ImgTuWen.ImageUrl = "weixinimg/fengmiandefault.jpg";
  124. this.ImgTuWen2.Visible = false;
  125. this.ImgTuWen2.ImageUrl = "";
  126. Session["fileNameimg"] = null;
  127. this.LinkBtnDeleteImg.Visible = false;
  128. }
  129. catch(Exception ex)
  130. {
  131. //错误处理:
  132. Response.Write(ex.Message.ToString());
  133. }
  134. }
  135. }
  136. }

新建单图文预览代码如下:

  1. /// <summary>
  2. /// 预览图文消息
  3. /// </summary>
  4. /// <param name="sender"></param>
  5. /// <param name="e"></param>
  6. protected void LinkBtnSendPreview_Click(object sender, EventArgs e)
  7. {
  8. Session["media_id"] = null;
  9. //非空验证
  10. if (String.IsNullOrWhiteSpace(this.txttuwen_title.Value.ToString()))
  11. {
  12. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('请输入图文标题!');", true);
  13. this.txttuwen_title.Focus();
  14. return;
  15. }
  16. if (this.ImgTuWen2.ImageUrl.ToString().Equals(""))
  17. {
  18. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('必须上传一张图片!');", true);
  19. this.ImgTuWen2.Focus();
  20. return;
  21. }
  22. if (String.IsNullOrWhiteSpace(this.tbContent.InnerText.ToString()))
  23. {
  24. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('请输入正文内容!');", true);
  25. this.tbContent.Focus();
  26. return;
  27. }
  28. //对各项进行赋值
  29. WeiXinServer wxs = new WeiXinServer();
  30. ///从缓存读取accesstoken
  31. string Access_token = Cache["Access_token"] as string;
  32. if (Access_token == null)
  33. {
  34. //如果为空,重新获取
  35. Access_token = wxs.GetAccessToken();
  36. //设置缓存的数据7000秒后过期
  37. Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
  38. }
  39. string Access_tokento = Access_token.Substring(17, Access_token.Length - 37);
  40. //POST数据例子: POST数据例子:
  41. //{
  42. // "articles": [{
  43. // "title": TITLE,
  44. // "thumb_media_id": THUMB_MEDIA_ID,
  45. // "author": AUTHOR,
  46. // "digest": DIGEST,
  47. // "show_cover_pic": SHOW_COVER_PIC(0 / 1),
  48. // "content": CONTENT,
  49. // "content_source_url": CONTENT_SOURCE_URL
  50. // },
  51. // //若新增的是多图文素材,则此处应还有几段articles结构
  52. // ]
  53. //}
  54. string isshow_cover_pic = "";
  55. if (this.CheckFengMianShow.Checked)
  56. {
  57. isshow_cover_pic = "1";
  58. }
  59. else
  60. {
  61. isshow_cover_pic = "0";
  62. }
  63. string description = NoHTML(this.tbContent.InnerText.ToString());
  64. string postData = "{\"articles\":[{\"title\":\"" + this.txttuwen_title.Value.ToString() +
  65. "\",\"thumb_media_id\":\"" + Session["imgmedia_id"].ToString() +
  66. "\",\"author\":\"" + this.txttuwen_author.Value.ToString() +
  67. "\",\"digest\":\"" + this.txtzhaiyao.InnerText.ToString() +
  68. "\",\"show_cover_pic\":\"" + isshow_cover_pic +
  69. "\",\"content\":\"" + description +
  70. "\",\"content_source_url\":\"" + this.txtYuanWenUrl.Text.ToString() +
  71. "\"}]}";
  72. string posturl = string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", Access_tokento);
  73. string jsonres = PostUrl(posturl, postData);
  74. if (jsonres.Contains("media_id"))
  75. {
  76. //使用前需要引用Newtonsoft.json.dll文件
  77. JObject jsonObj = JObject.Parse(jsonres);
  78. if (this.txttoUserName.Value.ToString().Trim().Equals("请输入用户微信号"))
  79. {
  80. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('请输入接收消息的用户微信号!');", true);
  81. return;
  82. }
  83. string posturls = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=" + Access_tokento;
  84. //预览图文消息的json数据{
  85. // "touser":"OPENID", 可改为对微信号预览,例如towxname:zhangsan
  86. // "mpnews":{
  87. // "media_id":"123dsdajkasd231jhksad"
  88. // },
  89. // "msgtype":"mpnews"
  90. //}
  91. string postDatas = "{\"towxname\":\"" + this.txttoUserName.Value.ToString() +
  92. "\",\"mpnews\":{\"media_id\":\"" + jsonObj["media_id"].ToString() +
  93. "\"},\"msgtype\":\"mpnews\"}";
  94. string tuwenres = wxs.GetPage(posturls, postDatas);
  95. //使用前需药引用Newtonsoft.json.dll文件
  96. JObject jsonObjss = JObject.Parse(tuwenres);
  97. if (jsonObjss["errcode"].ToString().Equals("0"))
  98. {
  99. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('发送预览成功!!');", true);
  100. return;
  101. }
  102. else
  103. {
  104. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('发送预览失败!!');", true);
  105. return;
  106. }
  107. }
  108. }
  109. public static string NoHTML(string Htmlstring)
  110. {
  111. //删除脚本
  112. Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
  113. //替换标签
  114. Htmlstring = Htmlstring.Replace("\r\n", " ");
  115. Htmlstring = Htmlstring.Replace("\"", "'");
  116. Htmlstring = Htmlstring.Replace(" ", " ");
  117. return Htmlstring;
  118. }

单击确定按钮代码如下:

  1. /// <summary>
  2. /// 确认选择
  3. /// </summary>
  4. /// <param name="sender"></param>
  5. /// <param name="e"></param>
  6. protected void LinkBtnSubSave_Click(object sender, EventArgs e)
  7. {
  8. Session["media_id"] = null;
  9. //非空验证
  10. if (String.IsNullOrWhiteSpace(this.txttuwen_title.Value.ToString()))
  11. {
  12. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('请输入图文标题!');", true);
  13. return;
  14. }
  15. if (this.ImgTuWen2.ImageUrl.ToString().Equals(""))
  16. {
  17. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('必须上传一张图片!');", true);
  18. return;
  19. }
  20. if (String.IsNullOrWhiteSpace(this.tbContent.InnerText.ToString()))
  21. {
  22. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('请输入正文内容!');", true);
  23. return;
  24. }
  25. //对各项进行赋值
  26. WeiXinServer wxs = new WeiXinServer();
  27. ///从缓存读取accesstoken
  28. string Access_token = Cache["Access_token"] as string;
  29. if (Access_token == null)
  30. {
  31. //如果为空,重新获取
  32. Access_token = wxs.GetAccessToken();
  33. //设置缓存的数据7000秒后过期
  34. Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
  35. }
  36. string Access_tokento = Access_token.Substring(17, Access_token.Length - 37);
  37. //POST数据例子: POST数据例子:
  38. //{
  39. // "articles": [{
  40. // "title": TITLE,
  41. // "thumb_media_id": THUMB_MEDIA_ID,
  42. // "author": AUTHOR,
  43. // "digest": DIGEST,
  44. // "show_cover_pic": SHOW_COVER_PIC(0 / 1),
  45. // "content": CONTENT,
  46. // "content_source_url": CONTENT_SOURCE_URL
  47. // },
  48. // //若新增的是多图文素材,则此处应还有几段articles结构
  49. // ]
  50. //}
  51. string isshow_cover_pic = "";
  52. if (this.CheckFengMianShow.Checked)
  53. {
  54. isshow_cover_pic = "1";
  55. }
  56. else
  57. {
  58. isshow_cover_pic = "0";
  59. }
  60. string description = NoHTML(this.tbContent.InnerText.ToString());
  61. string postData = "{\"articles\":[{\"title\":\"" + this.txttuwen_title.Value.ToString() +
  62. "\",\"thumb_media_id\":\"" + Session["imgmedia_id"].ToString() +
  63. "\",\"author\":\"" + this.txttuwen_author.Value.ToString() +
  64. "\",\"digest\":\"" + this.txtzhaiyao.InnerText.ToString() +
  65. "\",\"show_cover_pic\":\"" + isshow_cover_pic +
  66. "\",\"content\":\"" + description +
  67. "\",\"content_source_url\":\"" + this.txtYuanWenUrl.Text.ToString() +
  68. "\"}]}";
  69. string posturl = string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", Access_tokento);
  70. string jsonres = PostUrl(posturl, postData);
  71. if (jsonres.Contains("media_id"))
  72. {
  73. //使用前需要引用Newtonsoft.json.dll文件
  74. JObject jsonObj = JObject.Parse(jsonres);
  75. WxMpNewsInfo wmninfo = new WxMpNewsInfo();
  76. wmninfo.title = this.txttuwen_title.Value.ToString();
  77. wmninfo.contents = description.ToString();
  78. wmninfo.ImageUrl = this.ImgTuWen.ImageUrl.ToString();
  79. Session["wmninfo"] = wmninfo;
  80. Response.Redirect("WxMassManage.aspx?media_id=" + jsonObj["media_id"].ToString());
  81. }
  82. }
  83. /// <summary>
  84. /// 请求Url,发送数据
  85. /// </summary>
  86. public static string PostUrl(string url, string postData)
  87. {
  88. byte[] data = Encoding.UTF8.GetBytes(postData);
  89. // 设置参数
  90. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  91. CookieContainer cookieContainer = new CookieContainer();
  92. request.CookieContainer = cookieContainer;
  93. request.AllowAutoRedirect = true;
  94. request.Method = "POST";
  95. request.ContentType = "application/x-www-form-urlencoded";
  96. request.ContentLength = data.Length;
  97. Stream outstream = request.GetRequestStream();
  98. outstream.Write(data, 0, data.Length);
  99. outstream.Close();
  100. //发送请求并获取相应回应数据
  101. HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  102. //直到request.GetResponse()程序才开始向目标网页发送Post请求
  103. Stream instream = response.GetResponseStream();
  104. StreamReader sr = new StreamReader(instream, Encoding.UTF8);
  105. //返回结果网页(html)代码
  106. string content = sr.ReadToEnd();
  107. return content;
  108. }

Response.Redirect("WxMassManage.aspx?media_id=" + jsonObj["media_id"].ToString());
这句代码就是将上传图文后得到的media_Id参数传送到群发界面,群发界面接收代码如下:

  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if(!Page.IsPostBack)
  4. {
  5. BindNewsSucaiList();//绑定素材列表
  6. BindGroupList();//绑定分组列表
  7. BindMassCount();//绑定本月已群发条数
  8. this.DataBind();
  9. if (Request.QueryString["media_id"] != null)
  10. {
  11. this.RadioBtnList.SelectedValue = "1";
  12. this.showExpress.Visible = false;
  13. this.txtwenben.Visible = false;
  14. this.tuwen.Visible = true;
  15. this.tuwenxuan.Visible = false;
  16. this.tuwenjian.Visible = false;
  17. this.lbtuwenmedai_id.Visible = true;
  18. this.lbtuwenmedai_id.Text = Request.QueryString["media_id"].ToString();
  19. this.LinkBtndeletetuwen.Visible = true;
  20. this.Imageyixuan.Visible = true;
  21. }
  22. }
  23. }

最终界面如下:

我这里只接收了一个media_id值,相对于做的简单,直接将值赋值给了一个label用于显示,也可以做成像官网那样,确定选择后,按照图文样式显示.

最后一步:群发按钮代码:其实上一章已经将代码贴出去了,这一章,我就单独贴一遍吧。
 

  1. /// <summary>
  2. /// 群发
  3. /// </summary>
  4. /// <param name="sender"></param>
  5. /// <param name="e"></param>
  6. protected void LinkBtnSubSend_Click(object sender, EventArgs e)
  7. {
  8. //根据单选按钮判断类型,//如果选择的是图文消息
  9. if (this.RadioBtnList.SelectedValue.ToString().Equals("1"))
  10. {
  11. if (String.IsNullOrWhiteSpace(this.lbtuwenmedai_id.Text.ToString().Trim()))
  12. {
  13. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('请选择或新建图文素材再进行群发!');", true);
  14. return;
  15. }
  16. WxMassService wms = new WxMassService();
  17. List<WxMassInfo> wxmaslist = wms.GetMonthMassCount();
  18. if (wxmaslist.Count >= 4)
  19. {
  20. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('本月可群发消息数量已达上限!');", true);
  21. return;
  22. }
  23. else
  24. {
  25. //如何群发类型为全部用户,根据openID列表群发给全部用户,订阅号不可用,服务号认证后可用
  26. if (this.DDLMassType.SelectedValue.ToString().Equals("0"))
  27. {
  28. StringBuilder sbs = new StringBuilder();
  29. sbs.Append(GetAllUserOpenIDList());
  30. WeiXinServer wxs = new WeiXinServer();
  31. ///从缓存读取accesstoken
  32. string Access_token = Cache["Access_token"] as string;
  33. if (Access_token == null)
  34. {
  35. //如果为空,重新获取
  36. Access_token = wxs.GetAccessToken();
  37. //设置缓存的数据7000秒后过期
  38. Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
  39. }
  40. string Access_tokento = Access_token.Substring(17, Access_token.Length - 37);
  41. string posturl = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" + Access_tokento;
  42. ///群发POST数据示例如下:
  43. // {
  44. // "touser":[
  45. // "OPENID1",
  46. // "OPENID2"
  47. // ],
  48. // "mpnews":{
  49. // "media_id":"123dsdajkasd231jhksad"
  50. // },
  51. // "msgtype":"mpnews"
  52. //}
  53. string postData = "{\"touser\":[" + sbs.ToString() +
  54. "],\"mpnews\":{\"media_id\":\"" + this.lbtuwenmedai_id.Text.ToString() +
  55. "\"},\"msgtype\":\"mpnews\"}";
  56. string tuwenres = wxs.GetPage(posturl, postData);
  57. //使用前需药引用Newtonsoft.json.dll文件
  58. JObject jsonObj = JObject.Parse(tuwenres);
  59. if (jsonObj["errcode"].ToString().Equals("0"))
  60. {
  61. Session["media_id"] = null;
  62. WxMassInfo wmi = new WxMassInfo();
  63. if (Session["wmninfo"] != null)
  64. {
  65. WxMpNewsInfo wmninfo = Session["wmninfo"] as WxMpNewsInfo;
  66. wmi.title = wmninfo.title.ToString();
  67. wmi.contents = wmninfo.contents.ToString();
  68. wmi.ImageUrl = wmninfo.ImageUrl.ToString();
  69. wmi.type = "图文";
  70. if (this.DDLMassType.SelectedValue.ToString().Equals("0"))
  71. {
  72. wmi.massObject = this.DDLMassType.SelectedItem.Text.ToString();
  73. }
  74. else
  75. {
  76. wmi.massObject = this.DDLGroupList.SelectedItem.Text.ToString();
  77. }
  78. wmi.massStatus = "成功";//群发成功之后返回的状态码
  79. wmi.massMessageID = jsonObj["msg_id"].ToString();//群发成功之后返回的消息ID
  80. wmi.massDate = System.DateTime.Now.ToString();
  81. int num = wms.AddWxMassInfo(wmi);
  82. if (num > 0)
  83. {
  84. Session["wmninfo"] = null;
  85. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!数据已保存!');location='WxMassManage.aspx';", true);
  86. return;
  87. }
  88. else
  89. {
  90. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!数据保存失败!');", true);
  91. return;
  92. }
  93. }
  94. else
  95. {
  96. wmi.title = "";
  97. wmi.contents = "";
  98. wmi.ImageUrl = "";
  99. wmi.type = "图文";
  100. if (this.DDLMassType.SelectedValue.ToString().Equals("0"))
  101. {
  102. wmi.massObject = this.DDLMassType.SelectedItem.Text.ToString();
  103. }
  104. else
  105. {
  106. wmi.massObject = this.DDLGroupList.SelectedItem.Text.ToString();
  107. }
  108. wmi.massStatus = "成功";//群发成功之后返回的状态码
  109. wmi.massMessageID = jsonObj["msg_id"].ToString();//群发成功之后返回的消息ID
  110. wmi.massDate = System.DateTime.Now.ToString();
  111. int num = wms.AddWxMassInfo(wmi);
  112. if (num > 0)
  113. {
  114. Session["wmninfo"] = null;
  115. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!图文部分数据已保存!');location='WxMassManage.aspx';", true);
  116. return;
  117. }
  118. else
  119. {
  120. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!数据保存失败!');", true);
  121. return;
  122. }
  123. }
  124. }
  125. else
  126. {
  127. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务提交失败!!');", true);
  128. return;
  129. }
  130. }
  131. else
  132. {
  133. //根据分组进行群发,订阅号和服务号认证后均可用
  134. string group_id = this.DDLGroupList.SelectedValue.ToString();
  135. WeiXinServer wxs = new WeiXinServer();
  136. ///从缓存读取accesstoken
  137. string Access_token = Cache["Access_token"] as string;
  138. if (Access_token == null)
  139. {
  140. //如果为空,重新获取
  141. Access_token = wxs.GetAccessToken();
  142. //设置缓存的数据7000秒后过期
  143. Cache.Insert("Access_token", Access_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
  144. }
  145. string Access_tokento = Access_token.Substring(17, Access_token.Length - 37);
  146. string posturl = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" + Access_tokento;
  147. ///群发POST数据示例如下:
  148. // {
  149. // "filter":{
  150. // "is_to_all":false
  151. // "group_id":"2"
  152. // },
  153. // "mpnews":{
  154. // "media_id":"123dsdajkasd231jhksad"
  155. // },
  156. // "msgtype":"mpnews"
  157. //}
  158. string postData = "{\"filter\":{\"is_to_all\":\"false\"\"group_id\":\""+group_id+
  159. "\"},\"mpnews\":{\"media_id\":\"" + this.lbtuwenmedai_id.Text.ToString() +
  160. "\"},\"msgtype\":\"mpnews\"}";
  161. string tuwenres = wxs.GetPage(posturl, postData);
  162. //使用前需药引用Newtonsoft.json.dll文件
  163. JObject jsonObj = JObject.Parse(tuwenres);
  164. if (jsonObj["errcode"].ToString().Equals("0"))
  165. {
  166. Session["media_id"] = null;
  167. WxMassInfo wmi = new WxMassInfo();
  168. if (Session["wmninfo"] != null)
  169. {
  170. WxMpNewsInfo wmninfo = Session["wmninfo"] as WxMpNewsInfo;
  171. wmi.title = wmninfo.title.ToString();
  172. wmi.contents = wmninfo.contents.ToString();
  173. wmi.ImageUrl = wmninfo.ImageUrl.ToString();
  174. wmi.type = "图文";
  175. if (this.DDLMassType.SelectedValue.ToString().Equals("0"))
  176. {
  177. wmi.massObject = this.DDLMassType.SelectedItem.Text.ToString();
  178. }
  179. else
  180. {
  181. wmi.massObject = this.DDLGroupList.SelectedItem.Text.ToString();
  182. }
  183. wmi.massStatus = "成功";//群发成功之后返回的状态码
  184. wmi.massMessageID = jsonObj["msg_id"].ToString();//群发成功之后返回的消息ID
  185. wmi.massDate = System.DateTime.Now.ToString();
  186. int num = wms.AddWxMassInfo(wmi);
  187. if (num > 0)
  188. {
  189. Session["wmninfo"] = null;
  190. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!数据已保存!');location='WxMassManage.aspx';", true);
  191. return;
  192. }
  193. else
  194. {
  195. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!数据保存失败!');", true);
  196. return;
  197. }
  198. }
  199. else
  200. {
  201. wmi.title = "";
  202. wmi.contents = "";
  203. wmi.ImageUrl = "";
  204. wmi.type = "图文";
  205. if (this.DDLMassType.SelectedValue.ToString().Equals("0"))
  206. {
  207. wmi.massObject = this.DDLMassType.SelectedItem.Text.ToString();
  208. }
  209. else
  210. {
  211. wmi.massObject = this.DDLGroupList.SelectedItem.Text.ToString();
  212. }
  213. wmi.massStatus = "成功";//群发成功之后返回的状态码
  214. wmi.massMessageID = jsonObj["msg_id"].ToString();//群发成功之后返回的消息ID
  215. wmi.massDate = System.DateTime.Now.ToString();
  216. int num = wms.AddWxMassInfo(wmi);
  217. if (num > 0)
  218. {
  219. Session["wmninfo"] = null;
  220. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!图文部分数据已保存!');location='WxMassManage.aspx';", true);
  221. return;
  222. }
  223. else
  224. {
  225. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!数据保存失败!');", true);
  226. return;
  227. }
  228. }
  229. }
  230. else
  231. {
  232. ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务提交失败!!');", true);
  233. return;
  234. }
  235. }
  236. }
  237. }
  238. }

为什么叫群发任务提交成功或失败,因为将信息提交给微信服务器,微信服务器还需审核,审核过程中也有可能审核不通过,不给于群发,所以我起名叫这个,嘿嘿,随便你们怎么起。。。。。

至此群发图文信息功能,已完毕,最后是群发记录,还记得上一章提到的群发成功之后要在本地保存记录吗,保存记录的原因,用于计算当月已群发几条信息,另外还有一个功能就是,群发成功之后,会得到一个消息msgid,根据这个ID可以对已经发送成功的信息进行撤销(删除)操作,关于撤销操作:微信官方规定,对群发成功的图文和视频消息,半个小时之内可以进行删除操作,其他消息一经群发成功概不支持此操作。截图如下:

该类用于存储已群发记录的实体类

  1. /// <summary>
  2. /// 微信已群发消息实体类,用于记录已群发消息的条数,信息实体
  3. /// </summary>
  4. public class WxMassInfo
  5. {
  6. public int WxMassNo { get; set; }//群发消息编号,数据库自增列
  7. public string title { get; set; }//图文消息的标题,若消息是文本类型,此项不显示
  8. public string ImageUrl { get; set; }//图片地址,若消息是文本类型,此项不显示
  9. public string type { get; set; }//消息的类型,文本,图文,图片,语音,视频
  10. public string contents { get; set; }//文本消息的内容,图文消息的正文
  11. public string massObject { get; set; }//群发对象
  12. public string massStatus { get; set; }//群发状态
  13. public string massMessageID{ get; set; }//群发成功后返回的消息ID
  14. public string massDate { get; set; }//群发日期时间
  15. }

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

以上就是本文的全部内容,希望对大家的学习有所帮助。

人气教程排行