小弟需要将微信公众号接入大模型自动回复,使用https://github.com/zhayujie/chatgpt-on-wechat,记录一下实现过程和踩的坑。
一、服务器搭建
(一) 修改端口
在阿里云注册了一台服务器,由于需要能够让外网访问,故安装了nginx,默认访问80端口,但是vx公众号不能修改端口,故
# 查看80端口是否被占用
netstat -tulnp | grep :80
输出发现被nginx:master占用,故nginx默认的监听端口为80
所以需要把80端口释放出来,将nginx的监听端口改为8080:
在 Nginx 配置文件(/etc/nginx/nginx.conf
)中,将 listen
指令从 80
改为 8080
:
server {
listen 8080;
listen [::]:8080;
server_name _;
...
}
(二) 服务器端口开放
最后注意在阿里云服务器页面->网络与安全->添加入方向规则,将8080端口和80端口添加
此时,服务器相关的工作就准备好了
二、微信公众号接口配置
公众号这里需要去进行一些配置,在设置与开发->开发接口管理这里
(一) 保存开发者ID(AppID)、开发者密码(AppSecret)
(二) 账号开发信息->IP白名单中,将服务器IP加入白名单,否则无法获取Access token
(三) 接口权限->获取Access token
# 在服务器中输入下面指令发送GET请求,注意要加引号
curl "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"
# 然后返回json字段,获取access_token
{"access_token":"ACCESS_TOKEN","expires_in":7200}
(四) 进行服务器配置
1. 在服务器上编写main.py文件
# -*- coding: utf-8 -*-
# filename: main.py
import web
urls = (
'/wx', 'Handle',
)
class Handle(object):
def GET(self):
return "hello, this is handle view"
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()
python main.py 80
运行,查看网页http://服务器IP/wx是否有返回值
2. 修改main.py如下
(注意,微信官方给的实例是python2的代码,是跑不通的,我修改了一下,亲测在python3环境下可以跑通)
# -*- coding: utf-8 -*-
# filename: main.py
import web
import hashlib
urls = (
'/wx', 'Handle',
)
class Handle(object):
def GET(self):
try:
data = web.input()
if len(data) == 0:
return "hello, this is handle view"
signature = data.signature
timestamp = data.timestamp
nonce = data.nonce
echostr = data.echostr
token = "xxxxx" #请按照公众平台官网\基本配置中信息填写
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
for item in list:
sha1.update(item.encode('utf-8'))
# map(sha1.update, list)
hashcode = sha1.hexdigest()
print("handle/GET func: hashcode, signature: ", hashcode, signature)
if hashcode == signature:
return echostr
else:
return ""
except Exception as Argument:
return Argument
if __name__ == '__main__':
app = web.application(urls, globals())
app.run()
3. 在url验证窗口进行token验证
- AccessToken:即前面json返回字段的access_token
- URL:http://服务器ip/wx
- Token:自己指定,随意叫一个名字,和代码中token = "xxxxx"保持一致即可
然后python main.py 80
运行修改后的main.py,点击验证即可
4. 填写服务器配置
验证成功后,在开发接口管理->基本配置中,填写服务器配置
- URL:http://服务器ip/wx
- Token:自己指定,随意叫一个名字,和代码中token = "xxxxx"保持一致即可
- EncodingAESKey:随机生成即可
- 消息加解密方式:选明文模式即可
三、后续使用
只需要配置以下参数,即可连接公众号进行开发:
"wechatmp_token": "xxx",
"wechatmp_port": xxx,
"wechatmp_app_id": "xxx",
"wechatmp_app_secret": "xxx",
"wechatmp_aes_key": "xxx",