原理介紹
接收到客戶消息后就可以回復可以客戶一個圖文消息,實現方法:接收到消息數據后返回給微信服務器一個xml文本即可。Xml格式:
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>2</ArticleCount>
<Articles>
<item>
<Title><![CDATA[title1]]></Title>
<Description><![CDATA[description1]]></Description>
<PicUrl><![CDATA[picurl]]></PicUrl>
<Url><![CDATA[url]]></Url>
</item>
<item>
<Title><![CDATA[title]]></Title>
<Description><![CDATA[description]]></Description>
<PicUrl><![CDATA[picurl]]></PicUrl>
<Url><![CDATA[url]]></Url>
</item>
</Articles>
</xml>
參數詳情
1462332075915698.jpg
函數封裝
/* 回復圖文消息
* $msgArray格式
* $msgArray = array(
* array('項目標題', '描述', '圖片地址', '點擊項目打開的Url'),
* array('項目標題', '描述', '圖片地址', '點擊項目打開的Url'),
* 有幾個項目就設置幾個數組元素
* );
*/
public function reItemMsgs($msgArray){
$xml = '<xml><ToUserName><![CDATA['.$this->openId.']]></ToUserName><FromUserName><![CDATA['.$this->ourOpenId.']]></FromUserName><CreateTime>'.time().'</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>'.count($msgArray).'</ArticleCount><Articles>';
foreach($msgArray as $val){
$xml .= '<item><Title><![CDATA['.$val[0].']]></Title><Description><![CDATA['.$val[1].']]></Description><PicUrl><![CDATA['.$val[2].']]></PicUrl><Url><![CDATA['.$val[3].']]></Url></item>';
}
$xml .= '</Articles></xml>';
echo $xml;
}
完整演示代碼
<?php
/**
* wechat php test
*/
//define your token
define("TOKEN", "wxtext2017");
class weChat{
public $postObj; //接收到的xml對象
public $openId; //客戶的openId
public $ourOpenId; //我方公眾號的openId
//構造函數用于接收消息
public function __construct(){
if(!empty($GLOBALS["HTTP_RAW_POST_DATA"])){
$postStr=$GLOBALS["HTTP_RAW_POST_DATA"];
//將xml轉換成對象
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;
}
}
public function reItemMsgs($msgArray){
$xml = '<xml><ToUserName><![CDATA['.$this->openId.']]></ToUserName><FromUserName><![CDATA['.$this->ourOpenId.']]></FromUserName><CreateTime>'.time().'</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>'.count($msgArray).'</ArticleCount><Articles>';
foreach($msgArray as $val){
$xml .= '<item><Title><![CDATA['.$val[0].']]></Title><Description><![CDATA['.$val[1].']]></Description><PicUrl><![CDATA['.$val[2].']]></PicUrl><Url><![CDATA['.$val[3].']]></Url></item>';
}
$xml .= '</Articles></xml>';
echo $xml;
}
}
$wechatObj = new weChat();
//回復文本消息
$msgArray = array(
array('我是標題一', '我是描述一', 'http://51qiaoxifu.com/head.jpg', 'http://51qiaoxifu.com'),
array('我是標題二', '我是描述二', 'http://51qiaoxifu.com/img.jpg', 'http://51qiaoxifu.com')
);
$wechatObj->reItemMsgs($msgArray);
?>