使用ThinkPHP为微信公众号接入ChatGPT智能客服的注意事项

时间:23-05-11 栏目:网站开发 作者:admin 评论:0 点击: 918 次

作为国内知名的PHP开发框架,ThinkPHP在Web应用的开发和维护中有着广泛使用。而微信公众号作为一种强大的客户服务平台,它经常被用于企业内部客服,并且需要实现智能化的自动应答。ChatGPT是一个非常流行的开源项目,旨在提供端到端的生成式对话模型。 最近在处理一个问题时遇到过一些坑,为了让大家少走弯路,所以,这里将介绍使用ThinkPHP为微信公众号接入ChatGPT智能客服的注意事项。

由于公众号接入第三方的接口步骤比较多,而其他的问题在网上又有比较多的介绍,在此我就重点讲下和ChatGPT接入有关的部分。

因为ChatGPT思考问题有时时间比较长,公众号又要求5秒内要返回响应,虽然openai API支持响应流形式的输出,但公众号却不支持此类数据的接收。所以我们要用到被动回复和主动推送两类消息接口。

1、确定微信公众号的响应机制

在使用微信公众号进行聊天时,我们需要确定微信公众号的响应机制。 主要有两种不同的响应机制可供选择,即被动回复和主动推送。被动回复是指微信公众号主动推送消息并进行回复,而主动推送则是指在用户发送消息到微信公众号后,微信公众号将调用我们编写的API接口进行主动推送。

2、确定消息响应方案

之前 就因为不了解掉坑里了,现在了解了chatGPT的特点和微信公众号的响应机制后,我们就来制定消息响应方案:
第一步:接口收到公众号用户消息后,将请求chatGPT接口的工作添加到延时任务,后使用被动回复给用户推送一条消息:小凡AI寻找答案中......
第二步:延时任务请求chatGPT接口,返回结果 后向公众号主动推送回复内容(chatGPT数据流的方式分多段推送效果可能会更好这里暂没有作深入研究)。

3、具体实现代码


//接收公众号消息后被动处理
public function server()
{
self::$site_id = input('site', 1, 'intval');
$wxmpSetting = getSystemSetting(self::$site_id, 'wxmp');
$config = [
'app_id' => $wxmpSetting['appid'] ?? '',
'secret' => $wxmpSetting['appsecret'] ?? '',
'token' => $wxmpSetting['token'] ?? '',
'aes_key' => $wxmpSetting['aes_key'] ?? '',
'response_type' => 'array'
];

$app = \EasyWeChat\Factory::officialAccount($config);
$app->server->push(function ($message) use ($app) {
switch ($message['MsgType']) {
case 'event':
return $this->handleEvent($app, $message);
break;
case 'text':
return $this->handleText($app, $message);;
break;
case 'image':
return '收到图片消息';
break;
case 'voice':
return '收到语音消息';
break;
case 'video':
return '收到视频消息';
break;
case 'location':
return '收到坐标消息';
break;
case 'link':
return '收到链接消息';
break;
case 'file':
return '收到文件消息';
break;
}
});

$response = $app->server->serve();
ob_clean();
$response->send();
}
//以客服消息接口延迟发送的聊天结果
public function server2()
{

$openid = input('openid', '', 'trim');
$msg = input('msg', '', 'trim');

ignore_user_abort(1);//忽略浏览器端关闭中断,继续执行后面的任务
self::$site_id = input('site', 1, 'intval');
$wxmpSetting = getSystemSetting(self::$site_id, 'wxmp');
$config = [
'app_id' => $wxmpSetting['appid'] ?? '',
'secret' => $wxmpSetting['appsecret'] ?? '',
'token' => $wxmpSetting['token'] ?? '',
'aes_key' => $wxmpSetting['aes_key'] ?? '',
'response_type' => 'array'
];

$app = \EasyWeChat\Factory::officialAccount($config);

try{

self::$user = Db::name('user')
->where([
['site_id', '=', self::$site_id],
['openid_mp', '=', $openid]
])
->find();

$msg = $this->sendText($msg);//调用GPT 返回数据
$msg = str_replace('
',"\r\n",$msg);
$msg = str_replace(' '," ",$msg);
} catch (\Exception $e) {
$msg = $this->outError($e->getMessage());
}

$app->customer_service->message($msg)->to($openid)->send(); //调用客服消息接口,主动推送消息给公众号
}
//延时任务处理函数
private function offline_task($path, $post)
{
$url = $_SERVER['REQUEST_SCHEME'].'://127.0.0.1'.$path;
$headers=array(
'host: '.$_SERVER['HTTP_HOST']
);
$openid = $post['openid'];
$msg = $post['msg'];

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if($post){
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post));
}
// curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);//如果 要用信息流,启用此代码
// curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 10);
curl_exec($ch);
$info = curl_getinfo($ch);
if($info['appconnect_time_us']){

}

}

//处理公众号文本消息
private function handleText($app, $message)
{
//仅特定文本才触发chatGPT回复
if(strpos($message['Content'],'小凡')!==false){
$openid = $message['FromUserName'];

self::$user = Db::name('user')
->where([
['site_id', '=', self::$site_id],
['openid_mp', '=', $openid]
])
->find();

$use_offline = true;//消息回复机制开关
if($use_offline){//::分两次返回的方式
$msg = $message['Content'];
$path = '/web.php/wxmp/server2/site/'. self::$site_id
.'?&openid='.$openid.'&msg='.urlencode($msg);
$data=array(
'openid'=>$openid,
'msg'=>$msg,
);
$this->offline_task($path,$data); //添加延时任务,访问并忽略
//先返回提示
return '小凡AI寻找答案中......';
}else{//::直接返回结果的方式
try{
$msg = $this->sendText($message['Content']);
} catch (\Exception $e) {
return $this->outError($e->getMessage());
}
return $msg;
}

}
$msg = '您可以点击下方的AI中文、AI绘图按钮,即可开始与它交流。';
if($message['Content']=='chatgpt'){
$msg .= "\r\n".'我们将在下个月抽取幸运用户赠送年卡会员,有抽中会反馈您';
}elseif($message['Content']=='h5'){
$msg .= "\r\n".'PC网页端网址:';
$msg .= "\r\n".'https://ai.fan-b.com/';
}else{
$msg .= "\r\n".'回复{chatgpt}我们将抽取幸运用户赠送年卡会员。';
$msg .= "\r\n".'回复{h5}获取PC网页端网址。';
//
}
return $msg;
// return '请在网页端使用对话服务!';
}

 

4、特别要注意的是:

a、消息回复机制开关如果不启用被动回复和主动推送分离,很有可能用户在公众号发送消息后收不到任何回复
b、使用CURLOPT_TIMEOUT_MS而不是CURLOPT_TIMEOUT,因为后者最少单位是秒,会显得回复消息有点慢。
参数时间根据实际情况自己设置,之前使用的网站对外域名方式导致DNS解析花费时间太多,提前中断就导致即使有 ignore_user_abort(1);设置也无效。
后面改成请求127.0.0.1的方式并添加host头,省去了DNS查询时间,以下是失败与成功的两条curl info 记录可以对比
namelookup_time_us 是dns查询时间
appconnect_time_us 是与http服务器连接成功后开始计时

curl info:{"url":"////msg=%E5%B0%8F%E5%87%A1%EF%BC%8C%E4%BD%A0%E7%9C%9F%E6%BC%82%E4%BA%AE","content_type":null,"http_code":0,"header_size":0,"request_size":0,"filetime":-1,"ssl_verify_result":1,"redirect_count":0,"total_time":0.010175,"namelookup_time":0.003474,"connect_time":0.004057,"pretransfer_time":0,"size_upload":0,"size_download":0,"speed_download":0,"speed_upload":0,"download_content_length":-1,"upload_content_length":-1,"starttransfer_time":0,"redirect_time":0,"redirect_url":"","primary_ip":"47.52.209.54","certinfo":[],"primary_port":443,"local_ip":"172.31.219.81","local_port":53286,"http_version":0,"protocol":2,"ssl_verifyresult":0,"scheme":"HTTPS","appconnect_time_us":0,"connect_time_us":4057,"namelookup_time_us":3474,"pretransfer_time_us":0,"redirect_time_us":0,"starttransfer_time_us":0,"total_time_us":10175}

server_msg curl info:{"url":"////msg=%E5%B0%8F%E5%87%A1%EF%BC%8C%E4%BD%A0%E8%83%BD%E5%81%9A%E4%BB%80%E4%B9%88%EF%BC%9F","content_type":null,"http_code":0,"header_size":0,"request_size":210,"filetime":-1,"ssl_verify_result":0,"redirect_count":0,"total_time":0.050246,"namelookup_time":0.005377,"connect_time":0.005991,"pretransfer_time":0.014426,"size_upload":0,"size_download":0,"speed_download":0,"speed_upload":0,"download_content_length":-1,"upload_content_length":-1,"starttransfer_time":0,"redirect_time":0,"redirect_url":"","primary_ip":"47.52.209.54","certinfo":[],"primary_port":443,"local_ip":"172.31.219.81","local_port":54272,"http_version":0,"protocol":2,"ssl_verifyresult":0,"scheme":"HTTPS","appconnect_time_us":14397,"connect_time_us":5991,"namelookup_time_us":5377,"pretransfer_time_us":14426,"redirect_time_us":0,"starttransfer_time_us":0,"total_time_us":50246}

5、实现效果

 

1541683773947_.pic

5、体验方法

或小程序:小凡ai,

访问网址:https://o0b.cn/4HvSC2

搜索公众号:凡邦数据 ,

 

 

声明: 本文由( admin )原创编译,转载请保留链接: 使用ThinkPHP为微信公众号接入ChatGPT智能客服的注意事项

使用ThinkPHP为微信公众号接入ChatGPT智能客服的注意事项:等您坐沙发呢!

发表评论


------====== 本站公告 ======------
联系信息:
电话:19970108113(微信同号) QQ:3142401606
支付宝:https://me.alipay.com/lxq73061
相关插件程序等信息均会在站内发布,敬请关注。

读者排行