Gmail Push notification PHP backend error - php

This is my code for gmail watch request push notification
define('SCOPES', implode(' ', array(
Google_Service_Gmail::MAIL_GOOGLE_COM)
));
$this->client = new Google_Client();
$this->client->setApplicationName(APPLICATION_NAME);
$this->client->setScopes(SCOPES);
$this->client->setAuthConfig(CLIENT_SECRET_PATH);
$this->client->setAccessType('offline');
$this->client->setApprovalPrompt('force');
$credentialsPath = CREDENTIALS_PATH;
if(!file_exists($credentialsPath)){
redirect('gmail');
}
$accessToken = json_decode(file_get_contents($credentialsPath), true);
$this->token = $accessToken['access_token'];
$this->client->setAccessToken($accessToken);
if ($this->client->isAccessTokenExpired()) {
$refreshTokenSaved = $this->client->getRefreshToken();
$this->client->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
//$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($this->client->getAccessToken()));
}
$service = new Google_Service_Gmail($this->client);
$watchreq = new Google_Service_Gmail_WatchRequest();
$watchreq->setLabelIds(array('INBOX'));
$watchreq->setTopicName('projects/composed-field-201410/topics/wooglobe');
$msg = $service->users->watch('me', $watchreq);
i am getting this error
Type: Google_Service_Exception
Message: { "error": { "errors": [ { "domain": "global", "reason": "backendError", "message": "Backend Error" } ], "code": 500, "message": "Backend Error" } }
Filename: D:\xampp\htdocs\viralgreats\admin\vendor\google\apiclient\src\Google\Http\REST.php
Line Number: 118

Related

542{ "error": { "code": 400, "message": "'valueInputOption' is required but not specified", "errors": [ { "mes

I found the same problem with the solution for the same error in javascript but couldn't make it work for PHP so please help
ERROR: 542{ "error": { "code": 400, "message": "'valueInputOption' is required but not specified", "errors": [ { "message": "'valueInputOption' is required but not specified", "domain": "global", "reason": "badRequest" } ], "status": "INVALID_ARGUMENT" } }
this is the error i get when i use the following code:
<?php
$time = time();
$name = $_GET['cname'];
$invoiceNumber = $_GET['invoice'];
$date = $_GET['date'];
$percentage = $_GET['percentage'];
$taxableValue = $_GET['taxableValue'];
$discount = $_GET['discount'];
$invoictotoal = $_GET['total'];
$sgst = $percentage*$taxableValue/100;
echo $discount;
require __DIR__ . '/vendor/autoload.php';
/**
* Returns an authorized API client.
* #return Client the authorized client object
*/
function getClient()
{
$client = new \Google_Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAuthConfig('C:\Users\mitta\Desktop\Seagull\form\credentials.json');
$client->setAccessType('offline');
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$client->addScope(Google\Service\Drive::DRIVE);
$client->setScopes(['https://www.googleapis.com/auth/spreadsheets']);
$service = new Google\Service\Sheets($client);
// Prints the names and majors of students in a sample spreadsheet:
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
try{
$spreadsheetId = '1H6EHEHGsHyRZTE-j8er9DrZjj-b9TkRg0p96K-h90Pc';
$range = 'Form Responses 1';
$valuetoinsert = [
[$time,$name,$invoiceNumber,$date,$percentage,$invoictotoal,$taxableValue,$discount,$sgst,$sgst],
];
$body = new Google_Service_Sheets_ValueRange([
'values' => $valuetoinsert
]);
$params = [
'valueInputOption' => 'RAW'
];
$inset = [
"insertDataOption" => "INSERT_ROWS"
];
$result = $service->spreadsheets_values->append(
$spreadsheetId,
$range,
$body
);
}
catch(Exception $e) {
// TODO(developer) - handle error appropriately
echo $e->getMessage();
}
?>
so i added the valuInputOption parameter but then i get different error
error: Uncaught TypeError: implode(): Argument #2 ($array) must be of type ?array, string given in D:\xamp\htdocs\form\vendor\google\apiclient\src\Google\Service\Resource.php:291 Stack trace: #0 D:\xamp\htdocs\form\vendor\google\apiclient\src\Google\Service\Resource.php(291): implode(Array, '&') #1 D:\xamp\htdocs\form\vendor\google\apiclient\src\Google\Service\Resource.php(190): Google_Service_Resource->createRequestUri('v4/spreadsheets...', Array) #2 D:\xamp\htdocs\form\vendor\google\apiclient-services\src\Sheets\Resource\SpreadsheetsValues.php(83): Google_Service_Resource->call('append', Array, 'Google\Service\...') #3 D:\xamp\htdocs\form\insert.php(54): Google\Service\Sheets\Resource\SpreadsheetsValues->append('1H6EHEHGsHyRZTE...', 'Form Responses ...', Object(Google\Service\Sheets\ValueRange), Array, Array) #4 {main} thrown in D:\xamp\htdocs\form\vendor\google\apiclient\src\Google\Service\Resource.php on line 291
The code used for this error is the sam and i added 2 more parameters:
$result = $service->spreadsheets_values->append(
$spreadsheetId,
$range,
$body,
$inset,
$params
);

PHP Google Drive API V3: "Login Required" Error

I'm using Google Drive API v3 in my app. I want to have a simple file upload using the API. But it's giving me an error saying "Login Required" even after logging in and redirected.
gdrive_auth.php
<?php
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('MY CLIENT ID');
$client->setClientSecret('MYS SECRET');
$client->setRedirectUri('http://localhost/gdriveapi/index.php');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
session_start();
if (isset($_GET['code']) || (isset($_SESSION['access_token']) && $_SESSION['access_token'])) {
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
} else
$client->setAccessToken($_SESSION['access_token']);
} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
exit();
}
index.php (to which i'm redirected after authorization)
<?php
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('MY CLIENT ID');
$client->setClientSecret('MY SECRET');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_Service_Drive($client);
//Insert a file
$file = new Google_Service_Drive_DriveFile();
$file->setName(uniqid().'.jpg');
$file->setDescription('A test document');
$file->setMimeType('image/png');
$data = file_get_contents('Capture.png');
$createdFile = $service->files->create($file, array(
'data' => $data,
'mimeType' => 'image/png',
'uploadType' => 'multipart'
));
print_r($createdFile);
The error message:
Fatal error: Uncaught Google_Service_Exception: { "error": { "errors":
[ { "domain": "global", "reason": "required", "message": "Login
Required", "locationType": "header", "location": "Authorization" }
Any solution for this?

how to upload files to google drive using php with access token

Am trying to upload a files to my google drive account with php and curl. I do not want all these long authentication flow of a thing. To this effect,I implemented the code below
$secret ="xxxxxx";
$clientid ="xxxxxxx";
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => "https://www.googleapis.com/upload/drive/v3/files?uploadType=media&clientID=xxxxxxx&secret=xxxxxxx",
CURLOPT_HTTPHEADER => array (
'Content-Type: image/png'),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents ('iconc.png' ),
CURLOPT_RETURNTRANSFER => 1
) );
$res = curl_exec($ch);
$err = curl_error($ch);
echo $res;
var_dump($res);
echo "<br>";
echo "<br>";
echo $err ;
I have enabled my google Drive Api and I have been assigned client id and secret but when I run the code its saying invalid credentials as per below
{ "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } } string(238) "{ "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } } "
Please where do I pass the client id and secret in the code above or do i need something like access token. if yes where do I get the google drive API access token. any solution is welcome. Thanks
You have two options the first is to add the access token to the request
https://www.googleapis.com/upload/drive/v3/files?access_token={YourToken}
The second is to add it as a header in the request
curl -H 'Accept: application/json' -H "Authorization: Bearer ${TOKEN}"
https://www.googleapis.com/upload/drive/v3/files
Using the client id as you have done here clientID=xxxxxxx&secret=xxxxxxx is basic authorization not Oauth2 you are missing the authorization step.
You should consider following the php quickstart here
<?php
require __DIR__ . '/vendor/autoload.php';
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following 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);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Drive($client);
// Print the names and IDs for up to 10 files.
$optParams = array(
'pageSize' => 10,
'fields' => 'nextPageToken, files(id, name)'
);
$results = $service->files->listFiles($optParams);
if (count($results->getFiles()) == 0) {
print "No files found.\n";
} else {
print "Files:\n";
foreach ($results->getFiles() as $file) {
printf("%s (%s)\n", $file->getName(), $file->getId());
}
}

php Google spreadsheet API "Request had insufficient authentication scopes"

i have a Problem with the Spreadsheed api and the "scopes".
With these script i want to update Cells on a Sheet.
I do not work with composer ich have just download the package in intereating it. The Token is already there and the error is from these row:
"$response = $service->spreadsheets_values->get($spreadsheetId, $range);"
<?php
session_start();
require_once __DIR__.'/vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('oauth-credentials.json');
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
echo "<pre>";
$service = new Google_Service_Sheets($client);
$spreadsheetId = 'xxx';
$range = 'Tabellenblatt1!A2:E';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();
if (count($values) == 0) {
print "No data found.\n";
} else {
print "Name, Major:\n";
foreach ($values as $row) {
// Print columns A and E, which correspond to indices 0 and 4.
printf("%s, %s <br>", $row[0], $row[4]);
}
}
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/api/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>
These Code brings the following Error
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
"error": {
"code": 403,
"message": "Request had insufficient authentication scopes.",
"errors": [
{
"message": "Request had insufficient authentication scopes.",
"domain": "global",
"reason": "forbidden"
}
],
"status": "PERMISSION_DENIED"
}
}
You have this scope defined:
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
For accessing a spreadsheet value:
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
You should have:
$client->addScope(Google_Service_Sheets::SPREADSHEETS_READONLY);
or
$client->addScope(Google_Service_Sheets::SPREADSHEETS);
Source:
https://developers.google.com/identity/protocols/googlescopes#sheetsv4
You Must Update the scope as #random425 said,
but after that delete the Token.json.
that will start the process of verification again what will give you new token with new scope that you have changed to.

Google Directory API(PHP-client) - error 401 Login Required

I am trying to add user using Service Account and constantly get '401 Login Required' error.
I already put p12-key on server and add permission Service Account/Scope in Admin Console.
I had done implementation with usual authentication but got same problem.
<?php
session_start();
set_include_path($_SERVER['DOCUMENT_ROOT'].'/src/php/');
require_once ('Google/Client.php');
$scope = 'https://www.googleapis.com/auth/admin.directory.user';
$client_id = 'xxxxx.apps.googleusercontent.com'; //Client ID
$service_account_name = 'xxxxx#developer.gserviceaccount.com'; //Email Address
$key_file_location = 'key.p12'; //key.p12
$client = new Google_Client();
$client->setApplicationName("test product");
if (isset($_SESSION['service_token']))
{
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials
(
$service_account_name,
array($scope),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired())
{
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
if($client->getAccessToken())
{
$requestUrl = 'https://www.googleapis.com/admin/directory/v1/users';
$requestMethod = 'POST';
$requestHeader = array('Content-Type' => 'application/json', 'Content-Length' => 'CONTENT_LENGTH');
$postBody ='{
"primaryEmail": "newuser#testpurpose.esy.es",
"name": {
"givenName": "user_name",
"familyName": "user_familyName"
},
"suspended": false,
"password": "passpass",
"ims": [
{
"type": "work",
"protocol": "gtalk",
"im": "user_im#talk.example.com",
"primary": true
}
]
}';
$request = new Google_Http_Request($requestUrl , $requestMethod, $requestHeader, $postBody);
$result = $client->execute($request);
print_r($result);
}
?>
Error
Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/admin/directory/v1/users: (401) Login Required' in /home/u538421519/public_html/src/php/Google/Http/REST.php:79 Stack trace:
#0 /home/u538421519/public_html/src/php/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 /home/u538421519/public_html/src/php/Google/Client.php(556): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /home/u538421519/public_html/index.php(58): Google_Client->execute(Object(Google_Http_Request))
#3 {main} thrown in /home/u538421519/public_html/src/php/Google/Http/REST.php on line 79
Request is sent without token:
$request = new Google_Http_Request($requestUrl , $requestMethod, $requestHeader, $postBody);
$result = $client->execute($request);
Request is sent with token:
$request = new Google_Http_Request($requestUrl , $requestMethod, $requestHeader, $postBody);
$result = $client->getAuth()->authenticatedRequest($request);

Categories