Get users for all accounts with Google Analytics api - php

I am having problems getting a list of users for accounts
If I put the account number in the try me page (https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/accountUserLinks/list) it works
$client = new Google_Client();
$client->setAuthConfigFile($_SERVER['DOCUMENT_ROOT'] . '/client_secrets.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_MANAGE_USERS);
$client=gaGetClient();
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$analytics = new Google_Service_Analytics($client);
//this doesn't work
$accountUserlinks=$analytics->management_accountUserLinks->listManagementAccountUserLinks('123456');
//this works
$man_accounts = $analytics->management_accounts->listManagementAccounts();
$accounts = [];
foreach ($man_accounts['items'] as $account) {
$accounts[] = [ 'id' => $account['id'], 'name' => $account['name'] ];
echo $account['name'] . " (" . $account['id'] . ")<br/>";
}
}
I get this error message
Fatal error: Uncaught exception 'Google_Service_Exception' with
message 'Error calling GET
https://www.googleapis.com/analytics/v3/management/accounts/123456/entityUserLinks:
(403) Insufficient Permission' in
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Google/Http/REST.php:110
Stack trace: #0
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Google/Http/REST.php(62):
Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request),
Object(Google_Client)) #1 [internal function]:
Google_Http_REST::doExecute(Object(Google_Client),
Object(Google_Http_Request)) #2
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Google/Task/Runner.php(174):
call_user_func_array(Array, Array) #3
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Google/Http/REST.php(46):
Google_Task_Runner->run() #4
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Goo
in
/home/grant/www/productaudit.hcpservices.co.uk/htdocs/current/google-api-php-client/src/Google/Http/REST.php
on line 110
Can anyone think what I am doing wrong. I am thinking it is a scope issue, but I have stated my scopes
Thanks
Grant

Related

UnauthorizedException in reading emails with Oauth 2 using EWS

I am trying to load email list using oauth 2. Following is my code:
<?php
require_once "vendor/autoload.php";
use src\API\Type;
use garethp\ews\MailAPI as API;
$token='EwA......'; //access token
$api = API::withCallbackToken('outlook.office365.com', $token);
$mail = $api->getMailItems();
foreach ($mail as $email) {
$email = $api->getItem($email->getItemId());
$email_id=$email->getItemId();
$subject = $email->getSubject();
$sender = $email->getSender()->getMailbox()->getEmailAddress();
$body = (string) $email->getBody();
echo $body;
}
but getting response as follows:
Fatal error: Uncaught garethp\ews\API\Exception\UnauthorizedException
in
C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices.php:438
Stack trace: #0
C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices.php(356):
garethp\ews\API\ExchangeWebServices->handleNonSuccessfulResponses(NULL,
401) #1
C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices\MiddlewareFactory.php(57):
garethp\ews\API\ExchangeWebServices->processResponse(NULL) #2
C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices.php(497):
garethp\ews\API\ExchangeWebServices->garethp\ews\API\ExchangeWebServices{closure}(Object(garethp\ews\API\MiddlewareRequest),
Object(Closure)) #3
C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices\MiddlewareFactory.php(66):
garethp\ews\API\ExchangeWebServices->garethp\ews\API{closure}(Object(garethp\ews\API\MiddlewareRequest)) #4 C:\inetpub\wwwroot\bephpforTt in C:\inetpub\wwwroot\bephpforTteam\New\php_ews\php-ews-master\src\API\ExchangeWebServices.php
on line 438

Copy Play store report to personal Google Cloud Storage bucket

I have a problem using Google Cloud Storage and Google Play reports. I'd like to parse reports on my server in PHP. To do that I'd like to move the file in the default app bucket to a new one. When I try to do that, I get the following error :
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "errors": [ { "domain": "global", "reason": "notFound", "message": "Not Found" } ], "code": 404, "message": "Not Found" } } ' in /var/www/d2/libs/googleAPI/src/Google/Http/REST.php:118 Stack trace: #0 /var/www/d2/libs/googleAPI/src/Google/Http/REST.php(94): Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1 [internal function]: Google_Http_REST::doExecute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2 /var/www/d2/libs/googleAPI/src/Google/Task/Runner.php(181): call_user_func_array(Array, Array) #3 /var/www/d2/libs/googleAPI/src/Google/Http/REST.php(58): Google_Task_Runner->run() #4 /var/www/d2/libs/googleAPI/src/Google/Client.php(781): Google_Http_REST::execute(Object(GuzzleHttp\Client), Object(GuzzleHttp\Psr7\Request), 'Google_Service_...', Array) #5 /var/www/d2/libs/googleAPI/src/Google/Service in /var/www/d2/libs/googleAPI/src/Google/Http/REST.php on line 118
I don't know why because the destination bucket exists, origin file too.
This is my implementation of my PHP script :
<?php
session_start();
require_once dirname(__FILE__).'/../libs/googleAPI/vendor/autoload.php';
$scopes = array("https://www.googleapis.com/auth/cloud-platform");
// Create client object
$client = new Google_Client();
$client->setRedirectUri('http://CENSORED/TEST_API.php');
$client->setAuthConfig("client_credentials_OAUTH.json");
$client->addScope($scopes);
if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Storage($client);
$request = $service->objects->listObjects("statsinstalls");
$objects = $request->getItems();
$sourceBucket = "pubsite_prod_rev_CENSORED";
$sourceObject = "installs_CENSORED_" . date("Ym") . "_app_version.csv";
$destinationBucket = "statsinstalls";
$destinationObject = $sourceObject;
$postBody = new Google_Service_Storage_StorageObject($client);
$response = $service->objects->copy($sourceBucket, $sourceObject, $destinationBucket, $destinationObject, $postBody);
foreach ($objects as $item)
echo $item->id . "<br>";
}
else if (!isset($_GET['code']))
{
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
else
{
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://CENSORED/TEST_API.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Why I got a 404 error?
Thanks.
I found the solution. The source Object must be the full path of the file.
I just replace :
$sourceObject = "installs_CENSORED_" . date("Ym") . "_app_version.csv";
by :
$sourceObject = "stats/installs/installs_CENSORED_" . date("Ym") . "_app_version.csv";
and that work well now. Now I'll try to get this CSV into a PHP array

Google drive API 403 insufficent permission error (do I need a google for work account?)

I would like to create an application to add folders and data inside those folders in Google Drive.
I am succesfully creating an acccess token using the refresh_token value. I am attempting to do a very basic file upload but its failing. I am also getting a list of files just to see is anything else working and that certainly is.
After the list of files appear I get the following error...
Fatal error: Uncaught exception 'Google_Service_Exception' with
message 'Error calling POST
https://www.googleapis.com/upload/drive/v3/files?uploadType=media:
(403) Insufficient Permission' in
/var/www/html/google-api-php-client/src/Google/Http/REST.php:110
Stack trace: #0
/var/www/html/google-api-php-client/src/Google/Http/REST.php(62):
Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request),
Object(Google_Client))
1 [internal function]: Google_Http_REST::doExecute(Object(Google_Client),
Object(Google_Http_Request))
2 /var/www/html/google-api-php-client/src/Google/Task/Runner.php(174):
call_user_func_array(Array, Array)
3 /var/www/html/google-api-php-client/src/Google/Http/REST.php(46): Google_Task_Runner->run()
4 /var/www/html/google-api-php-client/src/Google/Client.php(593): Google_Http_REST::execute(Object(Google_Client),
Object(Google_Http_Request))
5 /var/www/html/google-api-php-client/src/Google/Service/Resource.php(240):
Google_Client->execute(Object(Google_H in
/var/www/html/google-api-php-client/src/Google/Http/REST.php on line
110
UPDATE: I tried this without using refresh_token too and simply using the latest access token but still getting the exact same error.
Initially setting up access to get myself to the consent screen...
require_once ('../autoload.php');
ini_set('display_errors',1);
error_reporting(E_ALL);
session_start();
$client = new Google_Client();
$client->setAuthConfig('client_secret.json');
$client->addScope("https://www.googleapis.com/auth/drive");
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->setRedirectUri('http://www.example.com/oauth2callback.php');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
print_r($_SESSION);
$client->setAccessToken($_SESSION['access_token']);
$drive_service = new Google_Service_Drive($client);
//$files_list = $drive_service->files->listFiles(array())->getItems();
//echo json_encode($files_list);
} else {
$redirect_uri = 'http:/www.example.com/google-api-php-client/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
And then attempting to upload the file
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once ('../autoload.php');
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
// this token is obtained the first time from refresh_token, it will not be shown after the initial requrest
$refreshToken ='xxx';
$client->refreshToken($refreshToken);
$service = new Google_Service_Drive($client);
$files_list = $service->files->listFiles(array())->getFiles();
echo '<pre>';
print_r($files_list);
echo '</pre>';
$client->addScope("https://www.googleapis.com/auth/drive");
DEFINE("TESTFILE", 'testfile-small.txt');
if (!file_exists(TESTFILE)) {
$fh = fopen(TESTFILE, 'w');
fseek($fh, 1024 * 1024);
fwrite($fh, "!", 1);
fclose($fh);
}
if ($client->getAccessToken()) {
// This is uploading a file directly, with no metadata associated.
$file = new Google_Service_Drive_DriveFile();
$result = $service->files->create(
$file,
array(
'data' => file_get_contents(TESTFILE),
'mimeType' => 'application/octet-stream',
'uploadType' => 'multipart'
)
);
}

Paypal SDK problen

Here is my code:
if($approved) {
$payerId = $_GET['PayerID'];
// Get payment_id from database
$paymentId = mysql_query("Select payment_id from transactions_paypal WHERE hash = '".$_SESSION['paypal_hash']."'");
$paymentId = mysql_fetch_array($paymentId);
$payment = Payment::get($paymentId, $apiContext);
echo "<pre>";
var_dump($payment);
echo "</pre>";
die();
}else {
header('Location: ../paypal/cancelled.php');
}
But I get this errors:
Notice: Array to string conversion in
C:\xampp\htdocs\Tipperen\test\PayPal-PHP-SDK\paypal\rest-api-sdk-php\lib\PayPal\Api\Payment.php
on line 322
or
Fatal error: Uncaught exception
'PayPal\Exception\PayPalConnectionException' with message 'Got Http
response code 404 when accessing
https://api.sandbox.paypal.com/v1/payments/payment/Array.' in
C:\xampp\htdocs\Tipperen\test\PayPal-PHP-SDK\paypal\rest-api-sdk-php\lib\PayPal\Core\PayPalHttpConnection.php:159
Stack trace: #0
C:\xampp\htdocs\Tipperen\test\PayPal-PHP-SDK\paypal\rest-api-sdk-php\lib\PayPal\Transport\PayPalRestCall.php(74):
PayPal\Core\PayPalHttpConnection->execute('') #1
C:\xampp\htdocs\Tipperen\test\PayPal-PHP-SDK\paypal\rest-api-sdk-php\lib\PayPal\Common\PayPalResourceModel.php(103):
PayPal\Transport\PayPalRestCall->execute(Array, '/v1/payments/pa...',
'GET', '', NULL) #2
C:\xampp\htdocs\Tipperen\test\PayPal-PHP-SDK\paypal\rest-api-sdk-php\lib\PayPal\Api\Payment.php(328):
PayPal\Common\PayPalResourceModel::executeCall('/v1/payments/pa...',
'GET', '', NULL, Object(PayPal\Rest\ApiContext), NULL) #3
C:\xampp\htdocs\Tipperen\test\paypal\pay.php(20):
PayPal\Api\Payment::get(Array, Object(PayPal\Rest\ApiContext)) in
C:\xampp\htdocs\Tipperen\test\PayPal-PHP-SDK\paypal\rest-api-sdk-php\lib\PayPal\Core\PayPalHttpConnection.php
on line 159
Please help me.

Google Spreadsheets API with PHP – Fatal error: Uncaught exception

I'm trying to get started with the google SpreadSheet API. I know there are a bunch of other languages but PHP is the only one I'm vaguely competent in. I keep falling at the first hurdle and getting:
Fatal error: Uncaught exception 'Google\Spreadsheet\Exception' in
/Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/ServiceRequestFactory.php:48
Stack trace: #0 /Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/SpreadsheetService.php(37):
Google\Spreadsheet\ServiceRequestFactory::getInstance()
#1 /Users/djave/Google Drive/Sites/practise/gdata/index.php(32): Google\Spreadsheet\SpreadsheetService->getSpreadsheets()
#2 {main} thrown in /Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/ServiceRequestFactory.php on line 48
How this happens:
Step 1 Download and add the folder google-api-php-client
Next, fiddle with the code until it works
set_include_path('lib/');
require_once 'lib/Google/Client.php';
require_once 'lib/Google/Service/Books.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("-------------------------------------");
$service = new Google_Service_Books($client);
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
foreach ($results as $item) {
echo $item['volumeInfo']['title'], "<br /> \n";
}
Result: prints out a list of books
Step 2 Download and install php-google-spreadsheet-client
First off I copy the example exactly below what I have, then include all the right files until it can find everything:
set_include_path('lib/');
require_once 'lib/Google/Client.php';
require_once 'lib/Google/Service/Books.php';
require_once 'lib/Google/Spreadsheet/SpreadsheetService.php';
require_once 'lib/Google/Spreadsheet/ServiceRequestFactory.php';
require_once 'lib/Google/Spreadsheet/Exception.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("-------------------------------------");
$service = new Google_Service_Books($client);
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
foreach ($results as $item) {
echo $item['volumeInfo']['title'], "<br /> \n";
}
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
$spreadsheet = $spreadsheetFeed->getByTitle('MySpreadsheet');
$worksheetFeed = $spreadsheet->getWorksheets();
But I just get
Fatal error: Uncaught exception 'Google\Spreadsheet\Exception' in /Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/ServiceRequestFactory.php:48 Stack trace: #0 /Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/SpreadsheetService.php(37): Google\Spreadsheet\ServiceRequestFactory::getInstance() #1 /Users/djave/Google Drive/Sites/practise/gdata/index.php(23): Google\Spreadsheet\SpreadsheetService->getSpreadsheets() #2 {main} thrown in /Users/djave/Google Drive/Sites/practise/gdata/lib/Google/Spreadsheet/ServiceRequestFactory.php on line 48
I'm doing something really stupid, right? Thanks for any help
Looks like you've forgotten to bootstrap the lib first: https://github.com/asimlqt/php-google-spreadsheet-client#bootstrapping
require 'vendor/autoload.php';
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;
$serviceRequest = new DefaultServiceRequest($accessToken);
ServiceRequestFactory::setInstance($serviceRequest);
Give edit permission to "client_email" field value in client_secret.json file by opening the actual spreadsheet, refer image.

Categories