Support the ongoing development of Laravel.io →
Authentication Requests Packages
Last updated 1 year ago.
0

Hi,

I have used the Google API client. It uses composer so using it with Laravel should be no problem. Here is some sample code I've gotten to work before.

<?php
//error_reporting(E_ERROR);
include_once('vendor/autoload.php');

define('APPLICATION_NAME', 'LawOne');
define('CREDENTIALS_PATH', '~/.credentials/calendar-api-quickstart.json');
define('CLIENT_SECRET_PATH', 'client_secret.json');
define('SCOPES', implode(' ', array(
  Google_Service_Calendar::CALENDAR_READONLY, 'https://www.googleapis.com/auth/calendar')
));

/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfigFile(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');
  //$client->setApprovalPrompt('force');
  //set the redirect url
  $redirectUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/freelancer/cloudprint/calendar.php';
  $client->setRedirectUri($redirectUrl);  
  return $client;
}


// Get the API client and construct the service object.
$client = getClient();

//check for a code or error ; this is the response from the redirect
if(isset($_GET['error']) || isset($_GET['code']))
{
    //var_dump($_GET);
    if(isset($_GET['code']))
    {
        $client->authenticate($_GET['code']);
        $access_Token = $client->getAccessToken();
        //store the access token
        /*
        $redirect = 'http://' . $_SERVER['HTTP_HOST'] . '/freelancer/cloudprint/calendar.php';
        header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));		
        */
        //echo "Access token is $access_Token";
        
        //save in token.json
        file_put_contents('token.json', $access_Token);
        echo "Token saved in token.json";
        exit;
    }
    if(isset($_GET['error']))
    {
        echo $_GET['error'];
        exit;
    }
}
//try loading the token from file if it exists
if(file_exists('token.json'))
{
    $token = file_get_contents('token.json');
    //set the token
    $client->setAccessToken($token);
}


//check if client has access token
if($client->getAccessToken())
{
  //echo "Authorization exists";
  //since token exists, check if it has expired, if so, renew it
  if($client->getAuth()->isAccessTokenExpired())
  {
        $client->getAuth()->refreshToken($client->getAuth()->getRefreshToken());
        $new_token = $client->getAccessToken();
        //save the new token file
        file_put_contents('token.json', $new_token);
        //echo "Token has expired<br>";
        //echo "New token is ".$new_token."<br>";
        //echo "Refresh token is ".$client->getAuth()->getRefreshToken();
  }
  else
  {
      //echo "Google calendar is authorized and ready for use";
      //exit;
  }

}
else
{
    //redirect the user	
    //get the url to redirect for the user to grant access
    $auth_url = $client->createAuthUrl();  
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
    //echo "Need to get authorization";
    exit;	
    //echo filter_var($auth_url, FILTER_SANITIZE_URL);
}



$service = new Google_Service_Calendar($client);


//test mode
if(isset($_GET['mode']) && $_GET['mode'] == 'test')
{
    // Print the next 10 events on the user's calendar.
    $calendarId = 'primary';
    $optParams = array(
      'maxResults' => 10,
      'orderBy' => 'startTime',
      'singleEvents' => TRUE,
      'timeMin' => date('c'),
    );
    $results = $service->events->listEvents($calendarId, $optParams);

    if (count($results->getItems()) == 0) {
      print "No upcoming events found.\n";
    } else {
      print "Upcoming events:\n";
      foreach ($results->getItems() as $event) {
        $start = $event->start->dateTime;
        if (empty($start)) {
          $start = $event->start->date;
        }
        printf("%s (%s)\n", $event->getSummary(), $start);
      }
    }
    
}

I follow the documentation here: https://developers.google.com/google-apps/calendar/?hl=en and it's helped quite a bit. The code I've given uses OAuth2 to get a token and then stores it in a file for future use. You will have to create an app and get the token in the developer console but following the docs should tell you how to do that.

Last updated 8 years ago.
0

anthonydarwesh said:

Hi,

I have used the Google API client. It uses composer so using it with Laravel should be no problem. Here is some sample code I've gotten to work befor...

For the token, can you share with me the OAuth callback url you used? I am not entirely sure on what type of OAuth client I should be using.

0

anthonydarwesh said:

Hi,

I have used the Google API client. It uses composer so using it with Laravel should be no problem. Here is some sample code I've gotten to work before.

<?php //error_reporting(E_ERROR); include_once('vendor/autoload.php'); define('APPLICATION_NAME', 'LawOne'); define('CREDENTIALS_PATH', '~/.credentials/calendar-api-quickstart.json'); define('CLIENT_SECRET_PATH', 'client_secret.json'); define('SCOPES', implode(' ', array( Google_Service_Calendar::CALENDAR_READONLY, 'https://www.googleapis.com/auth/calendar') )); /** * Returns an authorized API client. * @return Google_Client the authorized client object */ function getClient() { $client = new Google_Client(); $client->setApplicationName(APPLICATION_NAME); $client->setScopes(SCOPES); $client->setAuthConfigFile(CLIENT_SECRET_PATH); $client->setAccessType('offline'); //$client->setApprovalPrompt('force'); //set the redirect url $redirectUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/freelancer/cloudprint/calendar.php'; $client->setRedirectUri($redirectUrl); return $client; } // Get the API client and construct the service object. $client = getClient(); //check for a code or error ; this is the response from the redirect if(isset($_GET['error']) || isset($_GET['code'])) { //var_dump($_GET); if(isset($_GET['code'])) { $client->authenticate($_GET['code']); $access_Token = $client->getAccessToken(); //store the access token /* $redirect = 'http://' . $_SERVER['HTTP_HOST'] . '/freelancer/cloudprint/calendar.php'; header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); */ //echo "Access token is $access_Token"; //save in token.json file_put_contents('token.json', $access_Token); echo "Token saved in token.json"; exit; } if(isset($_GET['error'])) { echo $_GET['error']; exit; } } //try loading the token from file if it exists if(file_exists('token.json')) { $token = file_get_contents('token.json'); //set the token $client->setAccessToken($token); } //check if client has access token if($client->getAccessToken()) { //echo "Authorization exists"; //since token exists, check if it has expired, if so, renew it if($client->getAuth()->isAccessTokenExpired()) { $client->getAuth()->refreshToken($client->getAuth()->getRefreshToken()); $new_token = $client->getAccessToken(); //save the new token file file_put_contents('token.json', $new_token); //echo "Token has expired<br>"; //echo "New token is ".$new_token."<br>"; //echo "Refresh token is ".$client->getAuth()->getRefreshToken(); } else { //echo "Google calendar is authorized and ready for use"; //exit; } } else { //redirect the user //get the url to redirect for the user to grant access $auth_url = $client->createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); //echo "Need to get authorization"; exit; //echo filter_var($auth_url, FILTER_SANITIZE_URL); } $service = new Google_Service_Calendar($client); //test mode if(isset($_GET['mode']) && $_GET['mode'] == 'test') { // Print the next 10 events on the user's calendar. $calendarId = 'primary'; $optParams = array( 'maxResults' => 10, 'orderBy' => 'startTime', 'singleEvents' => TRUE, 'timeMin' => date('c'), ); $results = $service->events->listEvents($calendarId, $optParams); if (count($results->getItems()) == 0) { print "No upcoming events found.\n"; } else { print "Upcoming events:\n"; foreach ($results->getItems() as $event) { $start = $event->start->dateTime; if (empty($start)) { $start = $event->start->date; } printf("%s (%s)\n", $event->getSummary(), $start); } } } I follow the documentation here: https://developers.google.com/google-apps/calendar/?hl=en and it's helped quite a bit. The code I've given uses OAuth2 to get a token and then stores it in a file for future use. You will have to create an app and get the token in the developer console but following the docs should tell you how to do that.
0

sanketr43 said:

anthonydarwesh said:

-SNIP-

I suspect you are implying I should re-read @anthonydarwesh's post, however I realize that what I said was not at all what I meant to say.

My intended question was how would you get this to work without the manual entering of the access token.

0

This is my callback URL:

<?php
    $redirectUrl = 'http://' . $_SERVER['HTTP_HOST'] . '/freelancer/cloudprint/calendar.php';

In my case the value of $redirectUrl is just the same page which the code I have shown you is on. So the page does all the steps of redirecting to google and also storing and refreshing the token. You can set it to any value however the value should match in what's in the Developers Console. If it works you'll be redirected to Google where you give access then brought back to the callback URL. When you return, the token is in the query string and you can do as you please with it, store it in a file, or database or even paste it somewhere where you can keep reusing it.

This method uses OAuth2 to get the users access so the user will have to give permission at least once. For other methods, there should be a section on Authentication describing other approaches like service accounts but I can't advise on that since I have not used them myself.

Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.