小程序【客服消息】開發一 php實現基本回復功能(參考轉)

最近在開發微信小程序,前后端均是我一個人負責,也著實受了不少苦

網上客服消息開發挺多的,但是大多數說的都不詳盡對新人來說有很多坑,最后還是根據官方說明文檔一步一步走下來,寫一份新人版的供大家參考,望大佬指正

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

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

然后了解用戶在客服會話中發送文本消息時產生的數據包結構

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

最后再看咱們往客戶發送客服消息 的數據包結構

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

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

官方的客服消息分兩種

第一種是在小程序內添加contact-button標簽,點擊后會進入到“小程序客服消息”

第二種是網頁版 的“客服消息”,在小程序平臺里,選擇“客服消息”,添加客服人員即可這里就不講了

網上資料都讓大家配“消息推送”,其實“消息推送”就是實現第一種“客服消息”的功能,當你設置好“消息推送”后,你再進入客服消息時,微信后臺會自動發送數據包到你設置的url中,咱們獲取傳過來的數據再做相應處理即可

首先我們要配置“消息推送”,進入小程序平臺,選擇“設置”->“開發設置”->“消息推送”->點擊“啟用”

image

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

image

配置好后點擊提交,token驗證成功即可提交成功,下方即為驗證Token部分

$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
    
$token = TOKEN;  //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;
}

提交成功后,恭喜你離成功已經很近了,接下來打開url對應文件

    define("TOKEN", "");  //填寫自己的token
 
    if (isset($_GET['echostr'])) {          //校驗服務器地址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')獲取后臺post過來的數據
 
        if (!empty($postStr) && is_string($postStr)){
        $postArr = json_decode($postStr,true);
            if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){   //用戶發送文本消息
                $fromUsername = $postArr['FromUserName'];   //發送者openid
                $media_id = '';   //輸入想要回復的圖片消息的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'){ //用戶發送圖文消息
                $fromUsername = $postArr['FromUserName'];   //發送者openid
        $media_id = '';   //輸入想要回復的圖片消息的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'){ //用戶進入客服
                $fromUsername = $postArr['FromUserName'];   //此處為文字回復,不同的回復方式可參考文章頂部第三個鏈接“回復客戶消息”里查看
                $content = '你好,你的專屬海報正在制作中,請稍后回復“1”獲取海報';
                $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發送https請求客服接口api
         */
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        //以'json'格式發送post的https請求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 發送一個常規的Post請求
        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;
        }
    }       
    /* 調用微信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;
    }

最后進入自己的微信小程序,在需要的地方添加contact-button標簽即可

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

這里強調一下,在更改后臺代碼后一定要記得先清除微信的緩存,確保完全退出小程序后再次進入進行測試,確保咱們的改動可以實時更新

最后上一下效果圖,有問題的小伙伴大家可以討論一下~( ̄▽ ̄~)~


image

作者:取名點數增加的boy
原文:https://blog.csdn.net/weixin_42342572/article/details/80506303

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。