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

asp.net微信开发(高级群发图文),第1张

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

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

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

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

前台代码如下:

 <!--d出选择素材窗口-->  <div ID="shownewgroup">  <div  ><span >选择素材</span>  <span ><a href="WxNewTuWen.aspx"  onclick="hrefurl();" >新建图文素材</a></span>  <a ><img src="images/close1.png" alt="" /></a>  </div>    <div >  <asp:UpdatePanel ID="UpdatePanel2" runat="server">   <ContentTemplate>    <div ><asp:linkbutton ID="linkBtnSelect" runat="server" OnClick="linkBtnSelect_Click" ><div >确认选择</div></asp:linkbutton>    <span ><asp:linkbutton ID="linkbtnRefresh" CSSClass="linkbtnRefresh" runat="server" OnClick="linkbtnRefresh_Click"><div >刷新</div></asp:linkbutton></span>    <span ><asp:linkbutton ID="linkBtnDelete" CSSClass="linkbtnRefresh" runat="server" OnClick="linkBtnDelete_Click"><div >删除素材</div></asp:linkbutton></span>    </div>  <div  ID="lbnewssucai" runat="server">   <asp:Repeater ID="RepeatersucaiList" runat="server" OnItemDataBound="RepeatersucaiList_ItemDataBound">   <ItemTemplate>    <table  >    <tr>     <td ><asp:Image ID="ImageUrl" CSSClass="fenmianstyle2" runat="server" /></td>     <td >     <asp:Repeater ID="RepeatersucaiList2" runat="server">      <ItemTemplate>      <ul >       <li><%# Eval("Title") %></li>      </ul>      </ItemTemplate>     </asp:Repeater>     </td>     <td >     <asp:Label ID="lbUpate_time" runat="server" Text="Label"></asp:Label>     </td>     <td >     <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 >   <span >本类型素材总数量为:</span><span ><asp:Label ID="lbtotal_count" runat="server" Text="0"></asp:Label></span>     <span >本次获取的素材数量为:</span><span ><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 Pictures022775_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\images022775_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",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,barr.Length);  fs.Close();  Stream poststream = request.GetRequestStream();  poststream.Write(itemBoundaryBytes,itemBoundaryBytes.Length);  poststream.Write(postheaderBytes,postheaderBytes.Length);  poststream.Write(barr,barr.Length);  poststream.Write(endBoundaryBytes,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\images022775_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,"alert('必须上传一张图片!');",true);  this.imgTuWen2.Focus();  return;  }  if (String.IsNullOrWhiteSpace(this.tbContent.InnerText.ToString()))  {  ScriptManager.RegisterClIEntScriptBlock(this.Page,"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.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,"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,"alert('发送预览成功!!');",true);   return;  }  else  {   ScriptManager.RegisterClIEntScriptBlock(this.Page,"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,true);  return;  }  if (this.imgTuWen2.ImageUrl.ToString().Equals(""))  {  ScriptManager.RegisterClIEntScriptBlock(this.Page,true);  return;  }  if (String.IsNullOrWhiteSpace(this.tbContent.InnerText.ToString()))  {  ScriptManager.RegisterClIEntScriptBlock(this.Page,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",// //若新增的是多图文素材,则此处应还有几段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() +  "\",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,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,"alert('请选择或新建图文素材再进行群发!');",true);     return;    }    WxMassService wms = new WxMassService();    List<WxMassInfo> wxmasList = wms.GetMonthMassCount();    if (wxmasList.Count >= 4)    {     ScriptManager.RegisterClIEntScriptBlock(this.Page,"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",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,"alert('群发任务已提交成功!!!数据已保存!');location='WxMassManage.aspx';",true);         return;        }        else        {         ScriptManager.RegisterClIEntScriptBlock(this.Page,"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,"alert('群发任务已提交成功!!!图文部分数据已保存!');location='WxMassManage.aspx';",true);         return;        }       }      }      else      {       ScriptManager.RegisterClIEntScriptBlock(this.Page,"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.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"      // },// "msgtype":"mpnews"      //}      string postData = "{\"filter\":{\"is_to_all\":\"false\"\"group_ID\":\""+group_ID+       "\"},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微信开发教程汇总》,欢迎大家学习阅读。

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

总结

以上是内存溢出为你收集整理的asp.net微信开发(高级群发图文)全部内容,希望文章能够帮你解决asp.net微信开发(高级群发图文)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1260840.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存