Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the Group posting Interface in the Development of C# Wechat Public platform

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly shows you "how to achieve the mass posting interface in the development of the C# Wechat public platform". The content is simple and clear. I hope it can help you solve your doubts. Now let the editor lead you to study and learn the article "how to implement the mass posting interface in the development of the C# Wechat public platform".

First, the problems that need to be solved in order to realize the advanced group sending function.

1. When uploading picture and text message material through Wechat API, the picture in Json is not url but media_id. How to upload picture and obtain media_id of picture through Wechat API?

2. Where is the picture stored and how can I get it?

Second, the implementation steps, taking the group sending picture and text messages according to the OpenID list as an example

1. Prepare the data

I store the data in the database, and the ImgUrl field is the relative path of the image on the server (the server here is your own server, not Wechat's).

Get the data from the database and put it in DataTable:

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

2. Upload pictures through the Wechat API and return the media_id of the pictures.

Take the ImgUrl field data, obtain the physical address of the picture on the server through the MapPath method, read the picture with the FileStream class, and upload it to Wechat

HTTP upload file code (HttpRequestUtil class):

/ Http upload file / public static string HttpUploadFile (string url, string path) {/ / set the parameter 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"); / / Random Separator request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary Byte [] itemBoundaryBytes = Encoding.UTF8.GetBytes ("\ r\ nWhen -" + boundary + "\ r\ n"); byte [] endBoundaryBytes = Encoding.UTF8.GetBytes ("\ r\ nWhen -" + boundary + "- -\ r\ n"); int pos = path.LastIndexOf ("\"); string fileName = path.Substring (pos + 1); / / request header information StringBuilder sbHeader = new StringBuilder ("Content-Disposition:form-data;name=\" file\ ") Filename=\ "{0}\"\ r\ nContent-Type:application/octet-stream\ r\ r\ n\ 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 (); / / send the request and get the corresponding response data HttpWebResponse response = request.GetResponse () as HttpWebResponse; / / until the request.GetResponse () program starts sending Post requests Stream instream = response.GetResponseStream (); StreamReader sr = new StreamReader (instream, Encoding.UTF8) / / return the result web page (html) code string content = sr.ReadToEnd (); return content;}

Request the API Wechat, upload pictures, and return media_id (WXApi class):

/ / upload media return media ID/// public static string UploadMedia (string access_token, string type, string path) {/ / set parameter 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) / / the media IDstring media_id = Tools.GetJsonValue (msg, "media_id") is returned from the image.

Incoming path (code in the aspx.cs file):

String path = MapPath (data)

A picture-text message consists of several pictures and texts, each of which has a title, content, links, pictures, etc.

Go through each picture and text data, request Wechat API, upload pictures, and get media_id.

3. Upload picture and text message material

Stitching picture-text message material Json string (ImgItemDal class (class that operates picture-text message table):

/ spliced text message material Json string / 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\ ":\" the picture to be sent does not exist\ "}";} string msg = WXApi.UploadMedia (access_token, "image", path); / / Media 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\"}, ");} sbArticlesJson.Append ("]} "); return sbArticlesJson.ToString ();}

Upload the picture and text message material and obtain the media_id of the picture and text message:

/ / request Url, send data / public static string PostUrl (string url, string postData) {byte [] data = Encoding.UTF8.GetBytes (postData); / / set the parameter 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 (); / / send the request and get the corresponding response data HttpWebResponse response = request.GetResponse () as HttpWebResponse; / / until the request.GetResponse () program starts sending the Post request Stream instream = response.GetResponseStream () to the target web page; StreamReader sr = new StreamReader (instream, Encoding.UTF8); / / return the result page (html) code string content = sr.ReadToEnd (); return content } / upload picture and text message material return media_id/// 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. Send picture and text messages in groups

Get the OpenID collection of all followers (WXApi class):

/ get followers OpenID collection / public static List GetOpenIDs (string access_token) {List result = new List (); List 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 } / get follower OpenID collection / public static List GetOpenIDs (string access_token, string next_openid) {/ / set parameter 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 ();} else {return new List ();}}

List openidList = WXApi.GetOpenIDs (access_token); / / get the OpenID list of followers

Stitching picture and text messages Json (WXMsgUtil class):

/ json/// public static string CreateNewsJson (string media_id, List openidList) {StringBuilder sb = new StringBuilder (); sb.Append ("{\" touser\ ": ["); sb.Append (string.Join (",", openidList.ConvertAll (a = > "\" + a + "\"). ToArray ()); sb.Append ("],"); sb.Append ("\" msgtype\ ":\" mpnews\ ",") Sb.Append ("\" mpnews\ ": {\" media_id\ ":\" + media_id + "\"} "); sb.Append ("} "); return sb.ToString ();}

Send codes in groups:

ResultMsg = WXApi.Send (access_token, WXMsgUtil.CreateNewsJson (newsid, openidList)); / / send / 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) according to the OpenID list;}

The method to be called by the group send button (data is the id passed to the page, according to which data is fetched from the database):

/ Group / public string Send () {string type = Request ["type"]; string data = Request ["data"]; string access_token = AdminUtil.GetAccessToken (this); / / get access_token List openidList = WXApi.GetOpenIDs (access_token); / / get follower OpenID list UserInfo loginUser = AdminUtil.GetLoginUser (this); / / current login user string resultMsg = null / / send text if (type = = "1") {resultMsg = WXApi.Send (access_token, WXMsgUtil.CreateTextJson (data, openidList));} / send picture if (type = = "2") {string path = MapPath (data); if (! File.Exists (path)) {return "{\" code\ ": 0,\" msg\ ":\" the picture to be sent does not exist\ "};} 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));} / / send Teletext message 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));} / / result processing 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 parameter error\ ";}} above is all the contents of the article" how to implement the group posting interface for the development of C# Wechat public platform ". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report