* * 获取accesstoken * * @param int $id * @return hinkResponse */ public function AccessToken($appid) { //获取url $file = $this->accesstoken_url; if(!file_exists($file)){ $token = $this->get_accesstoken($appid); }else{ $fileInfo = explode(",",file_get_contents($file)); if(!empty(trim($fileInfo[0])) && $fileInfo[1] >= time()){ $token = $fileInfo[0]; }else{ $token = $this->get_accesstoken($appid); } } return $token; } /** * 获取token */ private function get_accesstoken($appid) { $data = [ "grant_type"=>"client_credential", "appid"=>$appid, "secret"=>$this->AppSecret ]; $url = $this->url_token; $tokeninfo = $this->jsonDecode(https_request($url,$data),"access_token"); if($tokeninfo){ $text = $tokeninfo.",".(time()+7000); //写入文件中 $file = $this->accesstoken_url; if(!file_exists($file)){ fopen($file,"wb"); } //把值存入文件中 $myfile = fopen($file,"w"); fwrite($myfile, $text);//写入文件 fclose($myfile);//关闭文件 } return $tokeninfo; } /** * json数据处理 */ private function jsonDecode($data,$key) { $new_data = json_decode($data,true); if(array_key_exists($key,$new_data)){ return $new_data[$key]; } return $data; }
PHP获取access_token
标签:get res amp app grant vat write pen code
小编还为您整理了以下内容,可能对您也有帮助:
weiphp。access_token获取失败
我们通过一些手段尝试性的触发问题现象:
1、测试环境下,清空access_token的redis数据。
2、正常测试,功能ok,查看access_token的redis内容,这里假设值为A。
3、手动调用接口刷新access_token,大概十几次后,值变化为B。
4、再次正常测试,发现功能异常(因为此时存储在redis的access_token已经过期)。
5、清空access_token的redis数据,再次测试,功能又恢复正常。
现在问题终于变成必现的了:)
解决方案
现在我们搞清楚问题的原因是存储在redis的access_token可能在很短的时间内过期(因为有太多中控服务器啦),但是我们一般设置的有效期都接近或等于7200s,这就导致一旦出现问题的话,如果不清理redis,问题就会持续2小时左右,这简直就是灾难!
目前想到的比较理想的解决方案就是:服务器发现功能异常时,刷新access_token并更新redis,然后再次调用接口。这种容错机制本来是微信的事-_-!
php怎么获取钉钉员工授权信息?
做过一个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']);
});
}
如何获取accessToken
通过用户验证登录和授权,获取Access Token,为下一步获取用户的OpenID做准备;
同时,Access Token是应用在调用OpenAPI访问和修改用户数据时必须传入的参数。
access token由每次用户登录时生成,过期时间默认为三个月,用户再次登录时自动刷新,请网站或应用做好防过期策略,或过期后提示用户再次授权。
OAuth2.0针对网站接入,提供了登录验证和授权流程,主要提供以下获取access token的方式:
1. server-side模式
即OAuth官方文档中提到的Authorization Code模式,适用于需要从web server访问的应用。
2. client-side模式
即OAuth官方文档中提到的Implicit模式,适用于需要通过客户端访问的方式。
以上两种模式仅在获取access_token时有所区别,后续获取openid、调用API等方式均相同。