亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

首頁 微信小程式 微信開發(fā) C#微信公眾平臺開發(fā)之高級群發(fā)介面

C#微信公眾平臺開發(fā)之高級群發(fā)介面

Feb 20, 2017 pm 02:54 PM

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

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

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

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

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

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

C#微信公眾平臺開發(fā)之高級群發(fā)介面

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

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

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

?取ImgUrl字段數(shù)據(jù),通過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);

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

請求微信接口,上傳圖片,返回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);

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

遍歷每條圖文數(shù)據(jù),分別請求微信接口,上傳圖片,獲取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>
/// 請求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ā)送請求并獲取相應(yīng)回應(yīng)數(shù)據(jù)
 HttpWebResponse response = request.GetResponse() as HttpWebResponse;
 //直到request.GetResponse()程序才開始向目標(biāo)網(wǎng)頁發(fā)送Post請求
 Stream instream = response.GetResponseStream();
 StreamReader sr = new StreamReader(instream, Encoding.UTF8);
 //返回結(jié)果網(wǎng)頁(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(&#39;,&#39;).ToList<string>();
 }
 else
 {
 return new List<string>();
 }
}

List 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是傳到頁面的id,根據(jù)它從數(shù)據(jù)庫中取數(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ù)錯誤\"}";
 }
}

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

更多C#微信公眾平臺開發(fā)之高級群發(fā)介面相關(guān)文章請關(guān)注PHP中文網(wǎng)!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)