1. 程式人生 > 實用技巧 >新浪微博回撥介面

新浪微博回撥介面

目錄

1.微博回撥介面

1.1 oauth/urls.py 中新增路由

 urlpatterns = [ 
     path('weibo/callback/', views.OauthWeiboCallback.as_view()), # 
 /oauth/weibo/callback/ 
 ]

1.2 oauth/views.py 中新增試圖函式

http://192.168.56.100:8888/oauth/weibo/callback/

 from .models import OauthUser
 from rest_framework_jwt.serializers import jwt_payload_handler,
 jwt_encode_handler
 from user.utils import jwt_response_payload_handler

 # 通過vue前端傳入的code,微博身份驗證
 class OauthWeiboCallback(APIView):
     # 自定義許可權類
     permission_classes = (AllowAny,)

     def post(self, request):
           # 接收vue端傳過來的code(微博的使用者code)
           # 1.使用微博使用者code+微博開發者賬號資訊換取微博的認證access_token
           code = request.data.get('code')
           data = {
                'client_id': '3516473472',
                'client_secret': '7862ee35a0dc6f0345d0464dc34f14fc',
                'grant_type': 'authorization_code',
                'code': code,
                'redirect_uri': 'http://127.0.0.1:8888/oauth/callback/',
           }
           url = 'https://api.weibo.com/oauth2/access_token'
           data = requests.post(url=url, data=data).json() # 拿取請求的返回結果
           access_token = data.get('uid') # 獲取到的微博token
           weibo_uid = data.get('access_token') # 獲取到少碼使用者的id

           # 2. 根據uid 查詢繫結情況
           try:
               oauth_user = OauthUser.objects.get(uid=weibo_uid, oauth_type='1')
           except Exception as e:
               oauth_user = None
           # 返回動作, 登入成功/需要繫結使用者 type 0 登入成功, 1, 授權成功, 需要繫結
           if oauth_user:
               # 4. 如果綁定了, 返回token, 登入成功
               user = oauth_user.user

               payload = jwt_payload_handler(user)
               token = jwt_encode_handler(payload)
               # jwt_response_payload_handler為user模組定義的jwt返回的資訊
               data = jwt_response_payload_handler(token, user)
               data['type'] = '0' # 指定為登入成功
               return Response({'code': 0, 'msg': '登入成功', 'data': data})
           else:
               # 5. 如果沒繫結, 返回標誌, 讓前端跳轉到繫結頁面
               return Response({'code': 0, 'msg': '授權成功', 'data': {'type': '1', 'uid': weibo_uid}})

oauth/models.py 中新增使用者繫結模型

 # 把三方的使用者資訊,和本地的使用者資訊進行繫結
 class OauthUser(models.Model):
     OAUTHTYPE = ( 
         ('1', 'weibo'), 
         ('2', 'weixin'), 
     )
     uid = models.CharField('三方使用者id', max_length=64)
  # 三方使用者id
     user = models.ForeignKey('user.User', on_delete=models.CASCADE)
 # 本地使用者外來鍵,關聯User表
     oauth_type = models.CharField('認證型別', max_length=10, choices=OAUTHTYPE)
  # 1,2 ...

1.4 遷移資料庫

 pytpython manager.py makemigrations 
 python manager.py migratehon