涉及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类):
/// <summary> /// Http上传文件 /// </summary> 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类):
/// <summary> /// 上传媒体返回媒体ID /// </summary> 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类(操作图文消息表的类)):
/// <summary> /// 拼接图文消息素材Json字符串 /// </summary> 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:
/// <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://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类):
/// <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://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<string>(); } else { return new List<string>(); } }
List<string> openidList = WXApi.GetOpenIDs(access_token); //获取关注者OpenID列表
拼接图文消息Json(WXMsgUtil类):
/// <summary> /// 图文消息json /// </summary> public static string CreateNewsJson(string media_id, List<string> openidList) { StringBuilder sb = new StringBuilder(); sb.Append(\"{\\\"touser\\\":[\"); sb.Append(string.Join(\",\", openidList.ConvertAll<string>(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)); /// <summary> /// 根据OpenID列表群发 /// </summary> 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,根据它从数据库中取数据):
/// <summary> /// 群发 /// </summary> public string Send() { string type = Request[\"type\"]; string data = Request[\"data\"]; string access_token = AdminUtil.GetAccessToken(this); //获取access_token List<string> 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参数错误\\\"}\"; } }
以上就是本文的全部内容,希望对大家的学习有所帮助。
本文地址:https://www.stayed.cn/item/20245
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我