用戶在關注與取消關注公眾號時,微信會把這個事件推送到開發者填寫的URL。方便開發者給用戶下發歡迎消息或者做帳號的解綁
下面是一個微信公眾平臺關注和取消關注的實例:responseMsg();
} else {
$wechatObj->valid();
}
class wechatCallbackapiTest {
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);
$RX_TYPE = trim($postObj->MsgType);
switch ($RX_TYPE) {
case "event":
$result = $this->receiveEvent($postObj);
breadk;
}
echo $result;
} else {
echo "";
exit;
}
}
private function receiveEvent($object) {
$content = "";
switch ($postObj->Event) {
case "subscribe":
$content = "歡迎關注網志博客"; //這里是向關注者發送的提示信息
break;
case "unsubscribe":
$content = "";
break;
}
$result = $this->transmitText($object, $content);
return $result;
}
private function transmitText($object, $content) {
$textTpl = "%s
0";
$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;
}
}
}
?>
代碼相關參數說明:
參數 描述
ToUserName 開發者微信號
FromUserName 發送方帳號(一個OpenID)
CreateTime 消息創建時間 (整型)
MsgType 消息類型,event
Event 事件類型,subscribe(訂閱)、unsubscribe(取消訂閱)
相關標簽:
本文原創發布php中文網,轉載請注明出處,感謝您的尊重!