Wordpress PHP Google Sheets API Access - php

I'm having issues accessing Google Sheets through PHP in WordPress (WP). I've accessed the same sheet before in a local python program and I recall that once the code first ran the google authorization window popped up asking for approval. This WP shortcode isn't getting to that point and instead outputs an error message to the WP page stating a valid API Key is missing. What am I missing here?
Shortcode:
require_once __DIR__ . '/vendor/autoload.php';
function excel_tester_function() {
$client = new Google_Client();
$client->setApplicationName('Google Sheets and PHP');
$client->setAuthConfig(__DIR__ . '/credentials.json');
$client->setScopes(Google_Service_Sheets::SPREADSHEETS);
$client->setAccessType('online');
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
$service = new Google_Service_Sheets($client);
$spreadsheetId = '{SHEET_ID}';
$get_range = '{RANGE}';
$response = $service->spreadsheets_values->get($spreadsheetId, $get_range);
$values = $response->getValues();
foreach ($val as $values) {
print($val);
}
}
add_shortcode('excel-tester', 'excel_tester_function');
Error:
Fatal error: Uncaught Google_Service_Exception: { "error": { "code": 403, "message": "The request is missing a valid API key.", "errors": [ { "message": "The request is missing a valid API key.", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } } in...
Please advise. Let me know if there is any info I can provide that could help solve this. Thank you.

Related

YouTube Data API: listLiveBroadcasts doesn't work... why?

I try to use the YouTube API, but when I wish to use the LiveBroadcasts.list API.
When I use the same JSON key to list my playlist it's OK... I don't understand why.
$client = new \Google_Client();
$client->setAuthConfig(__DIR__ . '/../../key/youtube_client.json');
$client->setApplicationName('Broadcast');
$client->setScopes([
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtube.upload',
'https://www.googleapis.com/auth/youtube.readonly'
]);
$service = new \Google_Service_YouTube($client);
$broadcastsResponse = $service->liveBroadcasts->listLiveBroadcasts(
'id,snippet,contentDetails',
array(
'broadcastType' => 'persistent',
'mine' => 'true',
)
);
The error message is:
{ "error": { "code": 401, "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.", "errors": [ { "message": "Login Required.", "domain": "global", "reason": "required", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED" } }
Can someone help me to know where is my mistake?
You appear to be missing a lot of the authorization code that is required in order to fetch an access token.
<?php
/**
* Sample PHP code for youtube.liveBroadcasts.list
* See instructions for running these code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#php
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
}
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setScopes([
'https://www.googleapis.com/auth/youtube.readonly',
]);
// TODO: For this request to work, you must replace
// "YOUR_CLIENT_SECRET_FILE.json" with a pointer to your
// client_secret.json file. For more information, see
// https://cloud.google.com/iam/docs/creating-managing-service-account-keys
$client->setAuthConfig('YOUR_CLIENT_SECRET_FILE.json');
$client->setAccessType('offline');
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open this 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);
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
$response = $service->liveBroadcasts->listLiveBroadcasts('');
print_r($response);
This sample is going to end up running more as a console application as it just builds the url for you. If you need it run as a web application let me know i have some other sampes just not for this API which you can find here. If you need help altering it let me know.

Google calendar api user defined id using php

I am creating hundreds of calendars and than assigning users. I need to update that calendars regularly so I need to create custom ID's for each calendar. No matter what I use it comes back as an invalid ID
Below is my Script in PHP
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Assignments Calendar');
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/Assignment_Calendars-701dce094981.json');
define('SCOPES', implode(' ', array(
Google_Service_Calendar::CALENDAR)
));
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes(SCOPES);
$calendarServiceAccount = new Google_Service_Calendar($client);
$calendarId="abcdefghijklmnopqrstuvwxyz1234567890";
$newCalendar = new Google_Service_Calendar_Calendar();
$newCalendar->setSummary("testing");
$newCalendar->setTimeZone('America/Chicago');
$newCalendar->setId($calendarId);
$calendar = $calendarServiceAccount->calendars->insert($newCalendar);
My Error message is
PHP Fatal error: Uncaught Google_Service_Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "Invalid resource id value."
}
],
"code": 400,
"message": "Invalid resource id value."
}
}
No matter what I change the $calendarId to it get the same error. If I remove
$newCalendar->setId($calendarId); it works perfectly
You can't assign a custom ID, the ID of a calendar is defined by the API. See API reference.
You will have to create the calendar, read the $calendar->id value after the insert call and store it somewhere to link it to the user by any means.

Delete file with google drive API PHP V3 permission error

I have an issue with google drive PHP API V3 I'm trying to remove a file from the drive using the code below:
This is the code I'm using:
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Google Drive API PHP');
define('CREDENTIALS_PATH', '/root/.credentials/drive-php.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Drive::DRIVE_METADATA_READONLY
)
));
if (php_sapi_name() != 'cgi-fcgi') {
throw new Exception('This application must be run on the command line.');
}
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
$accessToken = json_decode(file_get_contents(CREDENTIALS_PATH), true);
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents(CREDENTIALS_PATH, json_encode($client->getAccessToken()));
}
return $client;
}
$client = getClient();
$service = new Google_Service_Drive($client);
$optParams = array(
'fields' => 'files(id, createdTime)'
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) != 0) {
foreach ($results->getFiles() as $file) {
$service->files->delete($file['id']);
}
}
All is working I can get the ID of the file but when I try to delete it I get the below error.
Any idea why please?
Thanks
PHP Fatal error: Uncaught Google_Service_Exception: {
"error": {
"errors": [
{
"domain": "global",
"reason": "insufficientPermissions",
"message": "Insufficient Permission"
}
],
"code": 403,
"message": "Insufficient Permission"
}
}
Google_Service_Drive::DRIVE_METADATA_READONLY cannot be used for deleting files using Drive API. So how about using Google_Service_Drive::DRIVE as the scope?
When you modified the scope, please remove the file of drive-php.json at /root/.credentials/, and run the script again. By this, the access token and refresh token reflected the modified scope can be retrieved.
And then, please confirm whether Drive API is enabled again.
If this was not useful for you, I'm sorry.

Multichannels on YouTube with YouTube Analytics API

I have a youtube account with 5 channels. With the YouTube Analytics API can I get data from the primary youtube channel. But the other channels I get always error message
forbidden
Also I am the owner from these all channels.
Here my sourcecode:
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setScopes( array(
'https://www.googleapis.com/auth/youtube.force-ssl',
'https://www.googleapis.com/auth/youtubepartner-channel-audit',
'https://www.googleapis.com/auth/youtube',
'https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/yt-analytics.readonly',
'https://www.googleapis.com/auth/yt-analytics-monetary.readonly',
'https://www.googleapis.com/auth/youtubepartner')
);
$client->setAccessType("offline");
$json_str = file_get_contents("access_token.json");
$json = json_decode($json_str, true);
if (isset($json['access_token']) && $json['access_token']) {
$client->setAccessToken($json_str);
$youtube = new Google_Service_YouTubeAnalytics($client);
$report = $youtube->reports->query('channel==UC0xxxxxxxxxxx', '2017-04-01', '2017-04-30', 'views');
echo json_encode($report);
} else {
$redirect_uri = 'https://xxxxxxxxxx/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
If i have in the query-Command channel==MINE or the YouTube Channel-ID (UC0xxxxxxx) is work very well. But the other Channel-ID from the same youtube account I get this error:
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "Forbidden"
}
],
"code": 403,
"message": "Forbidden"
}
}
How I can fix it?

Add Post With Google Api to Blogger With Service account keys

I'm trying to create php script that post article to Blogger using Google API. I'm using library google/apiclient:^2.0. I'm choosing to use service account keys. Here's my codes:
require_once '../../vendor/autoload.php';
try {
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . __DIR__ . '/../../credentials/BeMine92929929.json');
$client = new Google_Client();
$client->setApplicationName('Be Mine');
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Blogger::BLOGGER);
$token = $client->fetchAccessTokenWithAssertion();
$client->setAccessToken($token);
// I dump $token here, and it's available. token generation is success.
$service = new Google_Service_Blogger($client);
$blog = $service->blogs->getByUrl('http://bemine.blogspot.com');
//this is part for sending post into blogger, which is getting
//error
$post = new Google_Service_Blogger_Post();
$post->setTitle('Coba Post Artikel Kedua');
$post->setContent('Artikel kedua ini dikirim melalui layanan Blogger api.');
$service->posts->insert('Here Is My Blog ID', $post);
//If I comment posting part, and try to get list article of
//my blog, It success.
$posts = $service->posts->listPosts($blog->getId());
//file_put_contents('/tmp/anarky.txt', var_export($posts, true));
} catch (\Exception $ex) {
echo $ex->getMessage();
}
The response when I try to post article :
{
"error": {
"errors": [
{
"domain": "global",
"reason": "forbidden",
"message": "We're sorry, but you don't have permission to access this resource."
}
],
"code": 403,
"message": "We're sorry, but you don't have permission to access this resource."
}
}
What do I miss Need your advise, thank you.

Categories