PHP Classes

Learn with a PHP OAuth2 Example Google API Access From the Console - PHP OAuth Library package blog

Recommend this page to a friend!
  All package blogs All package blogs   PHP OAuth Library PHP OAuth Library   Blog PHP OAuth Library package blog   RSS 1.0 feed RSS 2.0 feed   Blog Learn with a PHP OAut...  
  Post a comment Post a comment   See comments See comments (0)   Trackbacks (0)  

Author:

Updated on: 2023-11-01

Posted on: 2023-11-01

Package: PHP OAuth Library

Some applications need to access APIs from the console to perform background tasks using, for instance, the crontab available in Linux-based systems to execute jobs at scheduled times.

Read this article to learn how to develop PHP scripts that can get OAuth2-based tokens to access a Google API from the console or as a task executed by corn.

OAuth is a protocol often used to access API on behalf of a user that grants permissions to access the services of an API on behalf of that user.

This allows applications to call APIs even when the user is not present accessing a Web page.

This is possible because the OAuth protocol can be used by Web services to provide token string values that applications can use to access the APIs whenever they want, using a token string as evidence that the user granted permission to access the APIs anytime the application runs.

So, what applications need to do to access an API from a console or a task started with the cron tool is to obtain that token string.

That needs to happen with the presence of the user. The user needs to go to a page of the application. There, the user browser is redirected to a page of the API service provided. The user is requested to permit the application to perform specific actions by calling the API.

[OAuth permission request page image]

After the user provides the requested permissions, the user's browser is redirected back to the application page. Then, the application calls the API following the OAuth protocol to retrieve the access token.

[OAuth application page showing the access token image]

From now on, the application can use the access token to perform API calls to which the user gave permission.




Loaded Article

In this article you will learn about:

1. Why You May Need to Access API from the Console

2. What You Need to Do With to Access a OAuth-based API From the Console

3. How You Can Access an OAuth-Based API from the Console

4. How to Download or Install the OAuth Client Package using PHP Composer


1. Why You May Need to Access API from the Console

Many applications need to perform maintenance tasks regularly, like, for instance, taking backup copies of application data.

If you need to use an API of a file storage service like, for instance, Google Drive to send the backup file data, you need to have a way to call that API and upload the backup data files. 

2. What You Need to Do With to Access a OAuth-based API From the Console

OAuth is a protocol often used to access API on behalf of a user that grants permissions to access the services of an API on behalf of that user.

This allows applications to call APIs even when the user is not present accessing a Web page.

This is possible because the OAuth protocol can be used by Web services to provide token string values that applications can use to access the APIs whenever they want, using a token string as evidence that the user granted permission to access the APIs anytime the application runs.

So, what applications need to do to access an API from a console or a task started with the cron tool is to obtain that token string.

That needs to happen with the presence of the user. The user needs to go to a page of the application. There, the user browser is redirected to a page of the API service provided. The user is requested to permit the application to perform specific actions by calling the API.

After the user provides the requested permissions, the user's browser is redirected back to the application page. Then, the application calls the API following the OAuth protocol to retrieve the access token.

Google OAuth client results

From now on, the application can use the access token to perform API calls that the user gave permission. 

3. How You Can Access an OAuth-Based API from the Console

3.1. Retrieve and Store the OAuth Access Token

The first step is to ask the user to authorize your application to access the API and obtain the access token to make API calls.

Then your applications needs to store the access token somehow, so you retrieve the access token everytime your application needs to make API calls.

This step is a bit complex. Fortunately the PHP OAuth Library performs most of work for you.

Here is an example script of this step. Please read the code and comments next to the code. The code below is also available as a file for your to download.

What this script does is to present a page to the user that will do the OAuth token retrieval process by redirecting the user browser to a page of Google application authorization. If all goes well, the script will store the OAuth access token in a file named token.json.

You can try this script and make some adjustments to make it work with your application.

1. This example script includes the OAuth client class, the file OAuth client class and the HTTP client class using require statements. If you use PHP Composer to install these classes, you need to change the require statements to just use require('vendor/autoload.php');

2. The redirect_uri variable needs to be set to real URL of the page generated by this script your site

3. The client_id and client_secret variables need to be set to the credentials of your Google OAuth application.

4. The token is stored by this script in a file named token.json .You may want to change the path of this token file to a directory or file name that is more convenient to your application.

5. You may need to change the scope variable depending on the Google APIs that you application needs to use.

6. This example script makes a call to the Google API to get the current user profile information. This step is not necessary in real applications that just need to get the OAuth access token. So you may want to remove the CallAPI function call when you adapt this script to use in a real application.

<?php
/*
 * file_login_with_google.php
 *
 * @(#) $Id: file_login_with_google.php,v 1.1 2015/10/16 20:05:49 mlemos Exp $
 *
 */
 
	/*
	 *  Get the http.php file from http://www.phpclasses.org/httpclient
	 */
	require('http.php');
	require('oauth_client.php');
	require('file_oauth_client.php');
 
	/*
	 * Create an object of the sub-class of the OAuth client class that is
	 * specialized in storing and retrieving access tokens from files
	 * 
	 */
	$client = new file_oauth_client_class;
 
	/*
	 * Define options specific to your token file storage 
	 */
	$client->file = array(
		'name'=>'token.json',
	);
	$client->server = 'Google';
 
	/*
	 * Set the offline access only if you need to call an API
	 * when the user is not present and the token may expire
	 */
	$client->offline = true;
 
	$client->debug = true;
	$client->debug_http = true;
	$client->redirect_uri = 'https://'.$_SERVER['HTTP_HOST'].
		dirname(strtok($_SERVER['REQUEST_URI'],'?')).'/file_login_with_google.php';
 
	$client->client_id = ''; $application_line = __LINE__;
	$client->client_secret = '';
 
	if(strlen($client->client_id) == 0
	|| strlen($client->client_secret) == 0)
		die('Please go to Google APIs console page '.
			'https://console.cloud.google.com/apis/dashboard in the API access tab, '.
			'create a new client ID, and in the line '.$application_line.
			' set the client_id to Client ID and client_secret with Client Secret. '.
			'The callback URL must be '.$client->redirect_uri.' but make sure '.
			'the domain is valid and can be resolved by a public DNS.');
 
	/* API permissions
	 */
	$client->scope = 'https://www.googleapis.com/auth/userinfo.email '.
		'https://www.googleapis.com/auth/userinfo.profile';
	if(($success = $client->Initialize()))
	{
		$client->store_access_token_response = true;
		if(($success = $client->Process()))
		{
			if(strlen($client->authorization_error))
			{
				$client->error = $client->authorization_error;
				$success = false;
			}
			elseif(strlen($client->access_token))
			{
				$success = $client->CallAPI(
					'https://www.googleapis.com/oauth2/v1/userinfo',
					'GET', array(), array('FailOnAccessError'=>true), $user);
			}
		}
		$success = $client->Finalize($success);
	}
	if($client->exit)
		exit;
	if($success)
	{
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Google OAuth client results</title>
</head>
<body>
<?php
		echo '<h1>', HtmlSpecialChars($user->name),
			' you have logged in successfully with Google!</h1>';
		echo '<pre>', HtmlSpecialChars(print_r($user, 1)), '</pre>';
?>
</body>
</html>
<?php
	}
	else
	{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>OAuth client error</title>
</head>
<body>
<h1>OAuth client error</h1>
<pre>Error: <?php echo HtmlSpecialChars($client->error); ?></pre>
</body>
</html>
<?php
	}
 
?>

3.2. Use the Stored OAuth Access Token to Make API Calls From the Console

The next step is to use the access token obtained in the first step to make API calls from scripts run from the command line console, or terminal shell if you use Linux, or a cron job script.

The code is almost the same but it will not redirect the user to Google OAuth server pages because it already has the access token that was obtained in the previous step.

Take a look at the following code to learn how you can do this in practice. You can also download this example file from the file page.

<?php
/*
 * file_login_with_google.php
 *
 * @(#) $Id: file_get_google_account.php,v 1.1 2023/11/01 10:05:38 mlemos Exp $
 *
 */
 
	/*
	 *  Get the http.php file from http://www.phpclasses.org/httpclient
	 */
	require('http.php');
	require('oauth_client.php');
	require('file_oauth_client.php');
 
	/*
	 * Create an object of the sub-class of the OAuth client class that is
	 * specialized in storing and retrieving access tokens from files
	 * 
	 */
	$client = new file_oauth_client_class;
 
	/*
	 * Define options specific to your token file storage 
	 */
	$client->file = array(
		'name'=>'token.json',
	);
	$client->server = 'Google';
 
	/*
	 * Set the offline access only if you need to call an API
	 * when the user is not present and the token may expire
	 */
	$client->offline = true;
 
	$client->debug = true;
	$client->debug_http = true;
	$client->redirect_uri = '';
 
	$client->client_id = ''; $application_line = __LINE__;
	$client->client_secret = '';
 
	if(strlen($client->client_id) == 0
	|| strlen($client->client_secret) == 0)
		die('Please go to Google APIs console page '.
			'https://console.cloud.google.com/apis/dashboard in the API access tab, '.
			'create a new client ID, and in the line '.$application_line.
			' set the client_id to Client ID and client_secret with Client Secret. '.
			'The callback URL must be '.$client->redirect_uri.' but make sure '.
			'the domain is valid and can be resolved by a public DNS.');
 
	/* API permissions
	 */
	$client->scope = 'https://www.googleapis.com/auth/userinfo.email '.
		'https://www.googleapis.com/auth/userinfo.profile';
	if(($success = $client->Initialize()))
	{
		$client->store_access_token_response = true;
		if(($success = $client->CheckAccessToken($redirect_url)))
		{
			if(IsSet($redirect_url))
				die('Please obtain the access token first telling the user to access the page of the script file_login_with_google.php .');
			if(strlen($client->authorization_error))
			{
				$client->error = $client->authorization_error;
				$success = false;
			}
			elseif(strlen($client->access_token))
			{
				$success = $client->CallAPI(
					'https://www.googleapis.com/oauth2/v1/userinfo',
					'GET', array(), array('FailOnAccessError'=>true), $user);
			}
		}
		$success = $client->Finalize($success);
	}
	if($client->exit)
		exit;
	if($success)
	{
		echo "Google OAuth client results:", "\n";
		echo "This Google API OAuth Access token belongs to user ", $user->name, ".\n";
		echo HtmlSpecialChars(print_r($user, 1)), "\n";
	}
	else
	{
		echo "OAuth client error:", "\n";
		echo "Error: ", HtmlSpecialChars($client->error), "\n";
	}
?>

4. How to Download or Install the OAuth Client Package using PHP Composer

The PHP OAuth Library package can be download from the package download page or installed using the PHP Composer tool following instructions that can be found in the same page.



You need to be a registered user or login to post a comment

1,613,085 PHP developers registered to the PHP Classes site.
Be One of Us!

Login Immediately with your account on:



Comments:

No comments were submitted yet.



  Post a comment Post a comment   See comments See comments (0)   Trackbacks (0)  
  All package blogs All package blogs   PHP OAuth Library PHP OAuth Library   Blog PHP OAuth Library package blog   RSS 1.0 feed RSS 2.0 feed   Blog Learn with a PHP OAut...