思路
1.成为钉钉开放平台开发者
想要通过钉钉账号实现第三方登录,首先要成为钉钉开放平台开发者,从而获取APPID和appSecret
2.前端点击钉钉登录按钮发送登录请求到后端(携带一个code(临时授权码))
3.后端根据前端发送的code和Appid,appSecret构造跳转链接
appid = current_app.config.get('DINGDING_APPID')
appSecret = current_app.config.get('DINGDING_SECRET')
timestamp = str(int(time.time() * 1000))
base_url = "https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature="
signature = base64.b64encode(
hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'),
digestmod='sha256').digest())
url = base_url + urllib.parse.quote(signature.decode()) + '×tamp=' + timestamp
+ '&accessKey=' + appid
4.使用钉钉账号登录
5.根据临时授权码获取用户信息
data = json.dumps({'tmp_auth_code': code})
try:
resp = requests.post(url, data, headers={'Content-Type': 'application/json'})
print('resp>>>', resp.json())
except Exception as e:
return {'code': 500, 'message': '获取用户标识信息失败'}
user_info = resp.json()
if user_info['errcode'] != 0:
return {'code': 500, 'message': '获取用户标识信息失败'}
user_info_dict = user_info['user_info']
return user_info_dict
返回实例
{
"errcode":0,
"user_info":{
"nick":"名字",
"unionid":"dingdkjjojoixxxx",
"openid":"dingsdsqwlklklxxxx",
"main_org_auth_high_level":true
},
"errmsg":"ok"
}
6.判断钉钉账号是否与该用户绑定
user_info = self.get_dingding_user(code) openid = user_info['openid'] if openid: oauth_user = OAuthUserModel.query.filter_by(oauth_id=openid).first() if oauth_user: user = User.query.filter_by(uid=oauth_user.user).first() data = { 'username': user.username, 'uid': user.uid } token = _generate_token(data) return {'code': 200, 'account': user.username, 'uid': user.uid, 'token': token} else: return {'code': 500, 'message': '没用绑定用户,请重新绑定', 'uid': openid}
若已绑定则登录成功,若没有绑定需要先绑定在登录