热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

这篇文章主要介绍了asp.net微信开发中有关高级群发图文的相关内容,需要的朋友可以参考下
这篇文章主要介绍了asp.net微信开发中有关高级群发图文的相关内容,需要的朋友可以参考下

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

 
  

选择素材 新建图文素材

确认选择

刷新

删除素材

  • <%# Eval("title") %>

本类型素材总数量为: 本次获取的素材数量为:

后台代码如下:

 /// 
 /// 绑定图文素材列表
 /// 
 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 newssucaiitemlist = new List();
  List WxNewsSuCaiItemlist = new List();
  for (int i = 0; i  0)
  {
   for (int j = 0; j 

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

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

 /// 
 /// 
 /// 上传图片文件
 /// 
 /// 
 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("");
   }
   else
   {
   Response.Write("");
   }
   
  }
  else
  {
   Response.Write("");
  }
  }
  else
  {
  Response.Write("");
  }
 }
 ///  
 /// Http上传文件 
 ///  
 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;
 } 
 /// 
 /// 删除图片
 /// 
 /// 
 /// 
 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());
   }
  }
  }
 }

新建单图文预览代码如下:

 /// 
 /// 预览图文消息
 /// 
 /// 
 /// 
 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(&#39;请输入图文标题!&#39;);", true);
  this.txttuwen_title.Focus();
  return;
  }
  if (this.ImgTuWen2.ImageUrl.ToString().Equals(""))
  {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;必须上传一张图片!&#39;);", true);
  this.ImgTuWen2.Focus();
  return;
  }
  if (String.IsNullOrWhiteSpace(this.tbContent.InnerText.ToString()))
  {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;请输入正文内容!&#39;);", 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(&#39;请输入接收消息的用户微信号!&#39;);", 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(&#39;发送预览成功!!&#39;);", true);
   return;
  }
  else
  {
   ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;发送预览失败!!&#39;);", true);
   return;
  }
  }
 }
 public static string NoHTML(string Htmlstring)
 {

  //删除脚本 
  Htmlstring = Regex.Replace(Htmlstring, @"", "", RegexOptions.IgnoreCase);

  //替换标签
  Htmlstring = Htmlstring.Replace("\r\n", " ");
  Htmlstring = Htmlstring.Replace("\"", "&#39;");
  Htmlstring = Htmlstring.Replace(" ", " ");
  return Htmlstring;

 }

单击确定按钮代码如下:

 /// 
 /// 确认选择
 /// 
 /// 
 /// 
 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(&#39;请输入图文标题!&#39;);", true);
  return;
  }
  if (this.ImgTuWen2.ImageUrl.ToString().Equals(""))
  {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;必须上传一张图片!&#39;);", true);
  return;
  }
  if (String.IsNullOrWhiteSpace(this.tbContent.InnerText.ToString()))
  {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;请输入正文内容!&#39;);", 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());
  }
 }
 ///  
 /// 请求Url,发送数据 
 ///  
 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;
  }
  }
 }

最终界面如下:

 /// 
  /// 群发
  /// 
  /// 
  /// 
  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(&#39;请选择或新建图文素材再进行群发!&#39;);", true);
     return;
    }

    WxMassService wms = new WxMassService();

    List wxmaslist = wms.GetMonthMassCount();

    if (wxmaslist.Count >= 4)
    {
     ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;本月可群发消息数量已达上限!&#39;);", 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(&#39;群发任务已提交成功!!!数据已保存!&#39;);location=&#39;WxMassManage.aspx&#39;;", true);
         return;
        }
        else
        {
         ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;群发任务已提交成功!!!数据保存失败!&#39;);", 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(&#39;群发任务已提交成功!!!图文部分数据已保存!&#39;);location=&#39;WxMassManage.aspx&#39;;", true);
         return;
        }
        else
        {
         ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;群发任务已提交成功!!!数据保存失败!&#39;);", true);
         return;
        }
       }
      }
      else
      {
       ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;群发任务提交失败!!&#39;);", 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(&#39;群发任务已提交成功!!!数据已保存!&#39;);location=&#39;WxMassManage.aspx&#39;;", true);
         return;
        }
        else
        {
         ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;群发任务已提交成功!!!数据保存失败!&#39;);", 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(&#39;群发任务已提交成功!!!图文部分数据已保存!&#39;);location=&#39;WxMassManage.aspx&#39;;", true);
         return;
        }
        else
        {
         ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;群发任务已提交成功!!!数据保存失败!&#39;);", true);
         return;
        }
       }
      }
      else
      {
       ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;群发任务提交失败!!&#39;);", true);
       return;
      }
     }
    }
   }
  }

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

 /// 
 /// 微信已群发消息实体类,用于记录已群发消息的条数,信息实体
 /// 
 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微信开发(高级群发图文)相关文章请关注PHP中文网!

推荐阅读
  • 深入理解Cookie与Session会话管理
    本文详细介绍了如何通过HTTP响应和请求处理浏览器的Cookie信息,以及如何创建、设置和管理Cookie。同时探讨了会话跟踪技术中的Session机制,解释其原理及应用场景。 ... [详细]
  • 国内BI工具迎战国际巨头Tableau,稳步崛起
    尽管商业智能(BI)工具在中国的普及程度尚不及国际市场,但近年来,随着本土企业的持续创新和市场推广,国内主流BI工具正逐渐崭露头角。面对国际品牌如Tableau的强大竞争,国内BI工具通过不断优化产品和技术,赢得了越来越多用户的认可。 ... [详细]
  • 在Linux系统中配置并启动ActiveMQ
    本文详细介绍了如何在Linux环境中安装和配置ActiveMQ,包括端口开放及防火墙设置。通过本文,您可以掌握完整的ActiveMQ部署流程,确保其在网络环境中正常运行。 ... [详细]
  • 如何在WPS Office for Mac中调整Word文档的文字排列方向
    本文将详细介绍如何使用最新版WPS Office for Mac调整Word文档中的文字排列方向。通过这些步骤,用户可以轻松更改文本的水平或垂直排列方式,以满足不同的排版需求。 ... [详细]
  • 本文介绍如何使用阿里云的fastjson库解析包含时间戳、IP地址和参数等信息的JSON格式文本,并进行数据处理和保存。 ... [详细]
  • 2023 ARM嵌入式系统全国技术巡讲旨在分享ARM公司在半导体知识产权(IP)领域的最新进展。作为全球领先的IP提供商,ARM在嵌入式处理器市场占据主导地位,其产品广泛应用于90%以上的嵌入式设备中。此次巡讲将邀请来自ARM、飞思卡尔以及华清远见教育集团的行业专家,共同探讨当前嵌入式系统的前沿技术和应用。 ... [详细]
  • 深入理解 Oracle 存储函数:计算员工年收入
    本文介绍如何使用 Oracle 存储函数查询特定员工的年收入。我们将详细解释存储函数的创建过程,并提供完整的代码示例。 ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • 本文介绍如何在 Xcode 中使用快捷键和菜单命令对多行代码进行缩进,包括右缩进和左缩进的具体操作方法。 ... [详细]
  • 本文介绍如何在应用程序中使用文本输入框创建密码输入框,并通过设置掩码来隐藏用户输入的内容。我们将详细解释代码实现,并提供专业的补充说明。 ... [详细]
  • 本文介绍如何通过SQL查询从JDE(JD Edwards)系统中提取所有字典数据,涵盖关键表的关联和字段选择。具体包括F0004和F0005系列表的数据提取方法。 ... [详细]
  • 本文详细介绍了如何通过命令行启动MySQL服务,包括打开命令提示符窗口、进入MySQL的bin目录、输入正确的连接命令以及注意事项。文中还提供了更多相关命令的资源链接。 ... [详细]
  • 本文介绍如何使用 NSTimer 实现倒计时功能,详细讲解了初始化方法、参数配置以及具体实现步骤。通过示例代码展示如何创建和管理定时器,确保在指定时间间隔内执行特定任务。 ... [详细]
  • 本文介绍了在Windows环境下使用pydoc工具的方法,并详细解释了如何通过命令行和浏览器查看Python内置函数的文档。此外,还提供了关于raw_input和open函数的具体用法和功能说明。 ... [详细]
  • 本文介绍了如何使用PHP代码实现微信平台的媒体素材上传功能,详细解释了API接口的使用方法和注意事项,确保文件路径正确以避免常见的错误。 ... [详细]
author-avatar
周扒pi
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有