C # public platform development-advanced group interface,
For details about how to obtain access_token, refer to C # public platform development-how to obtain and store access_token.
I. problems to be solved in order to implement the advanced group Function
1. When uploading text and text message materials through the interface, the image in Json is not a url but a media_id. How can I upload the image and obtain the media_id of the image through the interface?
2. Where are images stored and how can they be obtained?
2. Implementation steps: Use the OpenID list to send group text messages as an Example
1. Prepare data
I store the data in the database, and the ImgUrl field is the relative path of the image on the server (here the server is its own server, no ).
Put the data obtained from the database into the DataTable:
DataTable dt = ImgItemDal. GetImgItemTable (loginUser. OrgID, data );View Code
2. Upload the image through the interface and return the media_id of the image
Obtain the ImgUrl field data, use the MapPath method to obtain the physical address of the image on the server, use the FileStream class to read the image, and upload it
HTTP File Upload code (HttpRequestUtil class ):
/// <Summary> /// upload a file over Http /// </summary> 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 \ n --" + boundary + "\ r \ n"); byte [] endBoundaryBytes = Encoding. UTF8.GetBytes ("\ r \ n --" + boundary + "-- \ r \ n"); int pos = path. lastIndexOf ("\"); string fileName = path. substring (pos + 1); // request header information StringBuilder sbHeader = new StringBuilder (string. format ("Content-Disposition: form-data; name = \" file \ "; filename = \" {0} \ "\ r \ nContent-Type: application/octet-stream \ 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 (); // send the request and obtain the response data HttpWebResponse response = request. getResponse () as HttpWebResponse; // wait until request. the GetResponse () program starts to send the Post request Stream instream = response to the target webpage. getResponseStream (); StreamReader sr = new StreamReader (instream, Encoding. UTF8); // returned result webpage (html) code string content = sr. readToEnd (); return content ;}View Code
Request interface: uploads an image and returns media_id (WXApi class ):
/// <Summary> /// ID of the media returned when the media is uploaded /// </summary> public static string UploadMedia (string access_token, string type, string path) {// set the 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 );}View Codestring msg = WXApi. UploadMedia (access_token, "image", path); // The IDstring media_id = Tools. GetJsonValue (msg, "media_id") of the media returned by a piece ");View Code
The passed path (code in the aspx. cs file ):
String path = MapPath (data );View Code
A text message consists of several text items, including titles, content, links, and images.
Traverse each graph data, request an interface to upload images, and obtain media_id
3. Upload text and text message Materials
Concatenate text message material Json string (ImgItemDal class (class used to operate text message tables )):
/// <Summary> // concatenate the Json string of the text message material /// </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 \ ": \" the image to be sent does not exist \"}";} string msg = WXApi. uploadMedia (access_token, "image", path); // The 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 \ "},");} I ++;} sbArticlesJson. append ("]}"); return sbArticlesJson. toString ();}View Code
Upload text message material to obtain the media_id of text message:
/// <Summary> /// request Url, send data /// </summary> public static string PostUrl (string url, string postData) {byte [] data = Encoding. UTF8.GetBytes (postData); // you can specify the parameter HttpWebRequest = 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 obtain the response data HttpWebResponse response = request. getResponse () as HttpWebResponse; // wait until request. the GetResponse () program starts to send the Post request Stream instream = response to the target webpage. getResponseStream (); StreamReader sr = new StreamReader (instream, Encoding. UTF8); // returned result webpage (html) code string content = sr. readToEnd (); return content ;}View Code /// <summary> /// upload the text message material and return 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 );}View Codestring articlesJson = ImgItemDal. getArticlesJsonStr (this, access_token, dt); string newsMsg = WXApi. uploadNews (access_token, articlesJson); string newsid = Tools. getJsonValue (newsMsg, "media_id ");View Code
4. Send group text messages
OpenID set for getting all referers (WXApi class ):
/// <Summary> /// obtain the OpenID set of the consumer /// </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> // get Set OpenID of the receiver /// </summary> public static List <string> GetOpenIDs (string access_token, string next_openid) {// set the 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 <string> () ;}else {return new List <string> ();}}View CodeList <string> openidList = WXApi. GetOpenIDs (access_token); // obtain the OpenID list of the publisher.View Code
Concatenate text message Json (WXMsgUtil class ):
/// <Summary> // json text message // </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 ();}View Code
Mass code:
ResultMsg = WXApi. Send (access_token, WXMsgUtil. CreateNewsJson (newsid, openidList ));View Code /// <summary> /// group by OpenID list /// </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 );}View Code
Method called by the Group button (data is the id of the page to be uploaded, based on which data is retrieved from the database ):
/// <Summary> /// group type /// </summary> public string Send () {string type = Request ["type"]; string data = Request ["data"]; string access_token = AdminUtil. getAccessToken (this); // obtain the access_token List <string> openidList = WXApi. getOpenIDs (access_token); // obtain the OpenID list UserInfo loginUser = AdminUtil of the publisher. getLoginUser (this); // string resultMsg = null for the current logon user; // send the text if (type = "1") {resultMsg = WXApi. send (acces S_token, WXMsgUtil. CreateTextJson (data, openidList);} // send the image if (type = "2") {string path = MapPath (data); if (! File. exists (path) {return "{\" code \ ": 0, \" msg \ ": \" the image 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 text message if (type = "3") {DataTable dt = ImgItemDal. getImgItemTable (loginUser. orgID, data); string articlesJson = ImgItemDal. G EtArticlesJsonStr (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 parameter error \"}";}}View Code
C # the source code for public platform development is displayed on the left of my blog homepage.