微信公眾平台開發關注/取消追蹤事件例子

來源:互聯網
上載者:User

下面是一個微信公眾平台關注和取消追蹤的執行個體:

 代碼如下 複製代碼

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 (!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 = "<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;
  }
 }
}

代碼相關參數說明:

參數 描述
ToUserName 開發人員微訊號
FromUserName  發送方帳號(一個OpenID)
CreateTime  訊息建立時間 (整型)
MsgType  訊息類型,event
Event  事件類型,subscribe(訂閱)、unsubscribe(取消訂閱)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.