微信公衆平臺消息接口PHP版

使用前提條件:擁有一個公網上的HTTP服務器主機空間,具有創建目錄、上傳文件等權限。

首先請註冊微信公衆平臺的賬號,註冊地址:http://mp.weixin.qq.com/


一、寫好接口程序

在你的服務器上上傳好一個接口程序文件,如http://www.yourdomain.com/weixin.php  內容如下:

<?php
define("TOKEN", "weixin");//自己定義的token 就是個通信的私鑰
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
//$wechatObj->responseMsg();
class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }
    public function responseMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr)){
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $keyword = trim($postObj->Content);
            $time = time();
            $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>0<FuncFlag>
            </xml>";
            if(!empty( $keyword ))
            {
                $msgType = "text";
                $contentStr = '你好啊,屌絲';
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                echo $resultStr;
            }else{
                echo '咋不說哈呢';
            }
        }else {
            echo '咋不說哈呢';
            exit;
        }
    }
 
    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token =TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
 
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}
?>

二、配置微信公衆平臺回覆接口

設置回覆接口,填好URL和Token(url填上面的http://www.yourdomain.com/weixin.php,token必須跟上面程序裏面定義的Token一致)





三、驗證接口

用自己的個人微信關注下你的公衆賬號,給這個賬號發一條消息過去,收到原樣的消息返回,即驗證成功了。

四、開始自定義回覆

註釋掉$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;
}

?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章