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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php怎么获取钉钉员工授权信息?相关的知识,希望对你有一定的参考价值。

我想要写一个钉钉的H5微应用,新员工加入公司的时候自动获取用户信息授权信息填充到数据库中,用来登录别的H5微应用。也就是新员工加入时自动注册一个帐号。但是在获取他们的用户信息授权信息的时候我有点懵逼,不知道该怎么获取

做过一个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']);

);

参考技术A 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;

追问

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

前端获取钉钉免登code

需求

简单的一个需求:通过阿里云提供的api接口,获取公司userinfo员工信息。主要目的是通过获取到的用户身份进行校验,登录内部系统
首先查阅官方文档:https://ding-doc.dingtalk.com/doc#/dev/about
推荐步骤:

  1. OA 控制台创建一个微应用: https://oa.dingtalk.com 我的应用是H5企业内部微应用
  2. 在工作中获取 appkeyappsecret ,建议先在官方api中调试:https://open-dev.dingtalk.com/apiExplorer
  3. 获取企业 CorpId,如:dingxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

开发思路

使用官方的api,先弹出免登code;使用该code获取员工信息,为真,进行登录。

通过官方文档,先写一段js函数:

dd.ready(function() {
            dd.runtime.permission.requestAuthCode({
                corpId : "dingxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                onSuccess : function(result) {
                    var code = result.code;
                    alert(‘获取成功,你的免登code为:‘ + code);            //将code 发往后台处理
                },
                onFail : function(err) {
                    alert(‘出错了, 你获取了一个自定义错误‘ + err);
                }
            });

        });

在前端使用html,写一个点击事件弹出获取到的信息

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>弹出函数</title>
    <!-- 引入外部js钉钉官方接口 -->
    <script src="https://g.alicdn.com/dingding/dingtalk-jsapi/2.10.3/dingtalk.open.js"></script>
    <!-- 引入刚刚写的js文件 -->
    <script type="text/javascript" src="../static/js/dd.js"></script>

</head>
<body>
    <button id="code" onclick="dd.ready()">获取授权码</button>
</body>
</html>

使用钉钉的控制台打开微应用,看下效果:

技术图片

通过api调试,获取下用户信息:

技术图片

以上是关于php怎么获取钉钉员工授权信息?的主要内容,如果未能解决你的问题,请参考以下文章

钉钉userid获取异常是啥意思

钉钉小窗口模式在哪里设置

钉钉开发入门,微应用识别用户身份,获取用户免登授权码code,获取用户userid,获取用户详细信息

Java钉钉开发_异常_01_error code:50002, error message:请求的员工userid不在授权范围内

钉钉授权第三方WEB网站扫码登录

Java钉钉开发_02_免登授权(身份验证)(附源码)