python實現QQ第三方登入
阿新 • • 發佈:2018-12-01
應用接入前,首先需進行申請,獲得對應的appid與appkey,以保證後續流程中可正確對網站與使用者進行驗證與授權。http://wiki.connect.qq.com/__trashed-2
QQ登入開發文件連線 http://wiki.connect.qq.com/準備工作_oauth2-0
騰訊QQ互聯平臺沒有python SDK,我們使用封裝好的SDK包
安裝:pip install QQLoginTool
匯入:from QQLoginTool.QQtool import OAuthQQ
OAuthQQ類中的方法:
__init__(self, client_id=None, client_secret=None, redirect_uri=None, state=None):
- client_id : 申請QQ登入成功後,分配給應用的appid。
- client_secret:申請QQ登入成功後,分配給網站的appkey。
- redirect_uri:成功授權後的回撥地址,必須是註冊appid時填寫的主域名下的地址,建議設定為網站首頁或網站的使用者中心。注意需要將url進行URLEncode。
- state:client端的狀態值。用於第三方應用防止CSRF攻擊,成功授權後回撥時會原樣帶回。請務必嚴格按照流程檢查使用者與state引數狀態的繫結。
get_qq_url(self) # 獲取QQ登入網頁網址 get_access_token(self, code) # 獲取access_token值 get_open_id(self, access_token) # 獲取open_id值
下面以Django為例實現QQ第三方登入
過程:
獲取QQ登入網頁網址
介面設計:
請求方式:GET /?state=xxx
請求引數:
引數名 | 型別 | 是否必須 | 說明 |
---|---|---|---|
state | str | 否 | 登入成功後的跳轉頁面路徑 |
返回資料:JSON
{ login_url": "https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=**&redirect_uri=**&state=**&scope=**" }
返回值 | 說明 |
---|---|
login_url | qq登入網址 |
程式碼實現:
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework.views import APIView
...
# 獲取login_url
class OauthQQLogin(APIView):
def get(self, request):
# 獲取前端傳入的引數
state = request.query_params.get('next', None)
# 判斷是否有,如果沒有後端建立一個
if not state:
state = '/'
# 例項化物件
oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI, state=state)
# 獲取login_url
login_url = oauth.get_qq_url()
# 返回login_url
return Response({'login_url': login_url})
獲取openid
在QQ將使用者重定向到此網頁的時候,重定向的網址會攜帶QQ提供的code引數,用於獲取使用者資訊使用,我們需要將這個code引數傳送給後端,在後端中使用code引數向QQ請求使用者的身份資訊
/oauth_callback.html?code=****&state=%2F
oauth_callback回撥頁,用於掃碼後接受Authorization Code
通過Authorization Code獲取Access Token
然後通過Access Token獲取openid
介面設計:
請求方式:GET /?code=xxx
請求引數:
引數名 | 型別 | 是否必須 | 說明 |
---|---|---|---|
code | str | 是 | qq返回的授權憑證code |
返回資料:JSON
{
"openid": xxxx
}
返回值 | 說明 |
---|---|
openid | 使用者的ID,與QQ號碼一一對應。 |
程式碼實現:
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from rest_framework.views import APIView
...
# 獲取openid
class OauthQQToken(APIView):
def get(self, request):
# 獲取前端傳入的code
code = request.query_params.get('code', None)
# 判斷是否有,如果沒有直接return
if not code:
return Response({'message': '缺少code'})
oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,redirect_uri=settings.QQ_REDIRECT_URI)
try:
# 使用code向QQ伺服器請求access_token
access_token = oauth.get_access_token(code)
# 使用access_token獲取openid
openid = oauth.get_open_id(access_token)
except:
return Response({'message': 'QQ服務異常'})
...
下面可以根據具體需求,進一步向後擴充套件…
以上內容僅供參考 -_- …為作者邊學習,邊摘抄和總計的內容