我想获取访问令牌以调用Google Directory API。我看过几篇有关PHP Curl代码的文章,但是每次必须进行人工操作才能允许访问,然后才能获得访问令牌。有没有办法提出CURL请求并直接获取访问令牌?
到目前为止,这是我的代码:
define("CALLBACK_URL","http://localhost/los/index");
define("AUTH_URL","https://accounts.google.com/o/oauth2/auth");
define("accESS_TOKEN_URL","https://oauth2.googleapis.com/token");
define("CLIENT_ID","**.apps.googleusercontent.com");
define("CLIENT_SECRET","**");
define("SCOPE","https://www.googleapis.com/auth/admin.directory.device.chromeos");
function getToken(){
$curl = curl_init();
$params = array(
CURLOPT_URL =>
accESS_TOKEN_URL."?"."&grant_type=authorization_code"."&client_id=".
CLIENT_ID."&client_secret=". CLIENT_SECRET."&redirect_uri=". CALLBACK_URL,CURLOPT_RETURNTRANSFER => true,CURLOPT_MAXREDIRS => 10,CURLOPT_SSL_VERIFYPEER => false,CURLOPT_TIMEOUT => 30,CURLOPT_ENCODING => '',CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,CURLOPT_CUSTOMREQUEST => "POST",CURLOPT_NOBODY => false,CURLOPT_HTTPHEADER => array(
"cache-control: no-cache","Content-Length: 0","content-type: application/x-www-form-urlencoded","accept: *","accept-encoding: gzip,deflate",),);
curl_setopt_array($curl,$params);
$response = curl_exec($curl);
$err = curl_error($curl);
echo $response;
curl_close($curl);
if ($err) {
echo "cURL Error #01: " . $err;
} else {
$response = json_decode($response,true);
if(array_key_exists("access_token",$response)) return $response;
if(array_key_exists("error",$response)) echo $response["error_description"];
echo "cURL Error #02: Something went wrong! Please contact admin.";
}
}
我运行它时收到以下错误消息:
{ "error": "invalid_request","error_description": "Missing required parameter: code" }Missing required parameter: codec