Using Service Account to access Google Analytics API doesn't work - php

I'm trying to access my Google Analytics data using a service account. I've created one in the Developers Console and I've enabled the Google Analytics API in that same console, but somehow, I can't manage to pull data from the API.
I've used the script on this page.
My code is as follows:
<?php
$keyfile = 'google/key.p12';
// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('MyNAME');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'XXXX#developer.gserviceaccount.com', array('https://www.googleapis.com/auth/analytics.readonly'), file_get_contents($keyfile)
)
);
$client->setClientId('XXXX.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
$analytics_id = 'ga:UA-XXXXXX-1'; // http://productforums.google.com/forum/#!topic/analytics/dRuAr1K4waI
// get data for the last 2 weeks
$lastWeek = date('Y-m-d', strtotime('-2 week'));
$today = date('Y-m-d');
// Test connection
try {
$results = $analytics->data_ga->get($analytics_id, $lastWeek, $today, 'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch (Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
?>
Note: if it says "XXXX", that means I've removed part of the string for security purposes; the proper strings are in my actual script.
It should either display the number of users or a error, but I just get a blank screen. I'm sure the URL to the keyfile is correct.
Does anybody have suggestions on how to fix this? That would be much appreciated.

It looks like you are using your property Id (UA-XXXXX-1) in place of your view (profile) id. If you go to Google Analytics Query Explorer it makes it easy to see what your actual ga:XXXX view (profile) id is. Any given property can have multiple view's (profiles). This reference guide gives a good description of the parameters that this request requires.

Related

How to Return List of Project Tasks in ActiveCollab

Sorry this may be a trivial question but I am new to PHP. In the documentation to retrieve project tasks, the following code is provided to connect to an Active Collab cloud account:
<?php
require_once '/path/to/vendor/autoload.php';
// Provide name of your company, name of the app that you are developing, your email address and password.
$authenticator = new \ActiveCollab\SDK\Authenticator\Cloud('ACME Inc', 'My Awesome Application', 'you#acmeinc.com', 'hard to guess, easy to remember');
// Show all Active Collab 5 and up account that this user has access to.
print_r($authenticator->getAccounts());
// Show user details (first name, last name and avatar URL).
print_r($authenticator->getUser());
// Issue a token for account #123456789.
$token = $authenticator->issueToken(123456789);
// Did we get it?
if ($token instanceof \ActiveCollab\SDK\TokenInterface) {
print $token->getUrl() . "\n";
print $token->getToken() . "\n";
} else {
print "Invalid response\n";
die();
}
This works fine. I can then create a client to make API calls:
$client = new \ActiveCollab\SDK\Client($token);
and get the list of tasks for a given project as shown in the documentation.
$client->get('projects/65/tasks'); // PHP object
My question is, what methods/attributes are available to get the list of tasks? I can print the object using print_r() (print will obviously not work), and what I really want is in the raw_response header. This is private however and I cannot access it. How do I actually get the list of tasks (ex: the raw_response either has a string or json object)?
Thanks in advance.
There are several methods to work with body:
$response = $client->get('projects/65/tasks');
// Will output raw JSON, as string.
$response->getBody();
// Will output parsed JSON, as associative array.
print_r($response->getJson());
For full list of available response methods, please check ResponseInterface.
If you wish to loop through tasks, use something like this:
$response = $client->get('projects/65/tasks');
$parsed_json = $response->getJson();
if (!empty($parsed_json['tasks'])) {
foreach ($parsed_json['tasks'] as $task) {
print $task['name'] . "\n"
}
}

What is a pagination cursor & how can I use it

I am trying to retrieve a list of customers using the square PHP SDK. If I leave the $cursor blank, I can see a list of all of my customer information. How do I use the pagination cursor to receive a customer by their name? Sample code below:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure OAuth2 access token for authorization: oauth2
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
$api_instance = new SquareConnect\Api\CustomersApi();
// string | A pagination cursor returned by a previous call to this endpoint.
//Provide this to retrieve the next set of results for your original query.
//See [Paginating results](#paginatingresults) for more information.
$cursor = "cursor_example";
try {
$result = $api_instance->listCustomers($cursor);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CustomersApi->listCustomers: '
, $e->getMessage(), PHP_EOL;
}
?>
The pagination cursor does not allow you to query for customers by name. If you have more than one "page" of customer, then it allows for you to get more customers by providing a token representing the next page.
If you have enough customers to fill multiple pages, a cursor would be returned in the response.

CalendarListEntry not showing up with Google PHP API

I am trying to add an entry with this sample of code :
<?php
$service = new \Google_Service_Calendar($client);
$calendarListEntry = new \Google_Service_Calendar_CalendarListEntry();
$calendarListEntry->setId($calendarId);
$calendarListEntry->setHidden(false);
$calendarListEntry->setSelected(true);
$calendarListEntry = $service->calendarList->insert($calendarListEntry);
The calendar is inserted but not shown on the Gmail Android App. I have to go to settings to display it.
I thought with setHidden() and setSelected() it would work but it didn't change anything. Plus, $calendarListEntry returned after insert has hidden = null.
Any thoughts ?

getting http 400 when trying to send data to paypal api

I have tried everything I can possibly think of, and nothing I do helps. I have even gone so far as to download the sample "Pizza Store" application they have on github. Every time, when I replace the "EndPoint" in the sdk-config.ini with "live" and then put in my clientID and clientSecret, and update the bootstrap.php file with that information, that I get from the "my Apps" section I get the error "Got Http response code 400 when accessing https://api.paypal.com/v1/vault/credit-cards."
I am even just using the sample application they provide, and I get that error. I have been searching and searching, and it look slike there are a good 40 different end points, but no documentation on how to use them, how to set them, or anything about it. The only thing I can gather from the sample app is that you can set the "mode" to live in the "setConfig" call, but that just results in the 400 error. I am desperate, I need some help here. I have even emailed their support, and haven't gotten a response. I am trying to help a friend out and get a website up where people can buy things, but this 400 error is driving me insane. Here is a direct copy of my code I am using to try this out...
$config = Config::getItem('merchant_settings', 'paypal');
$config = $config['production'];
$sdkConfig = array('mode' => 'live');
$apiContext = new ApiContext(new OAuthTokenCredential($config['client_id'], $config['client_secret']));
$apiContext->setConfig($sdkConfig);
$card = new CreditCard();
$card->setType('visa');
$card->setNumber('4446283280247004');
$card->setExpireMonth('11');
$card->setExpireYear('2018');
$card->setFirstName('Joe');
$card->setLastName('Shopper');
$funding_instrument = new FundingInstrument();
$funding_instrument->setCreditCard($card);
$payer = new Payer();
$payer->setPaymentMethod('credit_card');
$payer->setFundingInstruments($funding_instrument);
$amount = new Amount();
$amount->setCurrency('USD');
$amount->setTotal('15.85');
$transaction = new Transaction();
$transaction->setAmount($amount);
$transaction->setDescription('A test purchase');
$payment = new Payment();
$payment->setIntent('sale');
$payment->setPayer($payer);
$payment->setTransactions(array($transaction));
try {
$res = $payment->create($apiContext);
$this->set('data' , $res);
} catch(PayPalConnectionException $ex) {
$this->set('data', $ex);
} catch(Exception $e) {
$this->set('data', $e);
}
echo '<pre>';
print_r($data);
echo '</pre>';
And the error I am getting back is...
{"name":"MALFORMED_REQUEST","message":"Incoming JSON request does not map to API request","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#MALFORMED_REQUEST","debug_id":"2c61b8ecedfc6"}
I don't understand, I am using the exact same code as the sample application. Why am I getting that error. I have gone to that link, no help what so ever. Please, I am begging please help.
Yes, I realize that card information is fake, but I should be getting a credit card declined error, not a malformed request error. Please.
I don't know PHP but I think funding instrument is supposed to an array:
"payer":{
"payment_method":"credit_card",
"funding_instruments":[
{
"credit_card":{
If you create a funding instrument array ($fiArray) of length one, and set the first element to $funding_instrument, and pass the array to $payer->setFundingInstruments(fiArray).

Facebook API - really basic events.get() request, help needed

I want to get all the events of the logged in user, who has the app installed.
This is not intended to be a public app and is for me only. The user (me) has has given the app permissions like below:
I'm using this code:
<?php
// get all events for logged in fb user
require_once 'facebook.php';
$app_apikey = 'my-key-is-here';
$app_secret = 'my-secret-is-here';
$facebook = new Facebook($app_apikey, $app_secret);
$user_id = $facebook->require_login(); //returns my facebook user_id fine!
$events = $facebook->api_client->events_get($user_id); //returns nothing!
echo $events; //nothing
print_r($events); //no array to print
print_r(json_decode($events)); //no array to print
?>
Any ideas on why I'm getting a no results from events.get()?
It seems that you are using the old php-sdk? try using this one.
Make sure you have the user_events permission. Check this answer.
With the new SDK, it's as simple as:
$events= $facebook->api('/me/events');

Categories