PHP1 lecture: PHP WeChat public platform development (2) public platform sample code analysis

Source: Internet
Author: User
Tags php sample code sha1 encryption
The public platform provides a simple php sample code. before further development, we need to take a closer look at it.

The public platform provides a simple php sample code. before further development, we need to take a closer look at it.

II. get code

Official website: http://mp.weixin.qq.com/mpres/htmledition/res/wx_sample.zip

III. analyze code

The complete code is as follows:

 valid(); class wechatCallbackapiTest{ public function valid()    { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit;        }    } public function responseMsg()    { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //extract post data if (!empty($postStr)){ $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "
                             
  %s
                              
  %s
                              
  
   %s
                              
  %s
                              
  %s
                              
  
   0
                              
 "; if(!empty( $keyword ))                { $msgType = "text"; $contentStr = "Welcome to wechat world!"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr;                }else{ echo "Input something...";                }        }else { echo ""; exit;        }    } private function checkSignature()    { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true;        }else{ return false;        }    }} ?>

3.1 Overall analysis

The original sample code is roughly divided into four parts:

  • Define TOKEN
  • Declare a wechatCallbackapiTest class
  • Create an instance object like wechatCallbackapiTest $ wechatObj
  • Call the valid () method of the class.

3.2 Detailed analysis

3.2.1 define TOKEN

Define ("TOKEN", "weixin ");

Define is a function used to assign values to constants. this sentence means that the constant value "TOKEN" is "weixin ".

TOKEN is used for interactive security authentication. developers can define it at will, which should be the same as that set on the public platform.

3.2.2 declare a class

Class wechatCallbackapiTest {

}

Declare a wechatCallbackapiTest class that contains three methods (functions ).

A. public function valid ()

Used to send verification information to a developer upon application.

B. public function responseMsg ()

It is also the most commonly used function to process and reply to messages sent by users. almost all functions are implemented here.

ResponseMsg Function details:$ PostStr = $ GLOBALS ["HTTP_RAW_POST_DATA"]; receives user messages sent from the public platform. the Message data structure is XML and is not the default data type recognized by php, therefore, $ GLOBALS ['http _ RAW_POST_DATA '] is used for receiving and assigned to $ postStrif (! Empty ($ postStr) determines whether $ postStr is null. if it is not null (the data is received), the following statement is executed. if it is null, then jump to the corresponding else statement. $ PostObj = simplexml_load_string ($ postStr, 'simplexmlelement', LIBXML_NOCDATA); use the simplexml_load_string () function to load the received XML message data to the object $ postObj. This rigorous writing method is followed by a conditional statement to determine whether the load is successful, but it is okay if you do not write it. $ FromUsername = $ postObj-> FromUserName; assign the OPENID of the sender in the object $ postObj to the $ fromUsername variable $ toUsername = $ postObj-> ToUserName; assign the ID of the public account in the object $ postObj to the $ toUsername variable $ keyword = trim ($ postObj-> Content); trim () the function removes white spaces and other pre-defined characters from both ends of the string. the keyword $ time = time (); time () entered by the user can be obtained here () the function returns the Unix timestamp of the current time, that is, the number of seconds from the Unix epoch (GMT 00:00:00, January 1, January 1, 1970) to the current time. $ TextTpl ="
 
          
  %s
         
  %s
          
  
   
% S
         
  %s
         
  %s
         
  
   
0
         
 "; Save the template if (! Empty ($ keyword) checks whether $ keyword is null. if it is not null, the following statement is executed. if it is null, the corresponding else statement is redirected, echo "Input something... "; $ msgType =" text "; the message type is text type $ contentStr =" Welcome to wechat world! "; Reply message content $ resultStr = sprintf ($ textTpl, $ fromUsername, $ toUsername, $ time, $ msgType, $ contentStr); use sprintf () the function writes formatted data to the variable. $ fromUsername, $ toUsername, $ time, $ msgType, $ contentStr replaces the "% s" position in the template in sequence, that is, the variable "$ resultStr" is actually:


$toUsername
$fromUsername
$ Time
$msgType
$contentStr
0 // The message received by the star when 0x0001 is marked.

Echo $ resultStr; // output the reply message

C. private function checkSignature ()

The developer verifies the request by verifying signature (The following is a verification method ). If you confirm that the GET request is from the server and the echostr parameter is returned as is, the access takes effect. Otherwise, the access fails.

Signature combines the token parameter entered by the developer with the timestamp parameter and nonce parameter in the request.

Encryption/verification process: 1. sort the tokens, timestamp, and nonce in lexicographic order. splice the three parameter strings into one string for sha1 encryption. the encrypted string obtained by the developer can be compared with signature to identify that the request comes from

3.2.3 create an instance object

$ WechatObj = new wechatCallbackapiTest ();

3.2.4 Call method verification

$ WechatObj-> valid ();

Call the valid () method of the class to perform Interface Verification. after the interface is set successfully, comment it out.

IV. Summary

The above is an analysis of the official sample code. if the explanation is incorrect, please point it out. In addition, this code is just a simple sample code officially provided. if you want to perform complex development, you must rewrite the code in a rigorous development mode. we will explain it in subsequent tutorials.

V. References

Official public platform API documentation: http://mp.weixin.qq.com/wiki/index.php

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.