1. 程式人生 > >微信公眾平臺訊息介面PHP版

微信公眾平臺訊息介面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;
}

?>