微信小程序---客服消息接口调用,拿来即用
如果本文对你有用,请爱心点个赞,提高排名,帮助更多的人。谢谢大家!❤
如果解决不了,可以在文末进群交流。
如果对你有帮助的话麻烦点个【推荐】~最好还可以follow一下我的GitHub~感谢观看!
在页面中使用
<button open-type="contact" />可以显示进入客服会话按钮。<button open-type="contact" class='contactService' session-from="{{'https://https://mp.weixin.qq.com/debug/wxadoc/introduction/image/x11.png'}}" hover-class="none">联系客服获取二维码</button>当用户在客服会话发送消息(或进行某些特定的用户操作引发的事件推送时),微信服务器会将消息(或事件)的数据包(JSON或者XML格式)POST请求开发者填写的URL。开发者收到请求后可以使用发送客服消息接口进行异步回复。
微信服务器在将用户的消息发给小程序的开发者服务器地址(开发设置处配置)后,微信服务器在五秒内收不到响应会断掉连接,并且重新发起请求,总共重试三次,如果在调试中,发现用户无法收到响应的消息,可以检查是否消息处理超时。关于重试的消息排重,有msgid的消息推荐使用msgid排重。事件类型消息推荐使用FromUserName + CreateTime 排重。
服务器收到请求必须做出下述回复,这样微信服务器才不会对此作任何处理,并且不会发起重试,否则,将出现严重的错误提示。详见下面说明:
1、直接回复success(推荐方式)
2、直接回复空串(指字节长度为0的空字符串,而不是结构体中content字段的内容为空)
一旦遇到以下情况,微信都会在小程序会话中,向用户下发系统提示“该小程序客服暂时无法提供服务,请稍后再试”:
1、开发者在5秒内未回复任何内容
2、开发者回复了异常数据
消息推送配置
填写服务器配置
-

点击设置

消息推送配置

消息推送配置
验证消息的确来自微信服务器

开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上,GET请求携带参数如下表所示:
点击提交认证的时候,需要调用到如下方法,进行校验,校验通过,代表配置成功
- //实例化对象
$vyuanCustom = new vyuanCustomAPI();
//注意:第一步验证时打开,验证完成之后就可以注释了
$vyuanCustom->isValid();
以下,贴上项目中的部分代码,供大家参考,不懂地方可以进入微信技术交流群,如果过期可加我微信:mengyilingjian。

详细代码解析
<?php
//服务器配置接口地址
define("TOKEN", "vyuan"); //定义token
define("WXPAY_APPID", '***********'); //替换为自己的APPID
define("WXPAY_APPSECRET", '******************'); //替换为自己的APPSECRET
class vyuanCustomAPI{
//用于小程序后台第一步验证返回,验证成功后便可注释
public function isValid(){
$echoStr = $_GET["echostr"];
if ($this->checkSignature()) {
echo $echoStr;
exit;
}
}
//官方提供的验证demo
public 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;
}
}
//发送消息接口调用
public function send($data){
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->getAccessToken();
$data = urldecode(json_encode($data));
$this->curl_post($url,$data);
}
//xml数据转数组
public function xml2Array($contents = NULL, $encoding = 'UTF-8', $get_attributes = 1, $priority = 'tag'){
if (!$contents){
return array();
}
if (!function_exists('xml_parser_create')){
return array ();
}
$parser = xml_parser_create('');
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $encoding);
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, trim($contents), $xml_values);
xml_parser_free($parser);
if (!$xml_values) return array();
$xml_array = array ();
$parents = array ();
$opened_tags = array ();
$arr = array ();
$current = & $xml_array;
$repeated_tag_index = array ();
foreach ($xml_values as $data){
unset ($attributes, $value);
extract($data);
$result = array ();
$attributes_data = array ();
if (isset ($value)){
if ($priority == 'tag')
$result = trim($value);
else
$result['value'] = trim($value);
}
if (isset ($attributes) && $get_attributes) {
foreach ($attributes as $attr => $val){
if ($priority == 'tag')
$attributes_data[$attr] = $val;
else
$result['attr'][$attr] = $val;
}
}
if ($type == "open"){
$parent[$level -1] = & $current;
if (!is_array($current) || (!in_array($tag, array_keys($current)))) {
$current[$tag] = $result;
if ($attributes_data)
$current[$tag . '_attr'] = $attributes_data;
$repeated_tag_index[$tag . '_' . $level] = 1;
if (isset($tag) && $tag && isset($current[$tag])) {
$current = & $current[$tag];
}
}else{
if (isset ($current[$tag][0])){
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
$repeated_tag_index[$tag . '_' . $level]++;
}else{
$current[$tag] = array (
$current[$tag],
$result
);
$repeated_tag_index[$tag . '_' . $level] = 2;
if (isset ($current[$tag . '_attr'])){
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset ($current[$tag . '_attr']);
}
}
$last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
$current = & $current[$tag][$last_item_index];
}
}elseif ($type == "complete"){
if (!isset ($current[$tag])){
$current[$tag] = $result;
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' && $attributes_data) {
$current[$tag . '_attr'] = $attributes_data;
}
}else{
if (isset ($current[$tag][0]) && is_array($current[$tag])) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
if ($priority == 'tag' && $get_attributes && $attributes_data) {
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
$repeated_tag_index[$tag . '_' . $level]++;
}else{
$current[$tag] = array (
$current[$tag],
$result
);
$repeated_tag_index[$tag . '_' . $level] = 1;
if ($priority == 'tag' && $get_attributes) {
if (isset ($current[$tag . '_attr']) && is_array($current[$tag])){
$current[$tag]['0_attr'] = $current[$tag . '_attr'];
unset ($current[$tag . '_attr']);
}
if ($attributes_data){
$current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
}
}
$repeated_tag_index[$tag . '_' . $level]++;
}
}
}elseif ($type == 'close'){
$current = & $parent[$level -1];
}
}
return ($xml_array);
}
//获取accesstoken
public function getAccessToken() {
$tokenFile = "access_token.txt";
$data = json_decode(file_get_contents($tokenFile,FILE_USE_INCLUDE_PATH));
//accesstoken有效期是7200秒,这里用到的文件缓存
//注意:文件权限问题
if (!$data->expire_time || $data->expire_time < time()) {
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".WXPAY_APPID."&secret=".WXPAY_APPSECRET;
$res = json_decode(file_get_contents($url));
if($res) {
$arr = array();
$access_token = $res->access_token;
$arr['expire_time'] = time() + 7000;
$arr['access_token'] = $access_token;
$fp = fopen($tokenFile, "w");
fwrite($fp, json_encode($arr));
fclose($fp);
}
} else {
$access_token = $data->access_token;
}
return $access_token;
}
//post发送json数据
public function curl_post($url,$post_data){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$res = curl_exec($ch);
if(!$res){
throw new Exception('发送消息失败:'.curl_error($ch));
}
curl_close($ch);
}
//进入客服窗口,如果需要主动发起客服消息类型为图片,则需要获取media_id
public function getMedia_id($imageurl){
$foldername = date('Y-m-d',time()); //定义文件夹目录
$path = __DIR__.'/static/image/Code/'.$foldername.'/'; //服务器存放目录
if(!is_dir($path)){
mkdir($path,0777,true);
}else{
chmod($path,0777);
}
//下载二维码到本地
$imageInfo = $this -> getImage($imageurl,$path);
$imageurl = $imageInfo['save_path'];
$post_url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={$this->getAccessToken()}&type=image";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['media'=>'@'.$imageurl]);
$res = curl_exec($ch);
$a = json_decode($res);
$media_id = $a->media_id;
return $media_id;
}
//下载二维码
public function getImage($url,$save_dir,$filename='',$type=0){
if(trim($url)==''){
return array('file_name'=>'','save_path'=>'','error'=>1);
}
if(trim($filename)==''){//保存文件名
$ext=strrchr($url,'.');
if($ext!='.gif'&&$ext!='.jpg'){
return array('file_name'=>'','save_path'=>'','error'=>3);
}
$filename=time().$ext;
}
//获取远程文件所采用的方法
if($type){
$ch=curl_init();
$timeout=5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$img=curl_exec($ch);
curl_close($ch);
}else{
ob_start();
readfile($url);
$img=ob_get_contents();
ob_end_clean();
}
//下载文件
$fp2=@fopen($save_dir.$filename,'a');
fwrite($fp2,$img);
fclose($fp2);
unset($img,$url);
return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
}
};
//实例化对象
$vyuanCustom = new vyuanCustomAPI();
//注意:第一步验证时打开,验证完成之后就可以注释了
$vyuanCustom->isValid();
if($vyuanCustom->checkSignature() === true){
$xmlstring = file_get_contents("php://input");
$accept_info = $vyuanCustom->xml2Array($xmlstring)['xml'];
if($accept_info){
$ToUserName = $accept_info['ToUserName'];
$FromUserName = $accept_info['FromUserName'];
$CreateTime = $accept_info['CreateTime'];
$MsgType = $accept_info['MsgType'];
$data = array();
if($MsgType == 'text'){//接收文本
$Content = $accept_info['Content'];//文本内容
$data['touser'] = $FromUserName;
if($Content === '图文') {
$data['msgtype'] = 'link';
$data['link']['title'] = urlencode('文章标题');
$data['link']['description'] = urlencode('好文章要分享');
$data['link']['url'] = 'https://segmentfault.com';
$data['link']['thumb_url'] = 'https://static.segmentfault.com/v-5a7c12fe/global/img/logo-b.svg';
}else if($Content === '1'){
$data['msgtype'] = 'image';
$data['image']['media_id'] = 'q3oQpLPWOIB50tCKdR510qeNIGEQd9A0Ku7DJJmsTsXVeQZqq0sUMK2gbUyJZsYn';
$data['image']['picurl'] = 'this is image';
}else if($Content === '2'){
$data['msgtype'] = 'text';
$data['text']['content'] = urlencode('你好');//urlencode 解决中文乱码问题
}else{
$data['msgtype'] = 'text';
$data['text']['content'] = urlencode('对不起,我不知道您在说什么....');//urlencode 解决中文乱码问题
}
$vyuanCustom->send($data);exit;
}else if($MsgType === 'image') {//接收图片
}else if($MsgType === 'event') {//进入客服窗口事件
$Event = $accept_info['Event'];
$SessionFrom = $accept_info['SessionFrom']; //得到开发者在客服会话按钮设置的session-from属性
$media_id = $vyuanCustom -> getMedia_id($SessionFrom);
if($Event == 'user_enter_tempsession') {
$data['touser'] = $FromUserName;
if(!$media_id){
//红娘二维码不为空,发送二维码
$data['msgtype'] = 'image';
$data['image']['media_id'] = $media_id;
//$data['image']['media_id'] = 'D6SA5xGFDlrxspT2LovHD2gbMHrUjhcji7B6WUXZ2lG7rhWi4K8ExT0_6FF4uvJY';
$data['image']['picurl'] = 'this is image';
}else{
//红娘二维码为空,则发送文字
$data['msgtype'] = 'text';
$data['text']['content'] = urlencode('您好,请回复1获取我的微信');//urlencode 解决中文乱码问题
}
$vyuanCustom->send($data);exit;
}
}
echo '<xml><ToUserName><![CDATA['.$FromUserName.']]></ToUserName><FromUserName><![CDATA['.$ToUserName.']]></FromUserName><CreateTime>'.$CreateTime.'</CreateTime><MsgType><![CDATA[transfer_customer_service]]></MsgType></xml>';
}
}
微信小程序---客服消息接口调用,拿来即用的更多相关文章
- 微信小程序客服消息使用指南
客服消息使用指南 为丰富小程序的服务能力,提高服务质量,微信为小程序提供客服消息能力,以便小程序用户可以方便快捷地与小程序服务提供方进行沟通. 功能介绍 用户可使用小程序客服消息功能,与小程序的客服人 ...
- 微信小程序客服消息开发实战:实时在手机上接收小程序客服消息通知,以及在手机上回复
在微信小程序开发中,可以非常方便的集成客服功能,只需要一行代码便可以将用户引导至客服会话界面.这行代码就是: <button open-type="contact" bind ...
- 微信小程序客服消息使用
客服消息使用 为丰富小程序的服务能力,提高服务质量,微信为小程序提供客服消息能力,以便小程序用户可以方便快捷地与小程序服务提供方进行沟通. xiaokefu.com.cn 功能介绍 用户可使用小程序客 ...
- 微信小程序客服消息实时通知之最佳实践
我们做微信小程序开发的都知道,只要在小程序页面中添加如下代码即可进入小程序的客服会话界面: <button open-type="contact" >联系我们</ ...
- 微信小程序客服消息新增临时素材接口java实现
今天想在微信小程序的客服信息窗口里回复用户一个图片信息,发现还需要上传素材,但是微信文档的上传临时素材接口写的模模糊糊,无奈去百度,网上清一色的PHP实现方式,难道我穿越了?PHP已经把java给超越 ...
- 微信小程序 客服自动回复图片
产品需求是,在客服对话框里,发送特定的文字,回复我们的二维码: 小城程开发完成后,这个自动回复图片的功能就摆在了眼前.刚开始我们想到的是:在线客服功能的设置里设置好自动回复的图片,但是目前设置不支持自 ...
- 微信小程序客服系统
微信公众平台 点击 客服 添加 微信文档-接收消息和事件 在页面中使用 第三方客服系统 芝麻小客服 填写对应的 appid && AppSecret 等信息 微信文档-接收消息和事 ...
- Embed image in a <button> element 微信小程序 客服按钮
html - Embed image in a <button> element - Stack Overflow https://stackoverflow.com/questions/ ...
- 小程序客服下发消息禁止后 session from 还有用吗?
文章概要 1. 小程序下发政策调整分析 2. session from 数据还传到底三方了没? 1. 小程序下发政策调整分析 小程序客服功能下发策略调整 ...
随机推荐
- Jenkins 设置 源码库浏览器
玩转Jenkins - 源码库浏览器功能如何使用 - 简书https://www.jianshu.com/p/22f72effb4ef Jenkins上踩过的那些坑 - 简书https://www.j ...
- Nginx 必须知道哪些事?
Nginx(发音同engine x)是一个异步框架的 Web 服务器,也可以用作反向代理,负载平衡器 和 HTTP 缓存.该软件由 Igor Sysoev 创建,并于2004年首次公开发布.同名公司成 ...
- 【转载】 tensorflow的单层静态与动态RNN比较
原文地址: https://www.jianshu.com/p/1b1ea45fab47 yanghedada -------------------------------------------- ...
- Linux云主机(离线)搭建本地yum源
下载CentOS镜像 http://mirror.nsc.liu.se/centos-store/7.3.1611/isos/x86_64/ 离线yum源的配置 1.上传下载的镜像源iso 2.挂载i ...
- Spring MVC -- 转换器和格式化
在Spring MVC -- 数据绑定和表单标签库中我们已经见证了数据绑定的威力,并学习了如何使用表单标签库中的标签.但是,Spring的数据绑定并非没有任何限制.有案例表明,Spring在如何正确绑 ...
- 单例设计模式代码-bxy
struct ConnectInfo { const QObject *sender; //发送者 const char *signal_str; //发送信号 const QObject *reci ...
- [LeetCode] 369. Plus One Linked List 链表加一运算
Given a non-negative number represented as a singly linked list of digits, plus one to the number. T ...
- [LeetCode] 407. Trapping Rain Water II 收集雨水 II
Given an m x n matrix of positive integers representing the height of each unit cell in a 2D elevati ...
- Linux学习-文件基础权限
文件基本权限 drwxr-xr-x 第一个字符表示文件类型 d:表示是一个目录.-:表示这是一个普通的文件.l: 表示这是一个符号链接文件,实际上它指向另一个文件.b.c:分别表示区块设备和其他的外围 ...
- 20191213-RF中报告打不开提示Opening Robot Framework report failed
配置好Jenkins的RF框架后跑了一次autotest发现哦豁report打不开,网上找了一堆方法都是只能临时解决,重启后又失效了.现在给出临时解决方案和永久解决方案 首先错误信息如下: 临时解决 ...