溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

PHP對(duì)接微信公眾平臺(tái)消息接口開發(fā)的示例分析

發(fā)布時(shí)間:2021-06-07 10:20:56 來(lái)源:億速云 閱讀:235 作者:小新 欄目:移動(dòng)開發(fā)

這篇文章給大家分享的是有關(guān)PHP對(duì)接微信公眾平臺(tái)消息接口開發(fā)的示例分析的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來(lái)看看吧。

一、寫好接口程序

在你的服務(wù)器上上傳好一個(gè)接口程序文件內(nèi)容如下:

代碼如下:

<?php
define("TOKEN", "weixin");//自己定義的token 就是個(gè)通信的私鑰
$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;
        }
    }
}
?>

二、配置微信公眾平臺(tái)回復(fù)接口

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

PHP對(duì)接微信公眾平臺(tái)消息接口開發(fā)的示例分析
三、驗(yàn)證接口

用自己的個(gè)人微信關(guān)注下你的公眾賬號(hào),給這個(gè)賬號(hào)發(fā)一條消息過去,收到原樣的消息返回,即驗(yàn)證成功了。

四、開始自定義回復(fù)

注釋掉$wechatObj->valid(); 這行,同時(shí)去掉//$wechatObj->responseMsg();這行的注釋。
你可以修改responseMsg函數(shù)里面的代碼,根據(jù)用戶的消息類型('text','image','location')和消息內(nèi)容來(lái)回復(fù)用戶不同的內(nèi)容。
消息接口就可以使用了,發(fā)個(gè)消息試試看吧?

1.封裝weixin.class.php

由于微信公眾平臺(tái)的通信使用的是特定格式的XML數(shù)據(jù),每次接受和回復(fù)都要去做一大堆的數(shù)據(jù)處理。
我們就考慮在這個(gè)基礎(chǔ)上做一次封裝,weixin.class.php,代碼如下:

代碼如下:

<?php
class Weixin
{
    public $token = '';//token
    public $debug =  false;//是否debug的狀態(tài)標(biāo)示,方便我們?cè)谡{(diào)試的時(shí)候記錄一些中間數(shù)據(jù)
    public $setFlag = false;
    public $msgtype = 'text';   //('text','image','location')
    public $msg = array();
    public function __construct($token,$debug)
    {
        $this->token = $token;
        $this->debug = $debug;
    }
    //獲得用戶發(fā)過來(lái)的消息(消息內(nèi)容和消息類型  )
    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']);
        }
    }
  //回復(fù)文本消息
    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
            1  
            ]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>%s</FuncFlag>
            </xml>";
        return sprintf($textTpl,$text,$FuncFlag);
    }
    //根據(jù)數(shù)組參數(shù)回復(fù)圖文消息
    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;//微信公眾平臺(tái)圖文回復(fù)的消息一次最多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('認(rèn)證失敗');
            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){
        //這里是你記錄調(diào)試信息的地方  請(qǐng)自行完善   以便中間調(diào)試
    }
}
?>

2.調(diào)用weixin.class.php

把你的微信公眾平臺(tái)主接口文件中,修改代碼為:

代碼如下:

<?php
include_once('weixin.class.php');//引用剛定義的微信消息處理類
define("TOKEN", "mmhelper");
define('DEBUG', true);
$weixin = new Weixin(TOKEN,DEBUG);//實(shí)例化
$weixin->getMsg();
$type = $weixin->msgtype;//消息類型
$username = $weixin->msg['FromUserName'];//哪個(gè)用戶給你發(fā)的消息,這個(gè)$username是微信加密之后的,但是每個(gè)用戶都是一一對(duì)應(yīng)的
if ($type==='text') {
    if ($weixin->msg['Content']=='Hello2BizUser') {//微信用戶第一次關(guān)注你的賬號(hào)的時(shí)候,你的公眾賬號(hào)就會(huì)受到一條內(nèi)容為'Hello2BizUser'的消息
        $reply = $weixin->makeText('歡迎你關(guān)注哦,屌絲');
    }else{//這里就是用戶輸入了文本信息
        $keyword = $weixin->msg['Content'];   //用戶的文本消息內(nèi)容
                include_once("chaxun.php");//文本消息 調(diào)用查詢程序 
                $chaxun= new chaxun(DEBUG,$keyword,$username);
                $results['items'] =$chaxun->search();//查詢的代碼
                $reply = $weixin->makeNews($results);
    }
}elseif ($type==='location') {
      //用戶發(fā)送的是位置信息  稍后的文章中會(huì)處理                 
}elseif ($type==='image') {
      //用戶發(fā)送的是圖片 稍后的文章中會(huì)處理
}elseif ($type==='voice') {    
      //用戶發(fā)送的是聲音 稍后的文章中會(huì)處理
}
$weixin->reply($reply);
?>

3.查詢代碼

還需要將數(shù)據(jù)庫(kù)里面的查詢結(jié)果格式化為特定的形式

代碼如下:

<?php
public function search(){
       $record=array();  //定義返回結(jié)果的數(shù)組
       $list = $this->search($this->keyword);//普通的根據(jù)關(guān)鍵詞查詢數(shù)據(jù)庫(kù)的操作  代碼就不用分享了
    if(is_array($list)&&!empty($list)){                
               foreach($list as $msg){
            $record[]=array(//以下代碼,將數(shù)據(jù)庫(kù)中查詢返回的數(shù)組格式化為微信返回消息能接收的數(shù)組形式,即title、description、picurl、url 詳見微信官方的文檔描述
                        'title' =>$msg['title'],
                        'description' =>$msg['discription'],
                        'picurl' => $msg['pic_url'],
                        'url' =>$msg['url']
                    );
        }
    }
    return $record;
}
?>

感謝各位的閱讀!關(guān)于“PHP對(duì)接微信公眾平臺(tái)消息接口開發(fā)的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI