Questions before php WeChat official account development

Source: Internet
Author: User
Tags sha1 encryption
This article mainly introduces five pitfalls before the development of the php public account, which has some reference value, interested friends can refer to this article for details about the five pitfalls before the development of the php public account, which has some reference value. interested friends can refer

Public Account Development documentation, Official Edition (https://mp.weixin.qq.com/wiki)

First, you have to have a public platform account.

First pitfall,Do not think that development is not allowed if it is not an enterprise number. you can apply for a Test number, which is more than the so-called subscription number interface.

Public ActionResult Index () {if (Request. httpMethod. toLower () = "post") {if (CheckSignature () // verify whether the server passes {GetMenuList (); // load menu} else {Response. write ("Oh, let's meet on Mars !!! "); Response. End () ;}} else {CheckWechat () ;}return View ();}////// The return random number indicates that the verification is successful ///Private void CheckWechat () {if (string. isNullOrEmpty (Request. queryString ["echoStr"]) {Response. write ("message not from"); Response. end ();} string echoStr = Request. queryString ["echoStr"]; if (CheckSignature () {Response. write (echoStr); Response. end ();}}////// Verify the signature //////
 /// Sort the token, timestamp, and nonce parameters in lexicographic order. // concatenate the three parameter strings into one string for sha1 encryption. // The developer can obtain the encrypted string. compared with signature, identifies the Request source. Private bool CheckSignature () {string signature = Convert. toString (Request ["signature"]); string timestamp = Convert. toString (Request ["timestamp"]); string nonce = Convert. toString (Request ["nonce"]); string [] ArrTmp = {Token, timestamp, nonce}; Array. sort (ArrTmp); // Sort string tmpStr = string in alphabetical order. join ("", ArrTmp); tmpStr = FormsAuthentication. hashPasswordForStoringInConfigFile (tmpStr, "SHA1"); tmpStr = tmpStr. toLower (); if (tmpStr = signature) {return true;} else {return false ;}}

Then, the public platform uses custom menus with permissions. However, once a custom menu is started, the original manually edited menu cannot be used. that is to say, if the server passes verification, you must use your own code.

Let's take a look at the GetMenuList () method, which is actually very simple, that is, simply relying on a JSON string. Then you can call the interface. Public void GetMenuList ()


{String weixin1 = ""; weixin1 = @ "{" "button": [{"type": "" click "", "" name "": "" Hello! "", "" Key ":" "hello" "},{" "type": "" view "", "" name "": "" company profile "", "" url ":" "http://www.xnfhtech.com" "},{" "name": "product introduction" "," "sub_button "": [{"" type ":" "click" "," "name": "" product 1 "", "" key ":" p1 ""}, {"" type ":" "click" "," "name": "" product 2 "", "" key "": "" p2 ""}]} "; string access_token = Tools. WA_GetAccess_Token.IsExistAccess_Token (); string I = this. menuCreate (menu, access_token); Response. write (I );}


Public string MenuCreate (string MenuJson, string access_token) {JavaScriptSerializer Jss = new JavaScriptSerializer (); string setMenuUrl = "https://api.weixin.qq.com/cgi-bin/menu/create? Access_token = {0} "; setMenuUrl = string. Format (setMenuUrl, access_token); // Obtain the token and splice the url string respText = WebRequestPostOrGet (setMenuUrl, MenuJson); Dictionary
 
  
RespDic = (Dictionary
  
   
) Jss. DeserializeObject (respText); return respDic ["errcode"]. ToString (); // return 0 published successfully }///
   /// Post/get submit call capture //////
   Submission address///
   Parameters///
   
    
String
   Public string WebRequestPostOrGet (string sUrl, string sParam) {byte [] bt = System. text. encoding. UTF8.GetBytes (sParam); Uri uriurl = new Uri (sUrl); HttpWebRequest req = (HttpWebRequest) HttpWebRequest. create (uriurl); // HttpWebRequest req = (HttpWebRequest) HttpWebRequest. create (url + (url. indexOf ("? ")>-1? "":"? ") + Param); req. method = "Post"; req. timeout = 120*1000; req. contentType = "application/x-www-form-urlencoded;"; req. contentLength = bt. length; using (Stream reqStream = req. getRequestStream () // using can be used to release memory {reqStream. write (bt, 0, bt. length); reqStream. flush ();} try {using (WebResponse res = req. getResponse () {// process the received page content Stream resStream = res. getResponseStream (); StreamR Eader resStreamReader = new StreamReader (resStream, System. text. encoding. UTF8); string resLine; System. text. stringBuilder resStringBuilder = new System. text. stringBuilder (); while (resLine = resStreamReader. readLine ())! = Null) {resStringBuilder. append (resLine + System. environment. newLine);} resStream. close (); resStreamReader. close (); return resStringBuilder. toString () ;}} catch (Exception ex) {return ex. message; // return an error when a url error occurs }}
  
 

Well, I admit that I am a fool with unknown truth. why is there an additional access_token = IsExistAccess_Token ()? don't worry, please let me know.

When reading the document, we will find that the Access_Token here expires every two hours. The method here is to automatically obtain it when it expires.

Fifth pitfallHere, the JSON string, that is, the menu to be displayed, I hope everyone will use lower-case letters. if it is used in upper-case letters, then, haha, haha, really, really cool, he will tell you that UTF8 encoding is not used, but you have actually coded it, but it is a pity that it is still wrong, so it should be in lower case, alas

After two hours of automatic acquisition, you can use MenuCreate (call the menu interface) to output the data. On the code.


////// Prevent the token of each request from changing for two hours ///Public class WA_GetAccess_Token {public WA_GetAccess_Token () {} public static WAEntity. Access_token GetAccess_Token () {string url = "https://api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = "+ ConfigurationManager. appSettings ["AppID"] + "& secret =" + ConfigurationManager. deletetoken ["AppSecret"]; Access_token entity = new Access_token (); try {HttpWebRequest req = (HttpWebRequest) HttpWebRequest. create (url); req. method = "GET"; using (WebResponse wr = req. getResponse () {HttpWebResponse myResponse = (HttpWebResponse) req. getResponse (); StreamReader reader = new StreamReader (myResponse. getResponseStream (), System. text. encoding. UTF8); string content = reader. readToEnd (); Access_token token = new Access_token (); token = JsonHelper. parseFromJson (content); entity. access_token = token. access_token; entity. expires_in = token. expires_in ;}} catch {// Log} return entity ;}////// Determine whether the Access_Token is out of date based on the current date. if a new Access_Token is returned during the out-of-date period, the previous Access_Token is returned /////////
 Public static string IsExistAccess_Token () {try {string Token = string. empty; DateTime YouXRQ; // read data from the XML file and display string filepath = HttpContext. current. request. 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; WAEntity. access_token mode = GetAccess_Token (); xml. selectSingleNode ("xml "). selectSingleNode ("Access_Token "). innerText = mode. access_token; _ youxrq = _ youxrq. addSeconds (Convert. toInt32 (mode. expires_in); xml. selectSingleNode ("xml "). selectSingleNode ("Access_YouXRQ "). innerText = _ youxrq. toString (); xml. save (filepath); Token = mode. access_token;} return Token;} catch (Exception ex) {return ""; // record logs} public class Access_token {public Access_token () {} public string access_token {get; set;} public string expires_in {get; set ;}} public class JsonHelper {////// Generate Json format //////
 //////
 Public static string GetJson
 
  
(T obj) {DataContractJsonSerializer json = new DataContractJsonSerializer (obj. getType (); using (MemoryStream stream = new MemoryStream () {json. writeObject (stream, obj); string szJson = Encoding. UTF8.GetString (stream. toArray (); return szJson ;}}///
  /// Obtain the Json Model //////
  ///
  ///
  Public static T ParseFromJson
  
   
(String szJson) {T obj = Activator. CreateInstance
   
    
(); Using (MemoryStream MS = new MemoryStream (Encoding. UTF8.GetBytes (szJson) {DataContractJsonSerializer serializer = new DataContractJsonSerializer (obj. getType (); return (T) serializer. readObject (MS );}}}
   
  
 

Forgive me for not knowing the truth. what is the so-called XMLFile. xml? well, I don't really want to say this straightforward, but it's better to directly use the code.


 
 
  
Get TOKEN17:56:31
 

The above is a detailed description of the issue before php public account development. For more information, see other related articles on php Chinese network!

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.