PHP Micro-trust public Platform sample Code Analysis (ii) _php example

Source: Internet
Author: User
Tags cdata constant current time sha1 sha1 encryption sprintf

I. Summary

The micro-credit public platform provides a simple example code for PHP, which we need to learn more about before further development.

Second, get the code

Micro-letter Official website: http://xiazai.jb51.net/201612/yuanma/phpwxsample (jb51.net). rar

Three, analysis code

The complete code is as follows:

<?php/** * WeChat PHP Test * *//define Your token ("define", "token");
$WECHATOBJ = new Wechatcallbackapitest ();

$WECHATOBJ->valid ();

  Class Wechatcallbackapitest {public function valid () {$echoStr = $_get["Echostr"];
   Valid signature, option if ($this->checksignature ()) {echo $echoStr;
  Exit The Public Function responsemsg () {//get post data, May is due to the different environments $postStr = $GLOBALS [

  "Http_raw_post_data"]; Extract post Data if (!empty ($POSTSTR)) {$POSTOBJ = simplexml_load_string ($postStr, ' simplexmlelement ', LIBXM
    L_nocdata);
    $fromUsername = $POSTOBJ->fromusername;
    $toUsername = $POSTOBJ->tousername;
    $keyword = Trim ($postObj->content);
    $time = time (); $TEXTTPL = "<xml> <tousername><! [cdata[%s]]></tousername> <fromusername><! [cdata[%s]]></fromusername> <CreateTime>%s</CreateTime> <MsgType><! [cdata[%s]]></msgtype> <content><!    
    [cdata[%s]]></content> <FuncFlag>0</FuncFlag> </xml> ";
     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
  The 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 class Wechatcallbackapitest
Creates an instance object of the class Wechatcallbackapitest $WECHATOBJ
invokes the valid () method of the class.

3.2 Detailed analysis

3.2.1 Definition Token

Define ("TOKEN", "Weixin");

Define is a function that assigns a value to a constant, meaning "TOKEN" is given a constant value of "Weixin".

TOKEN is used for interactive security authentication, and developers are free to define them, as set out in the public platform.

3.2.2 declares a class

Class wechatcallbackapitest{

}

Declares a class wechatcallbackapitest, which contains three methods (functions).

A. Public function valid ()

Used to send authentication information to a micro-letter when requesting to be a developer.

B. Public function responsemsg ()

Processing and replying to the message sent by the user is also the most used function, almost all of the functions are implemented here.

responsemsg function Detailed:

$POSTSTR = $GLOBALS ["Http_raw_post_data"];
Receive the user message from the micro-credit public platform, the message data structure is XML, not the PHP default identification data type, so it is $globals[' http_raw_post_data ' to receive, and assigns the value to the $POSTSTR

if (!empty ($POSTSTR))
To determine if the $poststr is empty, if it is not empty (the data is received), proceed to the following statement, or, if it is null, jump to the else statement corresponding to it.

$POSTOBJ = simplexml_load_string ($postStr, ' simplexmlelement ', libxml_nocdata);
Loads the received XML message data into the object $postobj using the Simplexml_load_string () function. This rigorous writing has to be added to determine whether to load the success of the conditional statement, but do not write is OK.

$fromUsername = $POSTOBJ->fromusername;
Assigns the OpenID of the sending message user in 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);
The trim () function deletes whitespace characters and other predefined characters from both ends of the string, and here you can get the keywords that the user enters

$time = time ();
The time () function returns the current TIME's Unix timestamp, the number of seconds since the Unix era (GMT January 1, 1970 00:00:00) to the current time.

$TEXTTPL = "<xml>
<tousername><![ Cdata[%s]]></tousername>
<fromusername><![ cdata[%s]]></fromusername>
<CreateTime>%s</CreateTime>
<msgtype><![ Cdata[%s]]></msgtype>
<content><![ cdata[%s]]></content>
<FuncFlag>0</FuncFlag>
</xml> ";

Template for storing micro-letter output

if (!empty ($keyword))

To determine whether the $keyword is empty or empty, continue with the following statement, and if it is null, jump to the else statement corresponding to it, that is, echo "Input something ...";

$msgType = "text";

Message type is text type

$CONTENTSTR = "Welcome to WeChat world!";

Message content for replies

$RESULTSTR = sprintf ($TEXTTPL, $fromUsername, $toUsername, $time, $msgType, $CONTENTSTR);

Use the sprintf () function to write formatted data to a variable;
$fromUsername, $toUsername, $time, $msgType, $contentStr to replace the "%s" position in the template separately, which is the "$RESULTSTR" variable that finally actually:

<xml>
<tousername><![ cdata[$toUsername]]></tousername>
<fromusername><![ cdata[$fromUsername]]></fromusername>
<CreateTime> $time </CreateTime>
<msgtype ><! [cdata[$msgType]]></msgtype>
<content><![ cdata[$contentStr]]></content>
<FuncFlag>0</FuncFlag>  //bit 0x0001 is flagged when the star sign has just received the message.
</xml>

Echo $resultStr; To output the message of a reply

C. Private Function Checksignature ()

The developer verifies the request by checking the signature (there is a check method below). If you confirm that the GET request comes from a micro-trust server, the request returns the ECHOSTR parameter content, the access is valid, otherwise the access fails.

Signature combines the token parameters and timestamp parameters and Nonce parameters that are filled in by the developer.

Encryption/validation Process:
1. Sort token, timestamp, nonce three parameters in dictionary order
2. Concatenation of three parameter strings into a string for SHA1 encryption
3. The developer obtains the encrypted string to compare with the signature, identifies the request from the micro-letter
3.2.3 Create Instance objects

$WECHATOBJ = new Wechatcallbackapitest ();

3.2.4 Call class Method validation

$WECHATOBJ->valid ();

The valid () method of the calling class performs interface validation, which is commented out after the interface is successfully set.

Iv. Summary

The above is an analysis of the official sample code of the micro-letter, there is no explanation for the wrong place, but also asked the master pointed out. In addition, the code is just a simple example code given by the official, if you want to do complex development, or ask the developer to follow the rigorous development model rewrite the code, will be in the next tutorial to explain.

V. Reference

Micro-credit official public Platform API documentation: http://mp.weixin.qq.com/wiki/index.php

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.