代码已开源,戳这里: https://github.com/YzzHa/eapp-corp-quick-start-python,赠人玫瑰手有余香,采纳的小伙伴们点个star再走呗 O.o
话不多说上代码,以关键代码为例, 部分密匙信息采用***进行占位,请对号入座。代码来自钉钉官方Node版QuickStart
// 获取用户信息
app.use('/login', function(req, res) {
// 获取access_token
HttpUtils.get("/gettoken", {
"appkey": config.appkey,
"appsecret": config.appsecret,
}, function(err, body) {
if (!err) {
var code = req.body.authCode;
var accessToken = body.access_token;
//获取用户id 依赖access_token
HttpUtils.get("/user/getuserinfo", {
"access_token": accessToken,
"code": code,
}, function(err2, body2) {
if (!err2) {
//获取用户详细信息 依赖userid
HttpUtils.get("/user/get", {
"access_token": accessToken,
"userid": body2.userid,
}, function(err3, body3) {
console.log(body2, body3);
if (!err3) {
res.send({
// 返回数据格式, 坑位预留
result: {
userId: body2.userid,
userName: body3.name
}
});
} else {
console.err('获取用户信息失败');
}
});
} else {
console.err('获取用户id失败');
}
});
} else {
console.err('获取access_token失败');
}
});
});
1. https://oapi.dingtalk.com/gettoken
请求方式: GET(HTTPS),参数 { "appkey":***, "appsecret": ***}
参数说明, E应用密匙对,参考文档: https://open-doc.dingtalk.com/microapp/bgb96b/bcdlg8
// response values
{'errcode': 0, 'access_token': ***, 'errmsg': 'ok', 'expires_in': 7200}
2. https://oapi.dingtalk.com/user/getuserinfo
请求方式:GET(HTTPS), 参数{ "access_token":***, "code": ***}
参数说明:access_token~上一步返回Json对象中的access_token, code~小程序前端获取
// authCode E应用获取方式
dd.getAuthCode({
success: res => {
console.log(res.authCode)
// response values
{ "userid": "****", "sys_level": 1, "errmsg": "ok", "is_sys": true, "deviceId": "***","errcode": 0 }
返回结果: 参考文档~https://open-doc.dingtalk.com/microapp/serverapi2/clotub
3. https://oapi.dingtalk.com/user/get
请求方式:GET(HTTPS), 参数{ "access_token":***, "userid": ***}
参数说明:access_token~第一步的access_token, userid~第二步的userid,
预留坑位: 这一步会检查请求IP白名单, 报错信息如下
{
"errcode": 60020,
"errmsg": "请参考FAQ:https://open-doc.dingtalk.com/microapp/faquestions/cvbtph。错误原因:访问ip不在白名单之中,request ip=*** corpId(***)"
}
数据返回格式要求,对应钉钉官方E应用前端代码,默认返回data,记得参数需包裹在result中
const data = {
userId: res.data.result.userId,
userName: res.data.result.userName
}
this.setData({...data, hideList: false})
入口: run.py, 坑位预留request.json报错的话,替换成request.form
# -*- coding:utf-8 -*-
from flask import Flask, request, jsonify
from login import Login
app = Flask(__name__)
# Registration login event
@app.route('/login', methods=['POST'])
def user_login():
query = request.json # Set the value to request.form if error is reported
return jsonify(Login(query['authCode']).get_data())
# Start the service
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)
配置文件: config.json
{
"weburl": "https://oapi.dingtalk.com",
"app": {
"appkey": ***,
"appsecret": ***
}
}
核心: login.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
# @Time : 2019/6/2 14:04
# @Author : YzzHA
# @email : [email protected]
# @File : login.py
# @Software: PyCharm
# @desc : Ding E applies QuickStart in Python
'''
import json
import requests
class Login():
def __init__(self, auth_code = ''):
self.auth_code = auth_code
self.config = self.get_config_data('config.json')
def get_data(self):
data = self.get_user()
if ('errcode' in data): # Access IP is not on the whitelist
print("fail code: %s" % data['errcode'])
print(data) # check response
return data
def get_token(self, url = '/gettoken'):
token = requests.get(self.config['weburl'] + url, params=self.config['app']).json()
self.token = token['access_token']
return self.token
def get_userinfo(self, url = '/user/getuserinfo'):
data = {
"access_token": self.get_token(),
"code": self.auth_code
}
userinfo = requests.get(self.config['weburl'] + url, params=data).json()
return userinfo
def get_user(self, url = '/user/get'):
userinfo = self.get_userinfo()
if ('userid' not in userinfo):
return userinfo
data = {
"access_token": self.token,
"userid": userinfo['userid']
}
user = requests.get(self.config['weburl'] + url, params=data).json()
return {
"result": {
"userId": userinfo['userid'],
"userName": user["name"]
}
}
# Read json file
def get_config_data(self, url = ""):
with open(url, 'r') as f:
data = json.loads(f.read())
return data