使用python+django集成釘釘三方掃碼登陸


使用python+django集成釘釘三方掃碼登陸


參考博客:https://v3u.cn/a_id_124

釘釘開發文檔:https://ding-doc.dingtalk.com/doc#/serverapi2/kymkv6

釘釘開放平台:https://open-dev.dingtalk.com/#/loginMan

\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)

1. 進入釘釘開放平台---》點擊左下角 ----》移動接入應用----》登陸----》點擊創建掃碼登陸應用授權。

\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)

2. 創建一個網站應用,其中有用的信息是appid,appsecret,還有回調網址 。

\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)

3. 根據官方文檔構建登陸掃碼url。

#構造釘釘登錄url
def ding_url(request):
    appid = 'dingoaukgkwqknzjvamdqh'	#替換成自己的appid
    redirect_uri = 'http://localhost:8000/dingding_back/'	#替換成自己的回調路由

    return redirect('https://oapi.dingtalk.com/connect/qrconnect?appid='+appid+'&response_type=code&scope=snsapi_login&state=STATE&redirect_uri='+redirect_uri)

然后訪問http://localhost:7878/ding_url,就可以進行掃碼

\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)

4. 最后我們編寫回調url。將時間戳,秘鑰進行hmac加密

import time
import hmac
import base64
from hashlib import sha256
import urllib
import json

#構造釘釘回調方法
def ding_back(request):

    #獲取code
    code = request.GET.get("code")

    t = time.time()
    #時間戳
    timestamp = str((int(round(t * 1000))))
	#替換成自己的appSecret
    appSecret ='ly-AzMKMmCKQP3geaILT_An32kEfKO3HeOtApy5CgKwjytevVZC0WYsT2gxMB160'
    #構造簽名
    signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'),timestamp.encode('utf-8'), digestmod=sha256).digest())
    #請求接口,換取釘釘用戶名
    payload = {'tmp_auth_code':code}
    headers = {'Content-Type': 'application/json'}
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='+urllib.parse.quote(signature.decode("utf-8"))+"&timestamp="+timestamp+"&accessKey=dingoaukgkwqknzjvamdqh",data=json.dumps(payload),headers=headers)	#accessKey替換成自己的appid

    res_dict = json.loads(res.text)
    print(res_dict)
    return HttpResponse(res.text)

\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)

最后我們訪問路由就可以得到自己的個人信息。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM