php怎么获取钉钉员工授权信息?

发布网友 发布时间:2022-04-24 01:57

我来回答

2个回答

热心网友 时间:2022-04-11 06:19

做过一个E应用,使用lumen框架,和你的思路是一样的,新用户点进去就自动授权注册应用,数据存到我们自己的数据库中,不依赖钉钉,我们还同步了部门信息,如果粘贴复制和下面的那个同学一样,看上去你也会觉得懵,方法都是封装好了的。

建议你这样试试看:

 获取AccessToken:

后端通过corpid,corpsecret请求接口gettoken?corpid=id&corpsecret=secrect获取AccessToken

获取钉钉用户userid:

前端需要相应的处理,携带authCode请求,加上AccessToken这两个参数请求接口/user/getuserinfo?access_token=access_token&code=authCode这个

获取钉钉用户详情:

使用access_token和上一步的钉钉userid 请求接口 /user/get?access_token=ACCESS_TOKEN&userid=

插入钉钉用户的数据到你的 数据库中

我们这样做的:

/**

* 钉钉免登陆获获取用信息

* @param $authCode

* @param $url

* @return array

*/

static function outhLogin($authCode, $url)

{

if (empty($authCode) || empty($url)) {

return self::returnError('1101', self::$errorArray['1101']);

}

$accessToken = ComponentDingtalk::getPcAccessToken();

if ($accessToken['code']) {

self::logError(__CLASS__ . '->' . __FUNCTION__, '获取access_token失败');

return self::returnError('1102', self::$errorArray['1102']);

}

$dingUserId = ComponentDingtalk::getDingUserid($accessToken['data'], $authCode);

if ($dingUserId['code']) {

self::logError(__CLASS__ . '->' . __FUNCTION__, '用户userid获取失败(调用钉钉API)');

return self::returnError('1103', self::$errorArray['1103']);

}

$dinguserInfo = ComponentDingtalk::getDingUserInfo($accessToken['data'], $dingUserId['data']);

if ($dinguserInfo['code']) {

self::logError(__CLASS__ . '->' . __FUNCTION__, '用户信息获取失败(调用钉钉API)');

return self::returnError('1104', self::$errorArray['1004']);

}

$userInfo = $dinguserInfo['data'];

return self::transaction(function () use ($accessToken, $userInfo, $url) {

if (\count($userInfo['department']) > 1) {

$departIdArr = [];

$departNameArr = [];

for ($i = 0, $iMax = \count($userInfo['department']); $i < $iMax; $i++) {

$departInfo[$i] = ServerDepartment::getByDdDepartid($userInfo['department'][$i]);

$departIdArr[] = $departInfo[$i]['id'];

$departNameArr[] = $departInfo[$i]['name'];

}

$depart['id'] = implode(',', $departIdArr);

$depart['name'] = implode(',', $departNameArr);

} else {

$ddDepartmentId = implode(',', $userInfo['department']);

$depart = ServerDepartment::getByDdDepartid($ddDepartmentId);

}

//插入用户

$user = ServerEmployee::getByDdUserid($userInfo['userid']);

if ($user && $user['status'] == 2) {

return self::returnError('1105', self::$errorArray['1105']);

}

if (empty($user)) {

$roleId = 0;

$departId = $depart['id'];

$name = $userInfo['name'];

$mobile = $userInfo['mobile'];

$departName = $depart['name'];

$position = $userInfo['position'];

$ddUserid = $userInfo['userid'];

$ddStatus = $userInfo['active'] ? 1 : 2;

$ddInfo = json_encode($userInfo, JSON_UNESCAPED_UNICODE);

$tokenOverAt = (int)(time() + $_ENV['PROJECT_apiAppTokenOverTime']);

$token = self::_createToken($userInfo['userid'], $tokenOverAt);

$status = 1;

$userId = ServerEmployee::insert($roleId, $departId, $name, $mobile, $departName, $position, $ddUserid, $ddStatus, $ddInfo, $token, $tokenOverAt, $status);

if (!$userId) {

self::logError(__CLASS__ . '->' . __FUNCTION__, '用户初始化创建失败');

return self::returnError('1106', self::$errorArray['1106']);

}

}

$userId = $userId ?? $user['id'];

// 更新Token

$id = $userId;

$roleId = $user['roleId'];

$departId = $depart['id'];

$name = $userInfo['name'];

$mobile = $userInfo['mobile'];

$departName = $depart['name'];

$position = $userInfo['position'];

$ddUserid = $userInfo['userid'];

$ddStatus = $userInfo['active'] ? 1 : 2;

$ddInfo = json_encode($userInfo, JSON_UNESCAPED_UNICODE);

$tokenOverAt = (int)(time() + $_ENV['PROJECT_apiAppTokenOverTime']);

$token = self::_createToken($userInfo['userid'], $tokenOverAt);

$status = 1;

$updateParams = ServerEmployee::update($id, $roleId, $departId, $name, $mobile, $departName, $position, $ddUserid, $ddStatus, $ddInfo, $token, $tokenOverAt, $status);

if (!$updateParams) {

self::logError(__CLASS__ . '->' . __FUNCTION__, '用户信息更新失败' . json_encode($updateParams, JSON_UNESCAPED_UNICODE) . '/' . json_encode([$id, $roleId, $departId, $name, $mobile, $depart, $position, $ddUserid, $ddStatus, $ddInfo, $token, $tokenOverAt, $status]));

return self::returnError('1107', self::$errorArray['1107']);

}

// 前端的配置信息

// 获取jsTicket

$jsTicket = ComponentDingtalk::getPcJsTicket($accessToken['data']);

if ($jsTicket['code']) {

self::logError(__CLASS__ . '->' . __FUNCTION__, '获取jsTicket失败(调用钉钉API)');

return self::returnError('1111', self::$errorArray['1111']);

}

// 组装签名数据

$curUrl = $url;;

$nonceStr = uniqid('', true);

$agentId = $_ENV['PROJECT_ddInterfaceAgentID'];

$timeStamp = time();

$corpId = $_ENV['PROJECT_ddInterfaceCorpId'];

$signature = ComponentDingtalk::getSign($jsTicket['data'], $nonceStr, $timeStamp, $curUrl);

$config = array(

'url' => urldecode($curUrl),

'nonceStr' => $nonceStr,

'agentId' => $agentId,

'timeStamp' => $timeStamp,

'corpId' => $corpId,

'signature' => $signature

);

// 获取当前角色的权限

$roleInfo = ServerRole::getById($roleId);


// 当前用户的顶级部门(不含根部门)

$departInfo = ServerDepartment::getById($departId);

if ($departInfo['parentid'] == 1) {  // 二级部门(总经办)

$departRootId = $departId;

$departRootName = $departName;

} else {

$sonDepart = ServerDepartment::getById($departInfo['parentid']);//分组

if ($sonDepart['parentid'] == 1) {

$departRootId = $sonDepart['id'];

$departRootName = $sonDepart['name'];

} else {

$grandsonDepart = ServerDepartment::getById($sonDepart['parentid']);//部门

if ($grandsonDepart['parentid'] == 1) {

$departRootId = $grandsonDepart['id'];

$departRootName = $grandsonDepart['name'];

} else {

$grandchildDepart = ServerDepartment::getById($grandsonDepart['parentid']);//分公司

$departRootId = $grandchildDepart['id'];

$departRootName = $grandchildDepart['name'];

}

}

}

$company = ServerDepartment::get(['parentid' => 0, 'dd_departid' => 1]);


return self::returnSuccess(array(

'id' => $userId,

'name' => $name,

'token' => $token,

'tokenOverAt' => $tokenOverAt,

'config' => $config,

'power' => $roleInfo['power'] ?? '',

'departId' => $departId,

'departName' => $departName,

'departRootId' => $departRootId,

'departRootName' => $departRootName,

'company' => $company['name'],


));

}, function (\Exception $e) {

echo $e->getMessage();

self::logError(__CLASS__ . '->' . __FUNCTION__, $e->getMessage());

return self::returnError('1108', self::$errorArray['1108']);

});

}

热心网友 时间:2022-04-11 07:37

namespace app\ding\controller;

use think\Config;

class Index
{
public function getUserID($code)
{
$url = "https://oapi.dingtalk.com/user/getuserinfo?access_token=".$this->getAccessToken()."&code=".$code;

$user = $this->http($url);

return json_decode($user,JSON_UNESCAPED_UNICODE);
}

public function getUserInfo($userid)
{
$url = "https://oapi.dingtalk.com/user/get?access_token=".$this->getAccessToken()."&userid=".$userid;

$userinfo = $this->http($url);

return json_decode($userinfo,JSON_UNESCAPED_UNICODE);
}

public function getAccessToken()
{
$config = Config();

$appkey = $config['ding_auto_login_appkey'];
$appsecret = $config['ding_auto_login_appsecret'];

//定义token文件和路径,默认位于应用目录下
$token_file_name = APP_PATH.'/ding_access_token.php';
//如果token文件存在
if(file_exists($token_file_name)){
//json解码
$token_file_content = json_decode($this->get_php_file($token_file_name));
//如果token超时了
if($token_file_content->expire_time < time())
{
//从接口获取token
$token = $this->get_token($appkey,$appsecret,$token_file_name);
}else{
//否则使用缓存的token
$token = $token_file_content->access_token;
}
//否则token文件不存在
}else{
//从企业微信接口获取token
$token = $this->get_token($appkey,$appsecret,$token_file_name);
}

return $token;
}

private function get_token($appkey,$appsecret,$token_file_name)
{
$url = "https://oapi.dingtalk.com/gettoken?appkey=".$appkey."&appsecret=".$appsecret;
$get_result = json_decode($this->http($url),true);
if($get_result['errcode'] == '0')
{
$new_token = (object)[];
$token = $get_result['access_token'];
$new_token->expire_time = time() + 7000;
$new_token->access_token = $token;
$this->set_php_file($token_file_name,json_encode($new_token));
}else{
$token = 'get_token_error';
}

return $token;
}

private function get_php_file($filename)
{
return trim(substr(file_get_contents($filename), 15));
}

private function set_php_file($filename,$content) {
$fp = fopen($filename, "w");
fwrite($fp, "<?php exit();?>" . $content);
fclose($fp);

return;
}

public function http($url,$data=null)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, 0);
if(!empty($data))
{
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 500);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
curl_close($curl);

return $res;
}
}追问= =兄弟,这个不会是你直接从自己代码里面复制出来的吧,看着有点懵

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com