asp.net WeChat 개발(고급 대량 문자)

高洛峰
풀어 주다: 2017-02-22 14:14:38
원래의
1594명이 탐색했습니다.

본 글은 asp.net WeChat 개발에 있어서 고급 대량 문자 메시지 관련 내용을 주로 소개하고 있으니 필요한 친구들이 참고하시면 됩니다.

먼저 대량 문자 메시지 전송 과정을 설명하겠습니다. 프로그램은 먼저 UI가 있어야 코드 작성을 시작할 수 있습니다. 인터페이스는 다음과 같습니다.

asp.net WeChat 개발(고급 대량 문자)

asp.net WeChat 개발(고급 대량 문자) 사진을 보면 먼저 이 WeChat 계정을 얻어야 한다는 것을 알 수 있습니다. 계산 방법은 그룹에서 메시지가 성공적으로 전송되면 메시지가 저장됩니다. 메시지 수를 계산하기 위해 로컬 데이터베이스를 사용합니다(이 작업이 가능하다고 생각합니다). 4개 이상의 메시지가 전송되면 보낼 수 없습니다(서비스 계정은 한 달에 4개의 메시지만 보낼 수 있으므로 여기서는 이미 제한했습니다. 더 많이 보내도 소용이 없습니다. 미리보기 기능을 사용하여 하나씩 보내지 않으면 사용자는 4개의 메시지만 받을 수 있지만, 미리보기 기능을 사용하면 그룹 메시지를 보낼 수 있는 경우 100번만 보낼 수 있습니다. 몇 번이나 더, 그룹 메시지를 두 번 보낸 후 WeChat 공개 플랫폼 공식 웹사이트의 백엔드에 들어갔고 여전히 그룹 메시지 4개를 보낼 수 있다는 것을 알았기 때문에 약간 우울했습니다.), 그룹 메시지의 대상입니다! 전체 사용자 또는 그룹 사용자에게 보낼 수 있으며, 그룹 메시지 수를 저장하기 위해 여기서는 그룹 문자 메시지를 테스트하지 않습니다. 자세한 내용은 다음 코드를 참조하세요.

나머지 바인딩 이번 달 그룹 메시지 수

 /// <summary> 
 /// 绑定本月剩余群发条数
 /// </summary>
 private void BindMassCount()
 {
 WxMassService wms = new WxMassService();
 List<WxMassInfo> wxmaslist = wms.GetMonthMassCount();
 //官方微信服务号每月只能群发4条信息,(订阅号每天1条)多余信息,将不会成功推送,这里已经设定为4
 this.lbMassCounts.Text = (4 - int.Parse(wxmaslist.Count.ToString())).ToString();

 if (wxmaslist.Count >= 4)
 {
 this.LinkBtnSubSend.Enabled = false;
 this.LinkBtnSubSend.Attributes.Add("Onclick", "return confirm(&#39;群发信息已达上限!请下月初再试!&#39;)");
 }
 else
 {
 this.LinkBtnSubSend.Enabled = true;
 this.LinkBtnSubSend.Attributes.Add("Onclick", "return confirm(&#39;您确定要群发此条信息??&#39;)");
 }
 }
로그인 후 복사

그룹 목록 묶기

 /// <summary>
 /// 绑定分组列表
 /// </summary>
 private void BindGroupList()
 {
 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 jsonres = "";

 string content = Cache["AllGroups_content"] as string;

 if (content == null)
 {
 jsonres = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=" + Access_tokento;

 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(jsonres);
 myRequest.Method = "GET";
 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
 content = reader.ReadToEnd();
 reader.Close();

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

 //使用前需要引用Newtonsoft.json.dll文件
 JObject jsonObj = JObject.Parse(content);


 int groupsnum = jsonObj["groups"].Count();

 this.DDLGroupList.Items.Clear();//清除

 for (int i = 0; i < groupsnum; i++)
 {
 this.DDLGroupList.Items.Add(new ListItem(jsonObj["groups"][i]["name"].ToString() + "(" + jsonObj["groups"][i]["count"].ToString() + ")", jsonObj["groups"][i]["id"].ToString()));
 }
 }
 /// <summary>
 /// 选择群发对象类型,显示隐藏分组列表项
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void DDLMassType_SelectedIndexChanged(object sender, EventArgs e)
 {
 if (int.Parse(this.DDLMassType.SelectedValue.ToString()) > 0)
 {
 this.DDLGroupList.Visible = true;
 }
 else
 {
  this.DDLGroupList.Visible = false;
 }
 }
로그인 후 복사

보내기 차단



 /// <summary>
 /// 群发
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void LinkBtnSubSend_Click(object sender, EventArgs e)
 {
 //根据单选按钮判断类型,发送
 ///如果选择的是文本消息
 if (this.RadioBtnList.SelectedValue.ToString().Equals("0"))
 {
 if (String.IsNullOrWhiteSpace(this.txtwenben.InnerText.ToString().Trim()))
 {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;请输入您要群发文本内容!&#39;);", true);
  return;
 }
 if (this.txtwenben.InnerText.ToString().Trim().Length<10)
 {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;文本内容至少需要10个字符以上!&#39;);", true);
  return;
 }

 WxMassService wms = new WxMassService();
 List<WxMassInfo> 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"
  // ],
  // "msgtype": "text",
  // "text": { "content": "hello from boxer."}
  //}

  string postData = "{\"touser\":[" + sbs.ToString() +
  "],\"msgtype\":\"text\",\"text\":{\"content\":\"" + this.txtwenben.InnerText.ToString() +
  "\"}";


  string tuwenres = wxs.GetPage(posturl, postData);

  //使用前需药引用Newtonsoft.json.dll文件
  JObject jsonObj = JObject.Parse(tuwenres);

  if (jsonObj["errcode"].ToString().Equals("0"))
  {
   //群发成功后,保存记录
  WxMassInfo wmi = new WxMassInfo();

  wmi.ImageUrl = "";
  wmi.type = "文本";
  wmi.contents = this.txtwenben.InnerText.ToString().Trim();
  wmi.title = this.txtwenben.InnerText.ToString().Substring(0, 10) + "...";

  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"
  // },
  // "text":{
  // "content":"CONTENT"
  // },
  // "msgtype":"text"
  //}
  //}

  string postData = "{\"filter\":{\"is_to_all\":\"false\"\"group_id\":\"" + group_id +
  "\"},\"text\":{\"content\":\"" + this.txtwenben.InnerText.ToString() +
  "\"},\"msgtype\":\"text\"}";


  string tuwenres = wxs.GetPage(posturl, postData);

  //使用前需药引用Newtonsoft.json.dll文件
  JObject jsonObj = JObject.Parse(tuwenres);

  if (jsonObj["errcode"].ToString().Equals("0"))
  {
  //群发成功后,保存记录
  WxMassInfo wmi = new WxMassInfo();

  wmi.ImageUrl = "";
  wmi.type = "文本";
  wmi.contents = this.txtwenben.InnerText.ToString().Trim();
  wmi.title = this.txtwenben.InnerText.ToString().Substring(0, 10) + "...";

  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;
  }
  }

 
 }
 }
 //如果选择的是图文消息
 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<WxMassInfo> 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;
  }
  }
 }
 }
 }
로그인 후 복사

미리보기 전송


/// <summary>
 /// 发送前预览
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected void LinkBtnSendPreview_Click(object sender, EventArgs e)
 {
 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/preview?access_token=" + Access_tokento;

 ///如果选择的是文本消息
 if (this.RadioBtnList.SelectedValue.ToString().Equals("0"))
 {
 if (String.IsNullOrWhiteSpace(this.txtwenben.InnerText.ToString().Trim()))
 {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;请输入您要发送预览的文本内容!&#39;);", true);
  return;
 }
 if (this.txttoUserName.Value.ToString().Trim().Equals("请输入用户微信号"))
 {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;请输入接收消息的用户微信号!&#39;);", true);
  return;
 }
 //文本消息的json数据{
 // "touser":"OPENID", 可改为对微信号预览,例如towxname:zhangsan
 // "text":{ 
 // "content":"CONTENT" 
 // }, 
 // "msgtype":"text"
 //}
 string postData = "{\"towxname\":\"" + this.txttoUserName.Value.ToString() +
   "\",\"text\":{\"content\":\"" + this.txtwenben.InnerText.ToString() +
   "\"},\"msgtype\":\"text\"}";

 string tuwenres = wxs.GetPage(posturl, postData);

 //使用前需药引用Newtonsoft.json.dll文件
 JObject jsonObj = JObject.Parse(tuwenres);

 if (jsonObj["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;
 }
 }
 //如果选择的是图文消息
 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;
 }
 if (this.txttoUserName.Value.ToString().Trim().Equals("请输入用户微信号"))
 {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;请输入接收消息的用户微信号!&#39;);", true);
  return;
 }
 //图文消息的json数据{
 // "touser":"OPENID", 可改为对微信号预览,例如towxname:zhangsan
  // "mpnews":{ 
  // "media_id":"123dsdajkasd231jhksad" 
  // },
  // "msgtype":"mpnews" 
  //}
 string postData = "{\"towxname\":\"" + this.txttoUserName.Value.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;
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;发送预览成功!!&#39;);", true);
  return;
 }
 else
 {
  ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "", "alert(&#39;发送预览失败!!&#39;);", true);
  return;
 }


 }
 
 }
로그인 후 복사

핵심 부분은 모든 사용자의 openID를 가져와 문자열로 연결하는 것입니다.

 /// <summary>
 /// 获取所有微信用户的OpenID
 /// </summary>
 /// <returns></returns>
 protected string GetAllUserOpenIDList()
 {
 StringBuilder sb = new StringBuilder();

 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 jsonres = "";

 string content = Cache["AllUserOpenList_content"] as string;

 if (content == null)
 {
 jsonres = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + Access_tokento;

 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(jsonres);
 myRequest.Method = "GET";
 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
 content = reader.ReadToEnd();
 reader.Close();

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

 //使用前需要引用Newtonsoft.json.dll文件
 JObject jsonObj = JObject.Parse(content);


 if (jsonObj.ToString().Contains("count"))
 {
 int totalnum = int.Parse(jsonObj["count"].ToString());



 for (int i = 0; i < totalnum; i++)
 {
  sb.Append(&#39;"&#39;);
  sb.Append(jsonObj["data"]["openid"][i].ToString());
  sb.Append(&#39;"&#39;);
  sb.Append(",");
 }
 }

 return sb.Remove(sb.ToString().LastIndexOf(","),1).ToString();
 }
로그인 후 복사

이제 끝입니다. 다음 장에서는 그래픽 및 텍스트 정보를 그룹으로 보내기 전에 그래픽 및 텍스트 정보에 필요한 자료를 업로드해야 하기 때문에 계속해서 설명하겠습니다. text 정보를 얻고 media_id를 얻으므로 이번 장에서는 이에 대해 소개하지 않겠습니다. 다음 장에서는 단일 그래픽과 텍스트 메시지를 생성하여 그룹에 보내는 방법을 소개하겠습니다.

asp.net WeChat 개발(고급 그룹 텍스트) 관련 기사를 더 보려면 PHP 중국어 웹사이트를 주목하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!