【问题标题】:Google APIs RefreshToken does not work for Google DriveGoogle API RefreshToken 不适用于 Google Drive
【发布时间】:2019-11-16 08:14:12
【问题描述】:

我想在单击 Laravel 项目中的按钮时在 Google Drive 中创建一个文件夹。我正在关注本教程 API Keys, Refresh Token

以下代码运行良好。但在 1 小时(3600 秒)后,我无法创建文件夹,并且出现以下错误。

{
    "status": "Order not updated",
    "msg": "{\n \"error\": {\n  \"errors\": [\n   {\n    \"domain\": \"global\",\n    \"reason\": \"authError\",\n    \"message\": \"Invalid Credentials\",\n    \"locationType\": \"header\",\n    \"location\": \"Authorization\"\n   }\n  ],\n  \"code\": 401,\n  \"message\": \"Invalid Credentials\"\n }\n}\n",
    "is_success": false
}

那么,我想再次手动创建访问令牌,然后在此处更新。 代码如下

GooGleDriveController.php

<?php

namespace App\Http\Controllers;

use Exception;
use Google_Client;
use Google_Service_Drive;
use Google_Service_Drive_DriveFile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use App\Order;
use App\Enums\GoogleDriveEnum;

class GoogleDriveController extends Controller
{
    private $drive;

    public function getDrive($id)
    {
        try
        {
            $order=Order::find($id);
            $client = new Google_Client();
            $client->setClientId(GoogleDriveEnum::getValue('CLIENT_ID'));
            $client->setClientSecret(GoogleDriveEnum::getValue('CLIENT_SECRET'));
            $client->setRedirectUri(GoogleDriveEnum::getValue('REDIRECT'));
            $client->addScope(GoogleDriveEnum::getValue('SCOPE'));
            $client->setAccessToken(GoogleDriveEnum::getValue('ACCESSTOKEN'));
            $client->setIncludeGrantedScopes(true);
            $client->setApprovalPrompt("consent"); //none || consent || select_account
            $client->setAccessType("offline");
            $service = new Google_Service_Drive($client);

            $code="my_code_is_here";
            $refreshToken="my_refresh_token_is_here";
            // $client->authenticate($code);

            $tokens = $client->GetAccessToken(GoogleDriveEnum::getValue('CLIENT_ID'), GoogleDriveEnum::getValue('REDIRECT'), GoogleDriveEnum::getValue('CLIENT_SECRET'), $code);
            $client->setAccessToken($tokens["access_token"]);
            $this->drive = new Google_Service_Drive($client);

            $folder_meta = new Google_Service_Drive_DriveFile(array(
                'name' => $order->code,
                'mimeType' => 'application/vnd.google-apps.folder'));
            $folder = $this->drive->files->create($folder_meta, array(
                'fields' => 'id'));
            $order->google_drive_link = "https://drive.google.com/drive/u/0/folders/".$folder->id;
            $order->save();

            $response["msg"] = "Folder has been successfully created";
            $response["status"] = "Success";
            $response["is_success"] = true;
            return response()->json($response);

        }catch(\Exception $th)
        {
            $response["status"] = "Folder not created";
            $response["msg"] = $th->getMessage();
            $response["is_success"] = false;
            return response()->json($response);
        }
    }
}

GoogleDriveEnum.php

<?php

namespace App\Enums;

use BenSampo\Enum\Enum;

final class GoogleDriveEnum extends Enum
{
    const CLIENT_ID = 'my_client_id';
    const CLIENT_SECRET = 'my_client_secret';
    const REDIRECT = 'https://developers.google.com/oauthplayground';
    const SCOPE = 'https://www.googleapis.com/auth/drive';
    const ACCESSTOKEN = 'my_access_token';
    const REFRESHTOKEN = 'my_refresh_token';
    const CODE = 'my_code';
}

【问题讨论】:

    标签: php laravel-5 google-drive-api


    【解决方案1】:

    我建议您使用 credentials.json 文件将 PHP 快速入门 [1] 实施到您的代码中。使用访问令牌,您可以在每次过期(3600 秒)时更新刷新令牌,这是一种更好的方法:

    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()));
    }
    

    [1]https://developers.google.com/drive/api/v3/quickstart/php

    【讨论】:

    • 它显示Undefined index: expires_in,我想离线访问。不打开浏览器授权。
    • 使用手动方式,您仍然需要打开浏览器来获取令牌。如果您完全实现了快速入门,则只需第一次打开浏览器即可获取令牌,之后令牌将在即将到期时刷新。
    • 所以第一次需要从浏览器,然后不需要再次登录,对吗?
    • 没错,它会使用下载的token.json来刷新访问令牌。至少您稍后会添加更多范围,您需要为此删除 token.json,再次运行代码,这将提示您同意屏幕(登录)以使用您需要的新范围创建新的 token.json。
    • 您也可以查看services accounts,您可以使用它来进行API调用而无需进行身份验证。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    相关资源
    最近更新 更多