天天看點

微信公衆平台開發(十二) 發送客服消息

一、簡介

當使用者主動發消息給公衆号的時候(包括發送資訊、點選自定義菜單、訂閱事件、掃描二維碼事件、支付成功事件、使用者維權),微信将會把消息資料推送給開發者,開發者在一段時間内(目前修改為48小時)可以調用客服消息接口,通過POST一個JSON資料包來發送消息給普通使用者,在48小時内不限制發送次數。此接口主要用于客服等有人工消息處理環節的功能,友善開發者為使用者提供更加優質的服務。

二、思路分析

官方文檔中隻提供了一個發送客服消息的接口,開發者隻要POST一個特定的JSON資料包即可實作消息回複。在這裡,我們打算做成一個簡單的平台,可以記錄使用者消息,并且用網頁表格的形式顯示出來,然後可以對消息進行回複操作。

首先,我們使用資料庫記錄使用者主動發送過來的消息,然後再提取出來展示到頁面,針對該消息,進行回複。這裡我們隻讨論文本消息,關于其他類型的消息,大家自行研究。

三、記錄使用者消息

3.1 建立資料表

建立一張資料表tbl_customer 來記錄使用者消息。

--
-- 表的結構 `tbl_customer`
--

CREATE TABLE `tbl_customer` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '//消息ID',
  `from_user` char(50) NOT NULL COMMENT '//消息發送者',
  `message` varchar(200) NOT NULL COMMENT '//消息體',
  `time_stamp` datetime NOT NULL COMMENT '//消息發送時間',
  PRIMARY KEY (`id`),
  KEY `from_user` (`from_user`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;      

3.2 建立sql.func.php 檔案

建立 _query($_sql) {} 函數,來執行INSERT 操作。

function _query($_sql){
    if(!$_result = mysql_query($_sql)){
        exit('SQL執行失敗'.mysql_error());
    }
    return $_result;
}      

3.3 建立記錄消息的函數檔案record_message.func.inc.php

//引入資料庫處理函數
require_once 'sql.func.php';

function _record_message($fromusername,$keyword,$date_stamp){
    //調用_query()函數
    _query("INSERT INTO tbl_customer(from_user,message,time_stamp) VALUES('$fromusername','$keyword','$date_stamp')");
}      

3.4 處理并記錄文本消息

A. 引入回複文本的函數檔案,引入記錄消息的函數檔案

//引入回複文本的函數檔案
require_once 'responseText.func.inc.php';
//引入記錄消息的函數檔案
require_once 'record_message.func.inc.php';      

B. 記錄消息入資料庫,并傳回給使用者剛才發送的消息,在這裡,你可以修改成其他的文本,比如:“你好,消息已收到,我們會盡快回複您!” 等等。

//處理文本消息函數
    public function handleText($postObj)
    {
        //擷取消息發送者,消息體,時間戳
        $fromusername = $postObj->FromUserName;
        $keyword = trim($postObj->Content);
        $date_stamp = date('Y-m-d H:i:s');

        if(!empty( $keyword ))
        {
            //調用_record_message()函數,記錄消息入資料庫
            _record_message($fromusername,$keyword,$date_stamp);
            
            $contentStr = $keyword;
            //調用_response_text()函數,回複發送者消息
            $resultStr = _response_text($postObj,$contentStr);
            echo $resultStr;
        }else{
            echo "Input something...";
        }
    }      

四、網頁展示使用者消息

我們的最終效果大概如下所示,主要的工作在“資訊管理中心”這塊,其他的頁面布局等等,不在這裡贅述了,隻講解消息展示這塊。

微信公衆平台開發(十二) 發送客服消息

4.1 具體實施

引入資料庫操作檔案,執行分頁子產品,執行資料庫查詢,将查詢出來的結果賦給$_result 供下面使用。

//引入資料庫操作檔案
require_once 'includes/sql.func.php';

//分頁子產品
global $_pagesize,$_pagenum;
_page("SELECT id FROM tbl_customer",15);        //第一個參數擷取總條數,第二個參數,指定每頁多少條
$_result = _query("SELECT * FROM tbl_customer ORDER BY id DESC LIMIT $_pagenum,$_pagesize");      

将$_result 周遊出來,依次插入表格中。

<form>
    <table cellspacing="1">
        <tr><th>消息ID</th><th>發送者</th><th>消息體</th><th>消息時間</th><th>操作</th></tr>
        <?php 
            while(!!$_rows = _fetch_array_list($_result)){
                $_html = array();
                $_html['id'] = $_rows['id'];
                $_html['from_user'] = $_rows['from_user'];
                $_html['message'] = $_rows['message'];
                $_html['time_stamp'] = $_rows['time_stamp'];
        ?>
        <tr><td><?php echo $_html['id']?></td><td><?php echo $_html['from_user']?></td><td><?php echo $_html['message']?></td><td><?php echo $_html['time_stamp']?></td><td><a href="reply.php?fromusername=<?php echo $_html['from_user']?>&message=<?php echo $_html['message']?>"><input type="button" value="回複" /></a></td></tr>
        <?php 
            }
            _free_result($_result);
        ?>
    </table>
</form>      

說明:在每條消息後,都有一個“回複”操作,點選該按鈕,向reply.php檔案中傳入fromusername和使用者發送的消息,為回複使用者消息做準備。

五、消息回複

5.1 建立客服消息回複函數檔案customer.php

微信發送客服消息的接口URL如下:

https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN      

需要POST的JSON資料包格式如下:

{
    "touser":"OPENID",
    "msgtype":"text",
    "text":
    {
         "content":"Hello World"
    }
}      

是以,根據上面的提示,我們編寫處理函數 _reply_customer($touser,$content),調用的時候,傳入touser和需要回複的content,即可發送客服消息。

function _reply_customer($touser,$content){
    
    //更換成自己的APPID和APPSECRET
    $APPID="wxef78f22f877db4c2";
    $APPSECRET="3f3aa6ea961b6284057b8170d50e2048";
    
    $TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$APPSECRET;
    
    $json=file_get_contents($TOKEN_URL);
    $result=json_decode($json);
    
    $ACC_TOKEN=$result->access_token;
    
    $data = '{
        "touser":"'.$touser.'",
        "msgtype":"text",
        "text":
        {
             "content":"'.$content.'"
        }
    }';
    
    $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$ACC_TOKEN;
    
    $result = https_post($url,$data);
    $final = json_decode($result);
    return $final;
}

function https_post($url,$data)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url); 
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    if (curl_errno($curl)) {
       return 'Errno'.curl_error($curl);
    }
    curl_close($curl);
    return $result;
}      

下面,我們就将上面寫好的函數引入到消息回複頁面,實作發送客服消息的功能。

5.2 點選“回複”按鈕,帶上fromusername和message參數跳轉到reply.php。

微信公衆平台開發(十二) 發送客服消息

5.3 reply.php 頁面顯示

微信公衆平台開發(十二) 發送客服消息

5.4 reply.php檔案分析

//引入回複消息的函數檔案
require_once '../customer.php';      

form表單送出到relpy.php本身,帶有action=relpy.

<form method="post" action="reply.php?action=reply">
    <dl>
        <dd><strong>收件人:</strong><input type="text" name="tousername" class="text" value="<?php echo $from_username?>" /></dd>
        <dd><strong>原消息:</strong><input type="text" name="message" class="text" value="<?php echo $message?>" /></dd>
        <dd><span><strong>内 容:</strong></span><textarea rows="5" cols="34" name="content"></textarea></dd>
        <dd><input type="submit" class="submit" value="回複消息" /></dd>
    </dl>
</form>      

action=reply 動作處理。

if($_GET['action'] == "reply"){
    $touser = $_POST['tousername'];
    $content = $_POST['content'];
    $result = _reply_customer($touser, $content);
    
    if($result->errcode == "0"){
        _location('消息回複成功!', 'index.php');
    }
}      

說明:POST方式擷取touser, content,然後調用_reply_customer($touser, $content)方法處理,處理成功,則彈出“消息回複成功!”,然後跳轉到index.php頁面,完成發送客服消息過程。

六、測試

6.1 微信使用者發送消息

微信公衆平台開發(十二) 發送客服消息

6.2 平台消息管理

微信公衆平台開發(十二) 發送客服消息

6.3 發送客服消息

微信公衆平台開發(十二) 發送客服消息
微信公衆平台開發(十二) 發送客服消息

再次發送客服消息

微信公衆平台開發(十二) 發送客服消息
微信公衆平台開發(十二) 發送客服消息

發送客服消息測試成功!

七、代碼擷取

https://files.cnblogs.com/mchina/customer.rar

八、總結

微信發送客服消息本身很簡單,隻需POST一個JSON資料包到指定接口URL即可。這裡我們進行了擴充,寫成一個簡單的平台,友善企業的管理。還有很多需要補充和改進的地方,例如,記錄客服發送的消息;将相同使用者的消息記錄成一個集合;實作其他格式的消息回複等,有待讀者自行思考開發。

David Camp

  • 業務合作,請聯系作者QQ:562866602
  • 我的微信号:mchina_tang
  • 給我寫信:[email protected]

我們永遠相信,分享是一種美德 | We Believe, Great People Share Knowledge...

繼續閱讀