使用django钉钉第三方扫码登录

钉钉作为阿里旗下的一款免费移动通讯软件,受众群体越来越多,这里我们使用Django来集成一下钉钉的三方账号登录,首先注册钉钉开发平台:https://open-dev.dingtalk.com/

在移动应用中选择登录


创建一个网站应用,其中有用的信息是 appid , appsecret ,还有回调网址


随后,查看官方文档,查看如何构造登录url:https://ding-doc.dingtalk.com/doc#/serverapi2/kymkv6

这里我们用django视图来操作

    #构造钉钉登录url
    def ding_url(request):
        appid = 'dingoaukgkwqknzjvamdqh'
        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:8000/ding_url , 就可以进行扫码

随后,钉钉会将code返回到回调网址中,查看官方文档,只有 java 和 php 的 sdk,并没有python的


SDK请求示例(JAVA):

DefaultDingTalkClient  client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest();
req.setTmpAuthCode("4a2c5695b78738d495f47b5fee9160cd");
OapiSnsGetuserinfoBycodeResponse response = client.execute(req,"yourAppId","yourAppSecret");

SDK请求示例(PHP):

include "TopSdk.php";
$c = new DingTalkClient(DingTalkConstant::$CALL_TYPE_OAPI, DingTalkConstant::$METHOD_POST , DingTalkConstant::$FORMAT_JSON);
$req = new OapiSnsGetuserinfoBycodeRequest;
$req->setTmpAuthCode("4a2c5695b78738d495f47b5fee9160cd");
$resp=$c->executeWithAccessKey($req, "https://oapi.dingtalk.com/sns/getuserinfo_bycode","yourAppId","yourAppSecret");
var_dump($resp)

python 逻辑很简单,将时间戳,秘钥进行hmac加密即可

# 构造钉钉回调方法
# 导包:
import hmac
import base64
from hashlib import sha256
import urllib
import json

def ding_url(request):
    appid = 'dingoadckiwhdceemaxrza',
    redirect_uri = 'http://127.0.0.1:8000/ding_url'
    # 获取code
    code = request.GET.get("code")
    t = time.time()
    # 时间戳
    timestamp = str((int(round(t * 1000))))
    # 密钥
    appSecret = 'Uym9ecJfNF4vlQ9-8wAGl2J10GvyZNKJqiXvcuf0blp7ERTpWrif8IwWk_AGI1j-'
    # 构造签名
    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'}
    # parse(alt+回车 第二个 导包)
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(
        signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=dingoadckiwhdceemaxrza",
                        data=json.dumps(payload), headers=headers)
    res_dict = json.loads(res.text)
    print(res_dict)

访问一下,可以显示出钉钉的用户名


vue与django结合 钉钉第三放登录

//vue登录页面内点击事件

//钉钉登录
      dingding() {
        //拼接钉钉url
        let url = "https://oapi.dingtalk.com/connect/qrconnect?appid=dingoadckiwhdceemaxrza&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://127.0.0.1:8000/ding_url"
        //进行站外跳转
        window.location.href = url;
      },

django视图页面:

# 导包:
import hmac
import base64
from hashlib import sha256
import urllib
import json

def ding_url(request):
    appid = 'dingoadckiwhdceemaxrza',
    redirect_uri = 'http://127.0.0.1:8000/ding_url'
    # 'https: // oapi.dingtalk.com / connect / qrconnect?appid =dingoamo0tezhk5hsckrrk & response_type = code & scope = snsapi_login & state = STATE & redirect_uri =http://localhost:8000/dingding_back/'
    # 获取code
    code = request.GET.get("code")
    t = time.time()
    # 时间戳
    timestamp = str((int(round(t * 1000))))
    appSecret = 'Uym9ecJfNF4vlQ9-8wAGl2J10GvyZNKJqiXvcuf0blp7ERTpWrif8IwWk_AGI1j-'
    # 构造签名
    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'}
    # parse(alt+回车 第二个 导包)
    res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature=' + urllib.parse.quote(
        signature.decode("utf-8")) + "&timestamp=" + timestamp + "&accessKey=dingoadckiwhdceemaxrza",
                        data=json.dumps(payload), headers=headers)
    res_dict = json.loads(res.text)
    #判断是否为第一次登录
    user = models.User.objects.filter(username=str(res_dict['user_info']['nick'])).first()

    sina_name = ''
    user_id = ''
    # 代表曾经登陆
    if user:
        sina_name = user.username
        user_id = user.id
    else:
        # 首次登录 建立账号保存到数据库
        models.User(username=str(res_dict['user_info']['nick']), password=make_password(''), type=0).save()
        print('已创建钉钉账户')
        # 查询用户
        user = models.User.objects.filter(username=str(res_dict['user_info']['nick'])).first()
        sina_name = res_dict['user_info']['nick']
        user_id = user.id
    # 进行跳转
    return redirect("http://localhost:8080?sina_name=" + str(sina_name) + "&uid=" + str(user_id))
posted @ 2020-04-30 18:58  O泡小涵  阅读(2312)  评论(0编辑  收藏  举报
Live2D