C#微信公众平台开发之高级群发接口

2019-12-30 11:47:44王冬梅

上传图文消息素材,获取图文消息的media_id:

 


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


/// <summary>
/// 上传图文消息素材返回media_id
/// </summary>
public static string UploadNews(string access_token, string postData)
{
 return HttpRequestUtil.PostUrl(string.Format("https://www.easck.com/cgi-bin/media/uploadnews?access_token={0}", access_token), postData);
}

string articlesJson = ImgItemDal.GetArticlesJsonStr(this, access_token, dt);
string newsMsg = WXApi.UploadNews(access_token, articlesJson);
string newsid = Tools.GetJsonValue(newsMsg, "media_id");

4、群发图文消息

获取全部关注者OpenID集合(WXApi类):

 


/// <summary>
/// 获取关注者OpenID集合
/// </summary>
public static List<string> GetOpenIDs(string access_token)
{
 List<string> result = new List<string>();

 List<string> openidList = GetOpenIDs(access_token, null);
 result.AddRange(openidList);

 while (openidList.Count > 0)
 {
  openidList = GetOpenIDs(access_token, openidList[openidList.Count - 1]);
  result.AddRange(openidList);
 }

 return result;
}

/// <summary>
/// 获取关注者OpenID集合
/// </summary>
public static List<string> GetOpenIDs(string access_token, string next_openid)
{
 // 设置参数
 string url = string.Format("https://www.easck.com/cgi-bin/user/get?access_token={0}&next_openid={1}", access_token, string.IsNullOrWhiteSpace(next_openid) ? "" : next_openid);
 string returnStr = HttpRequestUtil.RequestUrl(url);
 int count = int.Parse(Tools.GetJsonValue(returnStr, "count"));
 if (count > 0)
 {
  string startFlg = ""openid":[";
  int start = returnStr.IndexOf(startFlg) + startFlg.Length;
  int end = returnStr.IndexOf("]", start);
  string openids = returnStr.Substring(start, end - start).Replace(""", "");
  return openids.Split(',').ToList<string>();
 }
 else
 {
  return new List<string>();
 }
}