Google API RefreshToken不适用于Google云端硬盘 [英] Google APIs RefreshToken does not work for Google Drive

查看:97
本文介绍了Google API RefreshToken不适用于Google云端硬盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Laravel项目中单击按钮的同时在Google云端硬盘中创建一个文件夹.我正在关注本教程 API密钥刷新令牌

I want to create a folder in Google Drive while clicking the button in the Laravel project. I am following this tutorial API Keys, Refresh Token

以下代码运行正常.但是在1小时(3600秒)之后,我无法创建该文件夹,并且出现以下错误.

The following code is working fine. But after 1 hour(3600 seconds) I am unable to create the folder and I am getting the following error.

{
    "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
}

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

So, then I want to create the access token again manually then update it here. The code as follows

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

推荐答案

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

I suggest you implement the PHP quickstart [1] into your code using the credentials.json file. With the access token you can update the refresh token everytime that expires (3600s), it's a better aproach:

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

这篇关于Google API RefreshToken不适用于Google云端硬盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆