Google Calendar API (v3) - PHP can write but not read? - php

I spent all day figuring out the Google Calendar API. I finally managed to insert an event in my Google Calendar but now I cannot seem to get the "list" command working.
The following code works:
<?php
$start = array(
"dateTime" => $date . "T" . $start_time . ":00",
"timeZone" => "Europe/Berlin"
);
$end = array(
"dateTime" => $date . "T" . $end_time . ":00",
"timeZone" => "Europe/Berlin"
);
$headerarray = array(
'Content-type: application/json',
'Authorization: Bearer ' . $access_token,
'X-JavaScript-User-Agent: Google APIs Explorer'
);
$post_data = array(
"start" => $start,
"end" => $end,
"summary" => $title,
"description" => $description,
"key" => $api_key
);
$post_data = json_encode($post_data);
$url = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerarray);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$response = json_decode($response);
?>
This piece of code creates a new event in my calendar, so I should have everything set up correctly, right?
However this code does not work:
<?php
$headerarray = array(
"Authorization: Bearer " . $access_token,
"X-JavaScript-User-Agent: Google APIs Explorer"
);
$url = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events?key=' . $api_key;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerarray);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$response = json_decode($response);
?>
In this case I get the following response: Access Not Configured. Please use Google Developers Console to activate the API for your project.
But that is not the case. I configured the access correctly, or else I would not be able to insert events into the calendar, right? Maybe I am not using cURL right?
This is the reference for the list function: https://developers.google.com/google-apps/calendar/v3/reference/events/list
What am I not seeing here? Any help is highly appreciated.

Try this one :
Go to : https://console.developers.google.com
select project
go to: APIs and auth
Activate calendar api

I spent my whole day to create the event , I'm able to fetch the event
here is my code to fetch data from google oauth and I am using the codeigniter framework.
<?php
// product_config
$config['google_id'] = '';
$config['google_secret'] = '';
// oauth file
function get_calendar_events(OAuth2_Token_Access $token){
try{
$max_results = 250;
$url = 'https://www.googleapis.com/calendar/v3/calendars/primary/events?showDeleted=false&$orderBy=email&maxResults='.$max_results.'&alt=json&v=3.0&oauth_token='.$token->access_token;
$google_events = json_decode(file_get_contents($url), true);
return $google_events;
}catch (Exception $e) {
// Exception
}
}
/*** Controller ***/
function myCalendar() {
try {
$events = array();
$provider_name = 'google';
$provider = $this->oauth2->provider($provider_name, array(
'id' => $this->config->item($provider_name.'_id', 'product_config'),
'secret' => $this->config->item($provider_name.'_secret', 'product_config'),
'scopes' => array('https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly')
));
if (!$this->input->get('code')){ // access authorizing
// By sending no options it'll come back here
$provider->authorize();
}else{
// Get the Token
$token = $provider->access($this->input->get('code'));
$events = $provider->get_calendar_events($token);
}catch (Exception $e) {
// Exception
}
}
?>

public function create_calendar_event(OAuth2_Token_Access $token,$description, $leaveDate , $toLeaveDate,$title, $stime, $etime ){
try {
$title = $title;
//$start_time = '00:00'; $end_time = '23:59';
$start_time = $stime;
$end_time = $etime;
$timezone = 'Asia/Kolkata';
$start = array(
"dateTime" => $leaveDate . "T" . $start_time . ":00",
"timeZone" => $timezone
);
$end = array(
"dateTime" => $toLeaveDate . "T" . $end_time . ":00",
"timeZone" => $timezone
);
$headerarray = array(
'Content-type: application/json',
'Authorization: Bearer ' . $token->access_token,
'X-JavaScript-User-Agent: Google APIs Explorer'
);
$post_data = array(
"start" => $start,
"end" => $end,
"summary" => $title,
"description" => $description,
"key" => $this->api_key
);
$post_data = json_encode($post_data);
$calendar_id = 'primary';
$url = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';
$result = $this->NewcurlRequest($url, $headerarray, $post_data);
}catch(Exception $e){
// Exception
}
}
public function NewcurlRequest($url,$headerarray,$post_data, $curl_call = true){
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
//curl_setopt($ch, curlopt_post, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerarray);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
return $response;
} catch (Exception $e) {
return $e;
}
}

Related

Creta Signature for Oauth 1.0 with Curl and Php - Fixing error "Unsupported signature method in the header. Require HMAC-SHA256"

What is wrong?
This is all my code, I think that it should be fine, but I don't know why... with postman I haven't errors and I receive the tokens while with Curl I receive this error. I'm working in local with Mamp pro.
The error received is:
My Code To generete the Signature and get the Token:
$url = "https://account.api.here.com/oauth2/token";
$data = array(
"grant_type" => "client_credentials"
);
$oauthNonce = mt_rand();
$oauthTimestamp = time();
$oauthCustomereKey = "******";
$oauthSignatureMethod = "HMAC-SHA256";
$httpMethod = "POST";
$oauthVersion = "1.0";
$keySecret = "*****";
$baseString = $httpMethod."&". urlencode($url);
$paramString =
"grant_type=client_credentials&".
"oauth_consumer_key=". urlencode($oauthCustomereKey).
"&oauth_nonce=". urlencode($oauthNonce).
"&oauth_signature_method=". urlencode($oauthSignatureMethod).
"&oauth_timestamp=". urlencode($oauthTimestamp).
"&oauth_version=". urlencode($oauthVersion)
;
$baseString = $baseString . "&" . urlencode($paramString);
var_dump($baseString);
$signingKey= urlencode($keySecret) . "&";
$signature = urlencode(
base64_encode(
hash_hmac(
'sha256',
$baseString,
$signingKey,
true
)
)
);
$params = [
"oauth_consumer_key" => $oauthCustomereKey,
"oauth_nonce" => $oauthNonce,
"oauth_signature_method" => $oauthSignatureMethod,
"oauth_timestamp" => $oauthTimestamp,
"oauth_version" => $oauthVersion,
"oauth_signature" => $signature
];
// $lol = 'oauth_consumer_key="' . $oauthCustomereKey . '",oauth_signature_method="'.$oauthSignatureMethod . '",oauth_timestamp="'.$oauthTimestamp.'",oauth_nonce="'.$oauthNonce.'",oauth_version="'.$oauthVersion.'",oauth_signature="'.$signature.'"';
/* This will give you the proper encoded string to include in your Authorization header */
$params = http_build_query($params, null, ',', PHP_QUERY_RFC3986);
$authorization = "Authorization: OAuth " . $params;
var_dump($authorization);
if(!$curl = curl_init()){
exit;
}
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Content-Type : application/x-www-form-urlencoded",
$authorization));
$token = curl_exec($curl);
curl_close($curl);
return $token;
Result basestring (dump on line 87):
string(253) "POST&https%3A%2F%2Faccount.api.here.com%2Foauth2%2Ftoken&grant_type%3Dclient_credentials%26oauth_consumer_key%3D********%26oauth_nonce%3D1468397107%26oauth_signature_method%3DHMAC-SHA256%26oauth_timestamp%3D1605523226%26oauth_version%3D1.0"
And on the doc here we have this example... it look the same:
POST
&https%3A%2F%2Faccount.api.here.com%2Foauth2%2Ftoken
&grant_type=client_credentials%26oauth_consumer_key%3Daccess-key-id-1234%26oauth_nonce%3DLIIpk4%26
oauth_signature_method%3DHMAC-SHA256%26oauth_timestamp%3D1456945283%26oauth_version%3D1.0
FIXED
Finally... after 2 days...
There are 2 errors on the code above:
The parameter $data to CURLOPT_POSTFIELDS
Oauth 1.0 wants the double quotes.
So change:
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
With
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
This is strange for me, because with curl I use http_build_query with GET request and not POST, where we can use $data directly like array.
And delete:
$params = http_build_query($params, null, ',', PHP_QUERY_RFC3986);
And write the query with your beautifuls hand because $params doesn't have double quote.

Trying to get attendees set in google calendar API / PHP

I´m trying to create an event and that part works, but it will not for some reason send out the invitations / attendees in the calendar system with google API using PHP. It does create the event but that also it. So I hope someone can help me figuring out what I´m doing wrong.
myfile.php
// Event details
parameters = { title: $("#event-title").val(),
event_time: {
start_time: $("#event-type").val() == 'FIXED-TIME' ? $("#event-start-time").val().replace(' ', 'T') + ':00' : null,
end_time: $("#event-type").val() == 'FIXED-TIME' ? $("#event-end-time").val().replace(' ', 'T') + ':00' : null,
event_date: $("#event-type").val() == 'ALL-DAY' ? $("#event-date").val() : null
},
'attendees': [
{'email': 'test#dds-slagelse.dk'},
],
all_day: $("#event-type").val() == 'ALL-DAY' ? 1 : 0,
};
$("#create-event").attr('disabled', 'disabled');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { event_details: parameters },
dataType: 'json',
success: function(response) {
$("#create-event").removeAttr('disabled');
alert('Event created with ID : ' + response.event_id);
},
error: function(response) {
$("#create-event").removeAttr('disabled');
alert(response.responseJSON.message);
}
});
ajax.php file
session_start();
header('Content-type: application/json');
require_once('google-calendar-api.php');
error_log($_SESSION['access_token']);
try {
// Get event details
$event = $_POST['event_details'];
error_log(__LINE__);
$capi = new GoogleCalendarApi();
error_log(__LINE__);
// Get user calendar timezone
$user_timezone = $capi->GetUserCalendarTimezone($_SESSION['access_token']);
error_log(__LINE__);
// Create event on primary calendar
error_log($event['attendees0']);
$event_id = $capi->CreateCalendarEvent('primary', $event['title'], $event['all_day'], $event['event_time'], $event['attendees'], $user_timezone, $_SESSION['access_token']);
error_log(__LINE__);
echo json_encode([ 'event_id' => $event_id ]);
}
catch(Exception $e) {
error_log($e->getMessage());
header('Bad Request', true, 400);
echo json_encode(array( 'error' => 1, 'message' => $e->getMessage() ));
}
google-calendar.api.php
class GoogleCalendarApi
{
public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
$url = 'https://accounts.google.com/o/oauth2/token';
$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to receieve access token');
return $data;
}
public function GetUserCalendarTimezone($access_token) {
$url_settings = 'https://www.googleapis.com/calendar/v3/users/me/settings/timezone';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_settings);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception($http_code);
return $data['value'];
}
public function GetCalendarsList($access_token) {
$url_parameters = array();
$url_parameters['fields'] = 'items(id,summary,timeZone)';
$url_parameters['minAccessRole'] = 'owner';
$url_calendars = 'https://www.googleapis.com/calendar/v3/users/me/calendarList?'. http_build_query($url_parameters);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_calendars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = json_decode(curl_exec($ch), true); //echo '<pre>';print_r($data);echo '</pre>';
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception('Error : Failed to get calendars list');
return $data['items'];
}
//'primary', $event['title'], $event['all_day'], $event['event_time'], $event['attendees'], $user_timezone, $_SESSION['access_token']
public function CreateCalendarEvent($calendar_id, $summary, $all_day, $event_time, $event_attendees, $event_timezone, $access_token) {
$url_events = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';
$curlPost = array('summary' => $summary);
if($all_day == 1) {
$curlPost['start'] = array('date' => $event_time['event_date']);
$curlPost['end'] = array('date' => $event_time['event_date']);
}
else {
$curlPost['start'] = array('dateTime' => $event_time['start_time'], 'timeZone' => $event_timezone);
$curlPost['end'] = array('dateTime' => $event_time['end_time'], 'timeZone' => $event_timezone);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_events);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));
$data = json_decode(curl_exec($ch), true);
$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($http_code != 200)
throw new Exception($http_code);
return $data['id'];
}
}
I hope this make sense as I have tried so many attempts that I have lost track of it.
The Form Data that is send (after what i can figure out from google chrome is the following:
event_details[title]: Privat
event_details[event_time][start_time]: 2018-08-11T13:00:00
event_details[event_time][end_time]: 2018-08-11T15:30:00
event_details[event_time][event_date]:
event_details[attendees][0][email]: test#dds-slagelse.dk
event_details[all_day]: 0
ADyson, thanks for your help / hint. It was the missing curl that was the solution.
$curlPost['attendees'] = $event_attendees;
I hope it wont be to much of a bother, but it seems that it does not send out the invites for the events as hoped, even thought it does add the "guests" to the event.
The starting point for this solution is found here: http://usefulangle.com/post/29/google-calendar-api-create-event-php and if someone can please helt me to get * "sendNotifications"=>true * inserted or set correctly I would be very thankful. (would like to see how that parameter / function is set).
Best Regards
Jess
This help to me:
$curlPost['attendees'] = [['email'=>$event_data['attendees']]];
$curlPost['sendUpdates'] = array("sendUpdates"=>"all");
$curlPost['reminders'] = array('useDefault' => true, 'overrides' => array('method' => 'email','minutes' => 20));

Uploaded file rename to untitled Google drive

I have done google api integration code as well as file is upload to a drive. I have issue regarding a uploaded file name is "Untitled". Please review code and guide me what is missing.
<?php
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$CLIENT_ID = '709846732498-t19mhuuvq0nqtng5ogg8XXXXXX0im8.apps.googleusercontent.com';
$CLIENT_SECRET = 'XXXXXXXXKa';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
//$content = { title "mypdf.pdf", description = "mypdf.pdf", mimeType = "application/pdf" };
$contentArry = array('title' =>'veridoc' );
$contentArry = json_encode($contentArry);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS,$contentArry);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : application/pdf','Content-Length:' . filesize($filename),'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
function getStoredCredentials($path)
{
$credentials = json_decode(file_get_contents($path), true);
if (isset($credentials['refresh_token']))
return $credentials;
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
{
$credentials = null;
unlink($path);
}
return $credentials;
}
function storeCredentials($path, $credentials)
{
$credentials['created'] = (new DateTime())->getTimestamp();
file_put_contents($path, json_encode($credentials));
return $credentials;
}
function requestAuthCode()
{
global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
$url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
);
header('Location:' . $url);
}
function requestAccessToken($access_code)
{
global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$url = $GOAUTH . 'token';
$post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
. '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
function getAccessToken($credentials)
{
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
return $credentials['refresh_token'];
else
return $credentials['access_token'];
}
function authenticate()
{
global $STORE_PATH;
if (file_exists($STORE_PATH))
$credentials = getStoredCredentials($STORE_PATH);
else
$credentials = null;
if (!(isset($_GET['code']) || isset($credentials)))
requestAuthCode();
if (!isset($credentials))
$credentials = requestAccessToken($_GET['code']);
if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
$credentials = storeCredentials($STORE_PATH, $credentials);
return $credentials;
}
$credentials = authenticate();
$result = uploadFile($credentials, 'veridoc.pdf', '');
if (!isset($result['id']))
throw new Exception(print_r($result));
else
echo 'File copied successfuly (file Id: ' . $result['id'] . ')';
echo '<pre>'; print_r($result);
`
going by the documentation at https://developers.google.com/drive/api/v3/reference/files/update , to rename a file, do a PATCH request to https://www.googleapis.com/drive/v3/files/<fileId> with the new name, in your case, i guess that would be
$postResult = curl_exec ( $ch );
$parsed = json_decode ( $postResult, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $postResult );
}
$id = $parsed ['id']; // ?? wait, is it id or fileId?
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . urlencode ( $id ),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => json_encode ( array (
'name' => basename ( $filename )
) ),
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_HTTPHEADER => array (
'Content-Type : application/json',
'Authorization: Bearer ' . getAccessToken ( $credentials )
)
) );
curl_exec($ch);
ps, don't set the Content-Length header manually when using CURLOPT_POSTFIELDS, because curl will do it for you, and if you're using multipart/form-data, the length you set yourself is very likely to be wrong even (doesn't concern your code as you're not using multipart/form-data, but it's a good habit to learn nonetheless, get rid of it.)

PHP Upload PDF to Google Drive API

I have website created in PHP. Basically it is a send document kind of project. It uses a document store in Azure I will call and send it into Azure. Now I want to send in email as well as store in Google drive.
So it should be stored to drive with public access. I have create following code. It works properly I don't want any input from user.
$client->setAccessToken($_SESSION['accessToken']);
$service = new Google_DriveService($client);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = new Google_DriveFile();
foreach ($files as $file_name) {
$file_path = 'files/'.$file_name;
$mime_type = finfo_file($finfo, $file_path);
$file->setTitle($file_name);
$file->setDescription('This is a '.$mime_type.' document');
$file->setMimeType($mime_type);
$service->files->insert(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => $mime_type
)
);
}
finfo_close($finfo);
I want upload from Azure URL using cURL or using API. When mail send it is automatically uploaded to drive at the same time.
Question Update
I have function to send a mail this is work perfectly. I would like to store an attachment to google drive and retrieve path store that path in to database.
This all work will be based on API no user interaction required. That file is PDF in formate and not specific bytes its different as per data of file.
Issue :
When I upload a file to Drive original file name is rename to untitled. Here is code.
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS, array("title" =>"newfile.txt"));
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : text/plain', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
==========================================
Updated code (Issue with Added code but still getting issue with Untitle.pdf in drive)
==========================================
<?php
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$CLIENT_ID = '709846732498-xxxxxxxx';
$CLIENT_SECRET = 'XXXXXXXXXXXXXX';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : application/pdf', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
function getStoredCredentials($path)
{
$credentials = json_decode(file_get_contents($path), true);
if (isset($credentials['refresh_token']))
return $credentials;
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
{
$credentials = null;
unlink($path);
}
return $credentials;
}
function storeCredentials($path, $credentials)
{
$credentials['created'] = (new DateTime())->getTimestamp();
file_put_contents($path, json_encode($credentials));
return $credentials;
}
function requestAuthCode()
{
global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
$url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
);
header('Location:' . $url);
}
function requestAccessToken($access_code)
{
global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$url = $GOAUTH . 'token';
$post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
. '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
function getAccessToken($credentials)
{
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
return $credentials['refresh_token'];
else
return $credentials['access_token'];
}
function authenticate()
{
global $STORE_PATH;
if (file_exists($STORE_PATH))
$credentials = getStoredCredentials($STORE_PATH);
else
$credentials = null;
if (!(isset($_GET['code']) || isset($credentials)))
requestAuthCode();
if (!isset($credentials))
$credentials = requestAccessToken($_GET['code']);
if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
$credentials = storeCredentials($STORE_PATH, $credentials);
return $credentials;
}
$credentials = authenticate();
$result = uploadFile($credentials, 'example.pdf', '');
if (!isset($result['id']))
throw new Exception(print_r($result));
else
echo 'File copied successfuly (file Id: ' . $result['id'] . ')';
echo '<pre>'; print_r($result);
going by https://developers.google.com/drive/api/v3/simple-upload , this should work:
<?php
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
CURLOPT_HTTPHEADER => array (
'Content-Type: application/pdf', // todo: runtime detection?
'Authorization: Bearer [YOUR_AUTH_TOKEN]'
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents ( '/path/to/file.pdf' ),
CURLOPT_RETURNTRANSFER => 1
) );
try {
if (false === ($resp = curl_exec ( $ch ))) {
throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
}
$parsed = json_decode ( $resp, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $resp );
}
} finally{
curl_close ( $ch );
}
var_dump($resp);
I am still not completely sure i understand your question. Assuming you just want to upload a file in php or curl here are two options.
Uploading to Google drive is in two parts the first part you create the meta data that being the file name and basic information about your fine. The second part is where you upload the actual data of your file.
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'My Report',
'mimeType' => 'application/vnd.google-apps.spreadsheet'));
$content = file_get_contents('files/report.csv');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'text/csv',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
Code ripped from media upload
If you want to do this in curl inserting the meta data shouldnt be an issue your issue will be uploading the file itself. You will need to POST the metadata to create the empty file and capture its file-id. Then use the file-id for a content upload. You can find more information on the requests you will nee dot make here simple upload request.
The code will probably look something like this but again your going to have to pass the file id.
curl
--silent
--request POST
--data-binary "#c:\temp\myfile.jpg"
-OL MyFolder\myfile2.jpeg
-H "Slug: myfile3.jpg"
-H "Authorization: Bearer [your access token here]"
-H "Content-Type: image/jpeg {"fileid":"1234"}"
"https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
Note i have not tested the upload in curl this is just a guess.
You can use Logic Apps to send the file from Azure Blob storage to Google Drive as well as an email attachment.
https://learn.microsoft.com/en-us/azure/connectors/connectors-create-api-azureblobstorage
Alternatively files stored in Azure Blobs can be addresses with a public URL assuming you have the right permissions set on the container and/or blob.

Google PageSpeed Insights API not working [PHP]

I'm a beginner in PHP, so maybe someone could help to fix this ?
My web application is showing Google PageInsights API error..
Here's the code, I tried to change version to /v2/, but it still didn't work..
public function getPageSpeed($domain, $api = "")
{
try
{
$callback_url = "https://www.googleapis.com/pagespeedonline/v1/runPagespeed?";
$data = array(
'url' => 'http://' . $domain,
'key' => (empty($api) ? $_SESSION['GOOGLEAPI_SERVERKEY'] : $api),
'fields' => 'score,pageStats(htmlResponseBytes,textResponseBytes,cssResponseBytes,imageResponseBytes,javascriptResponseBytes,flashResponseBytes,otherResponseBytes)'
);
$curl_response = $this->curl->get($callback_url . http_build_query($data, '', '&'));
if ($curl_response->headers['Status-Code'] == "200") {
$content = json_decode($curl_response, true);
$response = array(
'status' => 'success',
'data' => array(
'pagespeed_score' => (int)$content['score'],
'pagespeed_stats' => $content['pageStats']
)
);
} else {
$response = array(
'status' => 'error',
'msg' => 'Google API Error. HTTP Code: ' . $curl_response->headers['Status-Code']
);
}
}
catch (Exception $e)
{
$response = array(
'status' => 'error',
'msg' => $e->getMessage()
);
}
return $response;
}
<?php
function checkPageSpeed($url){
if (function_exists('file_get_contents')) {
$result = #file_get_contents($url);
}
if ($result == '') {
$ch = curl_init();
$timeout = 60;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$result = curl_exec($ch);
curl_close($ch);
}
return $result;
}
$myKEY = "your_key";
$url = "http://kingsquote.com";
$url_req = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY;
$results = checkPageSpeed($url_req);
echo '<pre>';
print_r(json_decode($results,true));
echo '</pre>';
?>
The code shared by Siren Brown is absolutely correct, except that
while getting the scores we need to send the query parameter &strategy=mobile or &strategy=desktop to get the respective results from Page speed API
$url_mobile = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=mobile';
$url_desktop = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url='.$url.'&screenshot=true&key='.$myKEY.'&strategy=desktop';

Categories