本文實例講述了微信公眾平台開發關注及取消關注事件的方法。分享給大家供大家參考。具體分析如下:
用戶在關注與取消關注公眾號時,微信會把這個事件推送到開發者填寫的URL,方便開發者給用戶下發歡迎消息或者做帳號的解綁.
下面是一個微信公眾平台關注和取消關注的實例,代碼如下:
復制代碼 代碼如下:define("TOKEN", "w3note");//定義識別碼
$wechatObj = new wechatCallbackapiTest();//實例化wechatCallbackapiTest類
if(!isset($_GET["echostr"])){
$wechatObj->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 (!emptyempty($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 = "<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;
}
}
}
代碼相關參數說明:
希望本文所述對大家的php程序設計有所幫助。