Django+wechatpy接入微信公众平台以及授权登录
-
确定Django环境可以正常运行,环境搭建见:Linux 搭建Nginx+uwsgi+Django环境
-
安装 wechatpy[cryptography]
sudo pip3 install wechatpy[cryptography]
-
修改settings.py
-
接入微信公众号的连接去掉csrf验证,详情参考:解决Django+Vue前后端分离的跨域问题及关闭csrf验证的后半部分
-
在settings.py 加入微信公众号配置
AppID = '' AppSecret = '' Token = ''
-
-
接入
-
Django接入微信公众号代码
# wx.view代码 from wechatpy.utils import check_signature from back import settings from wechatpy.exceptions import InvalidSignatureException from django.http import HttpResponse from wechatpy import parse_message, create_reply from wechatpy.replies import BaseReply from wechatpy import WeChatClient from wechatpy.oauth import WeChatOAuth from django.shortcuts import redirect import wx.wechat as wx_wechat # 连接微信公众号的方法 def serve(request): # GET 方式用于微信公众平台绑定验证 if request.method == 'GET': signature = request.GET.get('signature', '') timestamp = request.GET.get('timestamp', '') nonce = request.GET.get('nonce', '') echo_str = request.GET.get('echostr', '') try: check_signature(settings.Token, signature, timestamp, nonce) except InvalidSignatureException: echo_str = '错误的请求' response = HttpResponse(echo_str) else: msg = parse_message(request.body) msg_dict = msg.__dict__['_data'] # print(msg.id, msg.source, msg.create_time, msg.type, msg.target, msg.time, msg.__dict__['_data']['Event'], '====') if msg.type == 'text': pass elif msg.type == 'event': if msg_dict['Event'] == 'subscribe': # 关注后 将获取的用户的信息保存到数据库 wx_wechat.subscribe(getWxUserInfo(msg.source)) elif msg_dict['Event'] == 'unsubscribe': # 取关后,将用户的关注状态更改为 未关注 wx_wechat.unsubscribe(msg.source) else: pass response = HttpResponse('', content_type="application/xml") return response def getWxClient(): return WeChatClient(settings.AppID, settings.AppSecret) def getWxUserInfo(openid): wxClient = getWxClient() wxUserInfo = wxClient.user.get(openid) return wxUserInfo def getWeChatOAuth(redirect_url): return WeChatOAuth(settings.AppID, settings.AppSecret, redirect_url) # 定义授权装饰器 def oauth(method): def warpper(request): if request.session.get('user_info', None) is None: code = request.GET.get('code', None) wechat_oauth = getWeChatOAuth(request.get_raw_uri()) url = wechat_oauth.authorize_url if code: try: wechat_oauth.fetch_access_token(code) user_info = wechat_oauth.get_user_info() except Exception as e: print(str(e)) # 这里需要处理请求里包含的 code 无效的情况 # abort(403) else: request.session['user_info'] = user_info else: return redirect(url) return method(request) return warpper @oauth def get_wx_user_info(request): user_info = request.session.get('user_info') return HttpResponse(str(user_info))
# wx.url代码 from django.urls import path from . import views urlpatterns = [ path('wechat/', views.serve), path('user/info', views.get_wx_user_info) ]
这样等后台配置完毕后,就可以通过访问get_wx_user_info方法来获取当前授权登录的用户的信息
-
微信后台设置
-
如需转载请注明出处:https://www.cnblogs.com/zhuchenglin/p/10755547.html