程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#微信平台開辟之高等群發接口

C#微信平台開辟之高等群發接口

編輯:C#入門知識

C#微信"平台開辟之高等群發接口。本站提示廣大學習愛好者:(C#微信"平台開辟之高等群發接口)文章只能為提供參考,不一定能成為您想要的結果。以下是C#微信"平台開辟之高等群發接口正文


觸及access_token的獲得請參考《C#微信"平台開辟之access_token的獲得存儲與更新》

1、為了完成高等群發功效,須要處理的成績

1、經由過程微信接口上傳圖文新聞素材時,Json中的圖片不是url而是media_id,若何經由過程微信接口上傳圖片並獲得圖片的media_id?

2、圖片存儲在甚麼處所,若何獲得?

2、完成步調,以依據OpenID列表群發圖文新聞為例

1、預備數據

    我把數據存儲在數據庫中,ImgUrl字段是圖片在辦事器上的絕對途徑(這裡的辦事器是本身的辦事器,不是微信的哦)。

從數據庫中獲得數據放到DataTable中:

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

2、經由過程微信接口上傳圖片,前往圖片的media_id

 取ImgUrl字段數據,經由過程MapPath辦法獲得圖片在辦事器上的物理地址,用FileStream類讀取圖片,並上傳給微信

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

/// <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--" + 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();

 //發送要求並獲得響應回應數據
 HttpWebResponse response = request.GetResponse() as HttpWebResponse;
 //直到request.GetResponse()法式才開端向目的網頁發送Post要求
 Stream instream = response.GetResponseStream();
 StreamReader sr = new StreamReader(instream, Encoding.UTF8);
 //前往成果網頁(html)代碼
 string content = sr.ReadToEnd();
 return content;
}

要求微信接口,上傳圖片,前往media_id(WXApi類):

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

一個圖文新聞由若干條圖文構成,每條圖文有題目、內容、鏈接、圖片等

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

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

 //發送要求並獲得響應回應數據
 HttpWebResponse response = request.GetResponse() as HttpWebResponse;
 //直到request.GetResponse()法式才開端向目的網頁發送Post要求
 Stream instream = response.GetResponseStream();
 StreamReader sr = new StreamReader(instream, Encoding.UTF8);
 //前往成果網頁(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、群發圖文新聞

獲得全體存眷者OpenID聚集(WXApi類):

/// <summary>
/// 獲得存眷者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>
/// 獲得存眷者OpenID聚集
/// </summary>
public static List<string> GetOpenIDs(string access_token, string next_openid)
{
 // 設置參數
 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).WordStr("\"", "");
 return openids.Split(',').ToList<string>();
 }
 else
 {
 return new List<string>();
 }
}

List<string> openidList = WXApi.GetOpenIDs(access_token); //獲得存眷者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();
}

群發代碼:

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


/// <summary>
/// 依據OpenID列表群發
/// </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);
}

供群發按鈕挪用的辦法(data是傳到頁面的id,依據它從數據庫中取數據):

/// <summary>
/// 群發
/// </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); //獲得存眷者OpenID列表
 UserInfo loginUser = AdminUtil.GetLoginUser(this); //以後登錄用戶 

 string resultMsg = null;

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

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

 //發送圖文新聞
 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));
 }

 //成果處置
 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參數毛病\"}";
 }
}

出色專題分享:ASP.NET微信開辟教程匯總,迎接年夜家進修。

以上就是本文的全體內容,願望對年夜家的進修有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved