C#微信公众平台高级群发接口实现
关于access_token的获取、存储及更新机制,请参阅《C#微信公众平台开发之access_token的获取存储与更新》一文。
一、高级群发功能实现的关键问题
1. 在通过微信接口上传图文消息素材时,JSON数据中的图片字段要求使用media_id而非url,因此需解决如何通过接口上传图片并获取对应media_id的问题。
2. 明确图片文件的存储位置及其访问方式。
二、实现步骤详解:以根据OpenID列表群发图文消息为例
1. 数据准备阶段
将相关数据存入数据库,其中ImgUrl字段记录图片在自有服务器上的相对路径(注意:此处指开发者自建的服务器,非微信平台)。

从数据库中读取数据并存入DataTable对象中:
DataTable dt = ImgItemDal.GetImgItemTable(loginUser.OrgID, data);
2. 通过微信接口上传图片,获取图片的media_id
提取ImgUrl字段数据,利用MapPath方法转换为服务器物理路径,使用FileStream类读取图片文件内容,随后调用微信接口进行上传。
HTTP上传文件的核心代码封装在HttpRequestUtil类中:
///
/// 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;
}
请求微信接口完成图片上传并返回media_id的逻辑位于WXApi类中:
///
/// 上传媒体返回媒体ID
///
public static string UploadMedia(string access_token, string type, string path)
{
// 设置参数
string url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", access_token, type);
return HttpRequestUtil.HttpUploadFile(url, path);
}
string msg = WXApi.UploadMedia(access_token, "image", path); // 上图片返回媒体ID
string media_id = Tools.GetJsonValue(msg, "media_id");
传入的path参数(aspx.cs文件中的代码):
string path = MapPath(data);
一条完整的图文消息由若干条图文条目组成,每条条目包含标题、正文内容、跳转链接及封面图片等元素。
遍历每条图文数据,依次请求微信接口上传图片,从而获取每条图文所需的media_id。
3. 上传图文消息素材
拼接用于上传的图文消息素材JSON字符串,该逻辑封装在ImgItemDal类(负责操作图文消息表的类)中:
///
/// 拼接图文消息素材Json字符串
///
public static string GetArticlesJsonStr(PageBase page, string access_token, DataTable dt)
{
StringBuilder sbArticlesJson = new StringBuilder();
sbArticlesJson.Append("{\"articles\":[");
int i = 0;
foreach (DataRow dr in dt.Rows)
{
string path = page.MapPath(dr["ImgUrl"].ToString());
if (!File.Exists(path))
{
return "{\"code\":0,\"msg\":\"要发送的图片不存在\"}";
}
string msg = WXApi.UploadMedia(access_token, "image", path); // 上图片返回媒体ID
string media_id = Tools.GetJsonValue(msg, "media_id");
sbArticlesJson.Append("{");
sbArticlesJson.Append("\"thumb_media_id\":\"" + media_id + "\",");
sbArticlesJson.Append("\"author\":\"" + dr["Author"].ToString() + "\",");
sbArticlesJson.Append("\"title\":\"" + dr["Title"].ToString() + "\",");
sbArticlesJson.Append("\"content_source_url\":\"" + dr["TextUrl"].ToString() + "\",");
sbArticlesJson.Append("\"content\":\"" + dr["Content"].ToString() + "\",");
sbArticlesJson.Append("\"digest\":\"" + dr["Content"].ToString() + "\",");
if (i == dt.Rows.Count - 1)
{
sbArticlesJson.Append("\"show_cover_pic\":\"1\"}");
}
else
{
sbArticlesJson.Append("\"show_cover_pic\":\"1\"},");
}
i++;
}
sbArticlesJson.Append("]}");
return sbArticlesJson.ToString();
}
调用接口上传图文消息素材,并获取生成的图文消息media_id:
///
/// 请求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;
}
///
/// 上传图文消息素材返回media_id
///
public static string UploadNews(string access_token, string postData)
{
return HttpRequestUtil.PostUrl(string.Format("https://api.weixin.qq.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类提供:
///
/// 获取关注者OpenID集合
///
public static List GetOpenIDs(string access_token)
{
List result = new List();
List 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;
}
///
/// 获取关注者OpenID集合
///
public static List GetOpenIDs(string access_token, string next_openid)
{
// 设置参数
string url = string.Format("https://api.weixin.qq.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();
}
else
{
return new List();
}
}
List openidList = WXApi.GetOpenIDs(access_token); //获取关注者OpenID列表 接下来拼接用于群发的图文消息JSON,相关逻辑封装在WXMsgUtil类中:
///
/// 图文消息json
///
public static string CreateNewsJson(string media_id, List openidList)
{
StringBuilder sb = new StringBuilder();
sb.Append("{\"touser\":[");
sb.Append(string.Join(",", openidList.ConvertAll(a => "\"" + a + "\"").ToArray()));
sb.Append("],");
sb.Append("\"msgtype\":\"mpnews\",");
sb.Append("\"mpnews\":{\"media_id\":\"" + media_id + "\"}");
sb.Append("}");
return sb.ToString();
}
群发功能的执行代码:
resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateNewsJson(newsid, openidList));
///
/// 根据OpenID列表群发
///
public static string Send(string access_token, string postData)
{
return HttpRequestUtil.PostUrl(string.Format("https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={0}", access_token), postData);
}
供群发按钮调用的方法(data为页面传递的id,据此从数据库检索数据):
///
/// 群发
///
public string Send()
{
string type = Request["type"];
string data = Request["data"];
string access_token = AdminUtil.GetAccessToken(this); //获取access_token
List openidList = WXApi.GetOpenIDs(access_token); //获取关注者OpenID列表
UserInfo loginUser = AdminUtil.GetLoginUser(this); //当前登录用户
string resultMsg = null;
//发送文本
if (type == "1")
{
resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateTextJson(data, openidList));
}
//发送图片
if (type == "2")
{
string path = MapPath(data);
if (!File.Exists(path))
{
return "{\"code\":0,\"msg\":\"要发送的图片不存在\"}";
}
string msg = WXApi.UploadMedia(access_token, "image", path);
string media_id = Tools.GetJsonValue(msg, "media_id");
resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateImageJson(media_id, openidList));
}
//发送图文消息
if (type == "3")
{
DataTable dt = ImgItemDal.GetImgItemTable(loginUser.OrgID, data);
string articlesJson = ImgItemDal.GetArticlesJsonStr(this, access_token, dt);
string newsMsg = WXApi.UploadNews(access_token, articlesJson);
string newsid = Tools.GetJsonValue(newsMsg, "media_id");
resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateNewsJson(newsid, openidList));
}
//结果处理
if (!string.IsNullOrWhiteSpace(resultMsg))
{
string errcode = Tools.GetJsonValue(resultMsg, "errcode");
string errmsg = Tools.GetJsonValue(resultMsg, "errmsg");
if (errcode == "0")
{
return "{\"code\":1,\"msg\":\"\"}";
}
else
{
return "{\"code\":0,\"msg\":\"errcode:"
+ errcode + ", errmsg:"
+ errmsg + "\"}";
}
}
else
{
return "{\"code\":0,\"msg\":\"type参数错误\"}";
}
}
精彩专题分享:ASP.NET微信开发教程汇总,欢迎大家学习。
以上就是本文的全部内容,希望对大家的学习有所帮助。