涉及access_token的获取请参考《C#微信公众平台开发—access_token的获取存储与更新》
一、为了实现高级群发功能,需要解决的问题
1、通过微信接口上传图文消息素材时,Json中的图片不是url而是media_id,如何通过微信接口上传图片并获取图片的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参数错误\"}";
- }
- }
C#微信公众平台开发源码在我的博客首页左侧下面
原文链接:http://www.cnblogs.com/s0611163/p/4099735.html
文章题目:C#微信公众平台开发—高级群发接口
本文链接:http://www.shufengxianlan.com/qtweb/news17/330167.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联