【Django】wechat登录Django站点

微信登录Django站点

class GetWeChatOauth2(View):
    """发起授权"""

    def get(self, request):
        """发起授权,重定向到二维码扫码页面"""
        return redirect("https://open.weixin.qq.com/connect/qrconnect?appid=xxxx&redirect_uri=http%3a%2f%2fwww.xxxx.com%2floginwechat&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect")

class LoginWeChat(View):
    """用户登录微信
    步骤1:扫码授权后,wechat回调地址:http://www.xxxx.com/loginwechat
            地址中包含code信息,从url中获取code值
    步骤2:通过code获得openid、access_token
    步骤3:通过openid、access_token获得用户信息,登录成功
    附加步骤:刷新access_token过期时间,默认2小时,最长30天
    """

    def get(self, request):
        # 获取用户信息
        app_id = 'xxxx'
        app_secret = 'xxxx'
        # 【步骤1】获得回调url中code值
        code = request.GET.get("code")
        if not code:
            return HttpResponse("not find code")
        # 【步骤2】:通过code获得openid、access_token
        token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code"
        # 通过code 可以获取到access_token ,但是code 只能获取道一次获取token 的时候可能要刷新,不然会获取不到token
        data = requests.get(token_url.format(app_id, app_secret, code))
        # 转为json 格式的字符串
        data = json.loads(data.content.decode("utf-8"))
        # 获取access_token
        access_token = data['access_token']
        open_id = data['openid']
        refresh_token = data['refresh_token']
        if not access_token or not open_id:
            return None  # 判断是否有token 和open_id
        # 【步骤3】:通过openid、access_token获得用户信息,登录成功
        user_url = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh-CN"
        d = requests.get(user_url.format(access_token, open_id))
        d = d.content.decode("utf-8")
        response = HttpResponse(json.dumps(d))
        # 设置cookie 将用户信息保存到cookie里面
        response.set_cookie("userinfo", json.dumps(d), max_age=7 * 24 * 3600)  # 设置过期时间7天
        # #【附加步骤】:刷新access_token过期时间,默认2小时,最长30天
        # refresh_token_url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={0}&grant_type=refresh_token&refresh_token={1}"
        # r_d = requests.get(refresh_token_url.format(app_id, refresh_token))
        # r_d = json.loads(r_d.content.decode("utf-8"))
        return response
 """
{\"openid\":\"xxx\",\"nickname\":\"Magic\",\"sex\":1,\"language\":\"zh_CN\",\"city\":\"Chengdu\",\"province\":\"Sichuan\",\"country\":\"China\",\"headimgurl\":\"http:\\/\\/thirdwx.qlogo.cn\\/mmopen\\/vi_32\\/icQYRJ7RXlLRruzkGialtKz3EI3DmKbf1nm4VCczjBQEoib79WJ4xQ2icnSfMZDfRibRPibwiaFibw5PKgHzbX6h1yZQsw\\/132\",\"privilege\":[],\"unionid\":\"xx\"}
"""

你可能感兴趣的:(【Django】wechat登录Django站点)