微信学习之自动回复文本

<?php 
define("TOKEN","echo_server");

function checkSignature(){
	//获取GET参数
	$signature=$_GET['signature'];
	$nonce=$_GET['nonce'];
	$timestamp=$_GET['timestamp'];
	$echostr=$_GET['echostr'];
	
	//把nonce,timestamp,token组装到数组里并做排序
	$tmpArr=array($nonce,$timestamp,TOKEN);
	sort($tmpArr);
	
	//把数组中的元素合并成字符串
	$tmpStr=implode($tmpArr);
	
	//sha1加密
	$tmpStr=sha1($tmpStr);
	
	//判断加密后的字符串是否和signatures相等
	if($tmpStr==$signature){
		return true;
	}
	return false;
}

if(false==checkSignature()){
	exit(0);
}

//获取echostr
$echostr=$_GET['echostr'];
if($echostr){
	echo $echostr;
	exit(0);
}

//获取post数据
$PostData=$HTTP_RAW_POST_DATA;
//判断post数据是否为空
if(!$PostData){
	echo "wrong input";
	exit(0);
}
//解析xml字符串
$xmlObj=simplexml_load_string($PostData,"SimpleXMLElement",LIBXML_NOCDATA);
if(!$xmlObj){
	echo "wrong input";
	exit(0);
}
//获取FromUserName
$fromUserName=$xmlObj->FromUserName;
//获取ToUserName
$toUserName=$xmlObj->ToUserName;
//获取MsgType
$msgType=$xmlObj->MsgType;

if('text'!=$msgType){
	$retMsg="只支持文本信息";
}else{
	$content=$xmlObj->Content;
	$retMsg=$content;
}

//输出消息的xml模板
$retTmp="<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
			<FromUserName><![CDATA[%s]]></FromUserName>
			<CreateTime>%s</CreateTime>
			<MsgType><![CDATA[text]]></MsgType>
			<Content><![CDATA[%s]]></Content>
			<FuncFlag>0</FuncFlag>
		</xml>";

//对消息模板中的通配符进行替换
$resultStr=sprintf($retTmp,$fromUserName,$toUserName,time(),$retMsg);
echo $resultStr;

?>

  加了那个微信,发过去“你很帅”,结果真的自动回复“你很帅”了。好开心哦!

 

<a href="http://s.click.taobao.com/t?e=m%3D2%26s%3D8ZP%2B9BFH8dccQipKwQzePCperVdZeJviEViQ0P1Vf2kguMN8XjClAqdTPP%2BnwUxNRr%2B4el50HJcWjwYIGsh1SNLb45UgjmLHwHV06zwZE474PBd4WwVOW%2Bdn1BbglxZYxUhy8exlzcq9AmARIwX9K%2BnbtOD3UdznPV1H2z0iQv9eY%2By0blbhscYl7w3%2FA2kb" target="_blank"><img src="http://gtms01.alicdn.com/tps/i1/T1LuRAFspSXXX1pzZP-760-90.jpg" /></a>

  

posted @ 2014-04-19 21:16  天道酬勤,坚持!  阅读(3322)  评论(0编辑  收藏  举报