<?php
/**
* wechat php test
*/
//define your token
//定义TOKEN密钥(主要为了桥接微信服务器和自定义服务器)
//"weinxin"可以自己取名,比如取名为weixinabc
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
//调用valid方法,主要用于微信验证。
//(第一步验证)验证完成后,记得加上//进行注销valid()方法。
//$wechatObj->valid();
//(第二步启动回复功能)
$wechatObj->responseMsg();
//wechatCallbackapiTest类,主要用于微信开发验证与回复
class wechatCallbackapiTest
{
//定义验证方法
public function valid()
{
//echostr随机字符串,接收随机字符串
$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
//$GLOBALS可以接受xml数据.
$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 */
//安全处理,解析xml时不解析外部实体,防止文件产生泄露(xxe泄露)
libxml_disable_entity_loader(true);
//载入xml文件到字符串
$postObj = simplexml_load_string($postStr, ‘SimpleXMLElement‘, LIBXML_NOCDATA);
//发送者(手机客户端)
$fromUsername = $postObj->FromUserName;
//接受者(微信公众号)
$toUsername = $postObj->ToUserName;
//定义一个接受类型
$msgType=$postObj->MsgType;
//接受到的关键词
$keyword = trim($postObj->Content);
//时间戳
$time = time();
//文本消息xml模板
$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 = "欢迎来到崎沙火山岛旅游信息平台";
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}else{
echo "Input something...";
}
}else {
echo "";
exit;
}
}
//验证数字签名
private function checkSignature()
{
// you must define TOKEN by yourself
//校验TOKEN密钥
if (!defined("TOKEN")) {
throw new Exception(‘TOKEN is not defined!‘);
}
//接收数字签名
$signature = $_GET["signature"];
//接收时间戳
$timestamp = $_GET["timestamp"];
//接收随机数
$nonce = $_GET["nonce"];
//定义$token变量,接收TOKEN密钥
$token = TOKEN;
//把$token,$timestamp,$nonce组成数组
$tmpArr = array($token, $timestamp, $nonce);
// use SORT_STRING rule
//字典法排序
sort($tmpArr, SORT_STRING);
//转换数组为字符串
$tmpStr = implode( $tmpArr );
//通过哈希算法进行加密
$tmpStr = sha1( $tmpStr );
//与发送过来的数字签名$signature进行比对,成功则返回ture,否则返回false!
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}
?>