用戶在關(guān)注與取消關(guān)注公眾號(hào)時(shí),微信會(huì)把這個(gè)事件推送到開發(fā)者填寫的URL,方便開發(fā)者給用戶下發(fā)歡迎消息或者做帳號(hào)的解綁.
下面是一個(gè)微信公眾平臺(tái)關(guān)注和取消關(guān)注的實(shí)例,代碼如下:
- define("TOKEN", "w3note");//定義識(shí)別碼
- $wechatObj = new wechatCallbackapiTest();//實(shí)例化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()//執(zhí)行接收器方法
- {
- $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 = "歡迎關(guān)注網(wǎng)志博客";//這里是向關(guān)注者發(fā)送的提示信息
- 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 );
- //開源代碼Vevb.com
- if( $tmpStr == $signature ){
- return true;
- }else{
- return false;
- }
- }
- }
代碼相關(guān)參數(shù)說明:
參數(shù) 描述
ToUserName 開發(fā)者微信號(hào)
FromUserName 發(fā)送方帳號(hào)(一個(gè)OpenID)
CreateTime 消息創(chuàng)建時(shí)間 (整型)
MsgType 消息類型,event
Event 事件類型,subscribe(訂閱)、unsubscribe(取消訂閱)
新聞熱點(diǎn)
疑難解答