如何设置Gogle的人API

发布于 2025-01-23 19:09:49 字数 4951 浏览 4 评论 0 原文

我一直在尝试设置示例 php QuickStart

当我尝试按照以下错误来运行它时:

PHP Fatal error:  Uncaught InvalidArgumentException: missing the required redirect URI in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php:685
Stack trace:
#0 /opt/lampp/htdocs/rev_wip/vendor/google/apiclient/src/Client.php(406): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 /opt/lampp/htdocs/rev_wip/quickstart.php(40): Google\Client->createAuthUrl()
#2 /opt/lampp/htdocs/rev_wip/quickstart.php(64): getClient()
#3 {main}
  thrown in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php on line 685

所以我添加了一个URI:

// $redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['PHP_SELF'];

$client->setRedirectUri($redirect_uri);

现在得到(当我在浏览器上运行时):

Authorization Error
Error 400: redirect_uri_mismatch

You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy.

If you're the app developer, register the redirect URI in the Google Cloud Console.
Learn more
The content in this section has been provided by the app developer. This content has not been reviewed or verified by Google.
If you’re the app developer, make sure that these request details comply with Google policies.

redirect_uri: http://localhost/rev_wip/quickstart.php

我认为此示例是 desktop app and> and >因此,不应有重定向的URI。我,但是,当我在CLI上运行常见的URI错误。

我应该怎么做?

谢谢大家。

这是我正在使用的代码:

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
    $client = new Google_Client();
    $client->setApplicationName('People API PHP Quickstart');
    $client->setScopes(Google_Service_PeopleService::CONTACTS_READONLY);
    $client->setAuthConfig(__DIR__ . '/credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath   = __DIR__ . '/token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath) , true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        }
        else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode    = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath) , 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

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

// Print the names for up to 10 connections.
$optParams = array(
    'pageSize'           => 10,
    'personFields'           => 'names,emailAddresses',
);
$results   = $service
->people_connections
->listPeopleConnections('people/me', $optParams);

if (count($results->getConnections()) == 0) {
    print "No connections found.\n";
}
else {
    print "People:\n";
    foreach ($results->getConnections() as $person) {
        if (count($person->getNames()) == 0) {
            print "No names found for this connection\n";
        }
        else {
            $names = $person->getNames();
            $name  = $names[0];
            printf("%s\n", $name->getDisplayName());
        }
    }
}

?>

I've been trying to set up the sample PHP Quickstart.

When I try running it as is I get the following error :

PHP Fatal error:  Uncaught InvalidArgumentException: missing the required redirect URI in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php:685
Stack trace:
#0 /opt/lampp/htdocs/rev_wip/vendor/google/apiclient/src/Client.php(406): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
#1 /opt/lampp/htdocs/rev_wip/quickstart.php(40): Google\Client->createAuthUrl()
#2 /opt/lampp/htdocs/rev_wip/quickstart.php(64): getClient()
#3 {main}
  thrown in /opt/lampp/htdocs/rev_wip/vendor/google/auth/src/OAuth2.php on line 685

So I add a URI :

// $redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$redirect_uri = 'http://localhost/rev_wip/' . $_SERVER['PHP_SELF'];

$client->setRedirectUri($redirect_uri);

Now I get (when I run it on the browser) :

Authorization Error
Error 400: redirect_uri_mismatch

You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy.

If you're the app developer, register the redirect URI in the Google Cloud Console.
Learn more
The content in this section has been provided by the app developer. This content has not been reviewed or verified by Google.
If you’re the app developer, make sure that these request details comply with Google policies.

redirect_uri: http://localhost/rev_wip/quickstart.php

I am thinking that this example is a Desktop APP and so there should be no Redirect URI. I, however get the common redirect URI error when I run it on the CLI.

How should I go about it?

Thank you all in advance.

Here is the code that I am working with:

<?php
require __DIR__ . '/vendor/autoload.php';

if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
    $client = new Google_Client();
    $client->setApplicationName('People API PHP Quickstart');
    $client->setScopes(Google_Service_PeopleService::CONTACTS_READONLY);
    $client->setAuthConfig(__DIR__ . '/credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath   = __DIR__ . '/token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath) , true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        }
        else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode    = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath) , 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

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

// Print the names for up to 10 connections.
$optParams = array(
    'pageSize'           => 10,
    'personFields'           => 'names,emailAddresses',
);
$results   = $service
->people_connections
->listPeopleConnections('people/me', $optParams);

if (count($results->getConnections()) == 0) {
    print "No connections found.\n";
}
else {
    print "People:\n";
    foreach ($results->getConnections() as $person) {
        if (count($person->getNames()) == 0) {
            print "No names found for this connection\n";
        }
        else {
            $names = $person->getNames();
            $name  = $names[0];
            printf("%s\n", $name->getDisplayName());
        }
    }
}

?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

書生途 2025-01-30 19:09:49

在您要链接到的教程中,有一个称为“故障排除”的部分,其中有一个有关您面对的确切错误的部分:

https://developers.google.com/people/quickstart/php#uncaught_invalidargumentexception_missing_the_required_redirect_uri

未接收的无效Exception:缺少所需的重定向URI

当使用的凭证文件包含错误类型的客户端ID时,会发生此错误。
此代码需要类型其他类型的OAuth客户端ID,这将是
在步骤1中使用按钮时为您创建。如果创建自己的
客户端ID请确保您选择正确的类型。

这表明您没有正确完成步骤1,或者您提供了错误类型的客户ID。

In the tutorial you're linking to there's a section called "Troubleshooting" under which there's a section about the exact error you're facing:

https://developers.google.com/people/quickstart/php#uncaught_invalidargumentexception_missing_the_required_redirect_uri

Uncaught InvalidArgumentException: missing the required redirect URI

This error occurs when the credentials.json file used contains a client ID of the wrong type.
This code requires an OAuth client ID of type Other, which will be
created for you when using the button in Step 1. If creating your own
client ID please ensure you select the correct type.

This suggests you didn't complete step 1 properly or that you have supplied your own client ID of the wrong type.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文