asp.net微信开发(高级群发图文)
上一篇介绍了如何群发文本消息,本篇将介绍如何群发图文信息,上传图文信息所需的素材,界面如下:
我们先看从素材库中获取图文素材的代码,界面:
素材列表,我是使用的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> </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> <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\wwwroot\website1\images\20022775_m.jpg this.imgtuwen.imageurl = "~/weixinimg/" + fileuploadimg.filename; this.imgtuwen2.visible = true; this.imgtuwen2.imageurl = "~/weixinimg/" + fileuploadimg.filename; this.fileuploadimg.postedfile.saveas(serverpath);//将上传的文件另存为 this.linkbtndeleteimg.visible = true; session["filenameimg"] = this.fileuploadimg.postedfile.filename; //上传临时图片素材至微信服务器,3天后微信服务器会自动删除 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); //webclient wx_upload = new webclient(); //wx_upload.credentials = credentialcache.defaultcredentials; string url = string.format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", access_tokento, "image"); string result = httpuploadfile(url, serverpath); if (result.contains("media_id")) { //使用前需要引用newtonsoft.json.dll文件 jobject jsonobj = jobject.parse(result); session["imgmedia_id"] = jsonobj["media_id"].tostring(); } response.write("<script>alert('上传图片成功!')</script>"); } else { response.write("<script>alert('上传文件不能大于2m!')</script>"); } } else { response.write("<script>alert('只支持bmp,gif,png,jpg格式的图片!')</script>"); } } else { response.write("<script>alert('请选择图片!')</script>"); } } /// <summary> /// http上传文件 /// </summary> public static string httpuploadfile(string url, string path) { // 设置参数 httpwebrequest request = webrequest.create(url) as httpwebrequest; cookiecontainer cookiecontainer = new cookiecontainer(); request.cookiecontainer = cookiecontainer; request.allowautoredirect = true; request.method = "post"; string boundary = datetime.now.ticks.tostring("x"); // 随机分隔线 request.contenttype = "multipart/form-data;charset=utf-8;boundary=" + boundary; byte[] itemboundarybytes = encoding.utf8.getbytes("\r\n--" + boundary + "\r\n"); byte[] endboundarybytes = encoding.utf8.getbytes("\r\n--" + boundary + "--\r\n"); int pos = path.lastindexof("\\"); string filename = path.substring(pos + 1); //请求头部信息 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)); byte[] postheaderbytes = encoding.utf8.getbytes(sbheader.tostring()); filestream fs = new filestream(path, filemode.open, fileaccess.read); byte[] barr = new byte[fs.length]; fs.read(barr, 0, barr.length); fs.close(); stream poststream = request.getrequeststream(); poststream.write(itemboundarybytes, 0, itemboundarybytes.length); poststream.write(postheaderbytes, 0, postheaderbytes.length); poststream.write(barr, 0, barr.length); poststream.write(endboundarybytes, 0, endboundarybytes.length); poststream.close(); //发送请求并获取相应回应数据 httpwebresponse response = request.getresponse() as httpwebresponse; //直到request.getresponse()程序才开始向目标网页发送post请求 stream instream = response.getresponsestream(); streamreader sr = new streamreader(instream, encoding.utf8); //返回结果网页(html)代码 string content = sr.readtoend(); return content; } /// <summary> /// 删除图片 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void linkbtndeleteimg_click(object sender, eventargs e) { string filename = session["filenameimg"].tostring(); if (!string.isnullorempty(filename))//确保picpath有值并且不为空。 { string serverpath = server.mappath("~/weixinimg/") + filename;//取得文件在服务器上保存的位置c:\inetpub\wwwroot\website1\images\20022775_m.jpg if (file.exists(serverpath)) { try { file.delete(serverpath); this.imgtuwen.imageurl = "weixinimg/fengmiandefault.jpg"; this.imgtuwen2.visible = false; this.imgtuwen2.imageurl = ""; session["filenameimg"] = null; this.linkbtndeleteimg.visible = false; } catch(exception ex) { //错误处理: response.write(ex.message.tostring()); } } } }
新建单图文预览代码如下:
/// <summary> /// 预览图文消息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void linkbtnsendpreview_click(object sender, eventargs e) { session["media_id"] = null; //非空验证 if (string.isnullorwhitespace(this.txttuwen_title.value.tostring())) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('请输入图文标题!');", true); this.txttuwen_title.focus(); return; } if (this.imgtuwen2.imageurl.tostring().equals("")) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('必须上传一张图片!');", true); this.imgtuwen2.focus(); return; } if (string.isnullorwhitespace(this.tbcontent.innertext.tostring())) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('请输入正文内容!');", true); this.tbcontent.focus(); return; } //对各项进行赋值 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); //post数据例子: post数据例子: //{ // "articles": [{ // "title": title, // "thumb_media_id": thumb_media_id, // "author": author, // "digest": digest, // "show_cover_pic": show_cover_pic(0 / 1), // "content": content, // "content_source_url": content_source_url // }, // //若新增的是多图文素材,则此处应还有几段articles结构 // ] //} string isshow_cover_pic = ""; if (this.checkfengmianshow.checked) { isshow_cover_pic = "1"; } else { isshow_cover_pic = "0"; } string description = nohtml(this.tbcontent.innertext.tostring()); string postdata = "{\"articles\":[{\"title\":\"" + this.txttuwen_title.value.tostring() + "\",\"thumb_media_id\":\"" + session["imgmedia_id"].tostring() + "\",\"author\":\"" + this.txttuwen_author.value.tostring() + "\",\"digest\":\"" + this.txtzhaiyao.innertext.tostring() + "\",\"show_cover_pic\":\"" + isshow_cover_pic + "\",\"content\":\"" + description + "\",\"content_source_url\":\"" + this.txtyuanwenurl.text.tostring() + "\"}]}"; string posturl = string.format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", access_tokento); string jsonres = posturl(posturl, postdata); if (jsonres.contains("media_id")) { //使用前需要引用newtonsoft.json.dll文件 jobject jsonobj = jobject.parse(jsonres); if (this.txttousername.value.tostring().trim().equals("请输入用户微信号")) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('请输入接收消息的用户微信号!');", true); return; } string posturls = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=" + access_tokento; //预览图文消息的json数据{ // "touser":"openid", 可改为对微信号预览,例如towxname:zhangsan // "mpnews":{ // "media_id":"123dsdajkasd231jhksad" // }, // "msgtype":"mpnews" //} string postdatas = "{\"towxname\":\"" + this.txttousername.value.tostring() + "\",\"mpnews\":{\"media_id\":\"" + jsonobj["media_id"].tostring() + "\"},\"msgtype\":\"mpnews\"}"; string tuwenres = wxs.getpage(posturls, postdatas); //使用前需药引用newtonsoft.json.dll文件 jobject jsonobjss = jobject.parse(tuwenres); if (jsonobjss["errcode"].tostring().equals("0")) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('发送预览成功!!');", true); return; } else { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('发送预览失败!!');", true); return; } } } public static string nohtml(string htmlstring) { //删除脚本 htmlstring = regex.replace(htmlstring, @"<script[^>]*?>.*?</script>", "", regexoptions.ignorecase); //替换标签 htmlstring = htmlstring.replace("\r\n", " "); htmlstring = htmlstring.replace("\"", "'"); htmlstring = htmlstring.replace(" ", " "); return htmlstring; }
单击确定按钮代码如下:
/// <summary> /// 确认选择 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void linkbtnsubsave_click(object sender, eventargs e) { session["media_id"] = null; //非空验证 if (string.isnullorwhitespace(this.txttuwen_title.value.tostring())) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('请输入图文标题!');", true); return; } if (this.imgtuwen2.imageurl.tostring().equals("")) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('必须上传一张图片!');", true); return; } if (string.isnullorwhitespace(this.tbcontent.innertext.tostring())) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('请输入正文内容!');", true); return; } //对各项进行赋值 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); //post数据例子: post数据例子: //{ // "articles": [{ // "title": title, // "thumb_media_id": thumb_media_id, // "author": author, // "digest": digest, // "show_cover_pic": show_cover_pic(0 / 1), // "content": content, // "content_source_url": content_source_url // }, // //若新增的是多图文素材,则此处应还有几段articles结构 // ] //} string isshow_cover_pic = ""; if (this.checkfengmianshow.checked) { isshow_cover_pic = "1"; } else { isshow_cover_pic = "0"; } string description = nohtml(this.tbcontent.innertext.tostring()); string postdata = "{\"articles\":[{\"title\":\"" + this.txttuwen_title.value.tostring() + "\",\"thumb_media_id\":\"" + session["imgmedia_id"].tostring() + "\",\"author\":\"" + this.txttuwen_author.value.tostring() + "\",\"digest\":\"" + this.txtzhaiyao.innertext.tostring() + "\",\"show_cover_pic\":\"" + isshow_cover_pic + "\",\"content\":\"" + description + "\",\"content_source_url\":\"" + this.txtyuanwenurl.text.tostring() + "\"}]}"; string posturl = string.format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", access_tokento); string jsonres = posturl(posturl, postdata); if (jsonres.contains("media_id")) { //使用前需要引用newtonsoft.json.dll文件 jobject jsonobj = jobject.parse(jsonres); wxmpnewsinfo wmninfo = new wxmpnewsinfo(); wmninfo.title = this.txttuwen_title.value.tostring(); wmninfo.contents = description.tostring(); wmninfo.imageurl = this.imgtuwen.imageurl.tostring(); session["wmninfo"] = wmninfo; response.redirect("wxmassmanage.aspx?media_id=" + jsonobj["media_id"].tostring()); } } /// <summary> /// 请求url,发送数据 /// </summary> public static string posturl(string url, string postdata) { byte[] data = encoding.utf8.getbytes(postdata); // 设置参数 httpwebrequest request = webrequest.create(url) as httpwebrequest; cookiecontainer cookiecontainer = new cookiecontainer(); request.cookiecontainer = cookiecontainer; request.allowautoredirect = true; request.method = "post"; request.contenttype = "application/x-www-form-urlencoded"; request.contentlength = data.length; stream outstream = request.getrequeststream(); outstream.write(data, 0, data.length); outstream.close(); //发送请求并获取相应回应数据 httpwebresponse response = request.getresponse() as httpwebresponse; //直到request.getresponse()程序才开始向目标网页发送post请求 stream instream = response.getresponsestream(); streamreader sr = new streamreader(instream, encoding.utf8); //返回结果网页(html)代码 string content = sr.readtoend(); return content; }
response.redirect("wxmassmanage.aspx?media_id=" + jsonobj["media_id"].tostring());
这句代码就是将上传图文后得到的media_id参数传送到群发界面,群发界面接收代码如下:
protected void page_load(object sender, eventargs e) { if(!page.ispostback) { bindnewssucailist();//绑定素材列表 bindgrouplist();//绑定分组列表 bindmasscount();//绑定本月已群发条数 this.databind(); if (request.querystring["media_id"] != null) { this.radiobtnlist.selectedvalue = "1"; this.showexpress.visible = false; this.txtwenben.visible = false; this.tuwen.visible = true; this.tuwenxuan.visible = false; this.tuwenjian.visible = false; this.lbtuwenmedai_id.visible = true; this.lbtuwenmedai_id.text = request.querystring["media_id"].tostring(); this.linkbtndeletetuwen.visible = true; this.imageyixuan.visible = true; } } }
最终界面如下:
我这里只接收了一个media_id值,相对于做的简单,直接将值赋值给了一个label用于显示,也可以做成像官网那样,确定选择后,按照图文样式显示.
最后一步:群发按钮代码:其实上一章已经将代码贴出去了,这一章,我就单独贴一遍吧。
/// <summary> /// 群发 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void linkbtnsubsend_click(object sender, eventargs e) { //根据单选按钮判断类型,//如果选择的是图文消息 if (this.radiobtnlist.selectedvalue.tostring().equals("1")) { if (string.isnullorwhitespace(this.lbtuwenmedai_id.text.tostring().trim())) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('请选择或新建图文素材再进行群发!');", true); return; } wxmassservice wms = new wxmassservice(); list<wxmassinfo> wxmaslist = wms.getmonthmasscount(); if (wxmaslist.count >= 4) { scriptmanager.registerclientscriptblock(this.page, this.gettype(), "", "alert('本月可群发消息数量已达上限!');", true); return; } else { //如何群发类型为全部用户,根据openid列表群发给全部用户,订阅号不可用,服务号认证后可用 if (this.ddlmasstype.selectedvalue.tostring().equals("0")) { stringbuilder sbs = new stringbuilder(); sbs.append(getalluseropenidlist()); 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 posturl = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=" + access_tokento; ///群发post数据示例如下: // { // "touser":[ // "openid1", // "openid2" // ], // "mpnews":{ // "media_id":"123dsdajkasd231jhksad" // }, // "msgtype":"mpnews" //} string postdata = "{\"touser\":[" + sbs.tostring() + "],\"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; } } else { //根据分组进行群发,订阅号和服务号认证后均可用 string group_id = this.ddlgrouplist.selectedvalue.tostring(); 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 posturl = "https://api.weixin.qq.com/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微信开发教程汇总》,欢迎大家学习阅读。
以上就是本文的全部内容,希望对大家的学习有所帮助。
推荐阅读