0% found this document useful (0 votes)
225 views

Laravel Drive API

The document describes the steps to integrate Google Drive API with a Laravel application. It includes: 1. Creating a Google project, service account and API key to authorize the application to access Google Drive. 2. Installing Composer and Google API client library in Laravel. 3. Controllers for home, login, upload and download functions that use the Google API client to list, create, export and manage files in a user's Google Drive. 4. The login controller handles Google OAuth login and stores user data in session.

Uploaded by

hao
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
225 views

Laravel Drive API

The document describes the steps to integrate Google Drive API with a Laravel application. It includes: 1. Creating a Google project, service account and API key to authorize the application to access Google Drive. 2. Installing Composer and Google API client library in Laravel. 3. Controllers for home, login, upload and download functions that use the Google API client to list, create, export and manage files in a user's Google Drive. 4. The login controller handles Google OAuth login and stores user data in session.

Uploaded by

hao
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

-Step 1: Go to google app console: create project, Create service account key

-Step2: install composer


-laravel
-get api client
-make google login
Home Controller

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Input;
//use App\Http\Requests;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Session;
//use File;
class HomeController extends Controller{
public function index(Request $req){
$valueb = $req->session()->get('userdata');
if(!isset($valueb))
{
return Redirect::to('/login');
}
$client = new \Google_Client();

$client->setApplicationName('sweetest'); // name of your app


// set assertion credentials
$auth = new \Google_Auth_AssertionCredentials(
'[email protected]', // email you added to GA
array('https://www.googleapis.com/auth/drive'),
file_get_contents('C:\xampp\htdocs\complete\sweetest.p12') // keyfile you
downloaded
);
$auth->sub = '[email protected]';
$client->setAssertionCredentials($auth);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
// other settings
$client->setClientId('849141742918lmnq0ijddqqidi1347dq1eluv2l99sve.apps.googleusercontent.com'); // from API console
// create service and get data
$drive_service = new \Google_Service_Drive($client);
//$array = array('alt'=>'media');
$optParams = array(
'pageSize' => 365,
'fields' => "nextPageToken, files(id, name, mimeType, parents,
permissions, shared, ownedByMe, webViewLink, webContentLink)",
);
$files_list = $drive_service->files->listFiles($optParams);
/*foreach($files_list as $file)
{
echo '<pre>';
echo $file->getName();
print_r($file->getWebContentLink());
echo '</pre>';
}*/
/*$fileMetadata = new \Google_Service_Drive_DriveFile(array(
'name' => 'Upload File 2 test',
'mimeType' => 'application/vnd.google-apps.spreadsheet',
));
$content = file_get_contents('C:\xampp\htdocs\laravel_drive\a.csv');
$file = $drive_service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'text/csv',
'uploadType' => 'multipart',
'fields' => 'id'));*/
return view('home')->with(['files'=>$files_list, 'email'=>$valueb['email'],
'request'=>$req]);
}
//Upload file function ----------------------------------public function upload(){
//dd(Input::file('file'));
$client = new \Google_Client();
$client->setApplicationName('sweetest'); // name of your app
// set assertion credentials
$auth = new \Google_Auth_AssertionCredentials(
'[email protected]', // email you added to GA
array('https://www.googleapis.com/auth/drive'),
file_get_contents('C:\xampp\htdocs\complete\sweetest.p12'));// keyfile you
downloaded
$auth->sub = '[email protected]';
$client->setAssertionCredentials($auth);
if ($client->getAuth()->isAccessTokenExpired()) {

$client->getAuth()->refreshTokenWithAssertion();
}
// other settings
$client->setClientId('849141742918lmnq0ijddqqidi1347dq1eluv2l99sve.apps.googleusercontent.com'); // from API console
$drive_service = new \Google_Service_Drive($client);
//$strg = 'BIteam';
$name = Input::file('file')->getClientOriginalName();
$parents[] = $_POST['folderId'];
//var_dump($parents);
//var_dump($_FILES);
$mimetype = '';
/*switch($_GET['filetype']){
case '.docx':
$mimetype = 'application/vnd.google-apps.document';
break;
case '.xlsx':
$mimetype = 'application/vnd.google-apps.spreadsheet';
break;
case '.pdf':
$mimetype = 'application/pdf';
break;
case '.zip':
$mimetype = 'application/zip';
break;
case '.zip':
$mimetype = 'application/x-compressed';
break;
case '.png':
$mimetype = 'image/png';
break;
case '.jpeg':
$mimetype = 'image/jpeg';
break;
case '.jpg':
$mimetype = 'image/jpg';
break;
case '.gif':
$mimetype = 'image/gif';
break;
}*/
$mimetype = Input::file('file')->getMimeType();
//var_dump($mimetype);
$fileMetadata = new \Google_Service_Drive_DriveFile(array(
'name' => $name,
'mimeType' => $mimetype,
'parents' =>$parents
));
//$content = Input::file('file')->get
$content = File::get(Input::file('file')->getRealPath());
$file = $drive_service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimetype,
'uploadType' => 'multipart',
'fields' => 'id'));
//Return Redirect::to('/home');
}
//Download file funtion--------------------------------------------------public function download(){
//var_dump($_GET['linkdl']);

if(!empty($_GET['linkdl']))
{
return Redirect::to($_GET['linkdl']);
}
if(empty($_GET['role']))
{
if(!empty($_GET['linkdl']))
{
return Redirect::to($_GET['linkdl']);
}else
{return Redirect::to('/home');}
}elseif(isset($_GET['download'] ))
{
$client = new \Google_Client();
$client->setApplicationName('sweetest'); // name of your app
// set assertion credentials
$auth = new \Google_Auth_AssertionCredentials(
'[email protected]', // email you added
to GA
array('https://www.googleapis.com/auth/drive'),
file_get_contents('C:\xampp\htdocs\complete\sweetest.p12') // keyfile
you downloaded
);
$auth->sub = '[email protected]';
$client->setAssertionCredentials($auth);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
// other settings
$client->setClientId('849141742918lmnq0ijddqqidi1347dq1eluv2l99sve.apps.googleusercontent.com'); // from API console
// create service and get data
$drive_service = new \Google_Service_Drive($client);
global $extension ;
global $exporttype;
//$type = $_GET['filetype'];
//var_dump($_GET['filetype']);
switch($_GET['filetype']){
case 'application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet':
case 'application/vnd.google-apps.spreadsheet':
{ $extension = '.xlsx'; $exporttype =
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';}
break;
case 'application/pdf':
$extension = '.pdf';
$exporttype = 'application/pdf';
break;
case 'application/vnd.openxmlformatsofficedocument.wordprocessingml.document':
case 'application/vnd.google-apps.document':
$extension = '.docx';
$exporttype = 'application/vnd.openxmlformatsofficedocument.wordprocessingml.document';
break;
case 'image/png':
$extension = '.png';
$exporttype = 'image/png';

break;
case 'image/jpeg':
$extension = '.jpeg';
$exporttype = 'image/jpeg';
break;
}
//echo $exporttype;
$content = $drive_service->files->export($_GET['fileid'], $exporttype ,
array('alt' => 'media'));
//var_dump($content);
$path = $_GET['filename'].$extension;
file_put_contents($path, $content);
}
else{
//return Redirect::to('/home');
}
}
public function adduser($fileId, $role)
{
$client = new \Google_Client();
$client->setApplicationName('sweetest'); // name of your app
// set assertion credentials
$auth = new \Google_Auth_AssertionCredentials(
'[email protected]', // email you added to GA
array('https://www.googleapis.com/auth/drive'),
file_get_contents('C:\xampp\htdocs\complete\sweetest.p12') // keyfile you
downloaded
);
$auth->sub = '[email protected]';
$client->setAssertionCredentials($auth);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
// other settings
$client->setClientId('849141742918lmnq0ijddqqidi1347dq1eluv2l99sve.apps.googleusercontent.com'); // from API console
// create service and get data
$drive_service = new \Google_Service_Drive($client);
$permission = new \Google_Service_Drive_Permission();
$permission->setEmailAddress($_GET['email']);
$permission->setType('user');
$permission->setRole($_GET['userrole']);
$drive_service->permissions->create($_GET['fileId'] , $permission);
}
}

LoginController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
//use App\Http\Requests;
use Illuminate\Support\Facades\Redirect;

use Illuminate\Support\Facades\Session;
class LoginController extends Controller
{
public function index(Request $req){
if(isset($_GET['logout']))
{
$req->session()->forget('userdata');
}
//$req->session()->forget('userdata');
$temp = $req->session()->get('userdata');
if(isset($temp)){
return Redirect::to('/home');
}else {
return view('login');
}
}
public function login_process(Request $req)
{
$client = new \Google_Client();
$client->setAuthConfigFile('C:\xampp\htdocs\complete\client_secret.json');
$client>addScope(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleap
is.com/auth/userinfo.profile', ''));
//Send Client Request
$objOAuthService = new \Google_Service_Oauth2($client);
//var_dump($objOAuthService->userinfo->get());
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
//$req->session()->put('access_token', $client->getAccessToken());
$req->session()->put('userdata', $objOAuthService->userinfo->get());
return Redirect::to('/home');
}else{
$authUrl = $client->createAuthUrl();
return Redirect::to($authUrl);
}
//A cut part----------------------------------------email
//Set Access Token to make Request
/*if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}*/
//If New, Insert to Database
/*if ($client->getAccessToken()) {
//$_SESSION['userdata'] = $objOAuthService->userinfo->get();
// $req = new Request();
$req->session()->put('userdata', $objOAuthService->userinfo->get());
/*if(!empty($userData)) {
$objDBController = new DBController();
$existing_member = $objDBController->getUserByOAuthId($userData->id);
if(empty($existing_member)) {
$objDBController->insertOAuthUser($userData);
}
}
//$_SESSION['access_token'] = $client->getAccessToken();
$req->session('access_token', $client->getAcccessToken());
} else {

}*/
}
}

You might also like