php google ads api - unauthorized_client - php

I'm using 'Google_Client' class to authenticate access to adwords api so:
$REDIRECT_URI = 'http://localhost/GoogleAdwords/auth.php';
$client = new Google_Client();
$client->setApplicationName("App name");
$SCOPES = array('https://www.googleapis.com/auth/adwords'
);
$client->setIncludeGrantedScopes(true);
$client->setAccessType('offline');
$client->setRedirectUri($REDIRECT_URI);
$client->setScopes($SCOPES);
try{
$oauth2 = (new OAuth2TokenBuilder())
->withClientId($OAuthCredentials['clientId'])
->withClientSecret($OAuthCredentials['clientSecret'])
->withRefreshToken($client->getRefreshToken())
->build();
}catch(Exception $err){
//redirect("auth.php");
echo $err;
}
After authentication:
$oauth2 = (new OAuth2TokenBuilder())
->withClientId($OAuthCredentials['clientId'])
->withClientSecret($OAuthCredentials['clientSecret'])
->withRefreshToken($client->getRefreshToken())
->build();
$session = (new AdWordsSessionBuilder())
->fromFile()
->withOAuth2Credential($oauth2)
->build();
$adWordsServices = new AdWordsServices();
$managedCustomerService = $adWordsServices->get($session, ManagedCustomerService::class);
$selector = new Selector();
$selector->setFields(['CustomerId', 'Name']);
$selector->setOrdering([new OrderBy('CustomerId')]);
try{
$mccAccounts = $managedCustomerService->get($selector);
}catch(Exchange $e){
// echo $e->getMessage();
}
I'm pretty sure that the client is authenticated as I can get refreshToken and access token. But I'm getting this error:
Client error: `POST https://www.googleapis.com/oauth2/v4/token` resulted in a `401 Unauthorized` response: { "error": "unauthorized_client", "error_description": "Unauthorized" }
What could be the problem here? Am I missing something?
EDIT:
Using the same $client to access user information and shopping content works fine, but that's not the case for adwords.

This works for me, but I don't understand Google's libraries well enough to say if it's all necessary, maybe someone else can trim the fat.
$client = new \Google_Client();
$client->setApplicationName('NAME_HERE');
$client->setAuthConfig(__DIR__ . '/../Credentials/oauth.json');
$client->setAccessType('offline');
$client->setApiFormatV2(2);
//// Load previously authorized credentials from a file.
$oAuth = json_decode(file_get_contents(__DIR__ . '/../Credentials/oauth.json'), true);
$accessToken = json_decode(file_get_contents(__DIR__ . '/../Credentials/token.json'), true);
$client->setAccessToken($accessToken);
$oauth2 = (new OAuth2TokenBuilder())
->withClientId($oAuth['installed']['client_id'])
->withClientSecret($oAuth['installed']['client_secret'])
->withRefreshToken($client->getRefreshToken())
->build();
$session = (new AdWordsSessionBuilder())
->withDeveloperToken('TOKEN_HERE')
->withClientCustomerId("CUSTOMER_ID_HERE")
->withOAuth2Credential($oauth2)
->build();
$adWordsServices = new AdWordsServices();
$managedCustomerService = $adWordsServices->get($session, ManagedCustomerService::class);
$selector = new Selector();
$selector->setFields(['CustomerId', 'Name']);
$selector->setOrdering([new OrderBy('CustomerId')]);
$mccAccounts = $managedCustomerService->get($selector);
dd($mccAccounts) ;

Related

I have 400 Bad Request in REST.php on line 79 implementing GMAIL Api PHP

I am getting 400 Bad Request in REST.php on line 79 implementing GMAIL Api PHP
I have used below code to implement:
// Get the API client and construct the service object.
$client = new Google_Client();
$client->setDeveloperKey(API_KEY);
$client->setClientId(OAUTH_CLIENT_ID);
$client->setClientSecret(OAUTH_CLIENT_SECRET);
$client_email = MY_SERVICE_ACCOUNT_ID;
$private_key = file_get_contents('MYP12.p12');
$scopes = array(
'https://www.googleapis.com/auth/userinfo.email',
'https://mail.google.com'
);
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$client->setApplicationName("Gmail Sample");
$client->setAssertionCredentials($credentials);
//Refresh the token if it's expired.
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$token = $client->getAccessToken();
$client->setAccessToken($token);
$service = new Google_Service_Gmail($client);
$user = 'me';
$date_last = date('Y-m-d');
$newdate = strtotime('-1 day', strtotime($date_last));
$newdate = date('Y-m-d', $newdate);
$q = " 'after:".$newdate."'";
$messagesResponse = $service->users_messages->listUsersMessages($user, ['maxResults'=>1000 , 'q'=> $q]);
echo '<pre>';
print_r($messagesResponse);exit;
Fatal error: Uncaught exception 'Google_Service_Exception' with
message 'Error calling GET
https‍://www.googleapis.com/gmail/v1/users/me/messages?maxResults=1000&q=+%27after%3A2017-12-26%27&key=[API_KEY]:
(400) Bad Request' in
C:\wamp\www\google\google_calendar\src\Google\Http\REST.php on line 79
You have to replace API_KEY, OAUTH_CLIENT_ID, OAUTH_CLIENT_SECRET, [MY_SERVICE_ACCOUNT_ID] with your credentials.
$client->setDeveloperKey(API_KEY);
$client->setClientId(OAUTH_CLIENT_ID);
$client->setClientSecret(OAUTH_CLIENT_SECRET');
$client_email = '[MY_SERVICE_ACCOUNT_ID]';

Getting 'Forbidden error' when trying to execute youtube analytic API

I am receiving an error message when trying to execute youtube analytics API.
A service error occurred: Error calling GET
https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DUCaayLD9i5x4MmIoVZxXSv_g&start-date=2016-08-01&end-date=2016-08-07&metrics=views&dimensions=7DayTotals:
(403) Forbidden
Here is my code:
require_once __DIR__.'\google-api-php-client-1-master\src\Google\autoload.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Client.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Service\YouTube.php';
session_start();
$key = file_get_contents('mykey.json');
$OAUTH2_CLIENT_ID = 'xx-xx-xx';
$OAUTH2_CLIENT_SECRET = 'xxx';
$scope = array("https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtubepartner-channel-audit", "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly", "https://www.googleapis.com/auth/yt-analytics-monetary.readonly","https://www.googleapis.com/auth/youtubepartner");
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType('offline');
$client->setAccessToken($key);
$client->setScopes($scope);
if ($client->getAccessToken()) {
//Check to see if our access token has expired. If so, get a new one and save it to file for future use.
if($client->isAccessTokenExpired()) {
//refresh your access token if it's expired
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('mykey.json', $client->getAccessToken());
}
$analytics = new Google_Service_YouTubeAnalytics($client);
$channel_url = 'UCaayLD9i5x4MmIoVZxXSv_g';
$ids = 'channel==' . $channel_url . '';
$end_date = '2016-08-07';
$start_date = '2016-08-01';
$optparams = array(
'dimensions' => '7DayTotals',
);
$metric = 'views';
$api = $analytics->reports->query($ids, $start_date, $end_date, $metric, $optparams);
echo '<pre>';print_r($api);die;
}
I have already enable 'youtube analytic API' and I get the access_token from here
What is wrong with my code ,Or do we need to do some more stuff to get rid from this?
Looking at your code, it seems that you are generating a new access token at the point you save it to file (invalidating the first one).
Try :
if($client->isAccessTokenExpired()) {
//refresh your access token if it's expired
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('mykey.json', $newToken);
}

Uncaught exception 'Google_Auth_Exception' with message 'Invalid code'

i'm tring to migrate my google calendar access from Zend to new google API since they closed the service in november. My web app uses google api to create some events.
I'm facing a recurring message that i could not resolve : Uncaught exception 'Google_Auth_Exception' with message 'Invalid code'
Here's my code :
define('STDIN',fopen("php://stdin","r"));
require_once '../../utils/google-api-php-client-master/autoload.php';
/**********************
OAUTH 2.0 AUTHORIZATION
***********************/
$client = new Google_Client();
// OAuth2 client ID and secret can be found in the Google Developers Console.
$client->setClientId('XXXXXX);
$client->setClientSecret('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
$client->addScope('https://www.googleapis.com/auth/calendar');
$service = new Google_Service_Calendar($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:";
echo(trim(fgets(STDIN)));
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
Could someone please help me ?
I finally got this stuff to start working myself and a lot of searching. I was also using Zend before. There is a very good website at Daimto.com where you can see a bunch of tutorials. Here is the code that worked for me to add an event using the code form Daimto.com and adding code for adding an event in the body. Remember you need ot have the service email added to the share of your google calendar too!
<?php
session_start();
require_once './google-api-php-client/src/Google/Client.php';
require_once './google-api-php-client/src/Google/Service/Calendar.php';
$client_id = '6846057_YOUR_CLIENT_ID_HERE_pg3q8r6.apps.googleusercontent.com';
$Email_address = '68460_YOUR_SERVICE_EMAIL_HERE_developer.gserviceaccount.com';
$key_file_location = '_KEY_FILE_LOCATION_HERE_8.p12';
$client = new Google_Client();
$client->setApplicationName("_APP_NAME_HERE_");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$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);
?>
<html><body>
<?php
//$service = new Google_Service_Calendar($client);
//
$event = new Google_Service_Calendar_Event();
$event->setSummary('Event 2');
$event->setLocation('Somewhere');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2015-06-22T19:00:00.000+01:00');
$start->setTimeZone('Europe/London');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2015-06-22T19:25:00.000+01:00');
$end->setTimeZone('Europe/London');
$event->setEnd($end);
//
$calendar_id = "nm_GOOGLE_CAL_ID_HERE_#group.calendar.google.com";
//
$new_event = null;
//
try {
$new_event = $service->events->insert($calendar_id, $event);
//
$new_event_id= $new_event->getId();
} catch (Google_ServiceException $e) {
syslog(LOG_ERR, $e->getMessage());
}
//
$event = $service->events->get($calendar_id, $new_event->getId());
//
if ($event != null) {
echo "Inserted:";
echo "EventID=".$event->getId();
echo "Summary=".$event->getSummary();
echo "Status=".$event->getStatus();
}
?>

(401) Login Required Error for retrieve a users from Google apps domain?

how to retrieve a all users from a Google apps doamin . I have tried with the following coed but google return error like "Error calling GET https://www.googleapis.com/admin/directory/v1/users?domain=domainname.com: (401) Login Required "
set_include_path(get_include_path() . PATH_SEPARATOR . 'E:\wamp\www\Google APIs\google-api-php-client\src');
ini_set("memory_limit", -1);
require_once 'google-api-php-client/src/Google/Client.php';
require_once 'google-api-php-client/src/Google/Service/Drive.php';
require_once 'google-api-php-client/src/Google/Service/Oauth2.php';
require_once 'google-api-php-client/src/Google/Service/Directory.php';
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$client->setClientId('42X74XXXXXercontent.com');
$client->setClientSecret('OxzVALdXwd');
$client->setRedirectUri('http://localhost/Google%20APIs/index.php');
$client->setAccessType("offline");
$client->setApprovalPrompt("force");
$client->setDeveloperKey("AIXXXXXJDUdX48");
$SCOPES = array(
'https://www.googleapis.com/auth/admin.directory.user',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile');
$client->setScopes($SCOPES);
$token = '{"access_token":"ya29.1.AAXXXaeTg","token_type":"Bearer","expires_in":3600,"id_token":"eyJhbXXXXXXX9cEjDMUMe6PVrgo","refresh_token":"1\/sN-XXXXX5qdIGMeEW95tJv-0a1ujWk","created":1397878356}';
$decoded = json_decode($token);
$client->setAccessToken($token);
if ($client->isAccessTokenExpired()) {
$client->refreshToken($decoded->refresh_token);
}
$adminsdk = new Google_Service_Directory($client);
$users_list = $adminsdk->users->listUsers(array('domain'='domainon.info'));
Note : I have Perform a authorization with
$SCOPES = array(
'https://www.googleapis.com/auth/admin.directory.user',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile');
Please help me
You say you're performing the authorization for those scopes, but those scopes aren't included in the client. Make sure you include this code before you run $client->refreshToken():
$client->setScopes($SCOPES);

Google Calendar API v3 - Google_AuthException - Could not json decode the token issue

I've searched this Group, plus others, along with other websites and cannot find a solution to this. Error output is below. I definitely know that setAccessToken should NOT be NULL. Any guidance would be great here. the Google Calendar v3 API documentation is not so great...in fact, the samples are for older API versions.
PHP Fatal error: Uncaught exception 'Google_AuthException' with message 'Could not json decode the token' in google-api-php-client/src/auth/Google_OAuth2.php:162
Stack trace:
0 google-api-php-client/src/Google_Client.php(170): Google_OAuth2->setAccessToken(NULL)
1 Cal.php(16): Google_Client->setAccessToken(true)
2 {main}
thrown in google-api-php-client/src/auth/Google_OAuth2.php on line 162
Below is the code for my app:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
$client = new Google_Client();
$service = new Google_CalendarService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
} else {
$client->setAccessToken($client->authenticate($_GET['code']));
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$event = new Google_Event();
$event->setSummary('Appointment');
$event->setLocation('Somewhere');
$start = new Google_EventDateTime();
$start->setDateTime('2013-10-05T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-10-05T10:25:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_EventAttendee();
$attendee1->setEmail('my#email.com');
// ...
$attendees = array($attendee1);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('primary', $event);
echo $createdEvent->getId();
} else {
echo "failed hard";
}
?>
ClientID, Key, etc are kept in my google-api-php-client/src/config.php file
I haven't reviewed the api docs in a while but I use something like the following to configure the client. Maybe it will help.
$certFile = file_get_contents('/path/to/cert.p12');
$client = new Google_Client();
$client->setApplicationName('My App');
$client->setClientId($clientId);
$client->setScopes([
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly',
]);
if ($token = $_SESSION['google.calendar.token']) {
$client->setAccessToken($token);
}
$credentials = new Google_AssertionCredentials($service_email, $client->getScopes(), $certFile);
$client->setAssertionCredentials($credentials);
$service = new Google_CalendarService($client);

Categories