自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

C#微信公眾平臺開發(fā)—高級群發(fā)接口

開發(fā) 后端
為了實(shí)現(xiàn)高級群發(fā)功能,需要解決的問題:1、通過微信接口上傳圖文消息素材時(shí),Json中的圖片不是url而是media_id,如何通過微信接口上傳圖片并獲取圖片的media_id?

涉及access_token的獲取請參考《C#微信公眾平臺開發(fā)—access_token的獲取存儲與更新》

一、為了實(shí)現(xiàn)高級群發(fā)功能,需要解決的問題

1、通過微信接口上傳圖文消息素材時(shí),Json中的圖片不是url而是media_id,如何通過微信接口上傳圖片并獲取圖片的media_id?

2、圖片存儲在什么地方,如何獲???

二、實(shí)現(xiàn)步驟,以根據(jù)OpenID列表群發(fā)圖文消息為例

1、準(zhǔn)備數(shù)據(jù)

我把數(shù)據(jù)存儲在數(shù)據(jù)庫中,ImgUrl字段是圖片在服務(wù)器上的相對路徑(這里的服務(wù)器是自己的服務(wù)器,不是微信的哦)。

從數(shù)據(jù)庫中獲取數(shù)據(jù)放到DataTable中:

  1. DataTable dt = ImgItemDal.GetImgItemTable(loginUser.OrgID, data); 

2、通過微信接口上傳圖片,返回圖片的media_id

取ImgUrl字段數(shù)據(jù),通過MapPath方法獲取圖片在服務(wù)器上的物理地址,用FileStream類讀取圖片,并上傳給微信

HTTP上傳文件代碼(HttpRequestUtil類):

  1. /// <summary> 
  2. /// Http上傳文件 
  3. /// </summary> 
  4. public static string HttpUploadFile(string url, string path) 
  5.     // 設(shè)置參數(shù) 
  6.     HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 
  7.     CookieContainer cookieContainer = new CookieContainer(); 
  8.     request.CookieContainer = cookieContainer; 
  9.     request.AllowAutoRedirect = true
  10.     request.Method = "POST"
  11.     string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機(jī)分隔線 
  12.     request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary; 
  13.     byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n"); 
  14.     byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); 
  15.  
  16.     int pos = path.LastIndexOf("\\"); 
  17.     string fileName = path.Substring(pos + 1); 
  18.  
  19.     //請求頭部信息  
  20.     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)); 
  21.     byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); 
  22.  
  23.     FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); 
  24.     byte[] bArr = new byte[fs.Length]; 
  25.     fs.Read(bArr, 0, bArr.Length); 
  26.     fs.Close(); 
  27.  
  28.     Stream postStream = request.GetRequestStream(); 
  29.     postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length); 
  30.     postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); 
  31.     postStream.Write(bArr, 0, bArr.Length); 
  32.     postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length); 
  33.     postStream.Close(); 
  34.  
  35.     //發(fā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù) 
  36.     HttpWebResponse response = request.GetResponse() as HttpWebResponse; 
  37.     //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁發(fā)送Post請求 
  38.     Stream instream = response.GetResponseStream(); 
  39.     StreamReader sr = new StreamReader(instream, Encoding.UTF8); 
  40.     //返回結(jié)果網(wǎng)頁(html)代碼 
  41.     string content = sr.ReadToEnd(); 
  42.     return content; 

請求微信接口,上傳圖片,返回media_id(WXApi類):

  1. /// <summary> 
  2. /// 上傳媒體返回媒體ID 
  3. /// </summary> 
  4. public static string UploadMedia(string access_token, string type, string path) 
  5.     // 設(shè)置參數(shù) 
  6.     string url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", access_token, type); 
  7.     return HttpRequestUtil.HttpUploadFile(url, path); 

  1. string msg = WXApi.UploadMedia(access_token, "image", path); // 上圖片返回媒體ID 
  2. string media_id = Tools.GetJsonValue(msg, "media_id"); 

傳入的path(aspx.cs文件中的代碼):

  1. string path = MapPath(data); 

一個(gè)圖文消息由若干條圖文組成,每條圖文有標(biāo)題、內(nèi)容、鏈接、圖片等

遍歷每條圖文數(shù)據(jù),分別請求微信接口,上傳圖片,獲取media_id

3、上傳圖文消息素材

拼接圖文消息素材Json字符串(ImgItemDal類(操作圖文消息表的類)):

  1. /// <summary> 
  2. /// 拼接圖文消息素材Json字符串 
  3. /// </summary> 
  4. public static string GetArticlesJsonStr(PageBase page, string access_token, DataTable dt) 
  5.     StringBuilder sbArticlesJson = new StringBuilder(); 
  6.  
  7.     sbArticlesJson.Append("{\"articles\":["); 
  8.     int i = 0; 
  9.     foreach (DataRow dr in dt.Rows) 
  10.     { 
  11.         string path = page.MapPath(dr["ImgUrl"].ToString()); 
  12.         if (!File.Exists(path)) 
  13.         { 
  14.             return "{\"code\":0,\"msg\":\"要發(fā)送的圖片不存在\"}"
  15.         } 
  16.         string msg = WXApi.UploadMedia(access_token, "image", path); // 上圖片返回媒體ID 
  17.         string media_id = Tools.GetJsonValue(msg, "media_id"); 
  18.         sbArticlesJson.Append("{"); 
  19.         sbArticlesJson.Append("\"thumb_media_id\":\"" + media_id + "\","); 
  20.         sbArticlesJson.Append("\"author\":\"" + dr["Author"].ToString() + "\","); 
  21.         sbArticlesJson.Append("\"title\":\"" + dr["Title"].ToString() + "\","); 
  22.         sbArticlesJson.Append("\"content_source_url\":\"" + dr["TextUrl"].ToString() + "\","); 
  23.         sbArticlesJson.Append("\"content\":\"" + dr["Content"].ToString() + "\","); 
  24.         sbArticlesJson.Append("\"digest\":\"" + dr["Content"].ToString() + "\","); 
  25.         if (i == dt.Rows.Count - 1) 
  26.         { 
  27.             sbArticlesJson.Append("\"show_cover_pic\":\"1\"}"); 
  28.         } 
  29.         else 
  30.         { 
  31.             sbArticlesJson.Append("\"show_cover_pic\":\"1\"},"); 
  32.         } 
  33.         i++; 
  34.     } 
  35.     sbArticlesJson.Append("]}"); 
  36.  
  37.     return sbArticlesJson.ToString(); 

上傳圖文消息素材,獲取圖文消息的media_id:

  1. /// <summary> 
  2. /// 請求Url,發(fā)送數(shù)據(jù) 
  3. /// </summary> 
  4. public static string PostUrl(string url, string postData) 
  5.     byte[] data = Encoding.UTF8.GetBytes(postData); 
  6.  
  7.     // 設(shè)置參數(shù) 
  8.     HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 
  9.     CookieContainer cookieContainer = new CookieContainer(); 
  10.     request.CookieContainer = cookieContainer; 
  11.     request.AllowAutoRedirect = true
  12.     request.Method = "POST"
  13.     request.ContentType = "application/x-www-form-urlencoded"
  14.     request.ContentLength = data.Length; 
  15.     Stream outstream = request.GetRequestStream(); 
  16.     outstream.Write(data, 0, data.Length); 
  17.     outstream.Close(); 
  18.  
  19.     //發(fā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù) 
  20.     HttpWebResponse response = request.GetResponse() as HttpWebResponse; 
  21.     //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁發(fā)送Post請求 
  22.     Stream instream = response.GetResponseStream(); 
  23.     StreamReader sr = new StreamReader(instream, Encoding.UTF8); 
  24.     //返回結(jié)果網(wǎng)頁(html)代碼 
  25.     string content = sr.ReadToEnd(); 
  26.     return content; 

  1. /// <summary> 
  2. /// 上傳圖文消息素材返回media_id 
  3. /// </summary> 
  4. public static string UploadNews(string access_token, string postData) 
  5.     return HttpRequestUtil.PostUrl(string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", access_token), postData); 

  1. string articlesJson = ImgItemDal.GetArticlesJsonStr(this, access_token, dt); 
  2. string newsMsg = WXApi.UploadNews(access_token, articlesJson); 
  3. string newsid = Tools.GetJsonValue(newsMsg, "media_id"); 

4、群發(fā)圖文消息

獲取全部關(guān)注者OpenID集合(WXApi類):

  1. /// <summary> 
  2. /// 獲取關(guān)注者OpenID集合 
  3. /// </summary> 
  4. public static List<string> GetOpenIDs(string access_token) 
  5.     List<string> result = new List<string>(); 
  6.  
  7.     List<string> openidList = GetOpenIDs(access_token, null); 
  8.     result.AddRange(openidList); 
  9.  
  10.     while (openidList.Count > 0) 
  11.     { 
  12.         openidList = GetOpenIDs(access_token, openidList[openidList.Count - 1]); 
  13.         result.AddRange(openidList); 
  14.     } 
  15.  
  16.     return result; 
  17.  
  18. /// <summary> 
  19. /// 獲取關(guān)注者OpenID集合 
  20. /// </summary> 
  21. public static List<string> GetOpenIDs(string access_token, string next_openid) 
  22.     // 設(shè)置參數(shù) 
  23.     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); 
  24.     string returnStr = HttpRequestUtil.RequestUrl(url); 
  25.     int count = int.Parse(Tools.GetJsonValue(returnStr, "count")); 
  26.     if (count > 0) 
  27.     { 
  28.         string startFlg = "\"openid\":["
  29.         int start = returnStr.IndexOf(startFlg) + startFlg.Length; 
  30.         int end = returnStr.IndexOf("]", start); 
  31.         string openids = returnStr.Substring(start, end - start).Replace("\""""); 
  32.         return openids.Split(',').ToList<string>(); 
  33.     } 
  34.     else 
  35.     { 
  36.         return new List<string>(); 
  37.     } 

  1. List<string> openidList = WXApi.GetOpenIDs(access_token); //獲取關(guān)注者OpenID列表 

拼接圖文消息Json(WXMsgUtil類):

  1. /// <summary> 
  2. /// 圖文消息json 
  3. /// </summary> 
  4. public static string CreateNewsJson(string media_id, List<string> openidList) 
  5.     StringBuilder sb = new StringBuilder(); 
  6.     sb.Append("{\"touser\":["); 
  7.     sb.Append(string.Join(",", openidList.ConvertAll<string>(a => "\"" + a + "\"").ToArray())); 
  8.     sb.Append("],"); 
  9.     sb.Append("\"msgtype\":\"mpnews\","); 
  10.     sb.Append("\"mpnews\":{\"media_id\":\"" + media_id + "\"}"); 
  11.     sb.Append("}"); 
  12.     return sb.ToString(); 

群發(fā)代碼:

  1. resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateNewsJson(newsid, openidList)); 
  1. /// <summary> 
  2. /// 根據(jù)OpenID列表群發(fā) 
  3. /// </summary> 
  4. public static string Send(string access_token, string postData) 
  5.     return HttpRequestUtil.PostUrl(string.Format("https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token={0}", access_token), postData); 

供群發(fā)按鈕調(diào)用的方法(data是傳到頁面的id,根據(jù)它從數(shù)據(jù)庫中取數(shù)據(jù)):

  1. /// <summary> 
  2. /// 群發(fā) 
  3. /// </summary> 
  4. public string Send() 
  5.     string type = Request["type"]; 
  6.     string data = Request["data"]; 
  7.  
  8.     string access_token = AdminUtil.GetAccessToken(this); //獲取access_token 
  9.     List<string> openidList = WXApi.GetOpenIDs(access_token); //獲取關(guān)注者OpenID列表 
  10.     UserInfo loginUser = AdminUtil.GetLoginUser(this); //當(dāng)前登錄用戶  
  11.  
  12.     string resultMsg = null
  13.  
  14.     //發(fā)送文本 
  15.     if (type == "1"
  16.     { 
  17.         resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateTextJson(data, openidList)); 
  18.     } 
  19.  
  20.     //發(fā)送圖片 
  21.     if (type == "2"
  22.     { 
  23.         string path = MapPath(data); 
  24.         if (!File.Exists(path)) 
  25.         { 
  26.             return "{\"code\":0,\"msg\":\"要發(fā)送的圖片不存在\"}"
  27.         } 
  28.         string msg = WXApi.UploadMedia(access_token, "image", path); 
  29.         string media_id = Tools.GetJsonValue(msg, "media_id"); 
  30.         resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateImageJson(media_id, openidList)); 
  31.     } 
  32.  
  33.     //發(fā)送圖文消息 
  34.     if (type == "3"
  35.     { 
  36.         DataTable dt = ImgItemDal.GetImgItemTable(loginUser.OrgID, data); 
  37.         string articlesJson = ImgItemDal.GetArticlesJsonStr(this, access_token, dt); 
  38.         string newsMsg = WXApi.UploadNews(access_token, articlesJson); 
  39.         string newsid = Tools.GetJsonValue(newsMsg, "media_id"); 
  40.         resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateNewsJson(newsid, openidList)); 
  41.     } 
  42.  
  43.     //結(jié)果處理 
  44.     if (!string.IsNullOrWhiteSpace(resultMsg)) 
  45.     { 
  46.         string errcode = Tools.GetJsonValue(resultMsg, "errcode"); 
  47.         string errmsg = Tools.GetJsonValue(resultMsg, "errmsg"); 
  48.         if (errcode == "0"
  49.         { 
  50.             return "{\"code\":1,\"msg\":\"\"}"
  51.         } 
  52.         else 
  53.         { 
  54.             return "{\"code\":0,\"msg\":\"errcode:" 
  55.                 + errcode + ", errmsg:" 
  56.                 + errmsg + "\"}"
  57.         } 
  58.     } 
  59.     else 
  60.     { 
  61.         return "{\"code\":0,\"msg\":\"type參數(shù)錯(cuò)誤\"}"
  62.     } 

C#微信公眾平臺開發(fā)源碼在我的博客首頁左側(cè)下面

原文鏈接:http://www.cnblogs.com/s0611163/p/4099735.html

責(zé)任編輯:張偉 來源: 博客園
相關(guān)推薦

2013-04-10 16:15:40

微信公眾平臺接口開發(fā)

2013-04-10 18:45:52

微信公眾平臺接口開發(fā)

2014-03-29 22:42:00

微信公眾平臺開發(fā)C#

2013-04-10 18:07:08

微信公眾平臺接口開發(fā)

2013-04-10 18:19:40

微信公眾平臺接口開發(fā)

2013-04-10 18:24:48

微信公眾平臺接口開發(fā)

2013-04-10 18:29:09

微信公眾平臺接口開發(fā)

2013-04-10 17:59:50

微信公眾平臺接口開發(fā)

2013-04-15 16:56:48

微信公眾平臺Android開發(fā)

2013-04-10 16:51:56

微信公眾平臺接口開發(fā)

2013-11-13 07:19:19

2013-04-10 18:40:59

微信公眾平臺接口開發(fā)

2013-04-10 17:52:15

微信公眾平臺接口開發(fā)

2013-04-08 16:14:10

微信微信公眾平臺

2013-05-24 09:35:46

Java實(shí)現(xiàn)

2013-04-10 18:12:57

2013-04-09 23:38:02

微信公眾平臺開發(fā)者

2013-04-08 15:13:39

微信公眾平臺

2013-04-12 02:01:55

微信公眾平臺接口開發(fā)

2013-04-11 10:50:07

微信公眾平臺接口開發(fā)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號