使用前提條件:擁有一個公網上的HTTP服務器主機空間,具備建立目錄、上傳文件等權限。推薦新浪的SAE。http://sae.sina.com.cn/php
首先請註冊微信公衆平臺的帳號,註冊地址:http://mp.weixin.qq.com/html
本教程主要講解接口的開發流程。數據庫
官方的文檔很是簡潔:http://mp.weixin.qq.com/cgi-bin/indexpage?t=wxm-callbackapi-doc&lang=zh_CNapi
事例代碼也跑不通。我研究了一番,終於搞定。方法以下:數組
1、寫好接口程序服務器
在你的服務器上上傳好一個接口程序文件,如http://www.yourdomain.com/weixin.php 內容以下:微信
2、配置微信公衆平臺回覆接口微信公衆平臺
設置回覆接口,填好URL和Token(url填上面的http://www.yourdomain.com/weixin.php,token必須跟上面程序裏面定義的Token一致)dom
3、驗證接口curl
用本身的我的微信關注下你的公衆帳號,給這個帳號發一條消息過去,收到原樣的消息返回,即驗證成功了。
4、開始自定義回覆
註釋掉$wechatObj->valid(); 這行,同時去掉//$wechatObj->responseMsg();這行的註釋。
你能夠修改responseMsg函數裏面的代碼,根據用戶的消息類型('text','image','location')和消息內容來回複用戶不一樣的內容。
消息接口就可使用了,發個消息試試看吧?
封裝weixin.class.php
因爲微信公衆平臺的通訊使用的是特定格式的XML數據,每次接受和回覆都要去作一大堆的數據處理。
咱們就考慮在這個基礎上作一次封裝,weixin.class.php,代碼以下:
<?php
class Weixin
{
public $token = '';//token
public $debug = false;//是否debug的狀態標示,方便咱們在調試的時候記錄一些中間數據
public $setFlag = false;
public $msgtype = 'text'; //('text','image','location')
public $msg = array();
public function __construct($token,$debug)
{
$this->token = $token;
$this->debug = $debug;
}<br> //得到用戶發過來的消息(消息內容和消息類型 )
public function getMsg()
{
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
if ($this->debug) {
$this->write_log($postStr);
}
if (!empty($postStr)) {
$this->msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$this->msgtype = strtolower($this->msg['MsgType']);
}
}<br> //回覆文本消息
public function makeText($text='')
{
$CreateTime = time();
$FuncFlag = $this->setFlag ? 1 : 0;
$textTpl = "<xml>
<ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
<FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
<CreateTime>{$CreateTime}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
<FuncFlag>%s</FuncFlag>
</xml>";
return sprintf($textTpl,$text,$FuncFlag);
}<br> //根據數組參數回覆圖文消息
public function makeNews($newsData=array())
{
$CreateTime = time();
$FuncFlag = $this->setFlag ? 1 : 0;
$newTplHeader = "<xml>
<ToUserName><![CDATA[{$this->msg['FromUserName']}]]></ToUserName>
<FromUserName><![CDATA[{$this->msg['ToUserName']}]]></FromUserName>
<CreateTime>{$CreateTime}</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<Content><![CDATA[%s]]></Content>
<ArticleCount>%s</ArticleCount><Articles>";
$newTplItem = "<item>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>";
$newTplFoot = "</Articles>
<FuncFlag>%s</FuncFlag>
</xml>";
$Content = '';
$itemsCount = count($newsData['items']);
$itemsCount = $itemsCount < 10 ? $itemsCount : 10;//微信公衆平臺圖文回覆的消息一次最多10條
if ($itemsCount) {
foreach ($newsData['items'] as $key => $item) {
if ($key<=9) {
$Content .= sprintf($newTplItem,$item['title'],$item['description'],$item['picurl'],$item['url']);
}
}
}
$header = sprintf($newTplHeader,$newsData['content'],$itemsCount);
$footer = sprintf($newTplFoot,$FuncFlag);
return $header . $Content . $footer;
}
public function reply($data)
{
if ($this->debug) {
$this->write_log($data);
}
echo $data;
}
public function valid()
{
if ($this->checkSignature()) {
if( $_SERVER['REQUEST_METHOD']=='GET' )
{
echo $_GET['echostr'];
exit;
}
}else{
write_log('認證失敗');
exit;
}
}
private function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$tmpArr = array($this->token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
private function write_log($log){<br> //這裏是你記錄調試信息的地方 請自行完善 以便中間調試<br> }
}
?>
調用weixin.class.php
把你的微信公衆平臺主接口文件(如前面定義的http://www.yourdomain.com/weixin.php)中,修改代碼爲:
<?php
include_once('weixin.class.php');//引用剛定義的微信消息處理類<br>define("TOKEN", "mmhelper");<br>define('DEBUG', true);
$weixin = new Weixin(TOKEN,DEBUG);//實例化
$weixin->getMsg();
$type = $weixin->msgtype;//消息類型
$username = $weixin->msg['FromUserName'];//哪一個用戶給你發的消息,這個$username是微信加密以後的,可是每一個用戶都是一一對應的
if ($type==='text') {
if ($weixin->msg['Content']=='Hello2BizUser') {//微信用戶第一次關注你的帳號的時候,你的公衆帳號就會受到一條內容爲'Hello2BizUser'的消息
$reply = $weixin->makeText('歡迎你關注媽媽助手哦,屌絲');
}else{//這裏就是用戶輸入了文本信息
$keyword = $weixin->msg['Content']; //用戶的文本消息內容
include_once("chaxun.php");//文本消息 調用查詢程序
$chaxun= new chaxun(DEBUG,$keyword,$username);
$results['items'] =$chaxun->search();//查詢的代碼
$reply = $weixin->makeNews($results);
}
}elseif ($type==='location') {
//用戶發送的是位置信息 稍後的文章中會處理
}elseif ($type==='image') {
//用戶發送的是圖片 稍後的文章中會處理
}elseif ($type==='voice') {
//用戶發送的是聲音 稍後的文章中會處理
}
$weixin->reply($reply);
?>
查詢代碼
還須要將數據庫裏面的查詢結果格式化爲特定的形式
<?php
public function search(){
$record=array(); //定義返回結果的數組
$list = $this->search($this->keyword);//普通的根據關鍵詞查詢數據庫的操做 代碼就不用分享了
if(is_array($list)&&!empty($list)){
foreach($list as $msg){
$record[]=array(//如下代碼,將數據庫中查詢返回的數組格式化爲微信返回消息能接收的數組形式,即title、description、picurl、url 詳見微信官方的文檔描述
'title' =>$msg['title'],
'description' =>$msg['discription'],
'picurl' => $msg['pic_url'],
'url' =>$msg['url']
);
}
}
return $record;
}
?>
來源:http://www.weste.net/2013/4-27/90846.html