使用OAUTH的PHP API对Google表格的访问失败

时间:2019-01-30 15:10:51

标签: google-api google-sheets-api google-oauth2

我正在尝试将PHP应用程序连接到Google表格以读取和写入特定的表格,但是身份验证失败,其中包含不受支持的重定向URI或“ [[30-Jan-2019 09:54:09 America / New_York] PHP致命错误:消息“缺少所需的重定向URI”的未捕获异常'InvalidArgumentException'“

我们尝试使用服务帐户使用JSON凭据进行身份验证

function getClient()
{
    putenv('GOOGLE_APPLICATION_CREDENTIALS=/UR VSS Integration-3764362fbc4d.json');
    $client = new Google_Client();
//  $client->setRedirectUri('https://sdcvoipaxle.ur.com:8443/google.php');
//  $client->setApplicationName('UR VSS Integration');
//  $client->setScopes(Google_Service_Sheets::SPREADSHEETS);
//  $client->setAuthConfig('UR VSS Integration-3764362fbc4d.json');
//  $client->setAccessType('offline');
//  $client->setPrompt('select_account consent');
    $client->useApplicationDefaultCredentials();

    // 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 = '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;
}

是否有更好的方法来使用PHP处理服务器到服务器的身份验证,或者我可以进行更改以使其连接?

0 个答案:

没有答案