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.
Related
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.
I wish to develop one restful app where users will upload video to youtube via some admin interface. Since users will only upload on behalf of my name and in one channel I want to make authentication only once and then use refresh token to get access token.
So what I did is the following
I have visited https://developers.google.com and select and authorize all Youtube data API v3 API's with my email
Exchange authorization code for tokens (so now I have Authorization code, refresh and access token)
Code implementation (stuck here, can't imagine huh?)
$client = new Google_Client();
$client->setApplicationName('myApp');
$client->setClientId('<client-id>');
$client->setClientSecret('<client-secret>');
$client->setDeveloperKey('<dev-key>'); // <- do I really need that
$client->setScopes('https://www.googleapis.com/auth/youtube.force-ssl https://www.googleapis.com/auth/youtube.upload https://www.googleapis.com/auth/youtubepartner https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtubepartner-channel-audit https://www.googleapis.com/auth/youtube.readonly');
$client->refreshToken('<my-refresh-token>');
$client->setAuthConfig('client_secrets.json'); // <- is that the same as setting clientId and ClientSecret???
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$accessToken = $client->getAccessToken();
if (is_null($accessToken) || $client->isAccessTokenExpired()) {
// How to refresh token with REFRESH token?
dd($_GET);
}
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
// Define the $video object, which will be uploaded as the request body.
$video = new Google_Service_YouTube_Video();
// Add 'snippet' object to the $video object.
$videoSnippet = new Google_Service_YouTube_VideoSnippet();
$videoSnippet->setCategoryId('1');
$videoSnippet->setChannelId('<my-channel-id>');
$videoSnippet->setDescription('Description of uploaded video.');
$videoSnippet->setTags(['tag', 'tag2', 'tag3']);
$videoSnippet->setTitle('Test video upload.');
$video->setSnippet($videoSnippet);
// Add 'status' object to the $video object.
$videoStatus = new Google_Service_YouTube_VideoStatus();
$videoStatus->setEmbeddable(true);
$videoStatus->setLicense('youtube');
$videoStatus->setPrivacyStatus('private');
$video->setStatus($videoStatus);
$queryParams = [
'stabilize' => false
];
// TODO: For this request to work, you must replace "YOUR_FILE"
// with a pointer to the actual file you are uploading.
// The maximum file size for this operation is 64GB.
$response = $service->videos->insert(
'snippet,status',
$video,
$queryParams,
array(
'data' => file_get_contents($fullFilePath),
'mimeType' => 'video/*',
'uploadType' => 'multipart'
)
);
print_r($response);
So now I have several problems, which I don't know how to tackle.
Which $client->.... functions must be present if I'm already authorized (via OAuth playground)
How to refresh token with refresh token?
So far the only response I get is Google_Service_Exception
Message: { "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } }
It's my second day of trying to upload video via api with PHP and it's driving me nuts. I hope you guys will help me out.
If you need any additional informations, please let me know and I will provide. Thank you!!
UPDATE
After adding following code
$client->setAccessToken('<ACCESS_TOKEN>');
I get following errors
div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>An uncaught Exception was encountered</h4>
<p>Type: Google_Service_Exception</p>
<p>Message: {
"error": {
"errors": [
{
"domain": "youtube.quota",
"reason": "quotaExceeded",
"message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e."
}
],
"code": 403,
"message": "The request cannot be completed because you have exceeded your \u003ca href=\"/youtube/v3/getting-started#quota\"\u003equota\u003c/a\u003e."
}
}
</p>
<p>Filename: /home/vagrant/workspace/spot-scouting-adminpage/rest/vendor/google/apiclient/src/Google/Http/REST.php</p>
<p>Line Number: 118</p>
Which is of course not true, since I have never made a single successful request to google. Here is prof:
Maybe the problem is that a have generated access key via developers.google.com???
You have missed just a small step to set access token.
Once you get the access token set it with google client :
$client->setAccessToken($accessToken);
And then use youtube service:
$service = new Google_Service_YouTube($client);
I'm trying to create an automation script with php which adds a new row of information to a google sheet that I've shared. I've been scouring tutorials all morning trying to figure this out but each method is different and doesn't seem to be exactly what I need to do. Essentially this script will be triggers when a form is submitted on my site. Its going to take the form data and drop is into my google sheet.
I've created a service account under my project, which is stored inside the json file that was downloaded. Here's the script I have now. It's giving me the following error
{ "error": {
"code": 403,
"message": "The caller does not have permission",
"errors": [ {
"message": "The caller does not have permission",
"domain": "global",
"reason": "forbidden"
} ],
"status": "PERMISSION_DENIED"
}
and here's the code I'm running. (yes its incomplete because I can't get past the auth)
public function index()
{
$this->load->helper("url");
require APPPATH . 'third_party/GoogleAPI/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . APPPATH . 'third_party/GoogleAPI/bdgsheets.json');
$client = new Google_Client;
$client->useApplicationDefaultCredentials();
$client->setApplicationName("Is this working");
$client->setScopes(['https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds']);
$client->setAccessType('offline');
if ($client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
$accessToken = $client->fetchAccessTokenWithAssertion()["access_token"];
$sheets = new Google_Service_Sheets($client);
$data = [];
$current_row = 2;
$spreadsheet_id = "{my spreadsheet id here}";
$range = 'A1:H';
$rows = $sheets->spreadsheets_values->get($spreadsheet_id, $range, ['majorDimension' => 'ROWS']);
}
Thanks in advance for the help
Have you put the right scope when adding creating the access token. If you had used the scope value
"https://www.googleapis.com/auth/spreadsheets.readonly" instead of
"https://www.googleapis.com/auth/spreadsheets" you won't have write permission to the google sheet.
If you can share the code piece which creates the bdgsheets.json file it is easy to understand whether you have the "write" permission.
Also, try changing this piece of code
$client->setScopes(['https://www.googleapis.com/auth/drive','https://spreadsheets.google.com/feeds']);
to
$client->setScopes(['https://www.googleapis.com/auth/spreadsheets']);
and give it a shot
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.
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.