原理介紹
接收到客戶消息后就可以回復(fù)可以客戶一個(gè)消息,實(shí)現(xiàn)方法:接收到消息數(shù)據(jù)后返回給微信服務(wù)器一個(gè)xml文本即可。Xml格式:
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好]]></Content>
</xml>
參數(shù) 描述
ToUserName 開發(fā)者微信號
FromUserName 發(fā)送方帳號(一個(gè)OpenID)
CreateTime 消息創(chuàng)建時(shí)間 (整型)
MsgType text
Content 文本消息內(nèi)容
函數(shù)封裝
//回復(fù)文本消息
public function reTextMsg($msg){
$xml = '<xml><ToUserName><![CDATA['.$this->openId.']]></ToUserName><FromUserName><![CDATA['.$this->ourOpenId.']]></FromUserName><CreateTime>'.time().'</CreateTime>
<MsgType><![CDATA[text]]></MsgType><Content><![CDATA['.$msg.']]></Content></xml>';
echo $xml;
}
完成代碼
<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "wxtext2017");
class weChat{
public $postObj; //接收到的xml對象
public $openId; //客戶的openId
public $ourOpenId; //我方公眾號的openId
//構(gòu)造函數(shù)用于接收消息
public function __construct(){
if(!empty($GLOBALS["HTTP_RAW_POST_DATA"])){
$postStr=$GLOBALS["HTTP_RAW_POST_DATA"];
//將xml轉(zhuǎn)換成對象
libxml_disable_entity_loader(true);
$this->postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$this->openId = $this->postObj->FromUserName;
$this->ourOpenId = $this->postObj->ToUserName;
$this->msgType = $this->postObj->MsgType;
}
}
//回復(fù)文本消息
public function reTextMsg($msg){
$xml='<xml><ToUserName><![CDATA['.$this->openId.']]></ToUserName><FromUserName><![CDATA['.$this->ourOpenId.']]></FromUserName><CreateTime>'.time().'</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA['.$msg.']]></Content></xml>';
echo $xml;
}
}
$wechatObj = new weChat();
//回復(fù)文本消息
$wechatObj->reTextMsg('不論你說什么我都回復(fù)這個(gè)');
?>