php+CI 接入微信公众平台开发, 填写服务器配置验证Toke
class Api extends CI_Controller {
public function __construct()
{
parent::__construct();
}
//页面默认方法
public function index()
{
define("TOKEN", "weixin");
$this->valid();
}
public function valid()
{
$echoStr = $_GET["echostr"];
//valid signature , option
if($this->checkSignature())
{
echo $echoStr;
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 = "q2w3e4r5t";
$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;
}
}
/**
* 记录日志
* @param $str
* @param $mode
*/
public function write_log($str){
$mode='a';//追加方式写
$file = "Apilog.txt";
$oldmask = @umask(0);
$fp = @fopen($file,$mode);
@flock($fp, 3);
if(!$fp)
{
Return false;
}
else
{
@fwrite($fp,$str);
@fclose($fp);
@umask($oldmask);
Return true;
}
}