1、配置 公众号 -开发-网页服务-网页授权- 修改 网页授权获取用户基本信息 授权域名。 (注: 公众号自动回复开发,需要开启 服务器配置,单独的获取用户信息则不需要。 jssdk是 白名单授权管理。)
2、菜单 接入 : http:// XXX / user/info 访问时用户授权,授权以后跳转到 http://XXX/home?code=xxx (配置)此时再次 调用 http:// XXX / user/info 获取用户信息 放入session(供以后接口获取)
代码参考:
# setting.pyAppID = ‘‘AppSecret = ‘‘Token = ‘‘# view.py# wx.view代码from wechatpy.utils import check_signaturefrom back import settingsfrom wechatpy.exceptions import InvalidSignatureExceptionfrom django.http import HttpResponsefrom wechatpy import parse_message, create_replyfrom wechatpy.replies import BaseReplyfrom wechatpy import WeChatClientfrom wechatpy.oauth import WeChatOAuthfrom django.shortcuts import redirectimport 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 responsedef getWxClient(): return WeChatClient(settings.AppID, settings.AppSecret)def getWxUserInfo(openid): wxClient = getWxClient() wxUserInfo = wxClient.user.get(openid) return wxUserInfodef getWeChatOAuth(redirect_url): # redirect_url = "需要跳转的域名: dayu1.net/home" return WeChatOAuth(settings.AppID, settings.AppSecret, redirect_url, scope=‘snsapi_userinfo ‘)# 定义授权装饰器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@oauthdef get_wx_user_info(request): user_info = request.session.get(‘user_info‘) return HttpResponse(str(user_info))# url 配置# wx.url代码from django.urls import pathfrom . import viewsurlpatterns = [ path(‘wechat/‘, views.serve), path(‘user/info‘, views.get_wx_user_info)]