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

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

随后,查看官方文档,查看如何构造登录url:https://ding-doc.dingtalk.com/doc#/serverapi2/kymkv6
这里我们用django的视图来操作
2 获取 钉钉二维码url
def ding_url(request):
appid = 'dingoalwv7rbxle0ulczsx'
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,就可以进行扫码
3 回调接口登录绑定用户 测试·函数
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 ='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"))+"×tamp="+timestamp+"&accessKey=dingoaukgkwqknzjvamdqh",data=json.dumps(payload),headers=headers)
res_dict = json.loads(res.text)
print(res_dict)
return HttpResponse(res.text)
4 接口完善
class Dingding(APIView):
def ding_back(request):
#获取code
# code = request.GET.get('code')
print(code,'这是接受的code')
t = time.time()
#时间戳
timestamp = str((int(round(t * 1000))))
appSecret ='Zr4hdnTAss4sNVjRLQgLyRMpz4QCeYsTVHFoqwSI40xRPtLPJxsJ3n2mMF54srKp'
#构造签名
signature = base64.b64encode(hmac.new(appSecret.encode('utf-8'),timestamp.encode('utf-8'), digestmod=sha256).digest())
#请求接口,换取钉钉用户名
payload = {'tmp_auth_codeget':code}
headers = {'Content-Type': 'application/json'}
res = requests.post('https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='+urllib.parse.quote(signature.decode("utf-8"))+"×tamp="+timestamp+"&accessKey=dingoalwv7rbxle0ulczsx",data=json.dumps(payload),headers=headers)
res_dict = json.loads(res.text)
print(res_dict)
# return HttpResponse(res.text)
user = User.objects.filter(username=res_dict['user_info']['nick']).first()
if user:
# print('wwwwwwwww',user.username,user.id)
return redirect('http://localhost:8080/staition?uid='+ str(user.id) + '&username='+user.username)
else:
user=User(username=res_dict['user_info']['nick'])
user.save()
user = User.objects.filter(username=res_dict['user_info']['nick']).first()
id = str(user.id)
return redirect('http://localhost:8080/staition?uid='+str(id) + '&username='+user.username)
def ding_url(request):
appid = 'dingoalwv7rbxle0ulczsx'
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)