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获取用户信息的实例(PHP)
猜你喜欢
转载自blog.csdn.net/gdali/article/details/88821437
今日推荐
周排行