前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >小程序客服功能开发之对接闲聊机器人

小程序客服功能开发之对接闲聊机器人

作者头像
许坏
修改2019-08-07 19:23:59
1.5K0
修改2019-08-07 19:23:59
举报
文章被收录于专栏:宅机吧宅机吧

button组件设置open-type="contact"支持打开客服会话,但实际上很多人都不知道此功能如何使用,没必要去申请第三方平台,也不用认证企业号,什么类型的小程序都行,几行代码搞定

《实际功能展示》

搜索小程序:【宅梦网】-->【个人中心】-->【寂寞宅妹】

上面演示了实际效果,接下来我们就来看看实现原理:

首先,配置一下后台:

然后上php代码:

代码语言:javascript
复制
<?php
  
header('Content-type:text');
define("TOKEN", "zhai-78");//这里这个到时候你配置小程序后台消息推送需要

$wechatObj = new wechatCallbackapiTest();
if (isset($_GET['echostr'])) {
    $wechatObj->valid();
}else{
    $wechatObj->responseMsg();    
}  
class wechatCallbackapiTest
{
  
//第一次验证服务器用
public function valid()
{
        $echoStr = $_GET["echostr"];
if($this->checkSignature()){
            header('content-type:text');
echo $echoStr;
exit;
        }
    }
private 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 responseMsg()
{  
      
        $postStr = file_get_contents('php://input');  
if (!empty($postStr) && is_string($postStr)){
      $postArr = json_decode($postStr,true);
if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text'){   
                $fromUsername = $postArr['FromUserName'];                       
               /*$allUrl = 'http://你的闲聊接口地址'.$postArr['Content'];  //调用自动回复接口,推荐腾讯闲聊机器人
                $content = file_get_contents($allUrl);*/                    //获取回复内容
                $contentt='hello world';//配置好自动回复接口后就把这个注释掉
                $data=array(
"touser"=>$fromUsername,
"msgtype"=>"text",
"text"=>array("content"=>$content)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  //PHP版本5.4以上   
$this->post2($json);
            }else if(!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image'){ //用户发送图文消息
                $fromUsername =$postArr['FromUserName'];  //发送者openid
        $media_id = '';   //输入想要回复的图片消息的media_id
                $data=array(
"touser"=>$fromUsername,
"msgtype"=>"image",
"image"=>array("media_id"=>$media_id)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);  
$this->post2($json);        
            }else if($postArr['MsgType'] == 'event' && $postArr['Event']=='user_enter_tempsession'){ //用户进入客服
                $fromUsername = $postArr['FromUserName'];                  //用户第一次进入客服系统
                $content = '欢迎欢迎,我是宅小妹,我好喜欢和你聊天哟~~';
                $data=array(
"touser"=>$fromUsername,
"msgtype"=>"text",
"text"=>array("content"=>$content)
                );
                $json = json_encode($data,JSON_UNESCAPED_UNICODE);
$this->post2($json);  
            }else{
exit('error');
            }
        }else{
exit;
        }
    }
       
//获取access_token,不建议此方法,建议使用我之前教的存储后调用,参考文章https://mp.weixin.qq.com/s/qB_LJ7oiHJWiUHCwRyxV7Q
public function Curl() { 
      $appid="你的小程序appid"; 
      $appsecret="你的appsecret"; 
      $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$appsecret; //替换成自己的小程序id和secret
      $result = file_get_contents($url);
      $res = json_decode($result,true);   //json字符串转数组
return $res['access_token']; 
    }

//向客户端发送回复消息
public function post2($data){
        $access_token = $this->Curl();//原始方法获取Token
       // $file = fopen("token.txt","r");//获取token
       // $access_token = fread($file, 512); //这里是我推荐的办法获取token的代码
      $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        $opts = array('http' =>
array(
'method'  => 'POST',
'header'  => 'Content-type: text',
'content' => $data
                      )
        );
        $context = stream_context_create($opts);
        $result = file_get_contents($url, false, $context);
return $result;
    }
  
}
?>

强调一下,token值获取之后建议进行保存,每日似乎是限额2000次,对于客服机器人接口来说,次数太少了,所以推荐下面这种办法:access_token获取和缓存进行2小时刷新 但是很多时候它的token值不到2小时就失效了,具体说明:彻底解决access_token有效时间不稳定问题 多次实践,我推荐设置10分钟刷新一次,目前本人是如此配置的。

此外,聊天机器人地址:

https://ai.qq.com/product/nlpchat.shtml

我已经把源代码写好了,自己把appkey和appid改成你在腾讯AI那里申请的即可,都是傻瓜化操作了

代码语言:javascript
复制
<?php

//接收问题值
$word=$_SERVER["QUERY_STRING"];
$word = urldecode($word);
//机器人配置
$appkey = '你的key';
$app_id ='你的id';

function doHttpPost($url, $params)
{
    $curl = curl_init();
    $response = false;
do
    {
        curl_setopt($curl, CURLOPT_URL, $url);
        $head = array(
'Content-Type: application/x-www-form-urlencoded'
        );
        curl_setopt($curl, CURLOPT_HTTPHEADER, $head);
        $body = http_build_query($params);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_NOBODY, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $response = curl_exec($curl);
if ($response === false)
        {
            $response = false;
break;
        }
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($code != 200)
        {
            $response = false;
break;
        }
    } while (0);
    curl_close($curl);
return $response;
}
function getReqSign($params, $appkey)
{
    ksort($params);
    $str = '';
foreach ($params as $key => $value)
    {
if ($value !== '')
        {
            $str .= $key . '=' . urlencode($value) . '&';
        }
    }
    $str .= 'app_key=' . $appkey;
    $sign = strtoupper(md5($str));
return $sign;
}

$params = array(
'app_id'     => $app_id,
'session'    => '10000',
'question'   => $word,
'time_stamp' => strval(time()),
'nonce_str'  => strval(rand()),
'sign'       => '',
);
$params['sign'] = getReqSign($params, $appkey);
$url = 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_textchat';
$result = json_decode(doHttpPost($url, $params),true)["data"]["answer"]; 
echo $result;

?>

按照上面我的步骤配置,百分百可以用的,没啥其他的,特别要注意的就是token那个玩意儿,这在小程序服务器端是必不可少的,无可跳过的坑。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-07-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 宅机吧 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云开发 CloudBase
云开发(Tencent CloudBase,TCB)是腾讯云提供的云原生一体化开发环境和工具平台,为200万+企业和开发者提供高可用、自动弹性扩缩的后端云服务,可用于云端一体化开发多种端应用(小程序、公众号、Web 应用等),避免了应用开发过程中繁琐的服务器搭建及运维,开发者可以专注于业务逻辑的实现,开发门槛更低,效率更高。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档