微信关注与取消关注事件推送

<?php
//
// 关注/取消关注事件消息
// 微信公众账号关注与取消关注事件消息
//

define("TOKEN", "zhouqi");

$wechatObj = new wechatCallbackapiTest();
if (!isset($_GET['echostr'])) {
$wechatObj->responseMsg();
}else{
$wechatObj->valid();
}

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);
$RX_TYPE = trim($postObj->MsgType);

switch ($RX_TYPE)
{
case "event":
$result = $this->receiveEvent($postObj);
break;
}
echo $result;
}else {
echo "";
exit;
}
}

private function receiveEvent($object)
{
$content = "";
switch ($object->Event)
{
case "subscribe": //关注事件
$content = "欢迎关注周起,么么哒(づ ̄ 3 ̄)づ";
break;
case "unsubscribe": //取消关注事件
$content = "";
break;
}
$result = $this->transmitText($object, $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>
</xml>";
$result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content);
return $result;
}
}
?>
posted @ 2017-04-28 13:36  周起  阅读(4286)  评论(0编辑  收藏  举报