Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Google客户端API-缺少require参数:redirect\u uri_Php_Google Api_Google Calendar Api - Fatal编程技术网

Php Google客户端API-缺少require参数:redirect\u uri

Php Google客户端API-缺少require参数:redirect\u uri,php,google-api,google-calendar-api,Php,Google Api,Google Calendar Api,因此,我遵循指南,决定将其划分为一个名为scheduler的类。我正在编写身份验证代码,但我一直收到这样的消息:“错误400(OAuth 2错误)错误无效请求缺少必需的参数:redirect_uri” 类调度程序{ //Google客户端对象 私人$googleClient; //谷歌日历服务ojbect 私人服务; /* *谷歌日历设置 * *这将创建一个Google客户端对象,以便您可以创建一个Google日历对象。 * */ 函数_u构造(){ //设置应用程序名称 定义(“应用程序名称”

因此,我遵循指南,决定将其划分为一个名为scheduler的类。我正在编写身份验证代码,但我一直收到这样的消息:“错误400(OAuth 2错误)错误无效请求缺少必需的参数:redirect_uri”

类调度程序{
//Google客户端对象
私人$googleClient;
//谷歌日历服务ojbect
私人服务;
/*
*谷歌日历设置
*
*这将创建一个Google客户端对象,以便您可以创建一个Google日历对象。
*
*/
函数_u构造(){
//设置应用程序名称
定义(“应用程序名称”、“Web客户端1”);
//
定义(“CREDENTIALS_PATH”,“~/scheduler/CREDENTIALS.json”);
//
定义(“CLIENT\u SECRET\u PATH”,\uuu DIR\uuu.'/scheduler/CLIENT\u SECRET.json”);
//
定义(“范围”,内爆(“,数组(Google_服务_日历::日历_只读));
/*如果(php_sapi_name()!=“cli”){
抛出新异常(“此应用程序必须在命令行上运行”);
}*/
//创建google客户端
$this->googleClient=new Google_Client();
//设置客户端
$this->googleClient->setApplicationName(应用程序名称);
$this->googleClient->setDeveloperKey(“aizasybmjlvndmyufhvpwalkudystreboveayem”);
$this->googleClient->setScopes(范围);
$this->googleClient->setAuthConfigFile(客户机路径);
$this->googleClient->setAccessType(“脱机”);
//获取凭据文件路径
$credentialsPath=expandHomeDirectory(凭据路径);
//如果文件存在
如果(文件_存在($credentialsPath)){
//从文件中获取凭据
$accessToken=文件获取内容($credentialsPath);
}//如果没有
否则{
//请求授权url
$authURL=$this->googleClient->createAuthUrl();
//打印授权ulr
回声“

”; //提示用户输入身份验证代码 打印(“输入验证码:”); // $authCode=trim(fgets(STDIN)); //交换访问令牌的授权 $accessToken=$this->googleClient->authenticate($authCode); //将凭据存储到磁盘 如果(!file_存在(dirname($credentialsPath))){ mkdir(dirname($credentialsPath),0700,true); } //将内容放入凭证文件中 文件内容($credentialsPath,$accessToken); } $this->googleClient->setAccessToken($accessToken); //刷新令牌(如果其已过期) 如果($this->googleClient->isAccessTokenExpired()){ $this->googleClient->refreshttoken($client->getrefreshttoken()); 文件内容($credentialsPath,$this->googleClient->getAccessToken()); } }

我找到了问题的原因,但找不到解决方案。在我的Google Developer控制台下,我尝试将“”放入授权重定向URI部分。它会给我以下错误:“对不起,有问题。如果您输入了信息,请检查并重试。否则,问题可能会自行解决,请稍后再试。”有没有办法让Google Developer Console接受本地主机服务器的重定向uri?

我让它工作了。我要做的是回到Google Developer Console并删除我创建的项目。然后在创建新项目时,它允许我保存我的本地主机url。出现的问题是当我去添加我的url时ocalhost url指向重定向url时,它会说此时不可能。当我在点击“创建”按钮之前设置重定向url时,它会很好地接受它。

只需在客户端对象上使用方法
setRedirectUri($absoluteUrl)

$client = new Google_Client();
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
通过:

目前,谷歌针对Sheet API的“PHP快速入门”文档似乎已经过时

为了让他们的演示使用PHP7.2+,我不得不做了很多修改,现在还不太清楚到底发生了什么。下面是他们的快速入门的一个经过评论的更新版本,可能对其他在使用Google Sheets API和PHP时遇到困难的人有所帮助

<?php
/**
 * Updated Google Sheets Quickstart
 *
 * https://developers.google.com/sheets/api/quickstart/php
 */
require __DIR__ . '/vendor/autoload.php';

/**
* Appends one slash at the end, and removes any extra slashes
* https://stackoverflow.com/a/9339669/812973
*
* @return string $path with the slash appended
*/
function addTrailingSlash ($path)
{
    return rtrim ($path, '/') . '/';
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {

     // Change this to a secure location where you'll save your config *.json files
     // Make sure it isn't publicly available on the web
    $configPath = addTrailingSlash (getcwd());

    // This get's generated by the script, so don't create it
    $credentialsPath = $configPath . 'credentials.json';

    $client = new Google_Client();

    // Matches the "Application Name" you enter during the "Step 1" wizard
    $client->setApplicationName( 'API App Name' );
    $client->setScopes( Google_Service_Sheets::SPREADSHEETS_READONLY );

    // You need to go through "Step 1" steps to generate this file: https://developers.google.com/sheets/api/quickstart/php
    $client->setAuthConfig( $configPath . 'client_secret.json' );
    $client->setAccessType( 'offline' );

    // This must match the "callback URL" that you enter under "OAuth 2.0 client ID" in the Google APIs console at https://console.developers.google.com/apis/credentials
    $client->setRedirectUri( 'https://' . $_SERVER['HTTP_HOST'] . '/' . basename( __FILE__, '.php' ) );

    // We have a stored credentials file, try using the data from there first
    if ( file_exists( $credentialsPath ) ) {
        $accessToken = json_decode( file_get_contents( $credentialsPath ), true );
    }

    // No stored credentials found, we'll need to request them with OAuth
    else {

        // Request authorization from the user
        $authUrl = $client->createAuthUrl();
        if ( ! isset( $_GET['code'] ) ) {
            header( "Location: $authUrl", true, 302 );
            exit;
        }

        // The authorization code is sent to the callback URL as a GET parameter.
        // We use this "authorization code" to generate an "access token". The
        // "access token" is what's effectively used as a private API key.
        $authCode = $_GET['code'];
        $accessToken = $client->fetchAccessTokenWithAuthCode( $authCode );

        // Create credentials.json if it doesn't already exist (first run)
        if ( ! file_exists( dirname( $credentialsPath ) ) ) {
            mkdir( dirname( $credentialsPath ), 0700, true );
        }

        // Save the $accessToken object to the credentials.json file for re-use
        file_put_contents( $credentialsPath, json_encode( $accessToken ) );
    }

    // Provide client with API access token
    $client->setAccessToken( $accessToken );

    // If the $accessToken is expired then we'll need to refresh it
    if ( $client->isAccessTokenExpired() ) {
        $client->fetchAccessTokenWithRefreshToken( $client->getRefreshToken() );
        file_put_contents( $credentialsPath, json_encode( $client->getAccessToken() ) );
    }

    return $client;
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets( $client );

// Get values from a spreadheet and print
// https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get
$spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
$range = 'Class Data!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();

if (empty($values)) {
    print "No data found.\n";
} else {
    print "Name, Major:\n";
    foreach ($values as $row) {
        // Print columns A and E, which correspond to indices 0 and 4.
        printf("%s, %s\n", $row[0], $row[4]);
    }
}

只是改进了@kevinLeary的答案,使代码看起来更模块化:

<?php

    if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
        throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
    }

    require_once __DIR__ . '/vendor/autoload.php';

    $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . '/mydrive/index.php'; // <--- Change it to your web application path, host will be detected automatically  

    $auth_file = __DIR__ . DIRECTORY_SEPARATOR . 'drive-auth.json'; // <--- Your auth2 settings
    $auth_file = str_replace('\\', '/', $auth_file);

    $configPath = addTrailingSlash(getcwd());
    $credentials_file = $configPath . 'credentials.json'; // <--- This will generated automatically


    $app_name = 'MY APP NAME';
    $scopes = [
                Google_Service_Sheets::SPREADSHEETS_READONLY, 
            ];

    /**
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
     */
    function getClient($app_name, $auth_file, $credentials_file, $redirect_url, $scopes = array()) {
        // This get's generated by the script, so don't create it
        $credentialsPath = $credentials_file;

        $client = new Google_Client();

        // Matches the "Application Name" you enter during the "Step 1" wizard
        $client->setApplicationName( $app_name );
        $client->setScopes( $scopes );

        // You need to go through "Step 1" steps to generate this file: https://developers.google.com/sheets/api/quickstart/php
        $client->setAuthConfig( $auth_file );
        $client->setAccessType( 'offline' );

        // This must match the "callback URL" that you enter under "OAuth 2.0 client ID" in the Google APIs console at https://console.developers.google.com/apis/credentials
        $client->setRedirectUri( $redirect_url );

        // We have a stored credentials file, try using the data from there first
        if ( file_exists( $credentialsPath ) ) {
            $accessToken = json_decode( file_get_contents( $credentialsPath ), true );
        }

        // No stored credentials found, we'll need to request them with OAuth
        else {

            // Request authorization from the user
            $authUrl = $client->createAuthUrl();
            if ( ! isset( $_GET['code'] ) ) {
                header( "Location: $authUrl", true, 302 );
                exit;
            }

            // The authorization code is sent to the callback URL as a GET parameter.
            // We use this "authorization code" to generate an "access token". The
            // "access token" is what's effectively used as a private API key.
            $authCode = $_GET['code'];
            $accessToken = $client->fetchAccessTokenWithAuthCode( $authCode );

            // Create credentials.json if it doesn't already exist (first run)
            if ( ! file_exists( dirname( $credentialsPath ) ) ) {
                mkdir( dirname( $credentialsPath ), 0700, true );
            }

            // Save the $accessToken object to the credentials.json file for re-use
            file_put_contents( $credentialsPath, json_encode( $accessToken ) );
        }

        // Provide client with API access token
        $client->setAccessToken( $accessToken );

        // If the $accessToken is expired then we'll need to refresh it
        if ( $client->isAccessTokenExpired() ) {
            $client->fetchAccessTokenWithRefreshToken( $client->getRefreshToken() );
            file_put_contents( $credentialsPath, json_encode( $client->getAccessToken() ) );
        }

        return $client;
    }

    // Get the API client and construct the service object.
    $client = getClient();
    $service = new Google_Service_Sheets( $client );

    // Get values from a spreadheet and print
    // https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get
    $spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
    $range = 'Class Data!A2:E';
    $response = $service->spreadsheets_values->get($spreadsheetId, $range);
    $values = $response->getValues();

    if (empty($values)) {
        print "No data found.\n";
    } else {
        print "Name, Major:\n";
        foreach ($values as $row) {
            // Print columns A and E, which correspond to indices 0 and 4.
            printf("%s, %s\n", $row[0], $row[4]);
        }
    }



    function addTrailingSlash ($path)
    {
        return rtrim ($path, '/') . '/';
    }   
?>

我的问题是我没有在谷歌控制台中初始化URI
要解决此问题,请执行以下操作:

1-转到您的项目(从顶部选择项目)

2-搜索“Google sheet API”,确保其已启用

3-在左侧菜单上单击“凭证”

4-如果您已经创建了“OAuth 2.0客户端ID”,只需单击编辑并添加URI,否则创建新的“OAuth 2.0客户端ID”


5-记住重新下载“OAuth 2.0客户端ID”,它类似于“Client\u secret\u XXX.apps.googleusercontent.com”将其重命名为credentials.json并将其设置到您的项目上

有人愿意帮忙吗?感谢发布您的解决方案-我能够编辑现有项目并添加授权重定向URI…没问题,开发人员同事。很高兴提供帮助。原因是,您下载的客户端机密json文件需要更新同样。因此,如果您在没有uri的情况下创建凭据并下载json,则json没有“重定向uri”属性。如果您随后在仪表板中添加它,则需要重新下载客户端机密json并将其添加到您的项目中。这是否适用于服务帐户?没有添加重定向uri的选项。服务是什么Account?您能提供更多详细信息,以便我尝试重新创建您的特定问题吗?您好,@Kevin Leary,我想从浏览器而不是命令行运行此代码。我想在PHP网页上显示所有工作表数据。我遵循以下操作“”教程,但当点击页面URL时,它在浏览器上不起作用。你能帮我解决这个问题吗?
<?php

    if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
        throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
    }

    require_once __DIR__ . '/vendor/autoload.php';

    $redirect_url = 'http://' . $_SERVER['HTTP_HOST'] . '/mydrive/index.php'; // <--- Change it to your web application path, host will be detected automatically  

    $auth_file = __DIR__ . DIRECTORY_SEPARATOR . 'drive-auth.json'; // <--- Your auth2 settings
    $auth_file = str_replace('\\', '/', $auth_file);

    $configPath = addTrailingSlash(getcwd());
    $credentials_file = $configPath . 'credentials.json'; // <--- This will generated automatically


    $app_name = 'MY APP NAME';
    $scopes = [
                Google_Service_Sheets::SPREADSHEETS_READONLY, 
            ];

    /**
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
     */
    function getClient($app_name, $auth_file, $credentials_file, $redirect_url, $scopes = array()) {
        // This get's generated by the script, so don't create it
        $credentialsPath = $credentials_file;

        $client = new Google_Client();

        // Matches the "Application Name" you enter during the "Step 1" wizard
        $client->setApplicationName( $app_name );
        $client->setScopes( $scopes );

        // You need to go through "Step 1" steps to generate this file: https://developers.google.com/sheets/api/quickstart/php
        $client->setAuthConfig( $auth_file );
        $client->setAccessType( 'offline' );

        // This must match the "callback URL" that you enter under "OAuth 2.0 client ID" in the Google APIs console at https://console.developers.google.com/apis/credentials
        $client->setRedirectUri( $redirect_url );

        // We have a stored credentials file, try using the data from there first
        if ( file_exists( $credentialsPath ) ) {
            $accessToken = json_decode( file_get_contents( $credentialsPath ), true );
        }

        // No stored credentials found, we'll need to request them with OAuth
        else {

            // Request authorization from the user
            $authUrl = $client->createAuthUrl();
            if ( ! isset( $_GET['code'] ) ) {
                header( "Location: $authUrl", true, 302 );
                exit;
            }

            // The authorization code is sent to the callback URL as a GET parameter.
            // We use this "authorization code" to generate an "access token". The
            // "access token" is what's effectively used as a private API key.
            $authCode = $_GET['code'];
            $accessToken = $client->fetchAccessTokenWithAuthCode( $authCode );

            // Create credentials.json if it doesn't already exist (first run)
            if ( ! file_exists( dirname( $credentialsPath ) ) ) {
                mkdir( dirname( $credentialsPath ), 0700, true );
            }

            // Save the $accessToken object to the credentials.json file for re-use
            file_put_contents( $credentialsPath, json_encode( $accessToken ) );
        }

        // Provide client with API access token
        $client->setAccessToken( $accessToken );

        // If the $accessToken is expired then we'll need to refresh it
        if ( $client->isAccessTokenExpired() ) {
            $client->fetchAccessTokenWithRefreshToken( $client->getRefreshToken() );
            file_put_contents( $credentialsPath, json_encode( $client->getAccessToken() ) );
        }

        return $client;
    }

    // Get the API client and construct the service object.
    $client = getClient();
    $service = new Google_Service_Sheets( $client );

    // Get values from a spreadheet and print
    // https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get
    $spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
    $range = 'Class Data!A2:E';
    $response = $service->spreadsheets_values->get($spreadsheetId, $range);
    $values = $response->getValues();

    if (empty($values)) {
        print "No data found.\n";
    } else {
        print "Name, Major:\n";
        foreach ($values as $row) {
            // Print columns A and E, which correspond to indices 0 and 4.
            printf("%s, %s\n", $row[0], $row[4]);
        }
    }



    function addTrailingSlash ($path)
    {
        return rtrim ($path, '/') . '/';
    }   
?>