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

时间:2021-05-28

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

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

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

前台代码如下:

<!--弹出选择素材窗口--> <div id="shownewgroup"> <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> <span style="float:left;margin-left:20px;"><a href="WxNewTuWen.aspx" style="color:red;" onclick="hrefurl();" class="hrefurl">新建图文素材</a></span> <a class="closeloginpage"><img src="images/close1.png" alt="" /></a>&nbsp;&nbsp;</div> <div style="height:455px; width:100%;"> <asp:UpdatePanel ID="UpdatePanel2" runat="server"> <ContentTemplate> <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> <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> <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> </div> <div style="word-wrap:break-word;" id="lbnewssucai" runat="server"> <asp:Repeater ID="Repeatersucailist" runat="server" OnItemDataBound="Repeatersucailist_ItemDataBound"> <ItemTemplate> <table style="width:100%; border-top:1px solid #edc9df; border-collapse:collapse; font-size:12px;" > <tr> <td style="width:100px;"><asp:Image ID="ImageUrl" CssClass="fenmianstyle2" runat="server" /></td> <td style="text-align:left; width:470px; "> <asp:Repeater ID="Repeatersucailist2" runat="server"> <ItemTemplate> <ul style="margin:0px;padding:0px;"> <li><%# Eval("title") %></li> </ul> </ItemTemplate> </asp:Repeater> </td> <td style="width:130px;"> <asp:Label ID="lbUpate_time" runat="server" Text="Label"></asp:Label> </td> <td style="width:50px; text-align:center;"> <asp:CheckBox ID="CheckIn" runat="server" /> <asp:Label ID="lbmedia_id" runat="server" Visible="false" Text=""></asp:Label> </td> </tr> </table> </ItemTemplate> </asp:Repeater> <div style="font-size:14px; height:30px; line-height:30px; text-indent:10px; border-top:1px solid #ced9df;"> <span style="float:left;">本类型素材总数量为:</span><span style="float:left; color:red;"><asp:Label ID="lbtotal_count" runat="server" Text="0"></asp:Label></span>&nbsp;&nbsp; <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> </div> </div> </ContentTemplate> </asp:UpdatePanel> </div> </div> <div id="shownewgroupzhezhaoceng"></div>

后台代码如下:

/// <summary> /// 绑定图文素材列表 /// </summary> private void BindNewsSucaiList() { 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 posturl = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + Access_tokento; //POST数据例子: POST数据例子:{"type":TYPE,"offset":OFFSET,"count":COUNT} string postData = "{\"type\":\"news\",\"offset\":\"0\",\"count\":\"20\"}"; res = wxs.GetPage(posturl, postData); //使用前需要引用Newtonsoft.json.dll文件 JObject jsonObj = JObject.Parse(res); int groupsnum = jsonObj["item"].Count(); List<WxNewsSucaiIteminfo> newssucaiitemlist = new List<WxNewsSucaiIteminfo>(); List<WxNewsSuCaiItemlistinfo> WxNewsSuCaiItemlist = new List<WxNewsSuCaiItemlistinfo>(); for (int i = 0; i < groupsnum; i++) { WxNewsSucaiIteminfo newssucaiitem = new WxNewsSucaiIteminfo(); newssucaiitem.media_id = jsonObj["item"][i]["media_id"].ToString(); newssucaiitem.update_time = jsonObj["item"][i]["update_time"].ToString(); newssucaiitem.total_count = jsonObj["total_count"].ToString(); newssucaiitem.item_count = jsonObj["item_count"].ToString(); newssucaiitemlist.Add(newssucaiitem); int news_itemcount = jsonObj["item"][i]["content"]["news_item"].Count(); if (news_itemcount > 0) { for (int j = 0; j < news_itemcount; j++) { WxNewsSuCaiItemlistinfo wnscilinfo = new WxNewsSuCaiItemlistinfo(); wnscilinfo.title = jsonObj["item"][i]["content"]["news_item"][j]["title"].ToString(); wnscilinfo.thumb_media_id = jsonObj["item"][i]["content"]["news_item"][j]["thumb_media_id"].ToString(); wnscilinfo.show_cover_pic = int.Parse(jsonObj["item"][i]["content"]["news_item"][j]["show_cover_pic"].ToString()); wnscilinfo.author = jsonObj["item"][i]["content"]["news_item"][j]["author"].ToString(); wnscilinfo.digest = jsonObj["item"][i]["content"]["news_item"][j]["digest"].ToString(); wnscilinfo.content = jsonObj["item"][i]["content"]["news_item"][j]["content"].ToString(); wnscilinfo.url = jsonObj["item"][i]["content"]["news_item"][j]["url"].ToString(); wnscilinfo.content_source_url = jsonObj["item"][i]["content"]["news_item"][j]["content_source_url"].ToString(); wnscilinfo.media_id = newssucaiitem.media_id.ToString(); WxNewsSuCaiItemlist.Add(wnscilinfo); } } } Session["WxNewsSuCaiItemlist"] = WxNewsSuCaiItemlist; this.Repeatersucailist.DataSource = newssucaiitemlist; this.Repeatersucailist.DataBind(); }

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

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

/// <summary> /// /// </summary>上传图片文件 /// <param name="sender"></param> /// <param name="e"></param> protected void LinkBtnFileUploadImg_Click(object sender, EventArgs e) { if (this.FileUploadImg.HasFile) { string fileContentType = FileUploadImg.PostedFile.ContentType; if (fileContentType == "image/bmp" || fileContentType == "image/gif" || fileContentType == "image/png" || fileContentType == "image/x-png" || fileContentType == "image/jpeg" || fileContentType == "image/pjpeg") { int fileSize = this.FileUploadImg.PostedFile.ContentLength; if (fileSize <=2097152) { string fileName = this.FileUploadImg.PostedFile.FileName; // 客户端文件路径 string filepath = FileUploadImg.PostedFile.FileName; //得到的是文件的完整路径,包括文件名,如:C:\Documents and Settings\Administrator\My Documents\My Pictures\20022775_m.jpg //string filepath = FileUpload1.FileName; //得到上传的文件名20022775_m.jpg string filename = filepath.Substring(filepath.LastIndexOf("\\") + 1);//20022775_m.jpg string serverpath = Server.MapPath("~/WeiXinImg/") + filename;//取得文件在服务器上保存的位置C:\Inetpub\/cgi-bin/message/mass/send?access_token=" + Access_tokento; ///群发POST数据示例如下: // { // "filter":{ // "is_to_all":false // "group_id":"2" // }, // "mpnews":{ // "media_id":"123dsdajkasd231jhksad" // }, // "msgtype":"mpnews" //} string postData = "{\"filter\":{\"is_to_all\":\"false\"\"group_id\":\""+group_id+ "\"},\"mpnews\":{\"media_id\":\"" + this.lbtuwenmedai_id.Text.ToString() + "\"},\"msgtype\":\"mpnews\"}"; string tuwenres = wxs.GetPage(posturl, postData); //使用前需药引用Newtonsoft.json.dll文件 JObject jsonObj = JObject.Parse(tuwenres); if (jsonObj["errcode"].ToString().Equals("0")) { Session["media_id"] = null; WxMassInfo wmi = new WxMassInfo(); if (Session["wmninfo"] != null) { WxMpNewsInfo wmninfo = Session["wmninfo"] as WxMpNewsInfo; wmi.title = wmninfo.title.ToString(); wmi.contents = wmninfo.contents.ToString(); wmi.ImageUrl = wmninfo.ImageUrl.ToString(); wmi.type = "图文"; if (this.DDLMassType.SelectedValue.ToString().Equals("0")) { wmi.massObject = this.DDLMassType.SelectedItem.Text.ToString(); } else { wmi.massObject = this.DDLGroupList.SelectedItem.Text.ToString(); } wmi.massStatus = "成功";//群发成功之后返回的状态码 wmi.massMessageID = jsonObj["msg_id"].ToString();//群发成功之后返回的消息ID wmi.massDate = System.DateTime.Now.ToString(); int num = wms.AddWxMassInfo(wmi); if (num > 0) { Session["wmninfo"] = null; ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!数据已保存!');location='WxMassManage.aspx';", true); return; } else { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!数据保存失败!');", true); return; } } else { wmi.title = ""; wmi.contents = ""; wmi.ImageUrl = ""; wmi.type = "图文"; if (this.DDLMassType.SelectedValue.ToString().Equals("0")) { wmi.massObject = this.DDLMassType.SelectedItem.Text.ToString(); } else { wmi.massObject = this.DDLGroupList.SelectedItem.Text.ToString(); } wmi.massStatus = "成功";//群发成功之后返回的状态码 wmi.massMessageID = jsonObj["msg_id"].ToString();//群发成功之后返回的消息ID wmi.massDate = System.DateTime.Now.ToString(); int num = wms.AddWxMassInfo(wmi); if (num > 0) { Session["wmninfo"] = null; ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!图文部分数据已保存!');location='WxMassManage.aspx';", true); return; } else { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务已提交成功!!!数据保存失败!');", true); return; } } } else { ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert('群发任务提交失败!!');", true); return; } } } } }

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

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

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

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

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

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章