微信公众号开发(一)TOKEN验证(CI框架)
我先帖代码了,其他没啥意思。
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Wechat extends MY_Controller { public function __construct() { parent::__construct(); } public function valid() { $echoStr = $this->input->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 = "<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; } } private function checkSignature() { $signature = $this->input->get('signature'); $timestamp = $this->input->get('timestamp'); $nonce = $this->input->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; } } }
这个和官方一样,没啥改动的。放到你的回调地址就好。
还有一个地方,要注意,就是token这个放好。
defined('TOKEN') OR define('TOKEN', 'caisangzi');
把TOKEN放到constants.php里面。
发布时间:2018-05-21,16:58:30
微信公众平台开发中的第一步,TOKEN的验证,回调地址的操作。