//定义类文件
class wechatCallbackapiTest
{
//实现valid验证方法:实现对接微信公众平台
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
//接受用户端发送过来的xml数据
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
//extract post data
//判断xml数据是否为空
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);
//通过simplexml进行xml解析
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//接受微信的手机端
$fromUsername = $postObj->FromUserName;
//微信公众平台
$toUsername = $postObj->ToUserName;
//接受用户发送的关键词
$keyword = trim($postObj->Content);
//1.接受用户消息类型
$msgType = $postObj -> MsgType;
//时间戳
$time = time();
//文本发送模板
$textTpl = "
private function checkSignature()
{
// you must define TOKEN by yourself
//判断是否定义了TOKEN,如果没有就抛出一个异常
if (!defined("TOKEN")) {
throw new Exception('TOKEN is not defined!');
}