<?php
header('content-type:text/html;charset=utf-8');
define("TOKEN", "weixin"); //define your token
$wx = new wechatCallbackapiTest();
if($_GET['echostr']){
$wx->valid(); //如果发来了echostr则进行验证
}else{
$wx->responseMsg(); //如果没有echostr,则返回消息
}
class wechatCallbackapiTest{
//微信验证
public function valid(){ //valid signature , option
$echoStr = $_GET["echostr"];
if($this->checkSignature()){ //调用验证字段
echo $echoStr;
exit;
}
}
/*
返回消息数据
*/
public function responseMsg(){
$postStr = file_get_contents('php://input');//php7.0以上用这个接收参数、
//数据
// "<xml>
// <ToUserName><![CDATA[gh_bb86c5992fd8]]><\/ToUserName>\n
// <FromUserName><![CDATA[ojTmjwa0o63WAjWfbbkOUU-lr1IA]]><\/FromUserName>\n
// <CreateTime>1550115489<\/CreateTime>\n
// <MsgType><![CDATA[event]]><\/MsgType>\n
// <Event><![CDATA[subscribe]]><\/Event>\n
// <EventKey><![CDATA[]]><\/EventKey>\n
// <\/xml>"
//get post data, May be due to the different environments
// $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信发来的XML数据 版本php7.0以上这个函数已经作废
file_put_contents('02.txt',json_encode($postStr));
//extract post data
if(!empty($postStr)){
//解析post来的XML为一个对象$postObj
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName; //请求消息的用户
$toUsername = $postObj->ToUserName; //"我"的公众号id
$keyword = trim($postObj->Content); //消息内容
$time = time(); //时间戳
$msgtype = 'text'; //消息类型:文本
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
file_put_contents('01.txt',json_encode($postObj));
if(strtolower($postObj->MsgType == 'event' )){ //如果XML信息里消息类型为event
if($postObj->Event == 'subscribe'){ //如果是订阅事件
// $contentStr = $fromUsername."欢迎订阅misaka去年夏天32434!\n更多精彩内容:http://blog.csdn.net/misakaqunianxiatian";
// $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
// echo $resultStr;
$contentStrq = "欢迎订阅:请点击链接<a href='http://blog.csdn.net/misakaqunianxiatian'>wordwrap</a>";
$resultStrq = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStrq);
echo $resultStrq;
exit();
}
}
switch (keyword) {
case '1':
$contentStr = '我是1号';
break;
case '2':
$contentStr = '我是2号';
break;
default:
$contentStr = '输入数字试试';
break;
}
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
echo $resultStr;
file_put_contents('01.txt',json_encode($resultStr));
exit();
}else {
echo "";
exit;
}
}
//验证字段
private function checkSignature(){
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_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;
}
}
}