该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
header("content-type: text");
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();
if(isset($_GET["echostr"])){
$wechatObj->valid();
}else{
$wechatObj->responseMsg();
}
// 定义类
class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];
if($this->checkSignature()) {
echo $echoStr;
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;
}
}
//相应消息
public function responseMsg($value='')
{
//1.先接受微信服务器转发过来的信息
$xmlStr = file_get_contents("php://input");
//2.将第一步的xml字符串转化为对象
$xmlObj = simplexml_load_string($xmlStr, “SimpleXMLElement”, LIBXML_NOCDATA );
//3.判断消息的类型
switch ($xmlObj->MsgType) {
case 'text':
//粉丝发送的是文本消息
$result = $this->receiveTextMsg($xmlObj);
break;
case 'image':
//粉丝发送的是图片消息
break;
default:
//不能识别上述消息类型
break;
}
//响应结果
echo $result;
}
//接受并处理粉丝发送的消息
//$xmlobj 接受到的XML对象信息
public function receiveTextMsg($xmlObj)
{
//获取粉丝发送的内容
$keyword = trim($xmlObj->Content);
//响应内容给粉丝
$content = "你发送的内容是:".$keyword;
//拼接xml数据包
$result = $this->transitTextXML($xmlObj,$content);
}
//拼接xml数据包
public function transitTextXML($xmlObj,$content)
{
//通过占位符来表示变量
$tmpStr = '
%s
';
//格式化输出
$result = sprintf($tmpStr,$xmlObj->FromUserName,$xmlObj->ToUserName,time(),$content);
return $result;
}
}
?>