php获取当前钉钉用户信息
1.拿到企业corpId
2.去钉钉管理后台创建一个微应用
3.拿到微应用的AppKey和AppSecret
4.填写应用首页地址和服务器出口IP
5.服务器出口ip需是固定ip
- html步骤
//引入钉钉的js
<script src="https://g.alicdn.com/dingding/dingtalk-jsapi/2.10.3/dingtalk.open.js"></script>
<script>
if (dd.env.platform !== "notInDingTalk") { //如果当前打开的浏览环境是钉钉
dd.runtime.permission.requestAuthCode({
corpId: "钉钉所在企业的corpId",
onSuccess: function(result) {
if(result.code){
//获取用户信息存session
$.get(createLink('user', 'getdindinuser'), {"code":result.code}, function(res)
{
alert(JSON.stringify(res));//进行调试打印出钉钉个人信息
},'json')
}
},
onFail : function(err) {
alert(JSON.stringify(err));
}
})
}
</script>
- php方法
public function getdindinuser($code){
header("content-type:application/json");
$url = "https://oapi.dingtalk.com/user/getuserinfo?access_token=".$this->getDindinAccessToken()."&code=".$code;
$user = json_decode($this->http($url),true);
echo json_encode($user,true);
die();
}
/**
* 获取钉钉AccessToken
*
* @access public
* @return void
* */
public function getDindinAccessToken()
{
$appkey = $this->appKey;//微应用的appKey
$appsecret = $this->appSecret;//微应用的appSecret
//定义token文件和路径
$token_file_name = "www/data/upload/ding_access_token.php";//存的目录自己定义
if(file_exists($token_file_name)){
$token_file_content = json_decode($this->get_php_file($token_file_name));
//token超时
if($token_file_content->expire_time < time())
{
//从接口获取token
$token = $this->getDindinToken($appkey,$appsecret,$token_file_name);
}else{
//否则使用缓存的token
$token = $token_file_content->access_token;
}
}else{
//接口获取token
$token = $this->getDindinToken($appkey, $appsecret, $token_file_name);
}
return $token;
}
/**
* 获取钉钉AccessToken
*
* @param string $appkey
* @param string $appsecret
* @param string $token_file_name
* @access public
* @return void
* */
public function getDindinToken($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;
}
public function get_php_file($filename){
return trim(substr(file_get_contents($filename), 15));
}
public 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;
}