Missing end time Google Calendar when insert event - php

I trying to insert an event in the Google Calendar. The authentication and to fetch events works without any problems. Unfortunately I got the following error message:
{
error: {
errors: [
{
domain: "global",
reason: "required",
message: "Missing end time."
}
],
code: 400,
message: "Missing end time."
}
}
I request the site with cURL in PHP. To count the Content-Length for the request I using the function countArrayChars(). The following is my code:
$start = date("c", strtotime($start));
$end = date("c", strtotime($end));
$data_array = array(
"end"=>array("dateTime"=>$end),
"start"=>array("dateTime"=>$start),
"summary"=>$name
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.googleapis.com/calendar/v3/calendars/primary/events',
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array("Content-length: ".countArrayChars($data_array),"Content-type: application/json","Authorization: Bearer $access_token\r\n"),
CURLOPT_POSTFIELDS => $data_array
));
$resp = curl_exec($curl);
curl_close($curl);
echo $resp;
function countArrayChars(array $array){
$charNumber = 0;
array_walk_recursive($array, function($val, $key) use (&$charNumber)
{
$charNumber += strlen($val) + strlen($key);
});
return $charNumber;
}
What I also tried is to set the data as a http_build_query, as well as a json_encode result. Unfortunately this also didn't work.
Thanks for every response.
UPDATE:
$data_array = array(
"end"=>array("dateTime"=>$end,"timeZone"=>"Europe/Zurich"),
"start"=>array("dateTime"=>$start,"timeZone"=>"Europe/Zurich"),
"summary"=>$name
);
UPDATE 2:
This is the output of $end
string(25) "2017-03-10T00:00:00+01:00"

I don't know if this will help you, but this is the code I use to add events to google calendar through the API:
$event = new Google_Service_Calendar_Event(array(
'summary' => $summary,
'location' => $location,
'description' => $description,
'start' => array(
'dateTime' => $startdatetime,
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => $enddatetime,
'timeZone' => 'America/Los_Angeles',
),
'reminders' => array(
'useDefault' => FALSE,
),
));
You usually need to add a timezone, like I have, which could be your problem. I would suggest trying that out first.
Update:
I can't find anything else that could be wrong with your code, it's probably something having to do with how Google accepts data. All I can offer you now is exactly how I do mine, which I know works:
First, follow the instructions here to setup service account, if not done already. Make sure to create a .p12 file, instead of JSON.
You can download the PHP Google Calendar File here as well, without needing to use composer.
Next, work with the code below to suit your needs, but this should work for you. (The dateTime was properly formatted before it was sent in POST, so you may need to change that)
header('Content-type: application/json');
require_once __DIR__ . '/google-api-php-client/src/Google/autoload.php';
$summary = $_POST["summary"];
$location = $_POST["location"];
$description = $_POST["description"];
$startdatetime = $_POST["startdatetime"];
$enddatetime = $_POST["enddatetime"];
$client_email = "clientemail"; //client email setup when you create the authorization in Google Developer Console.
$private_key = file_get_contents("privatekey.p12"); //location on your server where the .p12 file you created is stored
$scopes = array('https://www.googleapis.com/auth/calendar');
$user_to_impersonate = "primary"; //This can also be an email address associated with the current gmail login if you don't want to use the default one
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate
); //Keep everything in this array the same
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$event = new Google_Service_Calendar_Event(array(
'summary' => $summary,
'location' => $location,
'description' => $description,
'start' => array(
'dateTime' => $startdatetime,
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => $enddatetime,
'timeZone' => 'America/Los_Angeles',
),
'reminders' => array(
'useDefault' => FALSE,
),
));
$service = new Google_Service_Calendar($client);
$calendarId = $useremail;
$event = $service->events->insert($calendarId, $event);
echo json_encode($event);

Check that $start is less than $end.

the error of google is not correct.
you have to check al inputfield for strange symbols. I had Straße in locationfield...that gave the missing endtime error.

Hi the problem may be on special characters in the variable, must try to encode UTF-8.
please try this
'summary' => utf8_encode($summary),
'description' => utf8_encode($descripcion),
'location' => utf8_encode($location),
regards,
Luis

Related

Send Onesignal notification using php api : The parameter "send_after" of onesignal's notification is not taken into consideration

Im working on a project using php/symfony 4, and after the creation of an object, I send a push notification, normaly without specifying the delivery parameter "send_after", it is working perfectly, and mobile devices receive the notification in the real time.
but whe I specify the date of delivery, they dont take it into consideration, and it is sent right at the moment of creation of my object, here is my snippet of code :
$fields = array(
'app_id' => $this->api_key,
'include_player_ids' => $devices,
'data' => array(
"type" => $type,
"url" => $url
),
'contents' => $content
);
if (null != $dateTime) {
date_time_set($dateTime, 9, 0, 0);
array_push($fields, [
'send_after' => $dateTime->format('Y-m-d H:i:s TO')] );
}
$fields = json_encode($fields);
so I try to respect this format mentioned in the doc : "2015-09-24 14:00:00 GMT-0700"
plz if someone has already encountered this issue, how could I resolve it?
Thanks in advance.
This should work:
$fields = array(
'app_id' => $this->api_key,
'include_player_ids' => $devices,
'data' => array(
"type" => $type,
"url" => $url
),
'contents' => $content
);
/* $dateTime=date_create("2020-08-12"); */
if (null != $dateTime) {
date_time_set($dateTime, 9, 0, 0);
/* $send_after = date_format($dateTime,'Y-m-d H:i:s TO'); */
$fields['send_after'] = $dateTime->format('Y-m-d H:i:s TO')] ); /* $send_after */
}
$fields = json_encode($fields);

Zoom Api - I can't update a meeting

I am trying to update a meeting using Zoom API but I can't get it to work. I'm trying to do a PATCH request using eleague oauth2 client like this:
require '../vendor/autoload.php';
require_once '../config.php';
$id = $_POST['id'];
$topic = $_POST['topic'];
$type = $_POST['type'];
$start_time = $_POST['start_time'];
$duration = $_POST['duration'];
$agenda = $_POST['agenda'];
$params = array(
'topic' => $topic,
'type' => $type,
'start_time' => $start_time,
'duration' => $duration,
'agenda' => $agenda,
'password' => '123456'
);
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => CONEXAO_API['clientId'],
'clientSecret' => CONEXAO_API['clientSecret'],
'redirectUri' => CONEXAO_API['redirect_url'],
'urlAuthorize' => 'https://zoom.us/oauth/authorize',
'urlAccessToken' => 'https://zoom.us/oauth/token',
'urlResourceOwnerDetails' => 'https://api.zoom.us/v2/users/me'
]);
$options['body'] = json_encode( $params );
$options['headers']['Content-Type'] = 'application/json';
$options['headers']['Accept'] = 'application/json';
$request = $provider->getAuthenticatedRequest( 'PATCH',
'https://api.zoom.us/v2/meetings/'.$id,
unserialize($_SESSION['token']),
$options
);
$retorno = $provider->getParsedResponse($request);
var_dump($retorno);
I'm getting an empty response, and I'm not sure what is missing. Can anyone help me?
basically the response given by the api is blank or just meeting updated which isn't in json format. So in case you want to check whether its working go to zoom meeting panel and open the meeting which you are updating using api and run the api and check the meeting is updated in zoom meeting panel.
The problem is that the method getParsedResponse for some reason is not returning any message. But the script is working, it's updating the meeting the way it supposed to.
If I get the response using the method getResponse I can see the statusCode 204, which means that everything went ok.

Php: Create web push notification

I want to create a web push notification in Php but I don't have the exact procedure for it. Following is the code I found, but it is not working.
<?php
require __DIR__ . '/../vendor/autoload.php';
use Minishlink\WebPush\WebPush;
$subscription = json_decode(file_get_contents('php://input'), true);
$auth = array(
'VAPID' => array(
'subject' => '`enter code here`',
'publicKey' => '**********',
'privateKey' => '***********',
),
);
$webPush = new WebPush($auth);
$res = $webPush->sendNotification(
$subscription['endpoint'],
"Hello!",
$subscription['key'],
$subscription['token'],
true
);
Please suggest the correct steps.
I spent some time my self figuring this out. I'm posting the code as it works for me. Generate the keys from here https://web-push-codelab.glitch.me/
<?php
require_once './vendor/autoload.php';
use Minishlink\WebPush\WebPush;
// array of notifications
$notifications = array(
array(
'endpoint' => 'https://fcm.googleapis.com/fcm/send/abcd........', // Chrome
'payload' => 'Hello',
'userPublicKey' => 'BFHh..........',
'userAuthToken' => 'DI............',
)
);
$auth = array(
'GCM' => 'AAAAKTK8bp4..............', // deprecated and optional, it's here only for compatibility reasons
'VAPID' => array(
'subject' => 'Some Text', // can be a mailto: or your website address
'publicKey' => 'BGsm2vrV2AMpT.............', // (recommended) uncompressed public key P-256 encoded in Base64-URL
'privateKey' => 'a89H............', // (recommended) in fact the secret multiplier of the private key encoded in Base64-URL
),
);
$defaultOptions = array(
'TTL' => 300, // defaults to 4 weeks
'urgency' => 'normal', // protocol defaults to "normal"
'topic' => 'push', // not defined by default - collapse_key
);
$webPush = new WebPush($auth, $defaultOptions);
$vr = $webPush->sendNotification(
$notifications[0]['endpoint'],
$notifications[0]['payload'], // optional (defaults null)
$notifications[0]['userPublicKey'], // optional (defaults null)
$notifications[0]['userAuthToken'], // optional (defaults null)
true // optional (defaults false)
);

move event from myservice account to my regular account error occur NOT FOUNND

Whenever i try to move event from myservice account to my regular account then the problem occur NOT FOUNND,everything is ok ,event id, calendar id, destination id, it even move from google interface Google Move, but from code it says not found, I Tried to move(last line) after inserting event
require 'src/Google/autoload.php';
require_once 'src/Google/Client.php';
require_once 'src/Google/Service/Calendar.php';
$Email_address = 'stafftesting#stafftesting-1204.iam.gserviceaccount.com';
$key_file_location = 'stafftesting-546f9e1a6522.p12';
$client = new Google_Client();
$client->setApplicationName("Google Calendar API PHP Quickstart");
$key = file_get_contents($key_file_location);
$scopes = "https://www.googleapis.com/auth/calendar";
$cred = new Google_Auth_AssertionCredentials(
$Email_address, array($scopes), $key);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Sushildai Event',
'location' => '800 Howard St., San Francisco, CA 94103',
'start' => array(
'dateTime' => '2016-01-30T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles', ),
'end' => array(
'dateTime' => '2016-01-30T11:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'attendees' => array(
array('email' => 'lpage#unifun.com'),
array('email' => 'sbrin#unifun.com'),
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
$result = $service->events->move('primary',$event->id,'soorazk#gmail.com');
printf('Event created: %s\n', $event->htmlLink);
$service->events->move('primary',$event->id, 'soorazkun1#gmail.com');
Based on the Official Google Documentation, '4*04 Not Found'* happen in several cases. Here are some examples:
* When the requested resource (with the provided ID) has never existed.
* When accessing a calendar that user can not access.
When encountering '404 Not Found' error message, the suggested action is to use 'Exponential Backoff'. Google Drive API documentation has a good explanation of exponential backoff and how to use it with the Google APIs. Exponential backoff is a standard error handling strategy for network applications in which the client periodically retries a failed request over an increasing amount of time.
Here's a useful Google documentation on Handling API Errors and How to implement exponential backoff:https://developers.google.com/google-apps/calendar/v3/errors

Mailchimp intergration error

We want to import all our database into one of your lists. We use php. The code is:
$api_key = "dXXXXXXX7eX276XXXXXXXX490";
$list_id = "7XXXb0XXXe";
$Mailchimp = new Mailchimp($api_key);
$Mailchimp_Lists = new Mailchimp_Lists($Mailchimp);
$batch = array();
$batch[] = array('email' => array(
'email' => 'xxxgmail.com',
"euid" => "xxx#gmail.com",
"leid" => "xxx#gmail.com"
),
'merge_vars' => array('FNAME' => 'XXX'));
$subscriber = $Mailchimp_Lists->batchSubscribe($list_id, $batch, false, true, true);
But I get an error
Mailchimp_User_DoesNotExist
Could not find user record with id
I tried many times, removed uuid and leid but no success. What is wrong? Thank you!
The API key used by me was incorrect.

Categories