<?php
header("Content-type: application/xml");
header('Access-Control-Allow-Origin:*');
$echostr=$_GET["echostr"];
//写入文件,测试是否连接成功使用,后期删除就行
$myfile = fopen("log.txt", "a+") or die("Unable to open file!");
$txt = $token." |echostr:".$echostr;
fwrite($myfile, $txt);
fclose($myfile);
//确认来自微信
if(checkSignature()){
//下面这句话这个在验证成功后删除了
// echo $echostr;
checkMesessage();
};
//检测是否来自微信的方法
function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = "12FHD90SJ0JM0J0FD";
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
//false
return false;
}
}
//本方法为接受用户文字信息并原样返回用户发送的文字
function checkMesessage(){
//获取xml数据包
$PostData=file_get_contents("php://input");
if(!$PostData)
{//未获取到数据包
echo_server_log("wrong input! PostData is NULL\\n");
echo "wrong input!";
exit(0);
}
//转化为xml对象
$xmlObj=simplexml_load_string($PostData,'SimpleXMLElement',LIBXML_NOCDATA);
if(!$xmlObj)
{//转化出错
echo_server_log("wrong input! xmlObj is NULL\\n");
echo "wrong input!";
exit(0);
}
//从xml对象中取出
$fromUserName=$xmlObj->FromUserName;
$toUserName=$xmlObj->ToUserName;
$msgType=$xmlObj->MsgType;
$myfile = fopen("log.txt", "a+") or die("Unable to open file!");
$txt = "msgType:".$msgType." |FromUserName:".$fromUserName."\n";
fwrite($myfile, $txt);
fclose($myfile);
if('text'!=$msgType)
{
$retMsg='只支持文本消息';
}
else
{
$content=$xmlObj->Content;
$retMsg=$content;
}
$timestamp=time();
//返回的xml串,注意一定在代码开头设为返回xml格式
$retTmp="<xml>
<ToUserName><![CDATA[".$fromUserName."]]></ToUserName>
<FromUserName><![CDATA[".$toUserName."]]></FromUserName>
<CreateTime>".$timestamp."</CreateTime>
<MsgType><![CDATA[".$msgType."]]></MsgType>
<Content><![CDATA[".$retMsg."]]></Content>
</xml>";
echo $retTmp;
}