WeChat public service platform development (. Net implementation) 11 ------- Customer Service Message (important OPENID of message push)

Source: Internet
Author: User
Tags openid

This time, let's take a look at "customer service messages". First, let's clarify the concept of "customer service messages. This is different from the previous "passive response message", that is to say, it is not the "instant response" of your words. In some cases, you may need to send messages to different people, for example, if your restaurant has launched a new Sichuan food product, you need to send messages to people who like Sichuan food, instead of waiting for the product to be sent "what is new" and then report it to the customer, what did I launch.


Someone may ask, isn't it a group? Can I send only one message every day? Do I send one service number each month? The answer is clearly "customer service messages", not Group messages. The difference between the answer and the answer is that if you pay attention to me, you can send messages to you in a group, in order to prevent users from getting annoying, we have made a strict limit on the number of groups. The "Customer Service Message" means that only those who follow you can actively push messages to you. Just like you can answer questions only when someone asks you, and continue to answer the questions. For another example, if you have been notified of my mobile phone number and saved it, then you suddenly called me, and I must be in conflict. However, if I call you and you know my number through the call display, and call me later, it means we know each other and I will not conflict with each other at least. This makes the essential difference between group sending, passive response, and customer service messages.


Just as we can collect phone numbers and customer information of our mobile phones, once their information is included by us. Then we can break through the limit on the number of groups. Only one (Service Number) can be sent in one month according to the limit, but "Customer Service Message" can be 50000 messages a day, enough.


The following question is how a mobile phone customer's "mobile phone number" contains an OPENID, which makes the mobile phone number a unique identifier that follows your user, this ID will not change, but if the same user pays attention to different numbers, their IDs in different numbers are different. How to obtain the OPENID?


I found some information on the Internet, some of which are indeed incorrect, and some also said that the authorization is required through OAuth 2.0. This is indeed acceptable, but it is too complicated, through my tests, I came to the conclusion that "as long as the user interacts with your public", his OPENID can be obtained. Just like making a phone call, as long as the user calls you, you must know his phone number. In this example, if a user sends a message to you, or clicks a menu, the sent message will have a "FromUserName", which will enable OPENID. We can create a database to collect the valuable user identity information, that is, to record his "Phone Number". With the phone number, we can call the customer frequently. I did this experiment:


First, record the user's OPENID and add a WriteLog (wx. FromUserName) to the second line of the OnLoad function; record it in a text file

Protected void Page_Load (object sender, EventArgs e) {wxmessage wx = GetWxMessage (); WriteLog (wx. FromUserName); string res = ""; if (! String. IsNullOrEmpty (wx. EventName) & wx. EventName. Trim () = "subscribe") {string content = ""; if (! Wx. eventKey. contains ("qrscene _") {content = "/: rose Welcome Beijing Yongjie youxin Technology Co., Ltd./: rose \ n directly reply" hello ""; res = sendTextMessage (wx, content);} else {content = "QR code parameter: \ n" + wx. eventKey. replace ("qrscene _", ""); res = sendTextMessage (wx, content) ;}} else if (! String. isNullOrEmpty (wx. eventName) & wx. eventName. toLower () = "scan") {string str = "QR code parameter: \ n" + wx. eventKey; res = sendTextMessage (wx, str);} else if (! String. isNullOrEmpty (wx. eventName) & wx. eventName. trim () = "CLICK") {if (wx. eventKey = "HELLO") res = sendTextMessage (wx, "HELLO, welcome to Beijing Yongjie youxin Technology Co., Ltd. public platform! ");} Else if (! String. isNullOrEmpty (wx. eventName) & wx. eventName. trim () = "LOCATION") {res = sendTextMessage (wx, "Your LOCATION is longitude:" + wx. latitude + ", dimension:" + wx. longpolling + ", geographic Longitude:" + wx. precision);} else {if (wx. msgType = "text" & wx. content = "hello") {res = sendTextMessage (wx, "Hello, welcome to Beijing Yongjie youxin Technology Co., Ltd. public platform! ");} Else if (wx. msgType = "voice") {res = sendTextMessage (wx, wx. recognition);} else if (wx. msgType = "location") {res = sendTextMessage (wx, "Your sending location is:" + wx. label + "; latitude:" + wx. location_X + "; longitude:" + wx. location_Y + "; scaling ratio:" + wx. scale);} else {res = sendTextMessage (wx, "Hello, failed to recognize the message! ") ;}} Response. Write (res );}
The WriteLog method is as follows:

/// <Summary> /// write logs (for tracking) /// </summary> private void WriteLog (string strMemo) {string filename = Server. mapPath ("/logs/log.txt"); if (! Directory. exists (Server. mapPath ("// logs //") Directory. createDirectory ("// logs //"); StreamWriter sr = null; try {if (! File. exists (filename) {sr = File. createText (filename);} else {sr = File. appendText (filename);} sr. writeLine (strMemo);} catch {} finally {if (sr! = Null) sr. Close ();}}
Please look at this file OPENID, my thing such as "oV93gjl5slD3p29yS1dOijy-pqZ8", with this OPENID a lot of things are easy to do, we will also introduce how to get the customer information. Let's talk about "customer messages" first.

Next we will create a new ASPX page where I can send messages to these users. This page (SendMessage. aspx. cs) uses two text boxes and one button:

String MyOpenID; string MyContent; protected void Page_Load (object sender, EventArgs e) {MyOpenID = "oV93gjl5slD3p29yS1dOijy-pqZ8"; MyContent = "this is a customer service message"; UserName. text = MyOpenID; Content. text = MyContent;} protected void button#click (object sender, EventArgs e) {string res = ""; string Access_Token = IsExistAccess_Token (); string posturl = "https://api.weixin.qq.com/cgi-bin/message/custom/se Nd? Access_token = "+ Access_Token; string postData =" {\ "touser \": \ "" + UserName. text + "\", \ "msgtype \": \ "text \", \ "text \": {\ "content \": \ "" + Content. text + "\" }}"; res = GetPage (posturl, postData); Response. write (res );}
The three functions mentioned above are also used in the middle:

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 the parameter request = WebRequest. create (posturl) as HttpWebRequest; CookieContainer cookieContainer = new CookieCont Ainer (); 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 obtain the response data response = request. getResponse () as HttpWebResponse; // wait until request. getResponse () Process Before sending the Post request instream = response to the target webpage. getResponseStream (); sr = new StreamReader (instream, encoding); // return result webpage (html) code string content = sr. readToEnd (); string err = string. empty; return content;} catch (Exception ex) {string err = ex. message; Response. write (err); return string. empty ;}} /// <summary> /// judge whether the Access_Token is out of date based on the current date. If the new Access_Token is returned during the expiration, otherwise, the previous Access_Token is returned. /// </summary> /// <par Am name = "datetime"> </param> // <returns> </returns> public static string IsExistAccess_Token () {string Token = string. empty; DateTime YouXRQ; // read and display the data in the XML file. Note that the file path is string filepath = HttpContext. current. server. mapPath ("XMLFile. xml "); StreamReader str = new StreamReader (filepath, System. text. encoding. UTF8); XmlDocument xml = new XmlDocument (); xml. load (str); str. close (); str. dispose (); Token = Xml. selectSingleNode ("xml "). selectSingleNode ("Access_Token "). innerText; YouXRQ = Convert. toDateTime (xml. selectSingleNode ("xml "). selectSingleNode ("Access_YouXRQ "). innerText); if (DateTime. now> YouXRQ) {DateTime _ youxrq = DateTime. now; Access_token mode = GetAccess_token (); xml. selectSingleNode ("xml "). selectSingleNode ("Access_Token "). innerText = mode. access_token; _ youxrq = _ youxrq. addSeconds (I Nt. parse (mode. expires_in); xml. selectSingleNode ("xml "). selectSingleNode ("Access_YouXRQ "). innerText = _ youxrq. toString (); xml. save (filepath); Token = mode. access_token;} return Token;} public static Access_token GetAccess_token () {string appid = "wx043225275885dafd"; string secret = "Token"; string strUrl = "https://api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = "+ appid +" & secret = "+ secret; Access_token mode = new Access_token (); HttpWebRequest req = (HttpWebRequest) HttpWebRequest. create (strUrl); req. method = "GET"; using (WebResponse wr = req. getResponse () {HttpWebResponse myResponse = (HttpWebResponse) req. getResponse (); StreamReader reader = new StreamReader (myResponse. getResponseStream (), Encoding. UTF8); string content = reader. readToEnd (); // Response. write (content); // here Access_token is assigned Access_token token = new Access_token (); token = JsonHelper. parseFromJson <Access_token> (content); mode. access_token = token. access_token; mode. expires_in = token. expires_in;} return mode ;}


This page is all about it. Open this page and try to send a message? It's good. In this way, our database can be used in combination. What loop is there, we can break through the restriction of Group Sending, so we can push Group messages for specific items! There are many types of messages: Text, voice, video, text, and images. It's just Json. If you are smart, you can definitely put it apart.




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.