django 钉钉登录

原理

先去获取钉钉用户信息,获取之后 去django User里面 查询 是否存在,不存在就创建,存在就正常登录。
根据唯一ID 进行判断

登录图

django 钉钉扫码登录_第1张图片

钉钉部分

请参考如下链接

https://open-doc.dingtalk.com/microapp/serverapi2/kymkv6

django部分

login页面

url 是 登录请求处理页面
appid 是 钉钉 id

views.py

appId 和 appSecret 是 钉钉信息

import requests
import random

def login_dingding(request):
    if request.method == "GET":
        code = request.GET.get('code', )
        state = request.GET.get('state', )

        appId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
        appSecret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

        token = requests.get(f'https://oapi.dingtalk.com/sns/gettoken?appid={appId}&appsecret={appSecret}')
        access_token = token.json()["access_token"]

        tmp_auth_code = requests.post(f"https://oapi.dingtalk.com/sns/get_persistent_code?access_token={access_token}",
                                      json={
                                          "tmp_auth_code": code
                                      })
        tmp_code = tmp_auth_code.json()
        print(tmp_code)
        openid = tmp_code['openid']
        persistent_code = tmp_code['persistent_code']

        sns_token_request = requests.post(f"https://oapi.dingtalk.com/sns/get_sns_token?access_token={access_token}",
                                          json={
                                              "openid": openid,
                                              "persistent_code": persistent_code
                                          })

        sns_token = sns_token_request.json()['sns_token']

        user_info_request = requests.get(f'https://oapi.dingtalk.com/sns/getuserinfo?sns_token={sns_token}')

        user_info = user_info_request.json()['user_info']
        print(user_info)

        try:
            user = User.objects.get(first_name=user_info['unionid'])
        except Exception as e:
            password = f'hequan{random.randint(1000,9999)}'
            try:
                user = User.objects.create(username=user_info['nick'], password=password,
                                           first_name=user_info['unionid'])
            except Exception as e:
                user = User.objects.create(username=f"{user_info['nick']}{random.randint(0,9999)}", password=password,
                                           first_name=user_info['unionid'])

        finally:
            login(request, user)
            request.session['is_login'] = True
            login_ip = request.META['REMOTE_ADDR']
            LoginLogs.objects.create(user=request.user, ip=login_ip)

        return redirect('/index.html')