国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > PHP > 正文

PHP對接微信公眾平臺消息接口開發流程詳解及實例

2020-03-22 18:40:11
字體:
來源:轉載
供稿:網友
這篇文章主要介紹了PHP對接微信公眾平臺消息接口開發流程,如何使用PHP版接口操作公眾平臺消息,需要的朋友可以參考下

一、寫好接口程序

在你的服務器上上傳好一個接口程序文件內容如下:

代碼如下:

<?phpdefine("TOKEN", "weixin");//自己定義的token 就是個通信的私鑰$wechatObj = new wechatCallbackapiTest();$wechatObj->valid();//$wechatObj->responseMsg();html' target='_blank'>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一致)

PHP對接微信公眾平臺消息接口開發流程詳解及實例
三、驗證接口

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

四、開始自定義回復

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

1.封裝weixin.class.php

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

代碼如下:

<?phpclass 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;    }    //獲得用戶發過來的消息(消息內容和消息類型  )    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']);        }    }  //回復文本消息    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);    }    //根據數組參數回復圖文消息    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){        //這里是你記錄調試信息的地方  請自行完善   以便中間調試    }}?>

2.調用weixin.class.php

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

代碼如下:

<?phpinclude_once('weixin.class.php');//引用剛定義的微信消息處理類define("TOKEN", "mmhelper");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);?>

3.查詢代碼

還需要將數據庫里面的查詢結果格式化為特定的形式

代碼如下:

<?phppublic 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;}?>

以上就是PHP對接微信公眾平臺消息接口開發流程詳解及實例的詳細內容,更多請關注 其它相關文章!

鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 龙泉市| 汽车| 和平县| 繁峙县| 石狮市| 渝北区| 哈巴河县| 丹东市| 那曲县| 盖州市| 长岛县| 兰州市| 乌兰县| 嘉荫县| 安福县| 星子县| 出国| 东源县| 平乡县| 弋阳县| 积石山| 陇川县| 勃利县| 咸丰县| 灵石县| 琼海市| 沽源县| 临泉县| 合江县| 乐亭县| 东台市| 比如县| 喀什市| 南召县| 英山县| 乐平市| 金昌市| 和田市| 蓬莱市| 青田县| 荥阳市|