Google Drive API installation procedure using PHP Quickstart
Aug 24, 2020
PHP
Beginner
GoogleDrive
I used Google Drive API, so I have a memo
Set up connection using Quickstart
Install Google Client Library
- Type the following on the command line
composer require google/apiclient:^2.0
Download credentials
*If you have already set up the OAuth 2.0 client (If not set, set OAuth 2.0 client first)
- Press “Credentials” from Google Cloud platform to open the credentials screen
- Click the download button at the right end of the created ID from the OAuth 2.0 client ID list to download the file
Creating a sample program
PHP Quickstart | Google Drive API | Google Developers https://developers.google.com/drive/api/v3/quickstart/php
- Open PHP Quickstart page from within Google Drive API documentation
- Copy the quickstart.php described in Step 3: Set up the sample
- Specify the application name set in the OAuth consent screen in setApplicationName(), specify the downloaded authentication information path in setAuthConfig()
<?php
require __DIR__ .'/vendor/autoload.php';
if (php_sapi_name() !='cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart'); //Specify the set application name
$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setAuthConfig('credentials.json'); //JSON path obtained here
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// 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);
}
Executing the sample program
- Run the following from the command line
php quickstart.php
Connection consent
- After executing the sample program, the URL is displayed, so copy it and access it from the browser
- When you access, the OAuth 2.0 consent screen will be displayed and you will be allowed to follow the screen. -If you access it and see “This app has not been confirmed.”
- Grant permission and copy the code below that says “Copy this code, switch to the application and paste it.”
- Paste it to Enter verification code: on the command line
[hoge@hogehoge hoge]$ php quickstart.php
Open the following link in your browser:
https://accounts.google.com/o/oauth2/auth?response_type........
Enter verification code: