一、授权需求
需求: 登陆主页后展示用户名,用户名使用用户的微信名
project/settings.py
代码语言:javascript复制TEMPLATES = [
{
<span class="hljs-string">'BACKEND'</span>: <span class="hljs-string">'django.template.backends.django.DjangoTemplates'</span>,
<span class="hljs-string">'DIRS'</span>: [os.path.join(BASE_DIR, <span class="hljs-string">"template"</span>)],
<span class="hljs-string">'APP_DIRS'</span>: <span class="hljs-keyword">True</span>,
<span class="hljs-string">'OPTIONS'</span>: {
<span class="hljs-string">'context_processors'</span>: [
<span class="hljs-string">'django.template.context_processors.debug'</span>,
<span class="hljs-string">'django.template.context_processors.request'</span>,
<span class="hljs-string">'django.contrib.auth.context_processors.auth'</span>,
<span class="hljs-string">'django.contrib.messages.context_processors.messages'</span>,
],
},
},
]
template/index.html
代码语言:javascript复制<!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
代码语言:javascript复制<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span><span class="hljs-params">(request)</span>:</span>
data = {
<span class="hljs-string">"name"</span>: request.session.get(<span class="hljs-string">"name"</span>, <span class="hljs-string">"游客"</span>)
}
<span class="hljs-keyword">return</span> render(request, <span class="hljs-string">"index.html"</span>, data)
二、授权原理
流程:
- 设置网页授权回调域名
- 用户同意授权获取code
- 通过code换取网页授权access_token
- 刷新access_token(如果需要)
- 拉取用户信息(需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鉴权
如果公众号登录授权给了第三方开发者来进行管理,则不必做任何设置,由第三方代替公众号实现网页授权即可
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://39.107.226.105/empower&response_type=code&scope=snsapi_base&state=1#wechat_redirec
微信扫描二维码:
- snsapi_userinfo https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxffde55b11cc79754&redirect_uri=http://39.107.226.105/empower&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirec
微信扫描二维码:
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数据包:
代码语言:javascript复制{
"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数据包:
代码语言:javascript复制{"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数据包
代码语言:javascript复制{
"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数据包:
代码语言:javascript复制{"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数据包
代码语言:javascript复制{
"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数据包
代码语言:javascript复制{"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
代码语言:javascript复制<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path, re_path
<span class="hljs-keyword">from</span> myApp <span class="hljs-keyword">import</span> views
urlpatterns = [
path(<span class="hljs-string">r'index/'</span>, views.index),
path(<span class="hljs-string">r'weixin/'</span>, views.weixin),
path(<span class="hljs-string">r'access/'</span>, views.access),
path(<span class="hljs-string">r'menu/'</span>, views.menu),
path(<span class="hljs-string">r'dlmenu/'</span>, views.menu),
path(<span class="hljs-string">r'empower/'</span>, views.empower),
]
myApp/views.py
代码语言:javascript复制<span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render, HttpResponse, redirect
<span class="hljs-keyword">from</span> django.views.decorators.csrf <span class="hljs-keyword">import</span> csrf_exempt
<span class="hljs-keyword">import</span> hashlib
<span class="hljs-keyword">import</span> xmltodict
<span class="hljs-keyword">import</span> time
<span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">from</span> myApp.accessToken <span class="hljs-keyword">import</span> AccessToken
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">responseXML</span><span class="hljs-params">(ToUserName, FromUserName, MsgType, **kwargs)</span>:</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-meta">@csrf_exempt</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">weixin</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">access</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">menu</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">dlmenu</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">empower</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-comment">#获得授权书</span>
code = request.GET.get(<span class="hljs-string">"code"</span>)
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> code:
<span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"您未授权,无法获取用户信息"</span>)
<span class="hljs-comment">#获取access_token和openid</span>
url = <span class="hljs-string">"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"</span>%(<span class="hljs-string">"wxffde55b11cc79754"</span>, <span class="hljs-string">"84e86527f090d6238ea1c0b96f5fc753"</span>, code)
res = requests.get(url)
resDict = json.loads(res.content)
access_token = resDict.get(<span class="hljs-string">"access_token"</span>)
<span class="hljs-keyword">if</span> access_token:
<span class="hljs-comment"># 获取用户信息</span>
url = <span class="hljs-string">"https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"</span>%(access_token, resDict.get(<span class="hljs-string">"openid"</span>))
ret = requests.get(url)
retDict = json.loads(ret.content)
print(<span class="hljs-string">"----------------------------"</span>)
print(retDict)
print(<span class="hljs-string">"----------------------------"</span>)
<span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"获取用户信息成功"</span>)
<span class="hljs-keyword">else</span>:
<span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"获取access_token失败"</span>)
三、登陆主页获取用户信息
project/settings.py
代码语言:javascript复制SESSION_ENGINE = <span class="hljs-string">"django.contrib.sessions.backends.cache"</span>
myApp/urls.py
代码语言:javascript复制<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path, re_path
<span class="hljs-keyword">from</span> myApp <span class="hljs-keyword">import</span> views
urlpatterns = [
path(<span class="hljs-string">r'index/'</span>, views.index),
path(<span class="hljs-string">r'weixin/'</span>, views.weixin),
path(<span class="hljs-string">r'access/'</span>, views.access),
path(<span class="hljs-string">r'menu/'</span>, views.menu),
path(<span class="hljs-string">r'dlmenu/'</span>, views.menu),
path(<span class="hljs-string">r'empower/'</span>, views.empower),
path(<span class="hljs-string">r'auth/'</span>, views.auth),
]
myApp/views.py
代码语言:javascript复制<span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render, HttpResponse, redirect
<span class="hljs-keyword">from</span> django.views.decorators.csrf <span class="hljs-keyword">import</span> csrf_exempt
<span class="hljs-keyword">import</span> hashlib
<span class="hljs-keyword">import</span> xmltodict
<span class="hljs-keyword">import</span> time
<span class="hljs-keyword">import</span> json
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">from</span> myApp.accessToken <span class="hljs-keyword">import</span> AccessToken
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">index</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">responseXML</span><span class="hljs-params">(ToUserName, FromUserName, MsgType, **kwargs)</span>:</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-meta">@csrf_exempt</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">weixin</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">access</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">menu</span><span class="hljs-params">(request)</span>:</span>
access_toke = AccessToken.getAccessToken(<span class="hljs-string">"client_credential"</span>, <span class="hljs-string">"wxffde55b11cc79754"</span>, <span class="hljs-string">"84e86527f090d6238ea1c0b96f5fc753"</span>)
url = <span class="hljs-string">"https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s"</span>�cess_toke
menu_data = {
<span class="hljs-string">"button"</span>: [
{
<span class="hljs-string">"type"</span>: <span class="hljs-string">"click"</span>,
<span class="hljs-string">"name"</span>: <span class="hljs-string">"sunck"</span>,
<span class="hljs-string">"key"</span>: <span class="hljs-string">"V1001_SUNCK"</span>
},
{
<span class="hljs-string">"type"</span>: <span class="hljs-string">"view"</span>,
<span class="hljs-string">"name"</span>: <span class="hljs-string">"主页"</span>,
<span class="hljs-string">"url"</span>: <span class="hljs-string">"http://39.107.226.105/auth/"</span>
},
{
<span class="hljs-string">"name"</span>: <span class="hljs-string">"佳丽"</span>,
<span class="hljs-string">"sub_button"</span>: [
{
<span class="hljs-string">"type"</span>: <span class="hljs-string">"click"</span>,
<span class="hljs-string">"name"</span>: <span class="hljs-string">"林志玲"</span>,
<span class="hljs-string">"key"</span>: <span class="hljs-string">"V1002_MASSAGE_BEAUTIFUL01"</span>
},
{
<span class="hljs-string">"type"</span>: <span class="hljs-string">"click"</span>,
<span class="hljs-string">"name"</span>: <span class="hljs-string">"范冰冰"</span>,
<span class="hljs-string">"key"</span>: <span class="hljs-string">"V1002_MASSAGE_BEAUTIFUL02"</span>
},
{
<span class="hljs-string">"type"</span>: <span class="hljs-string">"click"</span>,
<span class="hljs-string">"name"</span>: <span class="hljs-string">"关之琳"</span>,
<span class="hljs-string">"key"</span>: <span class="hljs-string">"V1002_MASSAGE_BEAUTIFUL03"</span>
},
{
<span class="hljs-string">"type"</span>: <span class="hljs-string">"view"</span>,
<span class="hljs-string">"name"</span>: <span class="hljs-string">"更多佳丽"</span>,
<span class="hljs-string">"url"</span>: <span class="hljs-string">"http://www.baidu.com/"</span>
}
]
}
]
}
data = json.dumps(menu_data, ensure_ascii=<span class="hljs-keyword">False</span>).encode()
res = requests.post(url, data, <span class="hljs-string">"json"</span>)
resDict = json.loads(res.content)
<span class="hljs-keyword">if</span> resDict.get(<span class="hljs-string">"errcode"</span>) == <span class="hljs-number">0</span>:
<span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"菜单修改成功"</span>)
<span class="hljs-keyword">else</span>:
<span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"菜单修改失败"</span>)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">dlmenu</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-keyword">pass</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">empower</span><span class="hljs-params">(request)</span>:</span>
<span class="hljs-comment">#获得授权书</span>
code = request.GET.get(<span class="hljs-string">"code"</span>)
<span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> code:
<span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"您未授权,无法获取用户信息"</span>)
<span class="hljs-comment">#获取access_token和openid</span>
url = <span class="hljs-string">"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code"</span>%(<span class="hljs-string">"wxffde55b11cc79754"</span>, <span class="hljs-string">"84e86527f090d6238ea1c0b96f5fc753"</span>, code)
res = requests.get(url)
resDict = json.loads(res.content)
access_token = resDict.get(<span class="hljs-string">"access_token"</span>)
<span class="hljs-keyword">if</span> access_token:
<span class="hljs-comment"># 获取用户信息</span>
url = <span class="hljs-string">"https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN"</span>%(access_token, resDict.get(<span class="hljs-string">"openid"</span>))
ret = requests.get(url)
retDict = json.loads(ret.content)
print(<span class="hljs-string">"----------------------------"</span>)
print(retDict)
print(<span class="hljs-string">"----------------------------"</span>)
request.session[<span class="hljs-string">"name"</span>] = retDict[<span class="hljs-string">"nickname"</span>]
<span class="hljs-keyword">return</span> redirect(<span class="hljs-string">"http://39.107.226.105/index/"</span>)
<span class="hljs-keyword">else</span>:
<span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"获取access_token失败"</span>)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">auth</span><span class="hljs-params">(request)</span>:</span>
url = <span class="hljs-string">"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxffde55b11cc79754&redirect_uri=http://39.107.226.105/empower&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirec"</span>
<span class="hljs-keyword">return</span> redirect(url)