微信公众号与企业号的TOKEN验证与使用

微信公众号与企业号的TOKEN验证与使用

上图是,微信客户端与微信服务端与公众号、企业号的服务器的原理架构,首先,我们如果使用应用服务器,则需要告诉微信服务器,它在哪里,所以TOKEN就是一个标识的作用,TOKEN是一个参数,是一个自定义的值,负责标识微信服务器和应用服务是不是一一对应。url就是应用服务器的地址。
当我们填写完url,token后,微信服务器就会发送请求到url,进行验证应用服务器,然后应用服务器做出对应响应给微信服务器完成对接。具体代码如下:
define("TOKEN", "derek"); 
$wechatObj = new wechatCallbackapi(); 
if (isset($_GET['echostr'])) {
 $wechatObj->valid(); 
}else{ 
 $wechatObj->responseMsg(); 
}
class wechatCallbackapi { 
 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)){
 /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself */ 
libxml_disable_entity_loader(true);
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);  $RX_TYPE = trim($postObj->MsgType);
//TODO
}
else { 
echo ""; 
 exit; 
 }
}
private function checkSignature() {
 // you must define TOKEN by yourself 
 if (!defined("TOKEN")) { 
 throw new Exception('TOKEN is not defined!');
 } 
 $signature = $_GET["signature"]; 
 $timestamp = $_GET["timestamp"]; 
 $nonce = $_GET["nonce"]; 
 $token = TOKEN; 
 $tmpArr = array($token, $timestamp, $nonce); 
 // use SORT_STRING rule 
 sort($tmpArr, SORT_STRING); 
 $tmpStr = implode( $tmpArr ); 
 $tmpStr = sha1( $tmpStr ); 
 if( $tmpStr == $signature ){ 
 return true; 
 }else{ 
 return false; 
 } }
}