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

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

Jun 13, 2016 am 09:35 AM
aspnet software programming

当用户主动发消息给公众号的时候(包括发送信息、点击自定义菜单、订阅事件、扫描二维码事件、支付成功事件、用户维权),微信将会把消息数据推送给开发者,开发者在一段时间内(目前修改为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 ;
Copy after login

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>
Copy after login

<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>
Copy after login

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';
Copy after login

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>
Copy after login

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

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>");
Copy after login

将$_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>
Copy after login

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

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

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

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

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

<span {
    "touser":"OPENID",
    "msgtype":"text",
    "text":
    {
         "content":"Hello World"
    }
}</span>
Copy after login

所以,根据上面的提示,我们编写处理函数 _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>
Copy after login

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

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

5.3 reply.php 页面显示

5.4 reply.php文件分析

<span //</span><span 引入回复消息的函数文件</span>
<span require_once</span> '../customer.php';
Copy after login

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>
Copy after login

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>
Copy after login

说明: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...

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The combination of Vue.js and ASP.NET provides tips and suggestions for performance optimization and expansion of web applications. The combination of Vue.js and ASP.NET provides tips and suggestions for performance optimization and expansion of web applications. Jul 29, 2023 pm 05:19 PM

The combination of Vue.js and ASP.NET provides tips and suggestions for performance optimization and expansion of web applications. With the rapid development of web applications, performance optimization has become an indispensable and important task for developers. As a popular front-end framework, Vue.js combined with ASP.NET can help us achieve better performance optimization and expansion. This article will introduce some tips and suggestions, and provide some code examples. 1. Reduce HTTP requests The number of HTTP requests directly affects the loading speed of web applications. pass

MySQL connection pool usage and optimization techniques in ASP.NET programs MySQL connection pool usage and optimization techniques in ASP.NET programs Jun 30, 2023 pm 11:54 PM

How to correctly use and optimize the MySQL connection pool in ASP.NET programs? Introduction: MySQL is a widely used database management system that features high performance, reliability, and ease of use. In ASP.NET development, using MySQL database for data storage is a common requirement. In order to improve the efficiency and performance of database connections, we need to correctly use and optimize the MySQL connection pool. This article will introduce how to correctly use and optimize the MySQL connection pool in ASP.NET programs.

Ten ways generative AI will change software development Ten ways generative AI will change software development Mar 11, 2024 pm 12:10 PM

Translator | Reviewed by Chen Jun | Chonglou In the 1990s, when people mentioned software programming, it usually meant choosing an editor, checking the code into the CVS or SVN code base, and then compiling the code into an executable file. Corresponding integrated development environments (IDEs) such as Eclipse and Visual Studio can integrate programming, development, documentation, construction, testing, deployment and other steps into a complete software development life cycle (SDLC), thus improving the work of developers. efficiency. In recent years, popular cloud computing and DevSecOps automation tools have improved developers' comprehensive capabilities, making it easier for more enterprises to develop, deploy and maintain software applications. Today, generative AI is the next generation development

How to reconnect to MySQL in ASP.NET program? How to reconnect to MySQL in ASP.NET program? Jun 29, 2023 pm 02:21 PM

How to reconnect to MySQL in ASP.NET program? In ASP.NET development, it is very common to use the MySQL database. However, due to network or database server reasons, the database connection may sometimes be interrupted or time out. In this case, in order to ensure the stability and reliability of the program, we need to re-establish the connection after the connection is disconnected. This article will introduce how to reconnect MySQL connections in ASP.NET programs. To reference the necessary namespaces first, reference them at the head of the code file

The combination of Vue.js and ASP.NET enables the development and deployment of enterprise-level applications The combination of Vue.js and ASP.NET enables the development and deployment of enterprise-level applications Jul 29, 2023 pm 02:37 PM

The combination of Vue.js and ASP.NET enables the development and deployment of enterprise-level applications. In today's rapidly developing Internet technology field, the development and deployment of enterprise-level applications has become more and more important. Vue.js and ASP.NET are two technologies widely used in front-end and back-end development. Combining them can bring many advantages to the development and deployment of enterprise-level applications. This article will introduce how to use Vue.js and ASP.NET to develop and deploy enterprise-level applications through code examples. First, we need to install

How to correctly configure and use MySQL connection pool in ASP.NET program? How to correctly configure and use MySQL connection pool in ASP.NET program? Jun 29, 2023 pm 12:56 PM

How to correctly configure and use MySQL connection pool in ASP.NET program? With the development of the Internet and the increase in data volume, the demand for database access and connections is also increasing. In order to improve the performance and stability of the database, connection pooling has become an essential technology. This article mainly introduces how to correctly configure and use the MySQL connection pool in ASP.NET programs to improve the efficiency and response speed of the database. 1. The concept and function of connection pooling. Connection pooling is a technology that reuses database connections. At the beginning of the program,

What are the built-in objects in aspnet? What are the built-in objects in aspnet? Nov 21, 2023 pm 02:59 PM

The built-in objects in ASP.NET include "Request", "Response", "Session", "Server", "Application", "HttpContext", "Cache", "Trace", "Cookie" and "Server.MapPath": 1. Request, indicating the HTTP request issued by the client; 2. Response: indicating the HTTP response returned by the web server to the client, etc.

Recommended configuration for ASP.NET development using Visual Studio on Linux Recommended configuration for ASP.NET development using Visual Studio on Linux Jul 06, 2023 pm 08:45 PM

Overview of the recommended configuration for using Visual Studio for ASP.NET development on Linux: With the development of open source software and the popularity of the Linux operating system, more and more developers are beginning to develop ASP.NET on Linux. As a powerful development tool, Visual Studio has always occupied a dominant position on the Windows platform. This article will introduce how to configure VisualStudio for ASP.NE on Linux

See all articles