define("TOKEN", "youtoken");//token内容识别码
$wechatObj = new wechatCallback();//实例化wechatCallback类
if (!isset($_GET["echostr"])) {
// 消息事件
$wechatObj->responseMsg();
} else {
file_put_contents('/var/www/api/logs/debug.log', 'req $_GET:' . print_r($_GET, true) . "\n", FILE_APPEND);
// 认证token
$wechatObj->valid();
}
class wechatCallback
{
public function valid()
{
$echoStr = $_GET["echostr"];
if ($this->checkSignature()) {
echo $echoStr;
exit;
}
}
public function responseMsg()//执行接收器方法
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if (!empty($postStr)) {
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
file_put_contents('/var/www/api/logs/debug.log', 'req $postObj =:' . print_r($postObj, true) . "\n", FILE_APPEND);
$RX_TYPE = trim($postObj->MsgType);
switch ($RX_TYPE) {
case "event":
$result = $this->receiveEvent($postObj);
break;
case "text":
// 用户向公众号发送文本消息
$content = '我回复你了';
$result = $this->transmitText($postObj, $content);
break;
}
echo $result;
exit();
} else {
echo "";
exit;
}
}
private function receiveEvent($postObj)
{
$content = "";
switch ($postObj->Event) {
case "subscribe":
// 用户关注公众号
$content = "欢迎关注暖心有你公众号";
break;
case "unsubscribe":
// 用户取消公众号关注
$content = "";
break;
}
$result = $this->transmitText($postObj, $content);
// return $result;
}
private function transmitText($object, $content)
{
$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>0</FuncFlag>
</xml>";
$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
return $result;
}
private function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode($tmpArr);
$tmpStr = sha1($tmpStr);
if ($tmpStr == $signature) {
return true;
} else {
return false;
}
}
}