Google People / Google Contacts API Failed - php

I'm using this library : https://github.com/rapidwebltd/php-google-people-api
here's my code :
<?php
require_once __DIR__ . '/vendor/autoload.php';
use RapidWeb\GooglePeopleAPI\GooglePeople;
use RapidWeb\GoogleOAuth2Handler\GoogleOAuth2Handler;
$clientId = '***-***.apps.googleusercontent.com';
$clientSecret = '***';
$refreshToken = '';
$scopes = ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/contacts',
'https://www.googleapis.com/auth/contacts.readonly'];
$googleOAuth2Handler = new GoogleOAuth2Handler($clientId, $clientSecret, $scopes, $refreshToken);
$people = new GooglePeople($googleOAuth2Handler);
$contacts = $people->all();
print_r($contacts);
?>
and I got this following error :
[fivesta1#sg21 googlecontacts]$ php create_contact.php
Fatal error: Uncaught exception 'Exception' with message '{
"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.",
"status": "UNAUTHENTICATED"
}
}
' in /home/fivesta1/public_html/googlecontacts/vendor/rapidwebltd/php-google-people-api/src/GooglePeople.php:63
Stack trace:
#0 /home/fivesta1/public_html/googlecontacts/create_contact.php(16): RapidWeb\GooglePeopleAPI\GooglePeople->all()
#1 {main}
thrown in /home/fivesta1/public_html/googlecontacts/vendor/rapidwebltd/php-google-people-api/src/GooglePeople.php on line 63
what did I miss here? thank you...

I had the same error and it's because your refresh token expires. You have to run the setup again:
php vendor/rapidwebltd/php-google-oauth-2-handler/src/setup.php
And give permission to your Google Account.

Related

Google Calendar API error Request had insufficient authentication scopes

I'm trying to change the color of a Google calendar event with PHP.
The code I'm using is this:
if(version_compare(PHP_VERSION, '7.2.0', '>=')) {
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING);
}
require_once __DIR__.'/vendor/autoload.php';
$hostname = 'localhost';
$username = 'root';
$password = '';
$database = 'pacientes';
try {
$conex = new PDO("mysql:host=$hostname;dbname=$database;charset=utf8", $username, $password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
catch(PDOException $e){
echo $e->getMessage();
}
session_start();
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
$client->addScope("https://www.googleapis.com/auth/calendar.events");
$client->addScope("https://www.googleapis.com/auth/calendar");
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$data = date("Y-m-d");
$date = date("Y-m-d", strtotime('+7 days', time()));
$status = "3";
$dados = $conex->prepare('SELECT * FROM pacientes WHERE status = ? LIMIT 1');
$dados->bindParam(1, $status);
$dados->execute();
if ($dados->rowCount() > 0) {
foreach($dados->fetchAll(PDO::FETCH_OBJ) as $key => $linha) {
$optParams = "".$linha->ide."";
$service = new Google_Service_Calendar($client);
$event = $service->events->get('primary', $optParams);
$event->setColorID('4');
$updatedEvent = $service->events->update('primary', $optParams, $event);
// Print the updated date.
echo $updatedEvent->getUpdated();
}
}
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
But when I run the code, I get the error:
Fatal error: Uncaught Google_Service_Exception: { "error": { "code": 403, "message": "Request had insufficient authentication scopes.", "errors": [ { "message": "Insufficient Permission", "domain": "global", "reason": "insufficientPermissions" } ], "status": "PERMISSION_DENIED" } } in C:\xampp\htdocs\google\calendar\vendor\google\apiclient\src\Google\Http\REST.php:118 Stack trace: #0 C:\xampp\htdocs\google\calendar\vendor\google\apiclient\src\Google\Http\REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google\Service\...') #1 C:\xampp\htdocs\google\calendar\vendor\google\apiclient\src\Google\Task\Runner.php(181): Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google\Service\...') #2 C:\xampp\htdocs\google\calendar\vendor\google\apiclient\src\Google\Http\REST.php(58): Google_Task_Runner->run() #3 C:\xampp\htdocs\google\calendar\vendor\google\apiclie in C:\xampp\htdocs\google\calendar\vendor\google\apiclient\src\Google\Http\REST.php on line 118
I recreated authorizations in Google Cloud Platform, made sure to grant authorization to edit events (/auth/calendar.events), but still the error persists.
Anyone have any suggestions?
Thanks
You appear to be trying to use the Events: update this method requires authorization with one of the following scopes
Now if we check your code we can see the following
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
$client->addScope("https://www.googleapis.com/auth/calendar.events");
$client->addScope("https://www.googleapis.com/auth/calendar");
the way you have added the last two as just the pure HTTPS scope name rather then the internal scope names supplied by the php client library. Implies to me that you ran your code once with the CALENDAR_READONLY and it didn't work and you checked the documentation and realized that you needed the higher level scope denoted in the documentation. Which is great and perfect. However when you ran your code again you didn't reset the authorization so its still running with the authorization from your first run with CALENDAR_READONLY
So the solution is to force your application to authorize again. The easiest way to do that is to go into your Google account and reset the third party consent and remove it for your app Manage third-party apps & services with access to your account alternately removing's the cookies in your browser might also work. you need to clear $_SESSION['access_token']. Although you are not using offline access so you could probably just wait for the access token to expire in an hour.
What you want is for the consent screen to popup again and request permission to access your account you should see the two new scopes on the screen now.

Getting error in testing facebook business-sdk

I started with facebook business sdk for php. Was following this doc: https://developers.facebook.com/docs/business-sdk/getting-started/
installed without trouble, then tried testing as they instructed,
created src/test.php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
$app_id = "{app-id}";
$app_secret = "{appsecret}";
$access_token = "{access-token}";
$account_id = "act_{{adaccount-id}}";
Api::init($app_id, $app_secret, $access_token);
$account = new AdAccount($account_id);
$cursor = $account->getCampaigns();
// Loop over objects
foreach ($cursor as $campaign) {
echo $campaign->{CampaignFields::NAME}.PHP_EOL;
}
filled in the required values. and ran the file. Getting this:
FacebookAds\CrashReporter : Enabled
FacebookAds\CrashReporter : Exception detected!
FacebookAds\CrashReporter : Successfully sent report
Fatal error: Uncaught FacebookAds\Http\Exception\AuthorizationException: Invalid OAuth access token. in C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Exception\RequestException.php:174
Stack trace:
#0 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Client.php(215): FacebookAds\Http\Exception\RequestException::create(Object(FacebookAds\Http\Response))
#1 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Request.php(286): FacebookAds\Http\Client->sendRequest(Object(FacebookAds\Http\Request))
#2 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Api.php(165): FacebookAds\Http\Request->execute()
#3 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Api.php(214): FacebookAds\Api->executeRequest(Object(FacebookAds\Http\Request))
#4 C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\ApiRequest.php(187): FacebookAds\Api->call('/act_3667840345...', 'GET', Array, Array)
#5 in C:\laragon\www\testPro\vendor\facebook\php-business-sdk\src\FacebookAds\Http\Exception\RequestException.php on line 174
Not sure what I am doing wrong. Didnt find much by searching. Can anyone please help?
The error you get is pretty explicit: "Invalid OAuth access token"
you can check the token you supplied using Facebook's token-debbuger # https://developers.facebook.com/tools/debug/accesstoken/
most probably you are missing the "ads_management" permission.

Wordpress PHP Google Sheets API Access

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.

Fatal error code 401 when connecting to Cloud Datastore

I am trying to connect to Google Cloud Datastore, using the code below. I have tried to follow these quidelines as well as these. I am using Composer and my code is in a Wordpress plugin. I have put my credentials file in the same folder as the script and it is found.
<?php # -*- coding: utf-8 -*-
/*
* Plugin Name: Cloud Datastore Connection
*/
add_shortcode( 'cd_connect', 'cloud_datastore_connection' );
use Google\Cloud\Core\ServiceBuilder;
use Google\Cloud\Datastore\DatastoreClient;
function cloud_datastore_connection( $attributes )
{
// For Composer
require 'vendor/autoload.php';
// Authenticate using keyfile data
$cloud = new ServiceBuilder([
'keyFile' => json_decode(file_get_contents('/www/.../XXX.json'), true)
]);
$datastore = new DatastoreClient(['projectId' => 'ultunaphotons']);
// Create an entity
$bob = $datastore->entity('Person');
$bob['firstName'] = 'Bob';
$bob['email'] = 'bob#example.com';
$datastore->insert($bob);
// Update the entity
$bob['email'] = 'bobV2#example.com';
$datastore->update($bob);
// testing
print bob['email'];
}
?>
I get this error message:
Fatal error: Uncaught Google\Cloud\Core\Exception\ServiceException: {
"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.",
"status": "UNAUTHENTICATED" } } in
/www/.../vendor/google/cloud-core/src/RequestWrapper.php:362
Stack trace: #0
/www/.../vendor/google/cloud-core/src/RequestWrapper.php(206): Google\Cloud\Core\RequestWrapper->convertToGoogleException(Object(GuzzleHttp\Exception\ClientException)) #1 /www/.../vendor/google/cloud-core/src/RestTrait.php(95):
Google\Cloud\Core\RequestWrapper->send(Object(GuzzleHttp\Psr7\Request),
Ar in
/www/.../vendor/google/cloud-core/src/RequestWrapper.php
on line 362
Any ideas what I'm doing wrong?

Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_client''

I am developing a mobile application with googleplus login. where I get the access token and send it to my server in order to verify it using Google APIs Client Library for PHP.
When I try to authenticate the token I got a Fatal Error Saying :
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_client'' in C:\xxx\vendor\google\apiclient\src\Google\Auth\OAuth2.php:127 Stack trace: #0 C:\xxx\vendor\google\apiclient\src\Google\Client.php(130): Google_Auth_OAuth2->authenticate('ya29.2QBihTdAag...') #1 C:\xxx\index.php(20): Google_Client->authenticate('ya29.2QBihTdAag...') #2 {main} thrown in C:\xxx\vendor\google\apiclient\src\Google\Auth\OAuth2.php on line 127
and here is my PHP code:
<?php
$google_client_id = 'XXXXX.apps.googleusercontent.com';
$google_client_secret = 'XXXXX';
$google_redirect_url = 'xxx';
$google_developer_key = 'XXXXXXXX';
$google_application_name = 'XXXX Login';
$google_application_scope = 'email'; /* I only needed the basic user info */
$google_redirect_uri='';
//include google api files
require_once 'vendor/autoload.php';
$gClient = new Google_Client();
$gClient->setApplicationName($google_application_name);
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_uri);
$gClient->setScopes($google_application_scope);
$gClient->setDeveloperKey($google_developer_key);
$gClient->authenticate("ya29.2QBihTdAagwpH5hHJUg5soIETLspVUgle6VPOT52UYPWkOKyHdUJlpUyvoMKPgkuqIS4PvgXQhfpHw");//Error Happened here
$token = json_decode($gClient->getAccessToken());
$google_oauthV2 = new Google_Service_Oauth2($gClient);
$user_info = $google_oauthV2->userinfo->get();
var_dump(user_info);
die();
?>
For $google_client_secret, instead of 'notasecret' use the value in the "CLIENT SECRET" section of your "Client ID for web application".

Categories