.pptx
file amoung others.
Using Google Slides to programmatically generate powerpoint files is straight forward, but isnt without its pitfuls. It requires some setup, configuration and some understanding of how OAuth 2 works in the Google environment.
The following is what is required:
APIs & Services
. Once you're there you'll see a bit blue link at the top of the page entitled "Enable APIs and services".
Once you're there you'll be able to search to enable the APIs. In our case we will just want to enable the Google Slides API
.
Setup OAuth
In short, OAuth is a modern standard of web-based API security using token-based authentication. The details of how this works are beyond the scope of this article but you can find more information here and a great introductory video here. If you haven't used OAuth before, I'd strongly suggest spending a few minutes understanding it, otherwise you're not going to have a good time.
The task here is to setup OAuth settings which will tell Google where is valid for API requests to come from domain name wise. Additionally the information entered here is presented to the end user of the application.
To get started, whilst viewing your project click the main hamburger menu, select APIs & Services
-> Credentials
. Once you're on the credentials page, select Create Credentials
, you'll want to use the selectable type OAuth Client ID
, then use Web application
in the following screen. The domain names listed here need to be real domain names used by your application. For the sake of this tutorial we'll be operating the API over the command line, so just use localhost
as the domain.
Fill out all the information it asks as best as you can. You can always revisit this stage later.
You'll then need to download the configuration file by selecting the download button under: APIs & Services
-> Credentials
-> OAuth 2.0 client IDs
-> {download button}
Retain the OAuth config files for later. At this point setup is done, let's get coding.
Get authenticated with code
We're going to be working off of the base example Google provide in the form of an official sample library. You can find their full code on their Github repo. We're also going to be using composer - the PHP defacto dependency management tool, if you don't know what that is, pause for 5 minutes to install it and read up on it on their official site.
First install the official PHP library as a dependency in your project by running this on the command line:
composer require google/apiclient:^2.0
Copy the credentials.json
file you downloaded in the previous step into the current directory. Then create a slides_tutorial_01.php
file. Your project directory should look like this:
vendor/
credentials.json
slides_tutorial_01.php
Add the following to your slides_tutorial_01_authenticate.php
:
<pre class="prettyprint linenums lang=php">
// create a google client
$client = new Google_Client();
// give the application a friendly name (for your benifit only)
$client->setApplicationName('Google Slides API PHP Quickstart');
/**
* this is the scope the application needs - the scopes defined here cannot exceed the scopes
* set in the `Enable Google Cloud APIs` step.
*/
$client->setScopes(Google_Service_Slides::PRESENTATIONS_READONLY);
// this is the file path to the `credentials.json` in our directory
$client->setAuthConfig('credentials.json');
/**
* by setting offline this will return an oauth token which will never expire (a refresh token)
* which will enable us to get more access tokens without require the user to accept again
*/
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
</pre>
Add the following to the end of your existing file, read through the inline comments yourself to get a better understanding of what's happening here. This essentially is taking care of authenticating, and will require some interaction via command line inputs:
<pre class="prettyprint linenums:18 lang=php">
// 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()));
}
</pre>
At this point, you're good to run the file and see how authentication flows! This is a rough rundown of what happens:
tokens.json
file, which is reused for future requestsLet's connect
Designed, coded & copyright NybbleMouse Limited, copyright 2023. Company number: 09769539