微信監聽到事件後回調到到我們公衆號配置好的接口地址
/**
* 配置Token!!!
*/
public function home(){
$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);
$echoStr = $_GET["echostr"];
if ($tmpStr == $signature) {
$this->responseMsg();
} else {
header('content-type:text');
ob_clean();
echo $echoStr;
}
exit();
}
首次關注
/**
* 發送消息
*/
public function responseMsg(){
$data = file_get_contents("php://input");
$this->res = (array)simplexml_load_string($data, "SimpleXMLElement", LIBXML_NOCDATA);
//判斷是否首次關注
if ($this->res['MsgType'] == 'event') {//事件
if ($this->res['Event'] == 'subscribe') {//關注
$this->sendText();
}
if ($this->res['Event'] == 'unsubscribe') {
echo "取消關注";
die;
}
if ($this->res['Event'] == 'CLICK') {//點擊事件
if ($this->res['EventKey'] == 'TO_IMG') {//圖片
$this->sendImg("6LGwaGlcL1nEFVNHiWH2YQv4ztDUvsq-7WTAhvUkRU4");
}
}
}
}
回覆關注文字消息:
/**
* 發送關注消息
* @param $content
*/
public function sendText($content){
echo "<xml>
<ToUserName><![CDATA[".$this->res['FromUserName']."]]></ToUserName>
<FromUserName><![CDATA[".$this->res['ToUserName']."]]></FromUserName>
<CreateTime>".time()."</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[".$content."]]></Content>
</xml>";
}
回覆圖片消息:(永久)參考:微信公衆號(四)——上傳永久素材(圖片)
/**
* 回覆圖片
* @param $content
*/
public function sendImg($content){
echo "<xml>
<ToUserName><![CDATA[".$this->res['FromUserName']."]]></ToUserName>
<FromUserName><![CDATA[".$this->res['ToUserName']."]]></FromUserName>
<CreateTime>".time()."</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[".$content."]]></MediaId>
</Image>
</xml>";
}