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

网络编程 2021-07-04 22:41www.168986.cn编程入门
这篇文章主要介绍了asp.微信开发中有关高级群发图文的相关内容,需要的朋友可以参考下

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

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

素材列表,我是使用的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-: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-: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 = "";

  ///从缓存读取aesstoken
  string Aess_token = Cache["Aess_token"] as string;

  if (Aess_token == null)
  {
  //如果为空,重新获取
  Aess_token = wxs.GetAessToken();

  //设置缓存的数据7000秒后过期
  Cache.Insert("Aess_token", Aess_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
  }

  string Aess_tokento = Aess_token.Substring(17, Aess_token.Length - 37);


  string posturl = "https://api.weixin.qq./cgi-bin/material/batchget_material?aess_token=" + Aess_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:\Ipub\root\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();

   ///从缓存读取aesstoken
   string Aess_token = Cache["Aess_token"] as string;

   if (Aess_token == null)
   {
    //如果为空,重新获取
    Aess_token = wxs.GetAessToken();

    //设置缓存的数据7000秒后过期
    Cache.Insert("Aess_token", Aess_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
   }

   string Aess_tokento = Aess_token.Substring(17, Aess_token.Length - 37);


   //WebClient wx_upload = new WebClient();
   //wx_upload.Credentials = CredentialCache.DefaultCredentials;
   string url = string.Format("http://file.api.weixin.qq./cgi-bin/media/upload?aess_token={0}&type={1}", Aess_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, FileAess.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:\Ipub\root\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();

  ///从缓存读取aesstoken
  string Aess_token = Cache["Aess_token"] as string;

  if (Aess_token == null)
  {
  //如果为空,重新获取
  Aess_token = wxs.GetAessToken();

  //设置缓存的数据7000秒后过期
  Cache.Insert("Aess_token", Aess_token, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
  }

  string Aess_tokento = Aess_token.Substring(17, Aess_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结构
  // ]
  / 

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by