Skip to content

Instantly share code, notes, and snippets.

@sergomet
Forked from ivanvermeyen/!NOTE.md
Created April 1, 2017 07:01
Show Gist options
  • Save sergomet/f234cc7a8351352170eb547cccd65011 to your computer and use it in GitHub Desktop.
Save sergomet/f234cc7a8351352170eb547cccd65011 to your computer and use it in GitHub Desktop.
Setup a Laravel Storage driver with Google Drive API

Setup a Laravel Storage driver with Google Drive API

Log in to your Google Account and go to this website:

https://console.developers.google.com/

Getting your Client ID and Client Secret

Create a new project using the dropdown at the top.

Create a new project

After you enter a name, it takes a few seconds before the project is successfully created on the server.

Make sure you have the project selected at the top.

Then go to Library and click on "Drive API" under "Google Apps APIs".

Find Google Drive API

And then Enable it.

Enable Google Drive API

Then, go to "Credentials" and click on the tab "OAuth Consent Screen". Fill in a "Product name shown to users" and Save it. Don't worry about the other fields.

Consent Screen

Then go back to Credentials, click the button that says "Create Credentials" and select "OAuth Client ID".

Create Credentials

Choose "Web Application" and give it a name.

Enter your "Authorized redirect URIs", preferably your test URL (http://mysite.dev) and your production URL (https://mysite.com) - or create a separate production key later. Also add https://developers.google.com/oauthplayground temporarily, because you will need to use that in the next step.

Credentials

Click Create and take note of your Client ID and Client Secret.

Getting your Refresh Token

Now head to https://developers.google.com/oauthplayground.

Make sure you added this URL to your Authorized redirect URIs in the previous step.

In the top right corner, click the settings icon, check "Use your own OAuth credentials" and paste your Client ID and Client Secret.

Use your own OAuth credentials

In step 1 on the left, scroll to "Drive API v3", expand it and check each of the scopes.

Check Scopes

Click "Authorize APIs" and allow access to your account when prompted.

When you get to step 2, check "Auto-refresh the token before it expires" and click "Exchange authorization code for tokens".

Exchange authorization code for tokens

When you get to step 3, click on step 2 again and you should see your refresh token.

Refresh Token

Getting your Folder ID

If you want to store files in your Google Drive root directory, then the folder ID can be null. Else go into your Drive and create a folder.

Because Google Drive allows for duplicate names, it identifies each file and folder with a unique ID. If you open your folder, you will see the Folder ID in the URL.

Folder ID

Install in Laravel

Pull in Flysystem Adapter for Google Drive:

composer require nao-pon/flysystem-google-drive:~1.1

Add the storage disk configuration to config/filesystem.php:

return [
  
    // ...
  
    'cloud' => 'google', // Optional: set Google Drive as default cloud storage
    
    'disks' => [
        
        // ...
        
        'google' => [
            'driver' => 'google',
            'clientId' => env('GOOGLE_DRIVE_CLIENT_ID'),
            'clientSecret' => env('GOOGLE_DRIVE_CLIENT_SECRET'),
            'refreshToken' => env('GOOGLE_DRIVE_REFRESH_TOKEN'),
            'folderId' => env('GOOGLE_DRIVE_FOLDER_ID'),
        ],
        
        // ...
        
    ],
    
    // ...
];

And update your .env file:

GOOGLE_DRIVE_CLIENT_ID=xxx.apps.googleusercontent.com
GOOGLE_DRIVE_CLIENT_SECRET=xxx
GOOGLE_DRIVE_REFRESH_TOKEN=xxx
GOOGLE_DRIVE_FOLDER_ID=null

Save GoogleDriveServiceProvider.php to app/Providers and add it to the providers array in config/app.php:

App\Providers\GoogleDriveServiceProvider::class,

Test Drive

Now you should be up and running:

Route::get('test', function() {
    Storage::disk('google')->put('test.txt', 'Hello World');
});
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class GoogleDriveServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
\Storage::extend('google', function($app, $config) {
$client = new \Google_Client();
$client->setClientId($config['clientId']);
$client->setClientSecret($config['clientSecret']);
$client->refreshToken($config['refreshToken']);
$service = new \Google_Service_Drive($client);
$adapter = new \Hypweb\Flysystem\GoogleDrive\GoogleDriveAdapter($service, $config['folderId']);
return new \League\Flysystem\Filesystem($adapter);
});
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
}
@netwons
Copy link

netwons commented Oct 29, 2021

yes

@jakecausier
Copy link

Unfortunately the refresh token expires after 30 or so days and required a new one to be generated, even with the "Auto-refresh the token" checkbox enabled. It returns a 403 code.
Any idea on how to bypass this?

@jrnbulu
Copy link

jrnbulu commented Dec 5, 2021

Stuck with below details. Any help!!!
Google\Service\Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}

  1. used secret and refresh token with double quote in .env file.
  2. Required configuration done at Google side
  3. calling Storage::cloud()->put("abc.png", $itemimage->imagedata); from a service file directly.
  4. code for GoogleDriveServiceProvider
setClientId($config['clientId']); $client->setClientSecret($config['clientSecret']); $client->refreshToken($config['refreshToken']); $service = new \Google_Service_Drive($client); $adapter = new \Hypweb\Flysystem\GoogleDrive\GoogleDriveAdapter($service, $config['folderId']); return new \League\Flysystem\Filesystem($adapter); }); } /** * Register the application services. * * @return void */ public function register() { // } } 5. app.php and filesystem.php required changes done.

@ChristianJAYs
Copy link

I am getting an error of: "ErrorException Undefined index:" on the "app\Providers\GoogleDriveServiceProvider." which is the Client ID. Does anyone knows how to solve this? Thank you

Copy link

ghost commented Dec 15, 2021

@ChristianJAYs It will me more clear If you can show your "app\Providers\GoogleDriveServiceProvider." file.

@ptucky
Copy link

ptucky commented Jan 7, 2022

Cool Thanks for this guide. Save my life ^_^

@akhmadgozali
Copy link

how to make token never expires?

@ankur377
Copy link

How to solve this eror
Failed to connect to oauth2.googleapis.com port 443: Timed out

@netwons
Copy link

netwons commented Jun 4, 2022

okey

@jocelinkisenga
Copy link

Is this package working in laravel 9?

@Jangbe
Copy link

Jangbe commented Jul 12, 2022

Is this package working in laravel 9?

I think this package is no longer supported for laravel 9, see this package instead Link

@eken007
Copy link

eken007 commented Aug 16, 2022

i have a 403 error (We are sorry but your computer or network may be sending automated requests.)

@thambaru
Copy link

Even though this package is widely explained in many tutorials, it no longer supports Laravel v9.

composer require nao-pon/flysystem-google-drive:~1.1

Problem 1
- Root composer.json requires nao-pon/flysystem-google-drive ~1.1 -> satisfiable by nao-pon/flysystem-google-drive[1.1.0, ..., 1.1.x-dev].
- nao-pon/flysystem-google-drive[1.1.0, ..., 1.1.x-dev] require league/flysystem ~1.0 -> found league/flysystem[1.0.0-alpha1, ..., 1.x-dev] but the package is fixed to 3.2.1 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.

@ItzSamdam
Copy link

Yes @thambaru Laravel 9 Support isn't available but i tried this out and it worked perfectly for all the laravel 9 i've worked with so far.
Check it out @ https://github.com/masbug/flysystem-google-drive-ext/tree/v2.2.0

@thambaru
Copy link

@ODEVLAB Indeed! That's what I finally ended up using. It has the same structure and I didn't have to change much to adapt it.
Thanks for the link - in name of the future viewers.

@masterewot
Copy link

Let Me try this.

@ItzSamdam
Copy link

@thambaru For the Love of the Game. Anytime Fam

@leosek
Copy link

leosek commented Oct 31, 2022

refresh token expired every week, even after selecting the "Auto-refresh the token before it expires" check box, Kindly help on this.
THANKS IN ADVANCE.

Follow the tutorial step step by step given above. Me too using the same and never got any token errors.

Facing same issue - refresh token expires. Isn't it meant that the token must be used before it expires? So disk access must be done relatively often?

Copy link

ghost commented Apr 7, 2023

I have an issue with how we manage folders with the same name every time when google drive creates a new folder with the same name. Can we handle this with this package or any other solution?

@reshma-noovosoft
Copy link

reshma-noovosoft commented Sep 27, 2023

I have an issue while uploading file on google drive as it uses a refresh token which expires after some time period that affects the file uploading flow .It gives error while uploading refresh token has been expired .What can be the solution on it ?

@Noctum98
Copy link

Noctum98 commented Oct 9, 2023

Hi, may i know why our refresh token expired every week? any suggestion? we already checked the Auto refresh before it expires

Could you solve it? the same happens to me

@lokmanm
Copy link

lokmanm commented Feb 7, 2024

We have written step-by-step instructions covering the latest updates:

@theanh-mume
Copy link

{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED", "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "CREDENTIALS_MISSING", "domain": "googleapis.com", "metadata": { "service": "drive.googleapis.com", "method": "google.apps.drive.v3.DriveFiles.Create" } } ] } }
Someone help me fix the bug

@addhes
Copy link

addhes commented May 16, 2024

how to delete data from google drive?

@rsddossantos
Copy link

Stuck with below details. Any help!!!

{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See ▶
"errors": [
{
"message": "Login Required.",
"domain": "global",
"reason": "required",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED",
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "CREDENTIALS_MISSING",
"domain": "googleapis.com",
"metadata": {
"method": "google.apps.drive.v3.DriveFiles.Create",
"service": "drive.googleapis.com"
}
}
]
}
}

@inaam-ul-haq
Copy link

I have successfully connected with Google Drive. is there any idea how I can make an expire refresh token which will never expire?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment