Get the number of visitors from script - php

I know how to access Google Analytics data with Data Studio or with Google Apps script in Javascript:
var account = Analytics.Management.Accounts.list().items[0];
var webProperties = Analytics.Management.Webproperties.list(account.id);
...
var report = Analytics.Data.Ga.get(tableId, startDate, endDate, metric,
options);
But in PHP, how is it possible to retrieve the number of visitors of a specific website or specific page, from a Google Analytics account / property / view? i.e.:
input: analytics account login/password/website code 'UA-XXXXX-Y'
output: [19873, 17873, 13999, 21032, ..., 16321] (i.e. the number of visits on www.example.com for each of the 30 last days, as a list of integers or JSON)

You can use Google Analytics API client in PHP.
Google analytic api client library
You can use the Query Explorer to create the queries to check.
Code Example:
$analytics = new analytics('username', 'password');
$analytics->setProfileByName('user.name');
//set the date range for which you want stats for
$analytics->setMonth(date('n'), date('Y'));
// it could also be $analytics->setDateRange('YYYY-MM-DD', 'YYYY-MM-DD'))
print_r($analytics->getVisitors());
print_r($analytics->getPageviews());
The above example used the Google Analytics API client in PHP. It was the first library released in PHP. Six years later, this software is outdated. Google changed the API.
As an alternative you can use GAPI library.
Above is the example how it would work, you can include gapi class to make it functional.
GAPI Analytic Library
Another way is that you can use the Google Analytics Reporting API v4 for PHP.
You can obtain this using composer:
composer require google/apiclient:^2.0
Guide to usage of this library is at github

I use this package:
https://github.com/google/google-api-php-client
You can use it to access all the Google APIs from PHP, including of course Google Analytics
Here's an example of how to use it:
// create client object and set app name
$client = new Google_Client();
$client->setApplicationName('Your app name'); // name of your app
// set assertion credentials
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'your_analytics_email#gmail.com', // email you added to GA
[
'https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents('/your/key/file.p12') // keyfile you downloaded
]
)
);
// other settings
$client->setClientId('your-client-id'); // from API console
$client->setAccessType('offline_access'); // this may be unnecessary?
// create service and get data
$service = new Google_AnalyticsService($client);
$from_date = date("Y-m-d",strtotime("-30 days")); // A month
$to_date = date("Y-m-d");
$response = $service->data_ga->get(
"ga:profile_id", // profile id
"$from_date", // start date
"$to_date", // end date
"ga:uniquePageviews",
[
'dimensions' => 'ga:pagePath', // Dimensions you want to include, pagePath in this example
'sort' => '-ga:uniquePageviews', // Sort order, order by unique page views from high to low in this case
'filters' => 'ga:pagePath=~\/articles\/[a-zA-Z0-9\-]+', // example url filter
'max-results' => '50' // Max results
]
);
foreach ($response["rows"] as $row) {
// ...do whatever you want with the results
}
Also, here's a guide on how to use the Google APIs:
https://developers.google.com/api-client-library/php/start/get_started
EDIT: You need to create credentials to access the Analytics API. You do it here: https://console.cloud.google.com/flows/enableapi?apiid=analyticsreporting.googleapis.com&credential=client_key. You need to register a project first, and then create the credentials. There are three options: API key, OAuth client ID and Service Account Key. I didn't want to use OAuth, so I used the Service Account Key. You can try using the API Key, in which case replace the $client->setAssertionCredentials(...) call for $client->setDeveloperKey(your_api_key). You can't use username and password directly AFAIK.

Related

Getting campaign stats (e.g. Clicks, CTR, CPC, etc.) via AdWords API

What I'm trying to currently do is fetch Campaign statistics such as Clicks, Impressions, CTR, Average CPC and etc for a particular campaign. Unfortunately, I can't find how to do it via the AdWords API.
What I've found up till now is that,
Maybe, in an earlier version of the CampaignService, we were able to obtain stats by doing something like $campaign->campaignStats. Unluckily, I'm using V201506 and in it there is no campaignStats object/variable.
I probably can get these stats using the 'CAMPAIGN_PERFORMANCE_REPORT' but it needs to be downloaded and I don't want to download the report. I just want an array or something similar returned so that I can process it. Also, I don't want to give any time frame, I just want all time stats to be returned for that campaign. Is it even possible?
If any one could help me out, I would really appreciate it. Kind of been stuck here for a few hours, skimmed through the whole AdWords API documentation but couldn't understand what would be the best and easy approach to this.
Now, Adwords API allowing stats only By reporting service.
And stats can be get using two methods.
1) By using reporting service as described
here
2) You can use Adwords Query Language. See
this
i don't know if you still need this but the API V201806 I found a solution. In this version of API exist the function getAsString() which returns the data in String and not download file, I request data in format XML and in PHP transform the response into a XML Object.
This is code I used:
class DownloadCriteriaReportWithAwql {
public static function runExample(AdWordsSession $session, $reportFormat){
// Create report query to get the data for last 7 days.
$query = (new ReportQueryBuilder())
->select([
'CampaignId',
'AdGroupId',
'Id',
'Criteria',
'CriteriaType',
'Impressions',
'Clicks',
'Cost',
'Conversions'
])
->from(ReportDefinitionReportType::CRITERIA_PERFORMANCE_REPORT)
->where('Status')->in(['ENABLED'])
->duringDateRange(ReportDefinitionDateRangeType::LAST_7_DAYS)
->build();
// Download report as a string.
$reportDownloader = new ReportDownloader($session);
// Optional: If you need to adjust report settings just for this one
// request, you can create and supply the settings override here.
// Otherwise, default values from the configuration
// file (adsapi_php.ini) are used.
$reportSettingsOverride = (new ReportSettingsBuilder())->includeZeroImpressions(false)->build();
$reportDownloadResult = $reportDownloader->downloadReportWithAwql(
sprintf('%s', $query),
$reportFormat,
$reportSettingsOverride
);
//print "Report was downloaded and printed below:\n";
$datos = $reportDownloadResult->getAsString();
return ($datos);
}
public static function main(){
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();
// See: AdWordsSessionBuilder for setting a client customer ID that is
// different from that specified in your adsapi_php.ini file.
// Construct an API session configured from a properties file and the
// OAuth2 credentials above.
$session = (new AdWordsSessionBuilder())
->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
$string = self::runExample($session, DownloadFormat::XML);
$xml = new \SimpleXMLElement($string);
return $xml;}}
The question was asked in 2015, since then they renamed the API to Google Ads API. The current version is V6 where getting clicks, CTR, CPC and other metrics is relatively simple.
The documentation here states:
This page shows all metrics and segments that can be put in the same SELECT clause as the fields of campaign
Based on that the AWQL for getting campaign together with clicks will look like this (tested):
$query = "SELECT campaign.id, campaign.name, campaign.status, metrics.clicks FROM campaign ORDER BY campaign.name"
Example in PHP how to iterate through results:
$stream = $googleAdsServiceClient->searchStream($customerId, $query);
foreach ($stream->iterateAllElements() as $googleAdsRow) {
/** #var GoogleAdsRow $googleAdsRow */
$data['campaigns'][] = [
'id' => $googleAdsRow->getCampaign()->getId(),
'clicks' => $googleAdsRow->getMetrics()->getClicks(),
];
}

How to update Google Sheets file with API PHP Client

I've been taking a look at the Google API PHP Client and would like to use it to add rows to a Google Sheet. From the code, it looks like one would use this method:
public function insert($fileId, Google_Service_Drive_Property $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('insert', array($params), "Google_Service_Drive_Property");
}
but I can't really tell what the parameters would be. Am I heading in the right direction? Also, not quite sure on how to connect to a specific Sheet. Please advise.
Thanks!
Use Google sheets class from zend framework 1.12. They have very nicely coded library for Google Spreadsheets
https://github.com/zendframework/zf1/tree/master/library/Zend/Gdata/Spreadsheets
I figured out how to work this and wanted to share with you guys. As I stated in a comment, I did not think using Zend's GData class was a good way for me since it's very dependent on other classes throughout the framework, thus being too heavy.
So I ended up using this Spreadsheet Client on top of Google's API. Google's API is used to authenticate my service, then I start calling the Spreadsheet Client library afterwards.
After spending over a day of Googling for various problems I had for the authentication process, here's what I did to make things work:
Created a new project for Google API here
Clicked "APIs" menu on the left side under "APIs & Auth"
Searched the Drive API and enabled it (can't remember if it was necessary)
Clicked the "Credentials" menu on the left
Clicked "Create new Client ID" button under OAuth
Selected "Service Account"
After info showed & json downloaded (not needed), I clicked "Generate new P12 Key" button
I saved the p12 file somewhere I could access it through PHP
Then in the code, I added the following lines:
$email = 'somethingsomethingblahblah#developer.gserviceaccount.com';
$CLIENT_ID = $email;
$SERVICE_ACCOUNT_NAME = $email;
$KEY_FILE = 'path/to/p12/file';
$SPREADSHEETS_SCOPE = 'https://spreadsheets.google.com/feeds';
$key = file_get_contents($KEY_FILE);
$auth = new Google_Auth_AssertionCredentials(
$SERVICE_ACCOUNT_NAME,
array($SPREADSHEETS_SCOPE),
$key
);
$client = new Google_Client();
$client->setScopes(array($SPREADSHEETS_SCOPE));
$client->setAssertionCredentials($auth);
$client->getAuth()->refreshTokenWithAssertion();
$client->setClientId($CLIENT_ID);
$accessToken = $client->getAccessToken();
Also, I had to make sure I:
Shared my spreadsheet specifically with the email address on my service account in the code above
Synced my server's time (I'm running Vagrant CentOS so it's slightly different)
I believe you can run this code with other services beyond Spreadsheets, such as Youtube, Analytics, etc., but you will need to get the correct scope link (see $SPREADSHEETS_SCOPE above). Remember, this is only when using the Service Account on the Google Console, which means you are programmatically getting data from your code. If you are looking to have others users sign in using the API, then it's different.

Want to add new record/row in Google spreadsheet in PHP

I want to add new records in Google spreadsheet by php coding. I had searched and found a solution which was using gmail id and password system for authentication. It was working initially but after 2 days it suddenly stop working. The code was as mentioned below:
<?php
include 'spreadsheet.php';
$Spreadsheet = new Spreadsheet("xxxxx#gmail.com", "xxxxxxx");
$Spreadsheet->setSpreadsheet("Tester")->setWorksheet("Sheet1")->add(array("First Name" => "Cell 1", "Last Name" => "Cell 2"));
?>
After it stops working I came to know that google has changed it's login system and I need to migrate to Oauth system for authentication.
After doing a long R & D I found one example - "https://github.com/asimlqt/php-google-spreadsheet-client" . But it was not working and after combing my various source of searching I have develop the following code:
<?php
include_once "google-api-php-client/examples/templates/base.php";
/************************************************
Make an API request authenticated with a service
account.
************************************************/
require_once realpath(dirname(__FILE__) . '/google-api-php-client/src/Google/autoload.php');
$accessToken = getGoogleTokenFromKeyFile("XXXXXXXXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXXXX");
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;
//ServiceRequestFactory::setInstance(new DefaultServiceRequest($accessToken));
// Load spreadsheet and worksheet
$worksheet = (new Google\Spreadsheet\SpreadsheetService())
->getSpreadsheets()
->getByTitle('Sheet1') // Spreadsheet name
->getWorksheets()
->getByTitle('Tester'); // Worksheet name
$listFeed = $worksheet->getListFeed();
// Uncomment this to find out what Google calls your column names
// print_r($listFeed->getEntries()[0]->getValues());
// Add a new blank row to the spreadsheet, using the column headings
$listFeed->insert(['name' => 'Simon', 'age' => 25, 'gender' => 'male']);
/**
* Retrieves a Google API access token by using a P12 key file,
* client ID and email address
*
* These three things may be obtained from
* https://console.developers.google.com/
* by creating a new "Service account"
*/
function getGoogleTokenFromKeyFile($clientId, $clientEmail, $pathToP12File) {
$client = new Google_Client();
$client->setClientId($clientId);
$cred = new Google_Auth_AssertionCredentials(
$clientEmail,
array('https://spreadsheets.google.com/feeds'),
file_get_contents($pathToP12File)
);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service_token = json_decode($client->getAccessToken());
return $service_token->access_token;
}
?>
But unfortunately this one is also not working and after sudden timeframe it is showing request time out error in my local xampp server.
And till date my application is on hold. Really not sure what to do now. If anybody has any concrete solution against that please share with me. my main purpose is to add data to google spreadsheet when a user submits his details in my website. Or if it is not possible after google's change in authentication system then please confirm me also. I want reachout a final solution of this problem.
Thanks in advance.
If you are able to retrieve a valid token, then pass the token in the request header with "Bearer yourtokenstring". google changed this recently from "GoogleLogin auth=yourtokenstring". Use the Bearer tag instead.
If you are struggling in your effort to retrieve a valid access token, consider using a Service Account with a p12 key file. Grant Edit privileges to your spreadsheet to the service account email address.

Manipulate an organisation's calendar with Google APIs

I'm trying to find out how to integrate the Google calendar using the v3 API with an existing application for a local non-profit organization.
The intent is the following: our organisation has a general public Google calendar (with Google account) that both visitors and active volunteers can subscribe to or show in their own calendar. We are in the process of developing a simple management web application (written in PHP) in which task forces can be created and managed. The core functionality is planning meetings (and managing the notes of these meetings, but this is not relevant to the question.). Users are notified via e-mail when a meeting is planned. It would also be very nice if the planned meetings could be programmatically added to the Google calendar. I now have to do this manually for every planned meeting.
I've been reading the documentation over at developers.google.com and the Google Code page for the php library for two days now and I find myself lost in different authentication schemes, account types, keys and many more, to the point where I'm starting to think that this is not an intended use case.
To come to the core of my question: I need to access the organisations Google calendar, and be able to post events, without any human interaction. Is this even possible? If so, Which account do i need to create (web app, service account or installed app?) in the Google APIs console? How would I authenticate the application? Do I need to grant rights to the application somehow? Is there an example somewhere I can refer to (possibly with a different API?)?
From what I've seen, the critical difference with all examples in Google's documentation, is that I do not want to modify a current or end-user's calendar, but the same calendar, regardless of the logged in user. (user authentication does not happen with the Google api, we rolled our own.) The redirect/user consent mechanism isn't exactly useful for me.
In this question, the asker is trying to achieve something similar. The full answer is not provided however. I can't seem to find some of the sources referred to in the accepted response.
You should be able to make a start with the sample code from here: https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/calendar/simple.php
And referring to here: https://developers.google.com/google-apps/calendar/v3/reference/events/quickAdd#examples
Regarding authentication, you'll need to visit https://code.google.com/apis/console?api=calendar to create and obtain the relevant keys, but it's not very clear so you might need to play around a bit.
I created a "service account" for API access, which gave me the client ID and let me download a private key, but I'm not sure without trying things further how that applies to the code sample linked above.
EDIT
I just found some old code that still works which creates events in calendars using the ZendGdata-1.10.2 library:
//for Google Calendar
set_include_path('./ZendGdata-1.10.2/library');
function createAlert($message, $date) {
$google = array();
// Define credentials for the Google Calendar account
$google['GCAL_USER'] = "info#example.com";
$google['GCAL_PASS'] = "password123";
// Include Zend GData client library
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');
// Get Google Calendar service name (predefined service name for calendar)
$service = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
// Authenticate with Google Calendar
$client = Zend_Gdata_ClientLogin::getHttpClient($google['GCAL_USER'], $google['GCAL_PASS'], $service);
date_default_timezone_set('GMT');
// Create a calendar object
$calendar = new Zend_Gdata_Calendar($client);
// Create a new event
$event = $calendar->newEventEntry();
$event->title = $calendar->newTitle($message);
// Add our message as the event content
$event->content = $calendar->newContent($message);
$when = $calendar->newWhen();
// Min time is 5 mins away
if ($date == "" || strtotime('+5 minute') >= strtotime($date)+300) {
$when->startTime = date("c", strtotime('+5 minute'));
$when->endTime = date("c", strtotime('+10 minute'));
} else {
$when->startTime = date("c", strtotime($date)+300);
$when->endTime = date("c", strtotime($date)+600);
}
$event->when = array($when);
// Setup reminders for event
$reminder = $calendar->newReminder();
$reminder->method = "all";
$when = $event->when[0];
$when->reminders = array($reminder);
// Send the new event to be added to Google Calendar
if (defined('GCAL_ID')) {
$newEvent = $calendar->insertEvent($event, 'http://www.google.com/calendar/feeds/' . $google['GCAL_ID'] . '/private/full');
} else {
$newEvent = $calendar->insertEvent($event);
}
// Check response
if (stripos($newEvent->id->text, "http://www.google.com/calendar/feeds/". str_replace('#', '%40', $google['GCAL_ID']) ."/private/full/") !== false) {
return "Sent!\n";
} else {
return $newEvent->id->text;
}
}

How do I use Google's "Simple API Access key" to access Google Calendar info (PHP)?

I'm trying to use the Google API v3 to access one google calendar and according to the documentation here : http://code.google.com/apis/calendar/v3/using.html#intro and here : https://code.google.com/apis/console/, the solution I need is the "Simple API Access" & "Key for server apps (with IP locking)".
Now, when I create a page with this code :
session_start();
require_once 'fnc/google-api-php-client/src/apiClient.php';
require_once 'fnc/google-api-php-client/src/contrib/apiCalendarService.php';
$apiClient = new apiClient();
$apiClient->setUseObjects(true);
$service = new apiCalendarService($apiClient);
if (isset($_SESSION['oauth_access_token'])) {$apiClient->setAccessToken($_SESSION['oauth_access_token']);
} else {
$token = $apiClient->authenticate();
$_SESSION['oauth_access_token'] = $token;
}
and in my "config.php" file I add ONLY my developper key (in place of the "X") :
global $apiConfig;
$apiConfig = array(
// True if objects should be returned by the service classes.
// False if associative arrays should be returned (default behavior).
'use_objects' => false,
// The application_name is included in the User-Agent HTTP header.
'application_name' => '',
// OAuth2 Settings, you can get these keys at https://code.google.com/apis/console
'oauth2_client_id' => '',
'oauth2_client_secret' => '',
'oauth2_redirect_uri' => '',
// The developer key, you get this at https://code.google.com/apis/console
'developer_key' => 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
// OAuth1 Settings.
// If you're using the apiOAuth auth class, it will use these values for the oauth consumer key and secret.
// See http://code.google.com/apis/accounts/docs/RegistrationForWebAppsAuto.html for info on how to obtain those
'oauth_consumer_key' => 'anonymous',
'oauth_consumer_secret' => 'anonymous',
But then I get errors and it tells me it's trying to authenticate using the "OAuth 2.0" system which I don't want to use. I only want to access one calendar with an API key.
And amazingly, when I search in google "Simple API Access key" I find nothing, nothing on their docs, no examples, no tutorials, nothing. Am I the only one using this thing?
So can someone tell me what I'm doing wrong?
(i know this is an old question but i would've been glad if someone
gave a real answer here so i'm doing it now)
I came on the same problem, Simple API access is not well documented (or maybe just not where i searched), but using the Google API Explorer i found a way to get what i need, which is in fact pretty straightforward. You don't need specific lib or anything : it's actually really simple.
In my case i simply needed to search a keyword on G+, so i just had to do a GET request:
https://www.googleapis.com/plus/v1/activities?query={KEYWORD}&key={YOUR_API_KEY}
Now, for a calendar access (see here), let's pretend we want to fetch access control rules list. We need to refer to calendar.acl.list which give us the URI :
https://www.googleapis.com/calendar/v3/calendars/{CALENDAR_ID}/acl?key={YOUR_API_KEY}
Fill in the blanks, and that's pretty much all you need to do. Get a server key (API Access submenu), store it somewhere in your project and call it within URIs you're requesting.
You cannot access your calendar information using API Key. API keys (or simple API acess key) are not authorized tokens and can only be used for some API calls such as a Google search query etc; API keys will not let you access any user specific data, which I am assuming is your objective through this calendar application.
Also, from what I see in your code, you are creating a client object which is going to use OAuth 2.0 authentication and hence you are getting authentication error messages.
There is no such a thing called Simple API Access key.
Normally OAuth 2.0 is used for authorization. But since you have your reason not to use it.
If you want to use OAuth1.0 for authorization. You need an API key in Simple API Access section on the API Access page.
If you want to use username & password login instead of OAuth, you can refer to ClientLogin, but this is not recommanded.
I got to this thread when trying to do the same today. Although this is way late, but the answer is YES, there is actually simple API key for those apis that does not need user authorizations, and the official client library support this.
The api library do this by Options, which is key, value pair.
Take the example of get information of a given youtube video, you would use this api: https://godoc.org/google.golang.org/api/youtube/v3#VideosListCall.Do
To use api key, simply make a type that implements the CallOption interface, and let it return the api key:
type APIKey struct {
}
func (k *APIKey) Get() (string, string) {
return "key", "YOU API KEY HERE"
}
Then when calling the API, supply the APIKey to it:
youtube, err := youtube.New(&http.Client{})
call := youtube.Videos.List("snippet,contentDetails,statistics").Id(id)
rsp, err := call.Do(opt)
This way, you can construct the youtube client with the vallina http client, rather than oauth client, and enjoy the simple api key.
The first answer said you can use http GET directly, but then you will need to handle the errors and parse the result yourself.
See below link which is helpfull to you. The Google API Client Library enables you to work with Google APIs such as Analytics, Adsense, Google+, Calendar, Moderator, Tasks, or Latitude on your server, in the language of your choice.
http://code.google.com/p/google-api-php-client/
Thanks,
Chintu

Categories