Skip to content
Snippets Groups Projects
Commit d0022745 authored by Kurniandha Sukma Yunastrian's avatar Kurniandha Sukma Yunastrian
Browse files

add google API for new topic

parent e21f9adf
2 merge requests!8Finalize,!3Course
Showing with 488 additions and 249 deletions
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Google_Client;
class LearnController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
}
/**
* Create new Spreadsheet.
*
* @return id_spreadsheet
*/
public function new()
{
echo 'nyampe1';
$client = LearnController::getClient();
$service = new \Google_Service_Sheets($client);
echo 'nyampe 2';
$spreadsheet = new \Google_Service_Sheets_Spreadsheet([
'properties' => [
'title' => 'Testing'
]
]);
echo 'nyampe 3';
$response = $service->spreadsheets->create($spreadsheet, ['fields' => 'spreadsheetId']);
echo 'nyampe';
$data = array(
'role' => 'owner',
'type' => 'user',
'emailAddress' => 'piscokn@gmail.com'
);
echo $response->spreadsheetId;
$service2 = new \Google_Service_Drive($client);
$permission2 = new \Google_Service_Drive_Permission([
'role' => 'writer',
'type' => 'user',
'emailAddress' => 'piscokn@gmail.com'
]);
// $permission2->setValue('piscokn@gmail.com');
// $permission2->setType('user');
// $permission2->setRole('owner');
$response2 = $service2->permissions->create($response->spreadsheetId, $permission2);
// # Create a connection
// echo $response->spreadsheetId . '\n';
// $url = 'https://www.googleapis.com/drive/v3/files/' . $response->spreadsheetId . '/permissions';
// echo $url;
// $ch = curl_init($url);
// # Form data string
// $postString = http_build_query($data, '', '&');
// # Setting our options
// curl_setopt($ch, CURLOPT_POST, 1);
// curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// # Get the response
// $responsee = curl_exec($ch);
// curl_close($ch);
// echo $responsee;
// return view('welcome');
// printf("Spreadsheet ID: %s\n", $spreadsheet->spreadsheetId);
}
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
public function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Datalearn');
$client->setAuthConfig(__DIR__.'/credentials.json');
$client->addScope(\Google_Service_Sheets::SPREADSHEETS);
$client->addScope(\Google_Service_Sheets::DRIVE);
$client->setAccessType('offline');
return $client;
}
}
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LearnControllerr extends Controller
{
//
}
<?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('Datalearn');
$client->setScopes(\Google_Service_Sheets::SPREADSHEETS);
$client->setAuthConfig('e3.json');
$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);
}
// If there is no previous token or it's expired.
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()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Sheets($client);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
$spreadsheet = new \Google_Service_Sheets_Spreadsheet([
'properties' => [
'title' => 'Testin'
]
]);
$response = $service->spreadsheets->create($spreadsheet, ['fields' => 'spreadsheetId']);
echo 'nyampe 4';
echo $response->spreadsheetId;
\ No newline at end of file
{"web":{"client_id":"1038840787003-olj0fj86t5t0g4rlsree58eh3knq2atk.apps.googleusercontent.com","project_id":"datalearn","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"u3hi8Sa59C6QAfInptyncvYd","javascript_origins":["http://localhost:8000"]}}
\ No newline at end of file
{
"type": "service_account",
"project_id": "datalearn",
"private_key_id": "049b061b5b9de5f1f32142109307deb932917eea",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCUa1lxNZ82CwFu\n48ndNtYB9MRwGLVy7OeE2S8m/WiMpXjGL23qdq8s9G1VBfBbf+ibMeVvQcUjXJHw\nUmoggvRgW6UJ5GjxNcprPMhghas84JCU8MB+qfvH3hXxEU/ZrXJ1e9WqWKLV2WmB\ni2TNPJOVSCTOEaxyuDQyS/8PNy25xRktf7O2aXeuhO/F1+6KGkfpXAf39NMdBQ2W\nbK61WIjWaHqWicBSDXgkxGGHyw28U3TDW5qXOjfzxxz+/aROv+qHb5uopeLJIBQI\n6SWDjRlRNh19N5dZm6/KVS81Cmx7HoZpOAjc0O3+kiBLOyPnYIvJOEVDNUeaFkrs\nU4zqJxizAgMBAAECggEADRM18nS8XWjzy96SYoQZr1tuUMfEeGbpcHknn8I0Syuq\nq57zCnRBM28nEJXw2ka26bEoGriLEvXtP2QrSEjxGWoJbIksO4+3EOJubp5n+vl3\nkz9wXdhAv5dPjIivZahTjIkHxjV/xuIb2t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lHaDs7EzoF2ag\n7GGhIVGKIIejOAH/1Oe9Rg==\n-----END PRIVATE KEY-----\n",
"client_email": "aljabar@datalearn.iam.gserviceaccount.com",
"client_id": "112946705019770577593",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/aljabar%40datalearn.iam.gserviceaccount.com"
}
{"web":{"client_id":"596977500283-23ka11e3cvdkqn74gum49huse2os9hvo.apps.googleusercontent.com","project_id":"quickstart-1586270192915","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"EilEhMA3QrB3T0o4AV9rNuux","javascript_origins":["http://localhost:8000"]}}
\ No newline at end of file
{"web":{"client_id":"596977500283-23ka11e3cvdkqn74gum49huse2os9hvo.apps.googleusercontent.com","project_id":"quickstart-1586270192915","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"EilEhMA3QrB3T0o4AV9rNuux","javascript_origins":["http://localhost:8000"]}}
\ No newline at end of file
{"installed":{"client_id":"596977500283-7put6bokjiqf0r63vb52ksja3umpssc7.apps.googleusercontent.com","project_id":"quickstart-1586270192915","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"Pm5stg2CPDYlRvIJFYq2QZel","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
\ No newline at end of file
{"access_token":"ya29.a0Ae4lvC0gzsPFpKrZaTMsmIJBn_Nhm5wVKXY2Lyy7A1kzxeCUZmiUdz5rH0ty4eRqTKD9g3SJskJMbQ203ufXWNCEPZao6v86JiZ5OvYe81zp2QP31xqpmiZcPSBfUADat5rvNeZLSfAjvtUHKuL0s6-HiLbPLQCOA1M","expires_in":3599,"refresh_token":"1\/\/0gemlmny29IG1CgYIARAAGBASNwF-L9Ir10D1ArUamttBe9ZBrrOu0-O4VfPwS927GKRWVJB0xMLAa3hRJbsiVm7pU6kEpyId7a4","scope":"https:\/\/www.googleapis.com\/auth\/spreadsheets","token_type":"Bearer","created":1586279916}
\ No newline at end of file
This diff is collapsed.
{"installed":{"client_id":"203499803850-801l1qnh8emaje13o69djnks4329517c.apps.googleusercontent.com","project_id":"datalearn-1584958564354","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"JWjkNxsT1JQssnD1MXaxlGAc","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}
\ No newline at end of file
<?php
session_start();
// init configuration
$clientID = '1038840787003-n9lfv6h5tg3pdu38c6lksvkvivl1geor.apps.googleusercontent.com';
$clientSecret = 'n9qmB0e0811fHzW4jgMBhAh7';
$redirectUri = 'http://localhost:8000/redirect.php';
// create Client Request to access Google API
$client = new Google_Client();
$client->setApplicationName("Datalearn");
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
// authenticate code from Google OAuth Flow
if (isset($_GET['code'])) {
// $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
// $client->setAccessToken($token['access_token']);
// // get profile info
// $google_oauth = new \Google_Service_Oauth2($client);
// $google_account_info = $google_oauth->userinfo->get();
// $email = $google_account_info->email;
// $name = $google_account_info->name;
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . filter_var($redirectUri, FILTER_SANITIZE_URL));
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}
echo 'berhasil';
// get profile info
$google_oauth = new Google_Service_Oauth2($client);
$google_account_info = $google_oauth->userinfo->get();
$email = $google_account_info->email;
$name = $google_account_info->name;
echo $name;
echo $email;
// now you can use this profile info to create account in your website and make user logged in.
} else {
echo "<a href='".$client->createAuthUrl()."'>Google Login</a>";
}
?>
\ No newline at end of file
{"access_token":"ya29.a0Adw1xeWgubk0UA2GfpfBcE4iZ2KcLD5_2tRMN8z4jo4wO1amESg-M1uof6iStIMrisGg8LPjGJu7rPCoNilqNhWzAnMvitwTZJHwsp2QHO3T1b0lY-Tz8xaFEJ2XS6SbRfGBam5XWsK1dkYpOTZ5G3kzbLSAy5aV21M","expires_in":3599,"refresh_token":"1\/\/0gSzfFC85SeXlCgYIARAAGBASNwF-L9Ir32KqSrEfEjJRCmTLVkBv_yPTMXD4Znx7FklpILGaXjgAFGe2CltDUmruEha5MHTc9mw","scope":"https:\/\/www.googleapis.com\/auth\/spreadsheets.readonly","token_type":"Bearer","created":1584960990}
\ No newline at end of file
......@@ -17,8 +17,12 @@ Route::get('/', function () {
Route::get('/test', function () {
return view('test');
});
Route::get('/redirect.php', function () {
return view('redirect');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/course/{id_course}', 'CourseController@index')->name('course');
Route::get('/course/{id_course}/learn/new', 'LearnController@new')->name('learn/new');
Route::get('/course/{id_course}/learn/{id_spreadsheet}', 'LearnController@index')->name('learn');
\ No newline at end of file
......@@ -19,3 +19,4 @@ if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
}
require_once __DIR__.'/public/index.php';
require_once __DIR__.'/vendor/autoload.php';
\ No newline at end of file
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment