组团学

微信公众号-网页授权

阅读 (463820)

一、授权需求

26e8823638a02a81bc3f77f28efdd447.jpg

需求: 登陆主页后展示用户名,用户名使用用户的微信名

project/settings.py

TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "template")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]

template/index.html

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> </head> <body> <h1>sunck is a good man</h1> <p>欢迎:{{name}}</p> </body> </html>

myApp/views.py

def index(request): data = { "name": request.session.get("name", "游客") } return render(request, "index.html", data)

ef1a448a537f9954dc40c250358d0fa2.jpg

二、授权原理

流程:

  1. 设置网页授权回调域名
  2. 用户同意授权获取code
  3. 通过code换取网页授权access_token
  4. 刷新access_token(如果需要)
  5. 拉取用户信息(需scope为 snsapi_userinfo)

1、设置网页授权回调域名:

在微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的“开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头

授权回调域名配置规范为全域名,比如需要网页授权的域名为:www.qq.com,配置以后此域名下面的页面http://www.qq.com/music.html 、 http://www.qq.com/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq.com 、 http://music.qq.com 、 http://qq.com 无法进行OAuth2.0鉴权

如果公众号登录授权给了第三方开发者来进行管理,则不必做任何设置,由第三方代替公众号实现网页授权即可

截屏2020051909_34_30.png

截屏2020051909_34_40.png

2、用户同意授权获取code:

在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口后,默认拥有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开如下页面:https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirec

参数 说明
appid 公众号的唯一标识
redirect_uri 授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理
response_type 返回类型,请填写code
scope 应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
state 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
#wechat_redirect 无论直接打开还是做页面302重定向时候,必须带此参数

如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE

  • snsapi_base

    https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxffde55b11cc79754&redirect_uri=http%3A//39.107.226.105/empower&response_type=code&scope=snsapi_base&state=1#wechat_redirec

    截屏2020051909.52.17.png

    微信扫描二维码:

5170eea1e88d868ba9db4b57552aaf06.jpg

  • snsapi_userinfo

    https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxffde55b11cc79754&redirect_uri=http%3A//39.107.226.105/empower&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirec

    截屏2020051909.52.37.png

    微信扫描二维码:

176c0c3bdf9e4642fa8083e6289ded95.jpg

5170eea1e88d868ba9db4b57552aaf069853305.jpg

3、通过code换取网页授权access_token:

首先请注意,这里通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token(该access_token用于调用其他接口)不同。公众号可通过下述接口来获取网页授权access_token。如果网页授权的作用域为snsapi_base,则本步骤中获取到网页授权access_token的同时,也获取到了openid,snsapi_base式的网页授权流程即到此为止

尤其注意:由于公众号的secret和获取到的access_token安全级别都非常高,必须只保存在服务器,不允许传给客户端。后续刷新access_token、通过access_token获取用户信息等步骤,也必须从服务器发起

获取code后,请求以下链接获取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

参数 是否必须 说明
appid 公众号的唯一标识
secret 公众号的appsecret
code 填写第一步获取的code参数
grant_type 填写为authorization_code

正确返回的JSON数据包:

{ "access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
属性 说明
access_token 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
expires_in access_token接口调用凭证超时时间,单位(秒)
refresh_token 用户刷新access_token
openid 用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID
scope 用户授权的作用域,使用逗号(,)分隔

关于网页授权access_token和普通access_token的区别:

  • 微信网页授权是通过OAuth2.0机制实现的,在用户授权给公众号后,公众号可以获取到一个网页授权特有的接口调用凭证(网页授权access_token),通过网页授权access_token可以进行授权后接口调用,如获取用户基本信息
  • 其他微信接口,需要通过基础支持中的“获取access_token”接口来获取到的普通access_token调用

错误时微信会返回JSON数据包:

{"errcode":40029,"errmsg":"invalid code"}

4、刷新access_token(如果需要):

由于access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新,refresh_token有效期为30天,当refresh_token失效之后,需要用户重新授权

请求方法

获取第二步的refresh_token后,请求以下链接获取access_token: https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

参数 是否必须 说明
appid 公众号的唯一标识
grant_type 填写为refresh_token
refresh_token 填写通过access_token获取到的refresh_token参数

正确时返回的JSON数据包

{ "access_token":"ACCESS_TOKEN", "expires_in":7200, "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
参数 说明
access_token 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
expires_in access_token接口调用凭证超时时间,单位(秒)
refresh_token 用户刷新access_token
openid 用户唯一标识
scope 用户授权的作用域,使用逗号(,)分隔

错误时微信会返回JSON数据包:

{"errcode":40029,"errmsg":"invalid code"}

5、拉取用户信息(需scope为 snsapi_userinfo):

请求方法

http:GET(请使用https协议) https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

参数 说明
access_token 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
openid 用户的唯一标识
lang 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语

正确时返回的JSON数据包

{ "openid":" OPENID", "nickname": NICKNAME, "sex":"1", "province":"PROVINCE", "city":"CITY", "country":"COUNTRY", "headimgurl": "http://thirdwx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46", "privilege":[ "PRIVILEGE1" "PRIVILEGE2" ], "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL" }
参数 描述
openid 用户的唯一标识
nickname 用户昵称
sex 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
province 用户个人资料填写的省份
city 普通用户个人资料填写的城市
country 国家,如中国为CN
headimgurl 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效
privilege 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
unionid 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段

错误时微信会返回JSON数据包

{"errcode":40003,"errmsg":" invalid openid "}

检验授权凭证(access_token)是否有效

请求方法

http:GET(请使用https协议) https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID

参数 说明
access_token 网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同
openid 用户的唯一标识

正确的JSON返回结果

{ "errcode":0,"errmsg":"ok"}

错误时的JSON

{ "errcode":40003,"errmsg":"invalid openid"}

代码示例

myApp/urls.py

from django.urls import path, re_path from myApp import views urlpatterns = [ path(r'index/', views.index), path(r'weixin/', views.weixin), path(r'access/', views.access), path(r'menu/', views.menu), path(r'dlmenu/', views.menu), path(r'empower/', views.empower), ]

myApp/views.py

from django.shortcuts import render, HttpResponse, redirect from django.views.decorators.csrf import csrf_exempt import hashlib import xmltodict import time import json import requests from myApp.accessToken import AccessToken def index(request): pass def responseXML(ToUserName, FromUserName, MsgType, **kwargs): pass @csrf_exempt def weixin(request): pass def access(request): pass def menu(request): pass def dlmenu(request): pass def empower(request): #获得授权书 code = request.GET.get("code") if not code: return HttpResponse("您未授权,无法获取用户信息") #获取access_token和openid url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"%("wxffde55b11cc79754", "84e86527f090d6238ea1c0b96f5fc753", code) res = requests.get(url) resDict = json.loads(res.content) access_token = resDict.get("access_token") if access_token: # 获取用户信息 url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"%(access_token, resDict.get("openid")) ret = requests.get(url) retDict = json.loads(ret.content) print("----------------------------") print(retDict) print("----------------------------") return HttpResponse("获取用户信息成功") else: return HttpResponse("获取access_token失败")

三、登陆主页获取用户信息

project/settings.py

SESSION_ENGINE = "django.contrib.sessions.backends.cache"

myApp/urls.py

from django.urls import path, re_path from myApp import views urlpatterns = [ path(r'index/', views.index), path(r'weixin/', views.weixin), path(r'access/', views.access), path(r'menu/', views.menu), path(r'dlmenu/', views.menu), path(r'empower/', views.empower), path(r'auth/', views.auth), ]

myApp/views.py

from django.shortcuts import render, HttpResponse, redirect from django.views.decorators.csrf import csrf_exempt import hashlib import xmltodict import time import json import requests from myApp.accessToken import AccessToken def index(request): pass def responseXML(ToUserName, FromUserName, MsgType, **kwargs): pass @csrf_exempt def weixin(request): pass def access(request): pass def menu(request): access_toke = AccessToken.getAccessToken("client_credential", "wxffde55b11cc79754", "84e86527f090d6238ea1c0b96f5fc753") url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s"%access_toke menu_data = { "button": [ { "type": "click", "name": "sunck", "key": "V1001_SUNCK" }, { "type": "view", "name": "主页", "url": "http://39.107.226.105/auth/" }, { "name": "佳丽", "sub_button": [ { "type": "click", "name": "林志玲", "key": "V1002_MASSAGE_BEAUTIFUL01" }, { "type": "click", "name": "范冰冰", "key": "V1002_MASSAGE_BEAUTIFUL02" }, { "type": "click", "name": "关之琳", "key": "V1002_MASSAGE_BEAUTIFUL03" }, { "type": "view", "name": "更多佳丽", "url": "http://www.baidu.com/" } ] } ] } data = json.dumps(menu_data, ensure_ascii=False).encode() res = requests.post(url, data, "json") resDict = json.loads(res.content) if resDict.get("errcode") == 0: return HttpResponse("菜单修改成功") else: return HttpResponse("菜单修改失败") def dlmenu(request): pass def empower(request): #获得授权书 code = request.GET.get("code") if not code: return HttpResponse("您未授权,无法获取用户信息") #获取access_token和openid url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"%("wxffde55b11cc79754", "84e86527f090d6238ea1c0b96f5fc753", code) res = requests.get(url) resDict = json.loads(res.content) access_token = resDict.get("access_token") if access_token: # 获取用户信息 url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"%(access_token, resDict.get("openid")) ret = requests.get(url) retDict = json.loads(ret.content) print("----------------------------") print(retDict) print("----------------------------") request.session["name"] = retDict["nickname"] return redirect("http://39.107.226.105/index/") else: return HttpResponse("获取access_token失败") def auth(request): url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxffde55b11cc79754&redirect_uri=http%3A//39.107.226.105/empower&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirec" return redirect(url)
需要 登录 才可以提问哦