button组件设置open-type="contact"支持打开客服会话,但实际上很多人都不知道此功能如何使用,没必要去申请第三方平台,也不用认证企业号,什么类型的小程序都行,几行代码搞定
《实际功能展示》
搜索小程序:【宅梦网】-->【个人中心】-->【寂寞宅妹】
上面演示了实际效果,接下来我们就来看看实现原理:
首先,配置一下后台:
然后上php代码:
<?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那里申请的即可,都是傻瓜化操作了
<?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那个玩意儿,这在小程序服务器端是必不可少的,无可跳过的坑。