appid = DD_APPKEY; $this->appsecret = DD_APPSECRET; $this->access_token = $access_token; $this->refresh_token = $refresh_token; } public static function createClient(){ $config = new Config([]); $config->protocol = "https"; $config->regionId = "central"; return new Dingtalk($config); } //生成授权地址 function authUrl($redirectUrl,$state){ return 'https://login.dingtalk.com/oauth2/auth?redirect_uri='.urlencode($redirectUrl).'&response_type=code&client_id='.$this->appid.'&scope=openid&state='.$state.'&prompt=consent'; } /* * 获取token */ public function getAccessToken($code) { //获取个人用户token $client = self::createClient(); $getUserTokenRequest = new GetUserTokenRequest([ "clientId" => $this->appid, "clientSecret" => $this->appsecret, "code" => $code, "grantType" => "authorization_code" ]); try { $result = $client->getUserToken($getUserTokenRequest); $accessToken = $result->body->accessToken; $refreshToken = $result->body->refreshToken; $expireIn = $result->body->expireIn; $array = ['access_token'=>$accessToken,'refresh_token'=>$refreshToken,'expires_in'=>$expireIn]; return $array; } catch (Exception $err) { if (!($err instanceof TeaError)) { $err = new TeaError([], $err->getMessage(), $err->getCode(), $err); } if (!Utils::empty_($err->code) && !Utils::empty_($err->message)) { // err 中含有 code 和 message 属性,可帮助开发定位问题 return ['errcode'=>$err->code,'msg'=>$err->message]; } } } /** * 个人免登场景签名算法 */ function getSignature($timestamp, $appSecret){ // 根据timestamp, appSecret计算签名值 $s = hash_hmac('sha256', $timestamp, $appSecret, true); $signature = base64_encode($s); $urlencode_signature = urlencode($signature); return $urlencode_signature; } /** * post 请求 * @param $remote_server * @param $post_string * @return bool|string */ function PostCurlRequest($remote_server, $code) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $remote_server); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8')); curl_setopt($ch, CURLOPT_POSTFIELDS, $code); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $data = curl_exec($ch); curl_close($ch); return $data; } //使用扫码登录的临时CODE获取用户信息 public function getUserInfoByCode() { $access_key = $this->appid; //应用的AppKey $app_secret = $this->appsecret; //应用秘钥 $code = json_encode(['tmp_auth_code' => $_GET['code']]); //获取临时code $time = time() . '000'; //毫秒时间戳 $urlencode_signature = $this->getSignature($time, $app_secret); //签名 //地址组装,获取用户信息 $remote_server = 'https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey='. $access_key .'×tamp=' . $time . '&signature=' . $urlencode_signature; $json = $this->PostCurlRequest($remote_server, $code); return $json; } }