C#微信公众平台开发之高级群发接口的示例分析
小编给大家分享一下C#微信公众平台开发之高级群发接口的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
成都创新互联是一家集网站建设,曲江企业网站建设,曲江品牌网站建设,网站定制,曲江网站建设报价,网络营销,网络优化,曲江网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
一、为了实现高级群发功能,需要解决的问题
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); // 上图片返回媒体IDstring 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 ListGetOpenIDs(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 ListGetOpenIDs(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 (); } }
拼接图文消息Json(WXMsgUtil类):
////// 图文消息json /// public static string CreateNewsJson(string media_id, ListopenidList) { 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 ListopenidList = 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#微信公众平台开发之高级群发接口的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!
分享文章:C#微信公众平台开发之高级群发接口的示例分析
本文路径:http://scyanting.com/article/pjieec.html