/*
方倍工作室 http://www.cnblogs.com/txw1958/
CopyRight 2013 www.doucube.com All Rights Reserved
这是一个很简单的微信开发程序
*/
//定义TOKEN常量
define("TOKEN", "weixin");
//实例化wechatCallbackapiTest这个类
$wechatObj = new wechatCallbackapiTest();
/**如果有get传参echostr,则调用valid方法,否则调用responseMsg方法。responseMsg方法就是微信自动回复消息
**/
if (isset($_GET['echostr'])) {
$wechatObj->valid();
}else{
$wechatObj->responseMsg();
}
//wechatCallbackapiTest类的定义
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()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)){
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$textTpl = "
%s
0
";
if($keyword == "?" || $keyword == "")
{
$msgType = "text";
$contentStr = date("Y-m-d H:i:s",time());
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;
}
}else{
echo "";
exit;
}
}
}
?>