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

1、簡介php

當用戶主動發消息給公衆號的時候(包括髮送信息、點擊自定義菜單、訂閱事件、掃描二維碼事件、支付成功事件、用戶維權),微信將會把消息數據推送給開發者,開發者在一段時間內(目前修改成48小時)能夠調用客服消息接口,經過POST一個JSON數據包來發送消息給普通用戶,在48小時內不限制發送次數。此接口主要用於客服等有人工消息處理環節的功能,方便開發者爲用戶提供更加優質的服務。html

2、思路分析mysql

官方文檔中只提供了一個發送客服消息的接口,開發者只要POST一個特定的JSON數據包便可實現消息回覆。在這裏,咱們打算作成一個簡單的平臺,能夠記錄用戶消息,而且用網頁表格的形式顯示出來,而後能夠對消息進行回覆操做。sql

首先,咱們使用數據庫記錄用戶主動發送過來的消息,而後再提取出來展現到頁面,針對該消息,進行回覆。這裏咱們只討論文本消息,關於其餘類型的消息,你們自行研究。數據庫

3、記錄用戶消息json

3.1 建立數據表api

建立一張數據表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 文件app

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

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、網頁展現用戶消息

咱們的最終效果大概以下所示,主要的工做在「信息管理中心」這塊,其餘的頁面佈局等等,不在這裏贅述了,只講解消息展現這塊。

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、消息回覆

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、測試

6.1 微信用戶發送消息

6.2 平臺消息管理

6.3 發送客服消息

再次發送客服消息

 

發送客服消息測試成功!

7、代碼獲取

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

8、總結

微信發送客服消息自己很簡單,只需POST一個JSON數據包到指定接口URL便可。這裏咱們進行了擴展,寫成一個簡單的平臺,方便企業的管理。還有不少須要補充和改進的地方,例如,記錄客服發送的消息;將相同用戶的消息記錄成一個集合;實現其餘格式的消息回覆等,有待讀者自行思考開發。

 


David Camp

  • 業務合做,請聯繫做者QQ:562866602
  • 個人微信號:mchina_tang
  • 給我寫信:mchina_tang@qq.com

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

相關文章
相關標籤/搜索