Django Wechat Api
djangowechatapi是基于wxpy和django制作的web应用
安装
-
使用
pippip install djangowechatapi -
源码安装
git clone https://github.com/Ivy-1996/wechatapi.git cd wechatapi python setup.py install
配置
-
该模块依赖
djangorestframework和django_filter,需要把他们一起注册到INSTALLED_APPS里 -
INSTALLED_APPS = [ \'django.contrib.admin\', \'django.contrib.auth\', \'django.contrib.contenttypes\', \'django.contrib.sessions\', \'django.contrib.messages\', \'django.contrib.staticfiles\', \'rest_framework\', \'django_filters\', \'wechat\', ] -
添加到urls
-
urlpatterns = [ path(\'admin/\', admin.site.urls), path(\'\', include(\'wechat.url\')) ] -
配置缓存
-
CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": f\'redis://127.0.0.1/8\', "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } -
如果使用
django默认的文件存储机制,需要在SETTINGS里面指定 -
MEDIA_PATH = os.path.join(BASE_DIR, \'media\') -
如果使用的是
mysql数据库存储,则需要制定数据库和表的编码为utf8mb4 -
执行迁移脚本
python manager.py migrate
应用接口详情
-
由于网页版微信的保密机制,无法捕捉到用户的唯一id,这里采用的是wxpy提供的puid作为用户的唯一身份标识。
-
创建微信应用:
- 命令行创建
python manager.py createwechatapp please enter the name of wechat app:<你的应用名> please enter the token of <你的应用名> app:<应用的token> create app successfuly! your app_id: <app_id> your app_secret: <app_secret> - 或者通过网页使用django-admin创建
- 命令行创建
-
获取
access_token-
所有api的默认的认证方式都是通过
access_token来实现的,access_token的有效期为2个小时(可以在settings.py里面设置ACCESS_TOKEN_EXPIRE_IN来修改默认的2个小时) -
如果你觉得
access_token不够安全,你也可以使用模块提供的SignatureAuthentication来实现实时用户认证。具体使用请参考源码。 -
获取
access_token(access_token依赖redis缓存,请确保上述配置均已配置完成)method:GETurl:/access_token?app_id=<app_id>&app_secret=<app_secret>正常情况下,会返回
{ "access_token": "ACCESS_TOKEN", "expire_in": 7200 }如果出错了
{ "errmsg": [ "无效的app" ] }
-
-
网页登陆
method:GETurl:/login?access_token=<access_token>return:json { "uuid": "wbQeNse67Q==", "status": "0", "qrcode": "https://login.weixin.qq.com/qrcode/wbQeNse67Q==" }
参数说明uuid: 登陆二维码的唯一标识status: 登陆状态qrcode: 获取登陆二维码的地址 -
登陆验证
method:GETurl:/check-login?access_token=<access_token>&uuid=<uuid>return:{ "status": "408", "alive": null, "avatar": null }status:
* 408:等待扫描登录
* 201:已扫描,但为点击确认登录(此时可以获取到用户的头像)
* 200:已扫描登录成功。avatar: 扫描用户的头像alive: 登录后为True,退出登录后为False,未登录为null如果是做成网页版登录,前端在拿到登录二维码之后可以轮询这个接口来判断用户的登录状况
-
获取好友列表
method:GETurl:/friends?access_token=<access_token>return:{ "count": 140, "next": "http://127.0.0.1:8000/friends?access_token=fc99fe6e-7771-4e22-b89d-e9827463bf65&page=4", "previous": "http://127.0.0.1:8000/friends?access_token=fc99fe6e-7771-4e22-b89d-e9827463bf65&page=2", "results": [ { "puid": "3b1b58a2", "name": "多吃点苹果