> php教程 > php手册 > 微信公众平台开发(十二) 发送客服消息

微信公众平台开发(十二) 发送客服消息

WBOY
풀어 주다: 2016-06-13 09:35:48
원래의
1015명이 탐색했습니다.

当用户主动发消息给公众号的时候(包括发送信息、点击自定义菜单、订阅事件、扫描二维码事件、支付成功事件、用户维权),微信将会把消息数据推送给开发者,开发者在一段时间内(目前修改为48小时)可以调用客服消息接口,通过POST一个JSON数据包来发送消息给普通用户,在48小时内不限制发送次数。此接口主要用于客服等有人工消息处理环节的功能,方便开发者为用户提供更加优质的服务。

官方文档中只提供了一个发送客服消息的接口,开发者只要POST一个特定的JSON数据包即可实现消息回复。在这里,我们打算做成一个简单的平台,可以记录用户消息,并且用网页表格的形式显示出来,然后可以对消息进行回复操作。

首先,我们使用数据库记录用户主动发送过来的消息,然后再提取出来展示到页面,针对该消息,进行回复。这里我们只讨论文本消息,关于其他类型的消息,大家自行研究。

3.1 创建数据表

创建一张数据表tbl_customer 来记录用户消息。

<span --
--</span><span  表的结构 `tbl_customer`</span><span 
--
</span>
<span CREATE</span> <span TABLE</span><span  `tbl_customer` (
  `id` </span><span bigint</span>(<span 20</span>) unsigned <span NOT</span> <span NULL</span> AUTO_INCREMENT COMMENT <span '</span><span //消息ID</span><span '</span><span ,
  `from_user` </span><span char</span>(<span 50</span>) <span NOT</span> <span NULL</span> COMMENT <span '</span><span //消息发送者</span><span '</span><span ,
  `message` </span><span varchar</span>(<span 200</span>) <span NOT</span> <span NULL</span> COMMENT <span '</span><span //消息体</span><span '</span><span ,
  `time_stamp` </span><span datetime</span> <span NOT</span> <span NULL</span> COMMENT <span '</span><span //消息发送时间</span><span '</span><span ,
  </span><span PRIMARY</span> <span KEY</span><span  (`id`),
  </span><span KEY</span><span  `from_user` (`from_user`)
) ENGINE</span><span =</span>MyISAM  <span DEFAULT</span> CHARSET<span =</span>utf8 ;
로그인 후 복사

3.2 创建sql.func.php 文件

创建 _query($_sql) {} 函数,来执行INSERT 操作。

<span function</span> _query(<span $_sql</span><span ){
    </span><span if</span>(!<span $_result</span> = <span mysql_query</span>(<span $_sql</span><span )){
        </span><span exit</span>('SQL执行失败'.<span mysql_error</span><span ());
    }
    </span><span return</span> <span $_result</span><span ;
}</span>
로그인 후 복사

<span //</span><span 引入数据库处理函数</span>
<span require_once</span> 'sql.func.php'<span ;

</span><span function</span> _record_message(<span $fromusername</span>,<span $keyword</span>,<span $date_stamp</span><span ){
    </span><span //</span><span 调用_query()函数</span>
    _query("INSERT INTO tbl_customer(from_user,message,time_stamp) VALUES('<span $fromusername</span>','<span $keyword</span>','<span $date_stamp</span>')"<span );
}</span>
로그인 후 복사

3.4 处理并记录文本消息

A. 引入回复文本的函数文件,引入记录消息的函数文件

<span //</span><span 引入回复文本的函数文件</span>
<span require_once</span> 'responseText.func.inc.php'<span ;
</span><span //</span><span 引入记录消息的函数文件</span>
<span require_once</span> 'record_message.func.inc.php';
로그인 후 복사

B. 记录消息入数据库,并返回给用户刚才发送的消息,在这里,你可以修改成其他的文本,比如:“你好,消息已收到,我们会尽快回复您!” 等等。

    <span //</span><span 处理文本消息函数</span>
    <span public</span> <span function</span> handleText(<span $postObj</span><span )
    {
        </span><span //</span><span 获取消息发送者,消息体,时间戳</span>
        <span $fromusername</span> = <span $postObj</span>-><span FromUserName;
        </span><span $keyword</span> = <span trim</span>(<span $postObj</span>-><span Content);
        </span><span $date_stamp</span> = <span date</span>('Y-m-d H:i:s'<span );

        </span><span if</span>(!<span empty</span>( <span $keyword</span><span  ))
        {
            </span><span //</span><span 调用_record_message()函数,记录消息入数据库</span>
            _record_message(<span $fromusername</span>,<span $keyword</span>,<span $date_stamp</span><span );
            
            </span><span $contentStr</span> = <span $keyword</span><span ;
            </span><span //</span><span 调用_response_text()函数,回复发送者消息</span>
            <span $resultStr</span> = _response_text(<span $postObj</span>,<span $contentStr</span><span );
            </span><span echo</span> <span $resultStr</span><span ;
        }</span><span else</span><span {
            </span><span echo</span> "Input something..."<span ;
        }
    }</span>
로그인 후 복사

我们的最终效果大概如下所示,主要的工作在“信息管理中心”这块,其他的页面布局等等,不在这里赘述了,只讲解消息展示这块。

4.1 具体实施

引入数据库操作文件,执行分页模块,执行数据库查询,将查询出来的结果赋给$_result 供下面使用。

<span //</span><span 引入数据库操作文件</span>
<span require_once</span> 'includes/sql.func.php'<span ;

</span><span //</span><span 分页模块</span>
<span global</span> <span $_pagesize</span>,<span $_pagenum</span><span ;
_page(</span>"SELECT id FROM tbl_customer",15);        <span //</span><span 第一个参数获取总条数,第二个参数,指定每页多少条</span>
<span $_result</span> = _query("SELECT * FROM tbl_customer ORDER BY id DESC LIMIT <span $_pagenum</span>,<span $_pagesize</span>");
로그인 후 복사

将$_result 遍历出来,依次插入表格中。

<span <</span><span form</span><span ></span>
    <span <</span><span table </span><span cellspacing</span><span ="1"</span><span ></span>
        <span <</span><span tr</span><span ><</span><span th</span><span ></span>消息ID<span </</span><span th</span><span ><</span><span th</span><span ></span>发送者<span </</span><span th</span><span ><</span><span th</span><span ></span>消息体<span </</span><span th</span><span ><</span><span th</span><span ></span>消息时间<span </</span><span th</span><span ><</span><span th</span><span ></span>操作<span </</span><span th</span><span ></</span><span tr</span><span ></span>
        <span <?</span><span 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'];
        </span><span ?></span>
        <span <</span><span tr</span><span ><</span><span td</span><span ></span><span <?</span><span php echo $_html['id']</span><span ?></span><span </</span><span td</span><span ><</span><span td</span><span ></span><span <?</span><span php echo $_html['from_user']</span><span ?></span><span </</span><span td</span><span ><</span><span td</span><span ></span><span <?</span><span php echo $_html['message']</span><span ?></span><span </</span><span td</span><span ><</span><span td</span><span ></span><span <?</span><span php echo $_html['time_stamp']</span><span ?></span><span </</span><span td</span><span ><</span><span td</span><span ><</span><span a </span><span href</span><span ="reply.php?fromusername=<?php echo $_html['from_user']?>&message=<?php echo $_html['message']?>"</span><span ><</span><span input </span><span type</span><span ="button"</span><span  value</span><span ="回复"</span> <span /></</span><span a</span><span ></</span><span td</span><span ></</span><span tr</span><span ></span>
        <span <?</span><span php 
            }
            _free_result($_result);
        </span><span ?></span>
    <span </</span><span table</span><span ></span>
<span </</span><span form</span><span ></span>
로그인 후 복사

说明:在每条消息后,都有一个“回复”操作,点击该按钮,向reply.php文件中传入fromusername和用户发送的消息,为回复用户消息做准备。

5.1 创建客服消息回复函数文件customer.php

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

https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN
로그인 후 복사

需要POST的JSON数据包格式如下:

<span {
    "touser":"OPENID",
    "msgtype":"text",
    "text":
    {
         "content":"Hello World"
    }
}</span>
로그인 후 복사

所以,根据上面的提示,我们编写处理函数 _reply_customer($touser,$content),调用的时候,传入touser和需要回复的content,即可发送客服消息。

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

</span><span function</span> https_post(<span $url</span>,<span $data</span><span )
{
    </span><span $curl</span> =<span  curl_init();
    curl_setopt(</span><span $curl</span>, CURLOPT_URL, <span $url</span><span ); 
    curl_setopt(</span><span $curl</span>, CURLOPT_SSL_VERIFYPEER, <span FALSE</span><span );
    curl_setopt(</span><span $curl</span>, CURLOPT_SSL_VERIFYHOST, <span FALSE</span><span );
    curl_setopt(</span><span $curl</span>, CURLOPT_POST, 1<span );
    curl_setopt(</span><span $curl</span>, CURLOPT_POSTFIELDS, <span $data</span><span );
    curl_setopt(</span><span $curl</span>, CURLOPT_RETURNTRANSFER, 1<span );
    </span><span $result</span> = curl_exec(<span $curl</span><span );
    </span><span if</span> (curl_errno(<span $curl</span><span )) {
       </span><span return</span> 'Errno'.curl_error(<span $curl</span><span );
    }
    curl_close(</span><span $curl</span><span );
    </span><span return</span> <span $result</span><span ;
}</span>
로그인 후 복사

下面,我们就将上面写好的函数引入到消息回复页面,实现发送客服消息的功能。

5.2 点击“回复”按钮,带上fromusername和message参数跳转到reply.php。

5.3 reply.php 页面显示

5.4 reply.php文件分析

<span //</span><span 引入回复消息的函数文件</span>
<span require_once</span> '../customer.php';
로그인 후 복사

form表单提交到relpy.php本身,带有action=relpy.

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

action=reply 动作处理。

<span if</span>(<span $_GET</span>['action'] == "reply"<span ){
    </span><span $touser</span> = <span $_POST</span>['tousername'<span ];
    </span><span $content</span> = <span $_POST</span>['content'<span ];
    </span><span $result</span> = _reply_customer(<span $touser</span>, <span $content</span><span );
    
    </span><span if</span>(<span $result</span>->errcode == "0"<span ){
        _location(</span>'消息回复成功!', 'index.php'<span );
    }
}</span>
로그인 후 복사

说明:POST方式获取touser, content,然后调用_reply_customer($touser, $content)方法处理,处理成功,则弹出“消息回复成功!”,然后跳转到index.php页面,完成发送客服消息过程。

6.1 微信用户发送消息

6.2 平台消息管理

6.3 发送客服消息

再次发送客服消息

 

发送客服消息测试成功!

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

微信发送客服消息本身很简单,只需POST一个JSON数据包到指定接口URL即可。这里我们进行了扩展,写成一个简单的平台,方便企业的管理。还有很多需要补充和改进的地方,例如,记录客服发送的消息;将相同用户的消息记录成一个集合;实现其他格式的消息回复等,有待读者自行思考开发。

 


David Camp

  • 业务合作,请联系作者QQ:562866602
  • 我的微信号:mchina_tang
  • 给我写信:mchina_tang@qq.com

我们永远相信,分享是一种美德 | We Believe, Great People Share Knowledge...

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿