涉及access_token的获取请参考《C#微信公众平台开发—access_token的获取存储与更新》
1、通过微信接口上传图文消息素材时,Json中的图片不是url而是media_id,如何通过微信接口上传图片并获取图片的media_id?
二、实现步骤,以根据OpenID列表群发图文消息为例
1、准备数据
我把数据存储在数据库中,imgurl字段是图片在服务器上的相对路径(这里的服务器是自己的服务器,不是微信的哦)。

DataTable dt = ImgItemDal.GetImgItemTable(loginUser.OrgID,data);
取imgurl字段数据,通过MapPath方法获取图片在服务器上的物理地址,用FileStream类读取图片,并上传给微信
@H_404_48@
/// <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); 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 = FileStream(path,FileMode.Open,FileAccess.Read); byte[] bArr = new byte[fs.Length]; fs.Read(bArr,0 request.GetRequestStream(); postStream.Write(itemBoundaryBytes,itemBoundaryBytes.Length); postStream.Write(postHeaderBytes,postHeaderBytes.Length); postStream.Write(bArr,bArr.Length); postStream.Write(endBoundaryBytes,endBoundaryBytes.Length); postStream.Close(); 发送请求并获取相应回应数据 HttpWebResponse response = request.GetResponse() HttpWebResponse; 直到request.GetResponse()程序才开始向目标网页发送Post请求 Stream instream = response.GetResponseStream(); StreamReader sr = StreamReader(instream,Encoding.UTF8); 返回结果网页(html)代码 string content = sr.ReadToEnd(); return content; }
请求微信接口,上传图片,返回media_id(WXApi类):
上传媒体返回媒体ID string UploadMedia(string access_token,1)">string type,1)"> 设置参数 string url = http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1} HttpRequestUtil.HttpUploadFile(url,path); }
string msg = WXApi.UploadMedia(access_token,image",path); 上图片返回媒体ID string media_id = Tools.GetJsonValue(msg,1)">media_id");
string path = MapPath(data);
一个图文消息由若干条图文组成,每条图文有标题、内容、链接、图片等
遍历每条图文数据,分别请求微信接口,上传图片,获取media_id
3、上传图文消息素材
拼接图文消息素材Json字符串(ImgItemDal类(操作图文消息表的类)):
拼接图文消息素材Json字符串 string GetArticlesJsonStr(PageBase page,1)"> access_token,DataTable dt) { StringBuilder sbArticlesJson = StringBuilder(); sbArticlesJson.Append({\"articles\":[int i = foreach (DaTarow dr in dt.Rows) { string path = page.MapPath(dr[imgurl].ToString()); if (!File.Exists(path)) { return {\"code\":0,\"msg\":\"要发送的图片不存在\"}; } 上图片返回媒体ID ); sbArticlesJson.Append({\"thumb_media_id\":\"" + media_id + \",1)">\"author\":\"" + dr[Author"].ToString() + \"title\":\"Title\"content_source_url\":\"TextUrl\"content\":\"Content\"digest\":\"); if (i == dt.Rows.Count - ) { sbArticlesJson.Append(\"show_cover_pic\":\"1\"}); } else { sbArticlesJson.Append(\"show_cover_pic\":\"1\"},1)">); } i++; } sbArticlesJson.Append(]} sbArticlesJson.ToString(); }
请求Url,发送数据 string PostUrl( postData) { byte[] data = Encoding.UTF8.GetBytes(postData); ; request.ContentType = application/x-www-form-urlencoded; request.ContentLength = data.Length; Stream outstream = request.GetRequestStream(); outstream.Write(data,data.Length); outstream.Close(); content; }
上传图文消息素材返回media_id string UploadNews(return HttpRequestUtil.PostUrl(https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}View Code
string articlesJson = ImgItemDal.GetArticlesJsonStr(thisstring newsMsg = WXApi.UploadNews(access_token,articlesJson); string newsid = Tools.GetJsonValue(newsMsg,1)">");
4、群发图文消息
获取全部关注者OpenID集合(WXApi类):
获取关注者OpenID集合 static List<string> GetopenIDs( access_token) { List<string> result = new List<string>(); List<string> openidList = GetopenIDs(access_token,1)">null); result.AddRange(openidList); while (openidList.Count > ) { openidList = GetopenIDs(access_token,openidList[openidList.Count - ]); result.AddRange(openidList); } result; } next_openid) { https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}&next_openid={1}string.IsNullOrWhiteSpace(next_openid) ? "" : next_openid); string returnStr = HttpRequestUtil.RequestUrl(url); int count = int.Parse(Tools.GetJsonValue(returnStr,1)">count)); if (count > ) { string startFlg = \"openid\":[; int start = returnStr.IndexOf(startFlg) + startFlg.Length; int end = returnStr.IndexOf(]string openids = returnStr.Substring(start,end - start).Replace(\"return openids.Split('').ToList<(); } { return (); } }
拼接图文消息Json(WxmsgUtil类):
图文消息json string CreateNewsJson(string media_id,List< openidList) { StringBuilder sb = StringBuilder(); sb.Append({\"touser\":[); sb.Append(string.Join(string>(a => " + a + ).ToArray())); sb.Append(],1)">); sb.Append(\"msgtype\":\"mpnews\",1)">\"mpnews\":{\"media_id\":\"\"}} sb.ToString(); }
群发代码:
根据OpenID列表群发 string Send(https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={0}View Code
供群发按钮调用的方法(data是传到页面的id,根据它从数据库中取数据):
群发 Send() { string type = Request[type]; string data = Request[data]; string access_token = AdminUtil.GetAccesstoken(this); 获取access_token List<获取关注者OpenID列表 UserInfo loginUser = AdminUtil.GetLoginUser(当前登录用户 string resultMsg = ; 发送文本 if (type == 1) { resultMsg = WXApi.Send(access_token,WxmsgUtil.CreateTextJson(data,openidList)); } 发送图片 2string path = MapPath(data); ); resultMsg =发送图文消息 3) { DataTable dt = ImgItemDal.GetImgItemTable(loginUser.OrgID,data); 结果处理 .IsNullOrWhiteSpace(resultMsg)) { string errcode = Tools.GetJsonValue(resultMsg,1)">errcodestring errmsg = Tools.GetJsonValue(resultMsg,1)">errmsgif (errcode == 0) { {\"code\":1,\"msg\":\"\"} { " + errcode + " + errmsg + ; } } 错误\"}; } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。