Php Google Admin SDK:您无权访问此API

Php Google Admin SDK:您无权访问此API,php,google-api,google-oauth,google-api-php-client,google-admin-sdk,Php,Google Api,Google Oauth,Google Api Php Client,Google Admin Sdk,自从上周谷歌登录认证被禁用以来,我正试图让OAuth2.0使用一个服务帐户。我们希望给我们内部web应用程序的用户一个离开办公室的机会 我下载了最新的。在中,我为我的应用程序创建了一个新项目,并创建了一个服务帐户凭据。我还在开发人员控制台中启用了API服务:AdminSDK 我已授予帐户用户ID访问正确范围的权限(我认为): 当我使用service-account.php示例并更改详细信息时,我收到一个带有访问令牌的JSON,但当我执行CURL请求(与以前相同)以从用户处获取电子邮件设置时,

自从上周谷歌登录认证被禁用以来,我正试图让OAuth2.0使用一个服务帐户。我们希望给我们内部web应用程序的用户一个离开办公室的机会

我下载了最新的。在中,我为我的应用程序创建了一个新项目,并创建了一个
服务帐户
凭据。我还在开发人员控制台中启用了API服务:
AdminSDK

我已授予帐户用户ID访问正确范围的权限(我认为):

当我使用service-account.php示例并更改详细信息时,我收到一个带有访问令牌的JSON,但当我执行CURL请求(与以前相同)以从用户处获取电子邮件设置时,会出现错误
“您无权访问此API。”

我的代码:

<?php

include_once "templates/base.php";
require_once realpath(dirname(__FILE__) . '/../src/Google/autoload.php');
$client_id = '124331845-DELETEDPART-hbh89pbgl20citf6ko.apps.googleusercontent.com'; //Client ID
$service_account_name = '124331845-DELETEDPART-89pbgl20citf6ko@developer.gserviceaccount.com'; //Email Address
$key_file_location = 'globaltext-4ce09b20cb73.p12'; //key.p12

$client = new Google_Client();
if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name,
    array('https://apps-apis.google.com/a/feeds/emailsettings/2.0/'),
    $key
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}

$aOutput = json_decode($client->getAccessToken());

$strEmailAdresSplit = explode('@', "FIRSTNAME.LASTNAME@DOMAIN.EXTENSION");
$strDomein = $strEmailAdresSplit[1];
$strAlias = $strEmailAdresSplit[0];

$resConnectionJobs = curl_init();
$aHeader = array();
$aHeader[] = 'Authorization: Bearer '.$aOutput->access_token; 
$aHeader[] = 'Content-Type: application/atom+xml'; 

curl_setopt($resConnectionJobs, CURLOPT_URL, "https://apps-apis.google.com/a/feeds/emailsettings/2.0/DOMAIN.EXTENSION/FIRSTNAME.LASTNAME/vacation"); 
curl_setopt($resConnectionJobs, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($resConnectionJobs, CURLOPT_HTTPHEADER, $aHeader);
curl_setopt($resConnectionJobs, CURLOPT_RETURNTRANSFER, true);
curl_setopt($resConnectionJobs, CURLOPT_HEADER, false);

$oCurlData = curl_exec($resConnectionJobs);

curl_close($resConnectionJobs);
echo $oCurlData;

?>

您确定您的凭证没有问题吗

请尝试以下步骤以确保您具有正确的凭据

创建API密钥

转到,然后执行以下步骤:

  • 选择您的项目
  • 选择菜单项“API和身份验证”
  • 选择菜单项“注册应用程序”
  • 注册“web应用程序”类型的应用程序
  • 根据您正在创建的应用类型,选择以下选项之一。服务器端语言应使用此选项:
    • 服务器应用的密钥(带IP锁定)

获取访问令牌和刷新令牌

创建包含以下代码的文件:

<?php

if (isset($_GET['code'])) {
    // try to get an access token
    $code = $_GET['code'];
    $url = 'https://accounts.google.com/o/oauth2/token';
    $params = array(
        "code" => $code,
        "client_id" => YOUR_CLIENT_ID,
        "client_secret" => YOUR_CLIENT_SECRET,
        "redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
        "grant_type" => "authorization_code"
    );

    $ch = curl_init();
    curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
    curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
    curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
    $output = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    if ($info['http_code'] === 200) {
        header('Content-Type: ' . $info['content_type']);
        return $output;
    } else {
        return 'An error happened';
    }
} else {

    $url = "https://accounts.google.com/o/oauth2/auth";

    $params = array(
        "response_type" => "code",
        "client_id" => YOUR_CLIENT_ID,
        "redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
        "scope" => "https://www.googleapis.com/auth/plus.me"
    );

    $request_to = $url . '?' . http_build_query($params);

    header("Location: " . $request_to);
}
结果可能包含其他字段,具体取决于您申请的范围


在后台连接谷歌系统

一旦实现上述功能,应用程序需要实现以下工作流:

1) 检查输入是否包含名为“code”的GET参数。如果存在“代码”,则获取新的访问令牌并重复此步骤(刷新页面) 如果“代码”不存在,请转至步骤2

2) 检查是否存储了服务的凭据。如果存在凭据,请检查您的访问令牌是否已过期或即将过期。然后转到步骤3。如果凭据不存在,请转到服务的身份验证路径以获取身份验证代码,然后返回步骤1(确保Google重定向到当前URL)

3) 如果需要刷新,请刷新页面并返回步骤1。 如果不需要刷新,那么您已经准备好实际执行一开始想要执行的操作


但是,如果oAuth2流适合您,Google的PHP库会很小心。如果你正在使用他们的库,三步流程中的每一步都由库负责,你应该可以直接使用谷歌的服务做任何你想做的事情。我自己也使用这种策略

但是,您可以编写自定义库并直接与服务连接。下面是我几个月前写的一个项目中的一些开发代码。虽然它不是开箱即用的(因为它是一个控制器,是一个更大的应用程序的一部分),但它应该可以帮助您理解Google的库在幕后处理的流程

namespace Application;

class Controller_API_Google_Youtube extends Controller_API {
    public function read() {
        $scope = "https://www.googleapis.com/auth/youtube";
        $this->doOauth($scope);
    }

    function doOauth($scope) {

        $oauth2Credentials = JSON_File::load(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json');

        $paths = array(
            'token' => 'https://accounts.google.com/o/oauth2/token',
            'auth' => "https://accounts.google.com/o/oauth2/auth"
        );

       $refreshtime = 300;

        if (isset($_GET['code'])) {
            // Get access code
            $query = $_GET;
            unset($query['code']);
            if (count($query) > 0) {
                $query = '?' . http_build_query($query);
            } else {
                $query = '';
            }

            $client = \PowerTools\HTTP_Client::factory(
                        array(
                            'maps' => array(
                                'url' => $paths['token'],
                                'returntransfer' => 1,
                                'post' => true,
                                'postfields' => array(
                                    'code' => $_GET['code'],
                                    "client_id" => $oauth2Credentials['client_id'],
                                    "client_secret" => $oauth2Credentials['client_secret'],
                                    "redirect_uri" => HTTP_PROTOCOL . URL_PATH . $query,
                                    "grant_type" => "authorization_code"
                                )
                            )
                        )
            )->execute();
            $responses = $client->getResponses();
            $response = array_pop($responses);
            $info = $response['maps']->getInfo();
            $content = $response['maps']->getContent();
            if ($info['http_code'] === 200) {
                $output = JSON::decode($content);
                $oauth2Credentials[$scope] = array();
                $oauth2Credentials[$scope]['expires'] = time() + $output['expires_in'];
                $oauth2Credentials[$scope]['access_token'] = $output['access_token'];
                $oauth2Credentials[$scope]['refresh_token'] = $output['refresh_token'];
                file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json', JSON::encode($oauth2Credentials));
                header("Location: " . HTTP_PROTOCOL . URL_PATH . $query);
            } else {
                echo "Something went wrong";
            }
        } elseif (!isset($oauth2Credentials[$scope])) {
            // Get auth code

            header("Location: " . $paths['auth'] . '?' . http_build_query(
                        array(
                            "response_type" => "code",
                            "client_id" => $oauth2Credentials['client_id'],
                            "redirect_uri" => HTTP_PROTOCOL . DOMAIN_PATH,
                            "scope" => $scope
                        )
            ));
        } elseif ($oauth2Credentials[$scope]['expires'] - $refreshtime < time()) {
            // Refresh access code

            $client = \PowerTools\HTTP_Client::factory(
                        array(
                            'maps' => array(
                                'url' => $paths['token'],
                                'returntransfer' => 1,
                                'post' => true,
                                'postfields' => array(
                                    "client_id" => $oauth2Credentials['client_id'],
                                    "client_secret" => $oauth2Credentials['client_secret'],
                                    "refresh_token" => $oauth2Credentials[$scope]['refresh_token'],
                                    "grant_type" => "refresh_token"
                                )
                            )
                        )
            )->execute();
            $responses = $client->getResponses();
            $response = array_pop($responses);
            $info = $response['maps']->getInfo();
            $content = $response['maps']->getContent();
            if ($info['http_code'] === 200) {
                $output = JSON::decode($response['maps']->getContent());
                $oauth2Credentials[$scope]['expires'] = time() + $output['expires_in'];
                $oauth2Credentials[$scope]['access_token'] = $output['access_token'];
                file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json', JSON::encode($oauth2Credentials));
                $this->read();
            } else {
                $this->output = array("error" => "Something went wrong");
            }
        } else {
            $this->doSomethinguseful($oauth2Credentials, $scope);
        }
        return $this;
    }


    function doSomethinguseful($oauth2Credentials, $scope) {
        // https://developers.google.com/youtube/v3/sample_requests?hl=nl
        $client = \PowerTools\HTTP_Client::factory(
                    array(
                        'maps' => array(
                            'useragent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13',
                            'url' => 'https://www.googleapis.com/youtube/v3/channels?part=contentDetails&mine=true',
                            'returntransfer' => true,
                            'httpheader' => array(
                                'Authorization: Bearer ' . $oauth2Credentials[$scope]['access_token'],
                                'Accept-Encoding: gzip, deflate'
                            )
                        )
                    )
        )->execute();
        $responses = $client->getResponses();
        $response = array_pop($responses);
        $content = $response['maps']->getContent();
        $this->output = JSON::decode(gzdecode($content));
    }
}
名称空间应用;
类控制器\ API \谷歌\ Youtube扩展控制器\ API{
公共功能read(){
$scope=”https://www.googleapis.com/auth/youtube";
$this->doOauth($scope);
}
函数doOauth($scope){
$oauth2Credentials=JSON_File::load(_DIR__.DIRECTORY_SEPARATOR.'Config.JSON');
$path=数组(
'令牌'=>'https://accounts.google.com/o/oauth2/token',
“auth'=>”https://accounts.google.com/o/oauth2/auth"
);
$refreshttime=300;
如果(isset($_GET['code'])){
//获取访问代码
$query=$\u GET;
未设置($query['code']);
如果(计数($query)>0){
$query='?'.http_build_query($query);
}否则{
$query='';
}
$client=\PowerTools\HTTP\u client::factory(
排列(
“映射”=>数组(
'url'=>$path['token'],
“returntransfer”=>1,
'post'=>正确,
“postfields”=>数组(
'code'=>$\u GET['code'],
“客户机id”=>$oauth2Credentials[“客户机id”],
“客户机密”=>$oauth2Credentials[“客户机密”],
“重定向\u uri”=>HTTP\u协议.URL\u路径.$query,
“授权类型”=>“授权代码”
)
)
)
)->执行();
$responses=$client->getResponses();
$response=array_pop($response);
$info=$response['maps']->getInfo();
$content=$response['maps']->getContent();
如果($info['http_code']==200){
$output=JSON::decode($content);
$oauth2Credentials[$scope]=array();
$oauth2Credentials[$scope]['expires']=time()+$output['expires\u in'];
$oauth2Credentials[$scope]['access\u token']=$output['access\u token'];
$oauth2Credentials[$scope]['refresh_token']=$output['refresh_token'];
文件内容('Config.json',json::encode($oauth2Credentials));
标题(“位置:“.HTTP\u协议.URL\u路径.$query”);
}否则{
呼应“出了问题”;
}
}elseif(!isset($oauth2Credentials[$scope])){
//获取身份验证代码
标题(“位置:“.$path['auth']”.?”。http\u build\u查询(
namespace Application;

class Controller_API_Google_Youtube extends Controller_API {
    public function read() {
        $scope = "https://www.googleapis.com/auth/youtube";
        $this->doOauth($scope);
    }

    function doOauth($scope) {

        $oauth2Credentials = JSON_File::load(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json');

        $paths = array(
            'token' => 'https://accounts.google.com/o/oauth2/token',
            'auth' => "https://accounts.google.com/o/oauth2/auth"
        );

       $refreshtime = 300;

        if (isset($_GET['code'])) {
            // Get access code
            $query = $_GET;
            unset($query['code']);
            if (count($query) > 0) {
                $query = '?' . http_build_query($query);
            } else {
                $query = '';
            }

            $client = \PowerTools\HTTP_Client::factory(
                        array(
                            'maps' => array(
                                'url' => $paths['token'],
                                'returntransfer' => 1,
                                'post' => true,
                                'postfields' => array(
                                    'code' => $_GET['code'],
                                    "client_id" => $oauth2Credentials['client_id'],
                                    "client_secret" => $oauth2Credentials['client_secret'],
                                    "redirect_uri" => HTTP_PROTOCOL . URL_PATH . $query,
                                    "grant_type" => "authorization_code"
                                )
                            )
                        )
            )->execute();
            $responses = $client->getResponses();
            $response = array_pop($responses);
            $info = $response['maps']->getInfo();
            $content = $response['maps']->getContent();
            if ($info['http_code'] === 200) {
                $output = JSON::decode($content);
                $oauth2Credentials[$scope] = array();
                $oauth2Credentials[$scope]['expires'] = time() + $output['expires_in'];
                $oauth2Credentials[$scope]['access_token'] = $output['access_token'];
                $oauth2Credentials[$scope]['refresh_token'] = $output['refresh_token'];
                file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json', JSON::encode($oauth2Credentials));
                header("Location: " . HTTP_PROTOCOL . URL_PATH . $query);
            } else {
                echo "Something went wrong";
            }
        } elseif (!isset($oauth2Credentials[$scope])) {
            // Get auth code

            header("Location: " . $paths['auth'] . '?' . http_build_query(
                        array(
                            "response_type" => "code",
                            "client_id" => $oauth2Credentials['client_id'],
                            "redirect_uri" => HTTP_PROTOCOL . DOMAIN_PATH,
                            "scope" => $scope
                        )
            ));
        } elseif ($oauth2Credentials[$scope]['expires'] - $refreshtime < time()) {
            // Refresh access code

            $client = \PowerTools\HTTP_Client::factory(
                        array(
                            'maps' => array(
                                'url' => $paths['token'],
                                'returntransfer' => 1,
                                'post' => true,
                                'postfields' => array(
                                    "client_id" => $oauth2Credentials['client_id'],
                                    "client_secret" => $oauth2Credentials['client_secret'],
                                    "refresh_token" => $oauth2Credentials[$scope]['refresh_token'],
                                    "grant_type" => "refresh_token"
                                )
                            )
                        )
            )->execute();
            $responses = $client->getResponses();
            $response = array_pop($responses);
            $info = $response['maps']->getInfo();
            $content = $response['maps']->getContent();
            if ($info['http_code'] === 200) {
                $output = JSON::decode($response['maps']->getContent());
                $oauth2Credentials[$scope]['expires'] = time() + $output['expires_in'];
                $oauth2Credentials[$scope]['access_token'] = $output['access_token'];
                file_put_contents(__DIR__ . DIRECTORY_SEPARATOR . 'Config.json', JSON::encode($oauth2Credentials));
                $this->read();
            } else {
                $this->output = array("error" => "Something went wrong");
            }
        } else {
            $this->doSomethinguseful($oauth2Credentials, $scope);
        }
        return $this;
    }


    function doSomethinguseful($oauth2Credentials, $scope) {
        // https://developers.google.com/youtube/v3/sample_requests?hl=nl
        $client = \PowerTools\HTTP_Client::factory(
                    array(
                        'maps' => array(
                            'useragent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13',
                            'url' => 'https://www.googleapis.com/youtube/v3/channels?part=contentDetails&mine=true',
                            'returntransfer' => true,
                            'httpheader' => array(
                                'Authorization: Bearer ' . $oauth2Credentials[$scope]['access_token'],
                                'Accept-Encoding: gzip, deflate'
                            )
                        )
                    )
        )->execute();
        $responses = $client->getResponses();
        $response = array_pop($responses);
        $content = $response['maps']->getContent();
        $this->output = JSON::decode(gzdecode($content));
    }
}