【问题标题】:Google drive api and php error 401谷歌驱动器 api 和 php 错误 401
【发布时间】:2018-07-10 08:52:09
【问题描述】:

我正在尝试运行 google drive API 示例。我在 google API 控制台中设置了我的项目。我将脚本上传到主机。

index.php
<?php 
require_once __DIR__.'/vendor/autoload.php';

session_start();
//session_unset();

$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
  $drive = new Google_Service_Drive($client);
  $files = $drive->files->listFiles(array())->getFiles();
  echo json_encode($files);
} else {
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


OAuth2callback.php
<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfigFile('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);

if (! isset($_GET['code'])) {
  $auth_url = $client->createAuthUrl();
  header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
  header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

它有效。但几个小时后,我收到了错误401。我取消了session_unset() 的注释;运行一次并再次发表评论。有用。我需要纠正什么?

【问题讨论】:

  • 401 表示您的访问令牌已过期。您需要查看 php 库的文档以了解如何使用新库。可能就像遇到 401 时给他打电话一样简单
  • 我无法拦截错误。错误 401 出现在 google php 库中。但是,如果我在它再次开始工作时取消设置会话。

标签: php google-api google-drive-api google-oauth google-api-php-client


【解决方案1】:

您应该请求离线访问,以便您拥有一个可用于请求新访问令牌的刷新令牌

以下文件相当大,我只复制了带有刷新令牌的部分。

Oauth2Authentication.php

 require_once __DIR__ . '/vendor/autoload.php';
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    $client = getOauth2Client();
    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
    }
return $client;
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2
 * Scopes will need to be changed depending upon the API's being accessed.
 * Example:  array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function buildClient(){

    $client = new Google_Client();
    $client->setAccessType("offline");        // offline access.  Will result in a refresh token
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope([YOUR SCOPES HERE]);
    $client->setRedirectUri(getRedirectUri());  
    return $client;
}
/**
 * Builds the redirect uri.
 * Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
 * Hostname and current server path are needed to redirect to oauth2callback.php
 * @return A redirect uri.
 */
function getRedirectUri(){
    //Building Redirect URI
    $url = $_SERVER['REQUEST_URI'];                    //returns the current URL
    if(strrpos($url, '?') > 0)
        $url = substr($url, 0, strrpos($url, '?') );  // Removing any parameters.
    $folder = substr($url, 0, strrpos($url, '/') );   // Removeing current file.
    return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}
/**
 * Authenticating to Google using Oauth2
 * Documentation:  https://developers.google.com/identity/protocols/OAuth2
 * Returns a Google client with refresh token and access tokens set. 
 *  If not authencated then we will redirect to request authencation.
 * @return A google client object.
 */
function getOauth2Client() {
    try {

        $client = buildClient();

        // Set the refresh token on the client. 
        if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
            $client->refreshToken($_SESSION['refresh_token']);
        }

        // If the user has already authorized this app then get an access token
        // else redirect to ask the user to authorize access to Google Analytics.
        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {

            // Set the access token on the client.
            $client->setAccessToken($_SESSION['access_token']);                 

            // Refresh the access token if it's expired.
            if ($client->isAccessTokenExpired()) {              
                $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
                $client->setAccessToken($client->getAccessToken()); 
                $_SESSION['access_token'] = $client->getAccessToken();              
            }           
            return $client; 
        } else {
            // We do not have access request access.
            header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
        }
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

oauth2callback.php

    require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
    $client = buildClient();
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
    $client = buildClient();
    $client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
    // Add access token and refresh token to seession.
    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();    
    //Redirect back to main script
    $redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());    
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

一旦您拥有刷新令牌,您的代码将能够在访问令牌过期后刷新用户的访问权限。

注意以上代码是我自己的示例代码,不是官方的google示例。

【讨论】:

  • 出现错误致命错误:在第 10 行的 /home/consult4/consultant.co.ua/gdrive/oauth2callback.php 中调用未定义函数 buildClient()
  • 构建客户端是这个文件的一部分github.com/LindaLawton/Google-APIs-PHP-Samples/blob/master/… 最好你在 Github 上检查这两个文件,因为有很多代码要复制到这个 anwser 中。
  • 我使用 oauth2 第 3 版,并按照 google 说明下载了所有内容。
  • 我的问题中有两个链接,您没有完整的文件,您需要完整的文件才能运行它。我现在已经在 anwser 中添加了完整的代码
猜你喜欢
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-09
  • 1970-01-01
相关资源
最近更新 更多