首先,先去微博开发平台 注册账号

微连接 — 网站接入 获取App Key, App Secret 在设置一个回调地址 这些都是要自己记住的 不要让别人知道

在setting中设置App Key, App Secret 和回调地址

1
2
3
WEIBO_APP_KEY = ''  # App Key
WEIBO_APP_SECRET = '' # App Secret
WEIBO_REDIRECT_URL = '' # 回调地址

生成微博登陆地址

1
2
3
4
class GetWEIBOurl(APIView):
# 生成微博的登陆地址
def get(self, request):
return Response(WEIBO_URL % (WEIBO_APP_KEY, WEIBO_REDIRECT_URL))

微博会返回你一个code值 判断是否存在数据库 没有就是新用户 可以绑定到自己的账户,绑定的直接登陆即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class GetWeiboToken(APIView):

def get(self, request, code):
data = {
'client_id': WEIBO_APP_KEY,
'client_secret': WEIBO_APP_SECRET,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': WEIBO_REDIRECT_URL
}
url = 'https://api.weibo.com/oauth2/access_token'
req = requests.post(url, data=data).text
uid = json.loads(req).get('uid')
if not uid:
return Response({
'code': 500,
'msg': '请重新扫码'
})
try:
weibo = WeiBo.objects.get(uid=uid)
except:
# 没有在平台中绑定,需要绑定一下
return Response({
'code': 404,
'uid': uid,
})
else:
# 这个用户是三方绑定过的,直接可以登陆
user = weibo.user
pa = {
'exp': datetime.datetime.utcnow() + datetime.timedelta(hours=1),
'user_id': user.id,
}
token = jwt.encode(payload=pa, key='abc')
return Response({
'code': 200,
'token': token,
'user_name': user.username,
'user_phone': user.phone,
})