微信小程序|微信开发
C# 微信 接口
微信小程序-微信开发
A、为了实现高级群发功能,需要解决的问题
易语言防偷源码,ubuntu中sawp作用,刚下的tomcat无法启动,php 爬虫 ip,php运行时接收消息,象山优化seolzw
1、通过微信接口上传图文消息素材时,Json中的图片不是url而是media_id,如何通过微信接口上传图片并获取图片的media_id?
asp源码 后台无限制版,ubuntu wine32,有灵性的爬虫,php编程技术二维数组排序,大浪seo公司lzw
2、图片存储在什么地方,如何获取?
弹弹堂游戏源码,vscode查看不了网页,ubuntu中文灰色,vue发布到tomcat,爬虫 数据收集,php 数组对象排序,seo关键词引流报价,个人主页网站源码免费下载,生活鲜花节模板lzw
B、实现步骤,以根据OpenID列表群发图文消息为例
1、准备数据
我把数据存储在数据库中,ImgUrl字段是图片在服务器上的相对路径(这里的服务器是自己的服务器,不是微信的哦)。
从数据库中获取数据放到DataTable中:
DataTable dt = ImgItemDal.GetImgItemTable(ID, data);
2、通过微信接口上传图片,返回图片的media_id
取ImgUrl字段数据,通过MapPath方法获取图片在服务器上的物理地址,用FileStream类读取图片,并上传给微信
HTTP上传文件代码(HttpRequestUtil类):
/// 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类):
/// public static string UploadMedia(string access_token, string type, string path){ // 设置参数 string url = string.Format("http://file.api./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类(操作图文消息表的类)):
/// 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:
/// 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;}
/// public static string UploadNews(string access_token, string postData){ return HttpRequestUtil.PostUrl(string.Format("https://api./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类):
/// 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;}/// public static List GetOpenIDs(string access_token, string next_openid){ // 设置参数 string url = string.Format("https://api./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类):
/// 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));/// public static string Send(string access_token, string postData){ return HttpRequestUtil.PostUrl(string.Format("https://api./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(ID, 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#微信公众平台开发之高级群发接口相关文章请关注PHP中文网!