小程序【客服消息】開(kāi)發(fā)一 php實(shí)現(xiàn)基本回復(fù)功能(參考轉(zhuǎn))

最近在開(kāi)發(fā)微信小程序,前后端均是我一個(gè)人負(fù)責(zé),也著實(shí)受了不少苦

網(wǎng)上客服消息開(kāi)發(fā)挺多的,但是大多數(shù)說(shuō)的都不詳盡對(duì)新人來(lái)說(shuō)有很多坑,最后還是根據(jù)官方說(shuō)明文檔一步一步走下來(lái),寫(xiě)一份新人版的供大家參考,望大佬指正

注:如果要參考官方文檔的話(huà),這里有一個(gè)我推薦的閱讀順序

https://developers.weixin.qq.com/miniprogram/dev/component/contact-button.html?t=20161221

contact-button 按鈕介紹,這是入口
https://developers.weixin.qq.com/miniprogram/dev/api/custommsg/receive.html#%E8%BF%9B%E5%85%A5%E4%BC%9A%E8%AF%9D%E4%BA%8B%E4%BB%B6

然后了解用戶(hù)在客服會(huì)話(huà)中發(fā)送文本消息時(shí)產(chǎn)生的數(shù)據(jù)包結(jié)構(gòu)

https://developers.weixin.qq.com/miniprogram/dev/api/custommsg/conversation.html

最后再看咱們往客戶(hù)發(fā)送客服消息 的數(shù)據(jù)包結(jié)構(gòu)

https://developers.weixin.qq.com/miniprogram/dev/api/custommsg/material.html?t=2018518

如果有圖片消息,再看獲取素材media_id(注意:微信公眾號(hào)的media_id和小程序的media_id的獲取接口是不同的,我當(dāng)初就沒(méi)仔細(xì)看坑了我好久)

官方的客服消息分兩種

第一種是在小程序內(nèi)添加contact-button標(biāo)簽,點(diǎn)擊后會(huì)進(jìn)入到“小程序客服消息”

第二種是網(wǎng)頁(yè)版 的“客服消息”,在小程序平臺(tái)里,選擇“客服消息”,添加客服人員即可這里就不講了

網(wǎng)上資料都讓大家配“消息推送”,其實(shí)“消息推送”就是實(shí)現(xiàn)第一種“客服消息”的功能,當(dāng)你設(shè)置好“消息推送”后,你再進(jìn)入客服消息時(shí),微信后臺(tái)會(huì)自動(dòng)發(fā)送數(shù)據(jù)包到你設(shè)置的url中,咱們獲取傳過(guò)來(lái)的數(shù)據(jù)再做相應(yīng)處理即可

首先我們要配置“消息推送”,進(jìn)入小程序平臺(tái),選擇“設(shè)置”->“開(kāi)發(fā)設(shè)置”->“消息推送”->點(diǎn)擊“啟用”

image

啟用后需要填寫(xiě)url(即你要處理消息回復(fù)消息,寫(xiě)邏輯功能的地方,我習(xí)慣用php做后臺(tái)所以服務(wù)器地址是http://XXX.php),Token隨便寫(xiě)只要和你url對(duì)應(yīng)的php里的token相同即可,最后數(shù)據(jù)格式就是你希望微信后臺(tái)向你發(fā)送什么格式的數(shù)據(jù)包,個(gè)人比較喜歡json,本文也用json做例子

image

配置好后點(diǎn)擊提交,token驗(yàn)證成功即可提交成功,下方即為驗(yàn)證Token部分

$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
    
$token = TOKEN;  //TOKEN 寫(xiě)自己在微信平臺(tái)填入的token
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
    
if( $tmpStr == $signature ){
     return true;
}else{
     return false;
}

提交成功后,恭喜你離成功已經(jīng)很近了,接下來(lái)打開(kāi)url對(duì)應(yīng)文件

    define("TOKEN", "");  //填寫(xiě)自己的token
 
    if (isset($_GET['echostr'])) {          //校驗(yàn)服務(wù)器地址URL
        valid();
    }else{
        responseMsg();
    }
     function valid()
    {
        $echoStr = $_GET["echostr"];
        if(checkSignature()){
            header('content-type:text');
            echo $echoStr;
            exit;
        }else{
            echo $echoStr.'+++'.TOKEN;
            exit;
        }
    }
     function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
    
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
    
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
     function responseMsg()
    {
        $postStr = file_get_contents('php://input');   //此處推薦使用file_get_contents('php://input')獲取后臺(tái)post過(guò)來(lái)的數(shù)據(jù)
 
        if (!empty($postStr) && is_string($postStr)){
        $postArr = json_decode($postStr,true);
            if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){   //用戶(hù)發(fā)送文本消息
                $fromUsername = $postArr['FromUserName'];   //發(fā)送者openid
                $media_id = '';   //輸入想要回復(fù)的圖片消息的media_id
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"image",
                    "image"=>array("media_id"=>$media_id)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //php5.4+
                requestAPI($json);
            }elseif(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image'){ //用戶(hù)發(fā)送圖文消息
                $fromUsername = $postArr['FromUserName'];   //發(fā)送者openid
        $media_id = '';   //輸入想要回復(fù)的圖片消息的media_id
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"image",
                    "image"=>array("media_id"=>$media_id)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //php5.4以上版本才可使用
                requestAPI($json);              
            }elseif($postArr['MsgType'] == 'event' && $postArr['Event']=='user_enter_tempsession'){ //用戶(hù)進(jìn)入客服
                $fromUsername = $postArr['FromUserName'];   //此處為文字回復(fù),不同的回復(fù)方式可參考文章頂部第三個(gè)鏈接“回復(fù)客戶(hù)消息”里查看
                $content = '你好,你的專(zhuān)屬海報(bào)正在制作中,請(qǐng)稍后回復(fù)“1”獲取海報(bào)';
                $data=array(
                    "touser"=>$fromUsername,
                    "msgtype"=>"text",
                    "text"=>array("content"=>$content)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //php5.4+
                requestAPI($json);   
            }else{
                exit('error');
            }
        }else{
            echo "empty";
            exit;
        }
    }
    function requestAPI($json){
        $access_token = get_accessToken();
        /* 
         * POST發(fā)送https請(qǐng)求客服接口api
         */
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        //以'json'格式發(fā)送post的https請(qǐng)求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 發(fā)送一個(gè)常規(guī)的Post請(qǐng)求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($json)){
            curl_setopt($curl, CURLOPT_POSTFIELDS,$json);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓異常
        }
        curl_close($curl);
        if($output == 0){
            echo 'success';exit;
        }
    }       
    /* 調(diào)用微信api,獲取access_token,有效期7200s*/
    function get_accessToken(){
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx****&secret='***'; //替換成自己的小程序id和secret
    @$weixin = file_get_contents($url);
    @$jsondecode = json_decode($weixin);
    @$array = get_object_vars($jsondecode);
    $token = $array['access_token'];
    return $token;
    }

最后進(jìn)入自己的微信小程序,在需要的地方添加contact-button標(biāo)簽即可

<contact-button 
          type="default-light" 
          size="27"             
          session-from="weapp"
></contact-button>
<!--  size值18~27 session-from攜帶參數(shù) -->

這里強(qiáng)調(diào)一下,在更改后臺(tái)代碼后一定要記得先清除微信的緩存,確保完全退出小程序后再次進(jìn)入進(jìn)行測(cè)試,確保咱們的改動(dòng)可以實(shí)時(shí)更新

最后上一下效果圖,有問(wèn)題的小伙伴大家可以討論一下~( ̄▽?zhuān)?~


image

作者:取名點(diǎn)數(shù)增加的boy
原文:https://blog.csdn.net/weixin_42342572/article/details/80506303

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容