In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to develop Wechat public platform with C #". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought. Let's study and learn how to develop Wechat public platform with C #.
Service number and Subscription account
The service number is the Wechat public account applied by the company. Subscription account applied for it personally. I personally applied for one, but I didn't use it much.
Service account
Only one group message can be sent within 1 month (30 days).
Messages sent to subscribers (fans) are displayed in each other's chat list.
When sending a message to the user, the user will receive an instant message reminder.
The service number will be in the address book of the subscriber (fan).
You can apply for a custom menu.
Subscription account
One mass message can be sent every day (within 24 hours).
Messages sent to subscribers (fans) will be displayed in each other's Subscription account folder.
Subscribers do not receive instant message alerts when sending messages to subscribers (fans).
Subscription account will be placed in Subscription account's folder in the address book of subscribers (fans).
Subscription account does not support applying for custom menus.
URL configuration
To enable the development mode, you need to become a developer first, and you can only choose one editing mode or development mode. Enter the Wechat public platform-development mode, as follows:
I need to fill in url and token. It took me a long time to fill in this. I thought it would be OK to fill in a server's url (port 80), but I couldn't, mainly because I didn't read the prompts carefully, so I always prompted.
As can be seen from the above, Wechat will send several parameters to the server we filled in after clicking submit, and then we need to return them as is, so when submitting the url, we first test the echostr parameters on the server creation API. Code:
/ / become a developer url test and return echoStr public void InterfaceTest () {string token = "filled in token"; if (string.IsNullOrEmpty (token)) {return;} string echoString = HttpContext.Current.Request.QueryString ["echoStr"] String signature = HttpContext.Current.Request.QueryString ["signature"]; string timestamp = HttpContext.Current.Request.QueryString ["timestamp"]; string nonce = HttpContext.Current.Request.QueryString ["nonce"]; if (! string.IsNullOrEmpty (echoString)) {HttpContext.Current.Response.Write (echoString) HttpContext.Current.Response.End ();}}
Call the above method in the ProcessRequest method of the general handler ashx. Url fills in the server address of the ashx. Token is a server tag that can be entered freely. The token in the code must be consistent with the application, and you can only develop as a developer.
Create menu
We add some Wechat service numbers, and there are menus under the chat window, which can be easily configured in edit mode or in development mode code. Wechat Public platform developer documentation: http://mp.weixin.qq.com/wiki/index.php?title= Custom menu creation API. You can see some key points of menu creation. The following API is debugged using web debugging tools, only to debug whether the API is available, and not to create menus directly. There are two menus:
Click: after the user clicks the click type button, the Wechat server will push the structure with message type event to the developer through the message API (see message API Guide) with the key value entered by the developer in the button, and the developer can interact with the user through the custom key value.
View: after the user clicks the view button, the Wechat client will open the URL value (that is, the web link) entered by the developer in the button to open the web page. It is recommended to combine with the API for web page authorization to obtain the user's basic information to obtain the user's login personal information.
The click menu needs to fill in a key, which is used when we click on the menu event. View is just a menu hyperlink. The menu data is in json format, and the official website is an example of php. In fact, the implementation of C # is very simple, that is, post sends a json data, and the sample code:
Public partial class createMenu: System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) {FileStream fs1 = new FileStream (Server.MapPath (".") + "\\ menu.txt", FileMode.Open); StreamReader sr = new StreamReader (fs1, Encoding.GetEncoding ("GBK")); string menu = sr.ReadToEnd (); sr.Close () Fs1.Close (); GetPage ("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=access_token", menu);} public string GetPage (string posturl, string postData) {Stream outstream = null; Stream instream = null; StreamReader sr = null; HttpWebResponse response = null HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; byte [] data = encoding.GetBytes (postData); / / prepare the request. Try {/ / set parameter request = WebRequest.Create (posturl) 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; outstream = request.GetRequestStream (); outstream.Write (data, 0, data.Length); outstream.Close () / / send the request and get the corresponding response data response = request.GetResponse () as HttpWebResponse; / / until the request.GetResponse () program starts sending the Post request to the target web page instream = response.GetResponseStream (); sr = new StreamReader (instream, encoding) / / return the result page (html) code string content = sr.ReadToEnd (); string err = string.Empty; Response.Write (content); return content;} catch (Exception ex) {string err = ex.Message Return string.Empty;}
The content in menu.text is the json sample menu. You can copy it from the example and modify it according to your needs.
About access_token, it is actually a request mark, and the way to get it is: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret orientation appId and secret are developer tags. As you can see in your information, you can get the access_ token value by returning a json data through this link.
It should be noted that access_token has a certain timeliness. If it fails, it needs to be re-obtained. This can be created locally without uploading to the server. The menu is created correctly, and the prompt message {"errcode": 0, "errmsg": "ok"} is returned. There is no screenshot here. If you try it, you can see the effect. Generally, the menu will take effect in one or two minutes. If it really doesn't work, just pay attention to it again.
Query, delete menu
Querying and deleting menus are also very simple, but they are only get requests, and there is no need to send data. Take a look at the sample code:
Public partial class selectMenu: System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) {GetPage ("https://api.weixin.qq.com/cgi-bin/menu/get?access_token=access_token"); / / GetPage (" https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=access_token");) } public string GetPage (string posturl) {Stream instream = null; StreamReader sr = null; HttpWebResponse response = null; HttpWebRequest request = null; Encoding encoding = Encoding.UTF8; / / prepare the request. Try {/ / set parameter request = WebRequest.Create (posturl) as HttpWebRequest; CookieContainer cookieContainer = new CookieContainer (); request.CookieContainer = cookieContainer; request.AllowAutoRedirect = true; request.Method = "GET" Request.ContentType = "application/x-www-form-urlencoded"; / / send the request and get the corresponding response data response = request.GetResponse () as HttpWebResponse; / / until the request.GetResponse () program begins to send the Post request instream = response.GetResponseStream () to the target web page Sr = new StreamReader (instream, encoding); / / return the result page (html) code string content = sr.ReadToEnd (); string err = string.Empty; Response.Write (content); return content } catch (Exception ex) {string err = ex.Message; return string.Empty;}
The access_token acquisition method has been mentioned above. The query menu returns json data, which is actually the content of the menu.txt in which we created the menu.
The message returned for successful deletion is: {"errcode": 0, "errmsg": "ok"}, which is fine as long as it is run locally.
Accept the message
Wechat public platform developer document: http://mp.weixin.qq.com/wiki/index.php?title= receives ordinary messages. We use Wechat to process the information sent by users. Here, take accepting ordinary messages as an example, such as voice messages, picture messages and so on.
It can be seen from the document that the received message is a xml format file. It was a bit silly at that time, which side am I going to accept the message? Also depressed for a long time, in fact, you started to fill in the url, is not very ashamed ah, .
1348831860 1234567890123456
Let's add the following code to ashx:
Public void ProcessRequest (HttpContext param_context) {string postString = string.Empty; if (HttpContext.Current.Request.HttpMethod.ToUpper () = = "POST") {using (Stream stream = HttpContext.Current.Request.InputStream) {Byte [] postBytes = new Byte [stream.Length] Stream.Read (postBytes, 0, (Int32) stream.Length); postString = Encoding.UTF8.GetString (postBytes); Handle (postString) } / process information and reply / private void Handle (string postStr) {messageHelp help = new messageHelp (); string responseContent = help.ReturnMessage (postStr); HttpContext.Current.Response.ContentEncoding = Encoding.UTF8 HttpContext.Current.Response.Write (responseContent);}
MessageHelp is a message processing help class. The next part of the code is provided here, and the complete code can be downloaded. The obtained postString is xml in the above format. We only need to convert it to XmlDocument for parsing:
/ / accept text message public string TextHandle (XmlDocument xmldoc) {string responseContent = "; XmlNode ToUserName = xmldoc.SelectSingleNode (" / xml/ToUserName "); XmlNode FromUserName = xmldoc.SelectSingleNode (" / xml/FromUserName "); XmlNode Content = xmldoc.SelectSingleNode (" / xml/Content ") If (Content! = null) {responseContent = string.Format (ReplyType.Message_Text, FromUserName.InnerText, ToUserName.InnerText, DateTime.Now.Ticks, "Welcome to the Wechat public account What you enter is: "+ Content.InnerText+"\ r\ nClick to enter ") } return responseContent } / plain text message / public static string Message_Text {get {return @ "{2} " }}
The above code is to accept the message, do some processing, and return the message.
Send messages (picture and text, menu event response)
There are three types of messages I send here: normal messages, graphic messages, and menu event responses. As a matter of fact, the general message is mentioned when accepting the message. Download the complete code below.
Let's first take a look at the Teletext message and menu event response. Wechat Public platform developer document: http://mp.weixin.qq.com/wiki/index.php?title= reply Teletext message # .E5.9B.9E.E5.A4.8D.E5.9B.BE.E6.96.87.E6.B6.88.E6.81.AF in xml format:
12345678 2
There are two types of picture and text messages. Let's take a look at the results and find the Wechat service number of Yuantong Express as an example:
At the beginning, I thought that the two interfaces should not be the same, but after searching for a long time in the document, I couldn't find anything other than this. I tried the next two picture and text messages and found that it was sent by this API. If there are more than one, the Description in item will fail and only Title will be displayed. Just try it. Sample code:
/ / event public string EventHandle (XmlDocument xmldoc) {string responseContent = "; XmlNode Event = xmldoc.SelectSingleNode (" / xml/Event "); XmlNode EventKey = xmldoc.SelectSingleNode (" / xml/EventKey "); XmlNode ToUserName = xmldoc.SelectSingleNode (" / xml/ToUserName "); XmlNode FromUserName = xmldoc.SelectSingleNode (" / xml/FromUserName ") If (Eventures null) {/ / menu click event if (Event.InnerText.Equals ("CLICK")) {if (EventKey.InnerText.Equals ("click_one")) / / click_one { ResponseContent = string.Format (ReplyType.Message_Text FromUserName.InnerText, ToUserName.InnerText, DateTime.Now.Ticks, "you clicked on click_one") } else if (EventKey.InnerText.Equals ("click_two")) / / click_two {responseContent = string.Format (ReplyType.Message_News_Main, FromUserName.InnerText, ToUserName.InnerText DateTime.Now.Ticks, "2", string.Format (ReplyType.Message_News_Item, "I want to send", "" http://www.soso.com/orderPlace.jpg", " "http://www.soso.com/")+ string.Format (ReplyType.Message_News_Item," order Management "," http://www.soso.com/orderManage.jpg", "http://www.soso.com/")); } else if (EventKey.InnerText.Equals ("click_three")) / / click_three {responseContent = string.Format (ReplyType.Message_News_Main, FromUserName.InnerText, ToUserName.InnerText DateTime.Now.Ticks, "1", string.Format (ReplyType.Message_News_Item, "title", "Summary", "http://www.soso.com/jieshao.jpg"," "http://www.soso.com/")); } return responseContent } / Teletext message body / public static string Message_News_Main {get {return @ " {2} {3} {4} " }} / Teletext message item / public static string Message_News_Item {get {return @ " " }}
It should be noted that: XmlNode Event = xmldoc.SelectSingleNode ("/ xml/Event") indicates that the event type is obtained, and XmlNode EventKey = xmldoc.SelectSingleNode ("/ xml/EventKey") represents the event tag, that is, we create a menu to add the key of click, and we can tell which menu is the point by key.
Another point is to reply to the hyperlink, sometimes some links will be sent in the service number, we will open the link directly to the relevant URL, just add to the reply: click to enter, you can.
Thank you for your reading, the above is the content of "how to develop Wechat public platform with C#". After the study of this article, I believe you have a deeper understanding of how to develop Wechat public platform with C#. The specific use also needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.