微信网页授权基础知识
网页授权的最终目的就是获取微信的用户信息,微信的网页授权方式有两种
- snsapi_base:只能获取用户的openid,静默授权
- snsapi_userinfo:获取用户信息,用户手动同意授权(这种方式是这篇文章主要讲述的)
微信网页授权的序列图
由于没正式学过怎么花序列图,该序列图肯定是不合规范的,但整个交互过程还是写清晰的了。需要明确的是在微信中用户访问网页要经过微信,后端返回数据也是要经过微信。
一些准备工作
填写好微信回调域名,用户访问的页面需要在该域名下。填错了,用户同意授权后,就会出现redirect_uri error。填写or修改地方在下图位置
代码书写:
urls.py的编写
#encoding=utf-8
from django.conf.urls import include, url
from .views import AuthView, GetUserInfoView, TestView, WxSignature
urlpatterns = [
# 授权
url(r'^auth/$', AuthView.as_view(), name='wx_auth'),
# 获取用户信息
url(r'^code/$', GetUserInfoView.as_view(), name='get_user_info'),
# 微信接口配置信息验证
url(r'^$', WxSignature.as_view(), name='signature'),
# 测试
url(r'^test/$', TestView.as_view(), name='test_view'),
]
判断是否已经有用户信息
这里主要利用了View类的实现机制,一个url请求过来后,会调用dispatch()方法,根据请求类型选取对应的处理方法,例如, GET请求,就会调用View类下的get()方法。现在新建一个auth_view.py文件,里面创建一个名为AuthView继承了View类的class,并改写dispatch()方法, 判断的关键是看session中是否存在'user'这个key, 该信息在获取到了用户信息后添加到session当中,另外请求参数path保存用户需要访问的网页的url地址。参数用来保存以后需要进行要求的网页,继承AuthView即可进行网页授权
#encoding=utf-8
import urllib
from django.views.generic import View
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
import youhui.settings as setting
class AuthView(View):
def dispatch(self, request, *args, **kwargs):
# 判断是否有授权
if not 'user' in request.session:
# 用户需要访问的url路径
path = request.get_full_path()
# 跳转url,
red_url = '%s?path=%s' % (reverse('wx_auth'), urllib.quote(path))
return redirect(red_url)
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
wechat_api.py
该微信api基本就只有网页授权部分,我把jeff大牛的wechat sdk, 中有用的部分抽离出来,并把网页授权的加了上去。jeff大牛写的wechat sdk在这里。授权部分在WechatApi类中, 创建时传入appid和appsecret就可以使用。
主要方法说明:
_process_response: 解析微信返回的json数据,返回相对应的dict
auth_url: 返回网页授权url
get_auth_access_token: 根据授权成功返回的code, 获取网页授权的access_token
get_user_info: 根据网页授权的access_token获取用户信息
#encoding=utf-8
import requests
import simplejson
import urllib
import logging
log = logging.getLogger('django')
class APIError(object):
def __init__(self, code, msg):
self.code = code
self.msg = msg
def wx_log_error(APIError):
log.error('wechat api error: [%s], %s' % (APIError.code, APIError.msg))
class WechatBaseApi(object):
API_PREFIX = u'https://api.weixin.qq.com/cgi-bin/'
def __init__(self, appid, appsecret, api_entry=None):
self.appid = appid
self.appsecret = appsecret
self._access_token = None
self.api_entry = api_entry or self.API_PREFIX
@property
def access_token(self):
if not self._access_token:
token, err = self.get_access_token()
if not err:
self._access_token = token['access_token']
return self._access_token
else:
return None
return self._access_token
# 解析微信返回的json数据,返回相对应的dict
def _process_response(self, rsp):
if 200 != rsp.status_code:
return None, APIError(rsp.status_code, 'http error')
try:
content = rsp.json()
except Exception:
return None, APIError(9999, 'invalid response')
if 'errcode' in content and content['errcode'] != 0:
return None, APIError(content['errcode'], content['errmsg'])
return content, None
def _get(self, path, params=None):
if not params:
params = {}
params['access_token'] = self.access_token
rsp = requests(self.api_entry + path, params=params)
return self._process_response(rsp)
def _post(self, path, data, type='json'):
header = {'content-type': 'application/json'}
if '?' in path:
url = self.api_entry + path + 'access_token=' + self.access_token
else:
url = self.api_entry + path + '?' + 'access_token=' + self.access_token
if 'json' == type:
data = simplejson.dumps(data, ensure_ascii=False).encode('utf-8')
rsp = requests.post(url, data, headers=header)
return self._process_response(rsp)
class WechatApi(WechatBaseApi):
def get_access_token(self, url=None, **kwargs):
params = {'grant_type': 'client_credential', 'appid': self.appid, 'secret': self.appsecret}
if kwargs:
params.update(kwargs)
rsp = requests.get(url or self.api_entry + 'token', params)
return self._process_response(rsp)
#返回授权url
def auth_url(self, redirect_uri, scope='snsapi_userinfo', state=None):
url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=%s#wechat_redirect' % \
(self.appid, urllib.quote(redirect_uri), scope, state if state else '')
return url
# 获取网页授权的access_token
def get_auth_access_token(self, code):
url = u'https://api.weixin.qq.com/sns/oauth2/access_token'
params = {
'appid': self.appid,
'secret': self.appsecret,
'code': code,
'grant_type': 'authorization_code'
}
return self._process_response(requests.get(url, params=params))
# 获取用户信息
def get_user_info(self, auth_access_token, openid):
url = u'https://api.weixin.qq.com/sns/userinfo?'
params = {
'access_token': auth_access_token,
'openid': openid,
'lang': 'zh_CN'
}
return self._process_response(requests.get(url, params=params))
view.py
这部分代码实现了上面授权序列图的步骤6到18,需要注意的是需要设置user信息到session中,当然也可以设置其他信息,在AuthView中判断条件要与之相对应即可。
#encoding=utf-8
import hashlib
import simplejson
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseServerError, Http404
from django.views.generic import View
from django.core.urlresolvers import reverse
from .models import User
from .serializers import UserSerializer
from .auth_view import AuthView as BaseView
from .wechat_api import WechatApi, wx_log_error
import youhui.settings as settings
from youhui.utils import log_err
# Create your views here.
class WecahtApiView(View):
# 填入公众号appid, appsecret
APPID = settings.APPID
APPSECRET = settings.APPSECRET
HOST = settings.HOST
wechat_api = WechatApi(appid=APPID, appsecret=APPSECRET)
class WxSignature(View):
pass #非重点省略
class AuthView(WecahtApiView):
def get(self, request):
path = request.GET.get('path')
if path:
if 'user' in request.session:
return redirect(path)
else:
red_url = '%s%s?path=%s' % (self.HOST, reverse('wx:get_user_info'), path)
redirect_url = self.wechat_api.auth_url(red_url)
print 'auth_url', redirect_url
return redirect(redirect_url)
else:
return Http404('parameter path not founded!')
class GetUserInfoView(WecahtApiView):
def get(self, request):
redir_url = request.GET.get('path')
code = request.GET.get('code')
if redir_url and code:
# 获取网页授权access_token
token_data, error = self.wechat_api.get_auth_access_token(code)
if error:
wx_log_error(error)
return HttpResponseServerError('get access_token error')
# 获取用户信息信息
user_info, error = self.wechat_api.get_user_info(token_data['access_token'], token_data['openid'])
if error:
wx_log_error(error)
return HttpResponseServerError('get userinfo error')
# 存储用户信息
user = self._save_user(user_info)
if not user:
return HttpResponseServerError('save userinfo error')
# 用户对象存入session
request.session['user'] = user
# 跳转回目标页面
return redirect(redir_url)
# 用户禁止授权后怎么操作
else:
return Http404('parameter path or code not founded!!')
def _save_user(self, data):
user = User.objects.filter(openid=data['openid'])
# 没有则存储用户数据,有返回用户数据的字典
if 0 == user.count():
user_data = {
'nick': data['nickname'].encode('iso8859-1').decode('utf-8'),
'openid': data['openid'],
'avatar': data['headimgurl'],
'info': self._user2utf8(data),
}
if 'unionid' in data:
user_data.update('unionid', data.unionid)
try:
new_user = User(**user_data)
new_user.save()
user_data.update({'id': new_user.id})
return user_data
except Exception, e:
log_err(e)
return None
else:
# 把User对象序列化成字典,具体看rest_framework中得内容
return UserSerializer(user[0]).data
# 解决中文显示乱码问题
def _user2utf8(self, user_dict):
utf8_user_info = {
"openid": user_dict['openid'],
"nickname": user_dict['nickname'].encode('iso8859-1').decode('utf-8'),
"sex": user_dict['sex'],
"province": user_dict['province'].encode('iso8859-1').decode('utf-8'),
"city": user_dict['city'].encode('iso8859-1').decode('utf-8'),
"country": user_dict['country'].encode('iso8859-1').decode('utf-8'),
"headimgurl": user_dict['headimgurl'],
"privilege": user_dict['privilege'],
}
if 'unionid' in user_dict:
utf8_user_info.update({'unionid': user_dict['unionid']})
return utf8_user_info
class TestView(BaseView):
def get(self, request):
return render(request, 'test.html')