微信公众号-关注和取消关注

关注和取消关注

<?php
define("APPID","wx4cff8e15a7a0801d");//填写自己的APPID
define("APPSECRET","4d7cb4b8b54412d9ef0c6a7c011cd570");//填写自己的APPSECRET
define("TOKEN", "weixin");//token随便填,只要一致就行。
$wechat = new wechat();
$wechat->responseMsg();
 
class wechat{
    private $_appid;
    private $_appsecret;
    private $_token;
	private $tpl=array(
				//发送文本消息模板
				'text' => '	<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[text]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							</xml>',
	);
    public function __construct(){
        $this->_appid =APPID;
        $this->_appsecret =APPSECRET;
        $this->_token =TOKEN;
    }
	/**
	  *响应微信平台发送的消息
	**/
    public function responseMsg()//所有的被动消息处理都从这里开始
    {
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];//获得用户发送信息
		$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);//解析XML到对象
		switch($postObj->MsgType){
			case 'text': //文本处理
				$this->_doText($postObj);
				break;
			case 'event': //事件处理
				$this->_doEvent($postObj);
				break;
			default: exit;
		}
	}
    /**
	  *_doText():处理文本消息
	  *@postObj:响应的消息对象
	**/
	private function _doText($postObj)
	{
		$fromUsername = $postObj->FromUserName;
		$toUsername = $postObj->ToUserName;
		$keyword = trim($postObj->Content);
		$time = time();           
		if(!empty( $keyword ))
		{
			$contentStr='hello world!';
			exit;
			//这里可以做一些业务处理
			if($keyword == "hello")
				$contentStr = "Welcome to wechat world!";
			$msgType = "text";
			$resultStr = sprintf($this->tpl['text'], $fromUsername, $toUsername, $time, $contentStr);
			echo $resultStr;
		}
        exit;	
	}
	/**
	  *_doEvent():处理事件消息
	  *@postObj:响应的消息对象
	**/
	private function _doEvent($postObj){ //事件处理
		switch($postObj->Event){
			case  'subscribe': //订阅
				$this->_doSubscribe($postObj);
				break;
			case 'unsubscribe': //取消订阅
				$this->_doUnsubscribe($postObj);
				break;
			default:;
		}
	}
	/**
	  *处理关注事件
	  *@postObj:响应的消息对象
	**/
	private function _doSubscribe($postObj){
		$contentStr='欢迎您关注我的公众号!';
		$str = sprintf($this->tpl['text'],$postObj->FromUserName,$postObj->ToUserName,time(),$contentStr);
		//还可以保存用户的信息到数据库
		echo $str;	
	}
	
	/**
	  *处理取消关注事件
	  *@postObj:响应的消息对象
	**/
	private function _doUnsubscribe($postObj){
		//把用户的信息从数据库中删除
		//获取用户的openid,在进行一些业务操作
		file_put_contents('useropenid.txt',$postObj->FromUserName);
	}
}

  

原文地址:https://www.cnblogs.com/ganwenjun/p/7160654.html