日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
C#微信公眾平臺(tái)開發(fā)—高級(jí)群發(fā)接口

涉及access_token的獲取請(qǐng)參考《C#微信公眾平臺(tái)開發(fā)—access_token的獲取存儲(chǔ)與更新》

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

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

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

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

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

我把數(shù)據(jù)存儲(chǔ)在數(shù)據(jù)庫中,ImgUrl字段是圖片在服務(wù)器上的相對(duì)路徑(這里的服務(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. ///  
  2. /// Http上傳文件 
  3. ///  
  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.     //請(qǐng)求頭部信息  
  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ā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù) 
  36.     HttpWebResponse response = request.GetResponse() as HttpWebResponse; 
  37.     //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁發(fā)送Post請(qǐng)求 
  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; 

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

 
 
  1. ///  
  2. /// 上傳媒體返回媒體ID 
  3. ///  
  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ù),分別請(qǐng)求微信接口,上傳圖片,獲取media_id

3、上傳圖文消息素材

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

 
 
  1. ///  
  2. /// 拼接圖文消息素材Json字符串 
  3. ///  
  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. ///  
  2. /// 請(qǐng)求Url,發(fā)送數(shù)據(jù) 
  3. ///  
  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ā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù) 
  20.     HttpWebResponse response = request.GetResponse() as HttpWebResponse; 
  21.     //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁發(fā)送Post請(qǐng)求 
  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. ///  
  2. /// 上傳圖文消息素材返回media_id 
  3. ///  
  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. ///  
  2. /// 獲取關(guān)注者OpenID集合 
  3. ///  
  4. public static List GetOpenIDs(string access_token) 
  5.     List result = new List(); 
  6.  
  7.     List 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. ///  
  19. /// 獲取關(guān)注者OpenID集合 
  20. ///  
  21. public static List 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(); 
  33.     } 
  34.     else 
  35.     { 
  36.         return new List(); 
  37.     } 

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

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

 
 
  1. ///  
  2. /// 圖文消息json 
  3. ///  
  4. public static string CreateNewsJson(string media_id, List openidList) 
  5.     StringBuilder sb = new StringBuilder(); 
  6.     sb.Append("{\"touser\":["); 
  7.     sb.Append(string.Join(",", openidList.ConvertAll(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. ///  
  2. /// 根據(jù)OpenID列表群發(fā) 
  3. ///  
  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. ///  
  2. /// 群發(fā) 
  3. ///  
  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 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#微信公眾平臺(tái)開發(fā)源碼在我的博客首頁左側(cè)下面

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


當(dāng)前文章:C#微信公眾平臺(tái)開發(fā)—高級(jí)群發(fā)接口
分享URL:http://www.dlmjj.cn/article/cdodidp.html