Dorokhov.codes
3. Setting up a library
Installation
composer.json
:
{
"require": {
"google/apiclient": "^2.16.0"
},
"scripts": {
"pre-autoload-dump": "Google\\Task\\Composer::cleanup"
},
"extra": {
"google/apiclient-services": [
"Drive",
"YouTube"
]
}
}
This example will remove all services other than “Drive” and “YouTube”.
docker container run --rm \
--interactive \
--tty \
--volume "$PWD:/app" \
--user $(id -u):$(id -g) \
composer install
Authorization
Next we need authorization. There are two main types of authorization:
- Using an API key.
- Using OAuth 2.0.
If we are using an API key:
$client->setDeveloperKey($api_key);
And if we are using OAuth 2.0.
$client->setAuthConfig('/path/to/service-account.json');
// Or:
$client->setAuthConfig([
'type' => 'service_account',
'project_id' => 'your-project-id',
'private_key_id' => 'your-private-key-id',
'private_key' => '-----BEGIN PRIVATE KEY-----\nYourPrivateKey\n-----END PRIVATE KEY-----\n',
'client_email' => 'your-client-email',
'client_id' => 'your-client-id',
'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' => 'your-client-x509-cert-url'
]);
Example
<?php
use Google\Service\YouTube;
require_once 'vendor/autoload.php';
$client = new Google\Client();
$client->setDeveloperKey(DEVELOPER_KEY);
$client->addScope(Youtube::YOUTUBE_READONLY);
$service = new YouTube($client);
try {
$response = $service->search->listSearch('snippet', [
'channelId' => 'UCMYA1rIPrIcgJXskjIDIM4Q',
'eventType' => 'completed',
'type' => 'video',
]);
if ($broadcasts = $response->getItems()) {
$broadcast = $broadcasts[0];
$id = $broadcast->getId()->videoId;
var_dump($id);
}
} catch (Exception $e) {
echo 'An error occurred: ' . $e->getMessage();
}