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微信开发教程汇总》,欢迎大家学习阅读。

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

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索asp.net
, 微信开发
高级群发图文
,以便于您获取更多的相关知识。

时间: 2024-10-03 13:49:21

asp.net微信开发(高级群发图文)_实用技巧的相关文章

asp.net微信开发(消息应答)_实用技巧

当普通微信用户向公众账号发消息时,微信服务器将POST消息的XML数据包到开发者填写的URL上.请注意: 1.关于重试的消息排重,推荐使用msgid排重. 2.微信服务器在五秒内收不到响应会断掉连接,并且重新发起请求,总共重试三次.假如服务器无法保证在五秒内处理并回复,可以直接回复空串,微信服务器不会对此作任何处理,并且不会发起重试.详情请见"发送消息-被动回复消息". 3.为了保证更高的安全保障,开发者可以在公众平台官网的开发者中心处设置消息加密.开启加密后,用户发来的消息会被加密,

VS2015 搭建Asp.net core开发环境的方法_实用技巧

前言 随着ASP.NET Core 1.0 rtm的发布,网上有许多相关.net core 相关文章,最近正好有时间就尝试VS2015 搭建Asp.net core开发环境,以下是简单的搭建过程,下面来一起看看吧. 步骤如下 一.首先你得装个vs2015 并且保证已经升级至 update3及以上(此处附上一个vs2015带up3的下载链接: ed2k://|file|cn_visual_studio_enterprise_2015_with_update_3_x86_x64_dvd_892329

ASP.NET Mvc开发之查询数据_实用技巧

对于.NET平台上开发WebForm项目,程序员操作数据的方法主要是通过使用ADO.NET.而我们MVC操作数据库呢?与ADO.NET相比又有怎样的优势呢? 一.大家都在谈的EF到底是什么? EF,全称EntityFramWork.就是微软以ADO.NET为基础发展的所谓ORM(对象关系映射框架,或者说是数据持久化框架). 简单的来说就是根据实体对象操作数据表中数据的一种面向对象的操作框架,具体的底层也是调用ADO.NET. 下面我们就来演示怎么使用EF来操作数据库: 在数据库关系图中,表之间的

Win 2000下ASP.NET开发环境的配置_实用技巧

Win 2000下ASP.NET的配置 Win 2000(包括Professional,Server和Advanced Server)在默认情况下是不支持ASP.NET的.必须对它进行一个环境的配置. 客户端 SQL Server .NET 数据提供程序 Microsoft 数据访问组件 (MDAC) 2.6 或更高版本 对系统管理信息的访问 Windows Management Instrumentation (WMI)(在 Windows 2000操作系统一起安装)COM+ 服务 Windo

ASP.NET MVC5+EF6+EasyUI后台管理系统 微信公众平台开发之消息管理_实用技巧

前言  回顾上一节,我们熟悉的了解了消息的请求和响应,这一节我们来建立数据库的表,表的设计蛮复杂  你也可以按自己所分析的情形结构来建表  必须非常熟悉表的结果才能运用这张表,这表表的情形涵盖比较多  思维导图  我这个人比较喜欢用思维导图来分析和表达一些模型:   表结构  根据思维导图,我们可以建立的表可以是3张表:消息表,规则表,类型表 消息表:实际的消息 规则表:文本.图文.语音等 类型表:文本.图文.语音(默认回复,订阅回复) 也可以是两张表:规制表,消息表(+一个类型字段)  我这里

.NET C#使用微信公众号登录网站_实用技巧

适用于:本文适用于有一定微信开发基础的用户 引言:花了300大洋申请了微信公众平台后,发现不能使用微信公众号登录网站(非微信打开)获得微信帐号.仔细研究后才发现还要再花300大洋申请微信开放平台才能接入网站的登录.于是做为屌丝程序员的我想到了自己做一个登录接口. 工具和环境:1. VS2013 .net4.0 C# MVC4.0 Razor 2.插件 A. Microsoft.AspNet.SignalR;时时获取后台数据 B.Gma.QrCodeNet.Encoding;文本生成二维码  实现

浅谈ASP.NET MVC应用程序的安全性_实用技巧

前言:保护Web应用程序的安全性看起来时间苦差事,这件必须要做的工作并不能带来太多的乐趣,但是为了回避尴尬的安全漏洞问题,程序的安全性通常还是不得不做的. 1.ASP.NET Web Forms开发人员   (1)因为ASP.NET MVC不像ASP.NET Web Forms那样提供了很多自动保护机制来保护页面不受恶意用户的攻击,所以阅读本博客来了解这方面的问题,更明确的说法是:ASP.NET Web Forms致力于使应用程序免受攻击.例如: 1)服务器组件对显示的值和特性进行HTML编码,

ASP.NET MVC3的伪静态实现代码_实用技巧

现在开始研究第一步,如何定义自己的路由规则,达到伪静态的功能需求. 基本实现原理如下图:   首先,关于命名空间. 路由的功能是为了让所有Asp.net网站开发都可以使用,所以dll并没有在MVC中,而是在System.Web中的System.web.Routing. 现在我们为了我们实际的需求,实现MVC3中的自定义路由功能(继承RouteBase,重写RouteData和VirtualPathData). 下面的例子实现以下目的:输入一个youdomin.com/product/123.ht

.net微信服务号发送红包_实用技巧

本文实例为大家分享了.net微信红包发送代码,供大家参考,具体内容如下 注:需要开通微信支付的服务号! //跳转微信登录页面 public ActionResult Index() { ViewBag.url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + {服务号appid} + "&redirect_uri=http%3A%2F%2F" + {微信重定向域名(填写程序域名,

Asp.net cookie的处理流程深入分析_实用技巧

一说到Cookie我想大家都应该知道它是一个保存在客户端,当浏览器请求一个url时,浏览器会携带相关的Cookie达到服务器端,所以服务器是可以操作Cookie的,在Response时,会把Cookie信息输出到客服端.下面我们来看一个demo吧,代码如下: 第一次请求结果如下: 第二次请求结果如下: 到这里我们可以看到第二次请求传入的Cookie正好是第一次请求返回的Cookie信息,这里的cookie信息的维护主要是我们客户端的浏览器,但是在Asp.net程序开发时,Cookie往往是在服务