Skip to content

Instantly share code, notes, and snippets.

@EdEichman
Last active March 6, 2022 08:50
Show Gist options
  • Save EdEichman/6261ecf8d6a45ca6aebb to your computer and use it in GitHub Desktop.
Save EdEichman/6261ecf8d6a45ca6aebb to your computer and use it in GitHub Desktop.
PHP Gmail API - getting past OAuth
<?php
//Create a composer project in PHP storm, and use their support for loading the needed includes.
//https://developers.google.com/api-client-library/php/start/installation
//https://www.jetbrains.com/phpstorm/help/composer-project-dialog.html
require_once 'autoload.php';
//the google code shown in https://www.youtube.com/watch?v=zSyGkfW9qY4 counts on the session
session_start();
//used https://www.youtube.com/watch?v=zSyGkfW9qY4 for info
$client = new Google_Client ();
//Create an API project in https://console.developers.google.com, and enable the GMail API
$client->setApplicationName ("{same as project ID from https://console.developers.google.com} - e.g. in my case, ed-stock");
$client->setClientId (' your oath client id from dev console'); //make new oath credentials in dev console
$client->setClientSecret (' your oath client secret from dev console'); //make new oath credentials in dev console
$client->setRedirectUri ("http://localhost:8090/index.php"); // the URL of your project
$client->addScope ('https://www.googleapis.com/auth/gmail.readonly'); //read about the scope you need at https://developers.google.com/gmail/api/auth/scopes
$service = new Google_Service_Gmail ($client);
//Check if the user is logged out
if (isset ($_REQUEST['logout']))
{
unset ($_SESSION['access_token']);
}
//check if we have an authorized token
if (isset ($_GET['code']))
{
$client->authenticate ($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header ('Location: '. filter_var ($url, FILTER_VALIDATE_URL));
}
//check if we have an access token in the session
if (isset ($_SESSION['access_token']))
{
$client->setAccessToken($_SESSION['access_token']);
}
else
{
$login_url = $client->createAuthUrl();
echo "Click <a href='$login_url'>here</a> to login";
}
try
{
//Check if we have an access token ready for API calls
if (isset ($_SESSION['access_token']) && $client->getAccessToken())
{
//Do your Gmail API work
}
}
catch (Google_Auth_Exception $e)
{
$login_url = $client->createAuthUrl();
echo "Look like your access token has expired. Click <a href='$login_url'>here</a> to login";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment