欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#微信公眾平臺(tái)開發(fā)之高級(jí)群發(fā)接口

 更新時(shí)間:2016年03月24日 14:12:33   作者:秋荷雨翔  
這篇文章主要為大家詳細(xì)介紹了C#微信公眾平臺(tái)開發(fā)之高級(jí)群發(fā)接口的相關(guān)資料,需要的朋友可以參考下

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

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

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

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

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

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

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

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

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

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

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

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

/// <summary>
/// Http上傳文件
/// </summary>
public static string HttpUploadFile(string url, string path)
{
 // 設(shè)置參數(shù)
 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"); // 隨機(jī)分隔線
 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);

 //請(qǐng)求頭部信息 
 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();

 //發(fā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
 HttpWebResponse response = request.GetResponse() as HttpWebResponse;
 //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求
 Stream instream = response.GetResponseStream();
 StreamReader sr = new StreamReader(instream, Encoding.UTF8);
 //返回結(jié)果網(wǎng)頁(yè)(html)代碼
 string content = sr.ReadToEnd();
 return content;
}

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

/// <summary>
/// 上傳媒體返回媒體ID
/// </summary>
public static string UploadMedia(string access_token, string type, string path)
{
 // 設(shè)置參數(shù)
 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);

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

遍歷每條圖文數(shù)據(jù),分別請(qǐng)求微信接口,上傳圖片,獲取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\":\"要發(fā)送的圖片不存在\"}";
 }
 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>
/// 請(qǐng)求Url,發(fā)送數(shù)據(jù)
/// </summary>
public static string PostUrl(string url, string postData)
{
 byte[] data = Encoding.UTF8.GetBytes(postData);

 // 設(shè)置參數(shù)
 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();

 //發(fā)送請(qǐng)求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
 HttpWebResponse response = request.GetResponse() as HttpWebResponse;
 //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁(yè)發(fā)送Post請(qǐng)求
 Stream instream = response.GetResponseStream();
 StreamReader sr = new StreamReader(instream, Encoding.UTF8);
 //返回結(jié)果網(wǎng)頁(yè)(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、群發(fā)圖文消息

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

/// <summary>
/// 獲取關(guān)注者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>
/// 獲取關(guān)注者OpenID集合
/// </summary>
public static List<string> GetOpenIDs(string access_token, string next_openid)
{
 // 設(shè)置參數(shù)
 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); //獲取關(guān)注者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();
}

群發(fā)代碼:

resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateNewsJson(newsid, openidList));


/// <summary>
/// 根據(jù)OpenID列表群發(fā)
/// </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);
}

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

/// <summary>
/// 群發(fā)
/// </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); //獲取關(guān)注者OpenID列表
 UserInfo loginUser = AdminUtil.GetLoginUser(this); //當(dāng)前登錄用戶 

 string resultMsg = null;

 //發(fā)送文本
 if (type == "1")
 {
 resultMsg = WXApi.Send(access_token, WXMsgUtil.CreateTextJson(data, openidList));
 }

 //發(fā)送圖片
 if (type == "2")
 {
 string path = MapPath(data);
 if (!File.Exists(path))
 {
  return "{\"code\":0,\"msg\":\"要發(fā)送的圖片不存在\"}";
 }
 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));
 }

 //發(fā)送圖文消息
 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));
 }

 //結(jié)果處理
 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參數(shù)錯(cuò)誤\"}";
 }
}

精彩專題分享:ASP.NET微信開發(fā)教程匯總,歡迎大家學(xué)習(xí)。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助。

相關(guān)文章

  • WPF中使用WebView2控件的方法及常見問(wèn)題

    WPF中使用WebView2控件的方法及常見問(wèn)題

    WebView2為WPF網(wǎng)頁(yè)瀏覽工具,具有簡(jiǎn)單易用,頁(yè)面顯示清晰的優(yōu)點(diǎn),下面這篇文章主要給大家介紹了關(guān)于WPF中使用WebView2控件的方法及常見問(wèn)題,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-02-02
  • C#在winform中實(shí)現(xiàn)數(shù)據(jù)增刪改查等功能

    C#在winform中實(shí)現(xiàn)數(shù)據(jù)增刪改查等功能

    本篇文章主要是介紹了C#在winform中操作數(shù)據(jù)庫(kù),實(shí)現(xiàn)數(shù)據(jù)增刪改查,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2016-11-11
  • C#關(guān)于類的只讀只寫屬性實(shí)例分析

    C#關(guān)于類的只讀只寫屬性實(shí)例分析

    這篇文章主要介紹了C#關(guān)于類的只讀只寫屬性實(shí)例分析,對(duì)于初學(xué)者更好的理解類的只讀只寫屬性有一定的幫助,需要的朋友可以參考下
    2014-07-07
  • C#解析json字符串總是多出雙引號(hào)的原因分析及解決辦法

    C#解析json字符串總是多出雙引號(hào)的原因分析及解決辦法

    json好久沒(méi)用了,今天在用到j(luò)son的時(shí)候,發(fā)現(xiàn)對(duì)字符串做解析的時(shí)候總是多出雙引號(hào),下面給大家介紹C#解析json字符串總是多出雙引號(hào)的原因分析及解決辦法,需要的朋友參考下吧
    2016-03-03
  • C#數(shù)據(jù)導(dǎo)入到EXCEL的方法

    C#數(shù)據(jù)導(dǎo)入到EXCEL的方法

    今天小編就為大家分享一篇關(guān)于C#數(shù)據(jù)導(dǎo)入到EXCEL的方法,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-01-01
  • C#圖像處理的多種方法

    C#圖像處理的多種方法

    這篇文章主要為大家詳細(xì)介紹了C#圖像處理的多種方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-09-09
  • C#使用Task實(shí)現(xiàn)執(zhí)行并行任務(wù)的原理的示例詳解

    C#使用Task實(shí)現(xiàn)執(zhí)行并行任務(wù)的原理的示例詳解

    Task是一個(gè)表示異步操作的類,它提供了一種簡(jiǎn)單、輕量級(jí)的方式來(lái)創(chuàng)建多線程應(yīng)用程序。本文就來(lái)和大家聊聊在C#中如何使用Task執(zhí)行并行任務(wù)吧
    2023-04-04
  • C#?Chart控件標(biāo)記問(wèn)題詳解

    C#?Chart控件標(biāo)記問(wèn)題詳解

    這篇文章主要介紹了C#?Chart控件標(biāo)記問(wèn)題詳解,在做項(xiàng)目的時(shí)候,遇到一個(gè)需求,需要我對(duì)Chart圖標(biāo)標(biāo)記數(shù)據(jù)正在運(yùn)行,實(shí)現(xiàn)數(shù)據(jù)可視化,文章通過(guò)圍繞主題展開詳情,需要的朋友可以參考一下
    2022-08-08
  • c# dynamic的好處

    c# dynamic的好處

    這篇文章主要介紹了c# dynamic的好處,以示例代碼幫助大家更好的了解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-12-12
  • 一個(gè)進(jìn)程間通訊同步的C#框架引薦

    一個(gè)進(jìn)程間通訊同步的C#框架引薦

    這篇文章主要介紹了一個(gè)進(jìn)程間通訊同步的C#框架,代碼具有相當(dāng)?shù)姆€(wěn)定性和可維護(hù)性,隨著.NET的開源也會(huì)被注入更多活力,推薦!需要的朋友可以參考下
    2015-07-07

最新評(píng)論