Google Analytics, Dimensions & Metrics - How to? - php

I've finally figured out how i connected to the Google Analytics, correct - and I'm now able to access data to some point. I'm using the google-api-php-client.
I can work with metrics just fine fx, by doing
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions,ga:pageviews,ga:sessionDuration');
which will return me number of sessions, pageviews, and session duration. But now lets say I am interested in using some of the dimensions as well - Maybe i want the query return site usage data for all traffic by search engine, sorted by pageviews in descending order.
dimensions=ga:source
metrics=ga:pageviews,ga:sessionDuration,ga:exits
filters=ga:medium==cpa,ga:medium==cpc,ga:medium==cpm,ga:medium==cpp,ga:medium==cpv,ga:medium==organic,ga:medium==ppc
sort=-ga:pageviews
the data_ga->get function calls for the following parameters: $ids, $startDate, $endDate, $metrics, $optParams = array()
I tried supplying the dimensions and filters in a array, but it returns me the following errors
Warning: Illegal string offset 'type' in
xxxxxxxxx/src/Google/Service/Resource.php on line 269
Warning: Illegal string offset 'location' in
xxxxxxxxx/src/Google/Service/Resource.php on line 272
Warning: Illegal string offset 'location' in
xxxxxxxxx/src/Google/Service/Resource.php on line 274

Dimensions are not required so there for they are part of option parameters.
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12- 14", "ga:users,ga:sessions", $params );
Filters and sort can also be added to the $parms array

Related

Twitter API - Count number of tweets of a specific string

I'm using the twitter api to try to get an integer that tells me how many tweets there are to a certain string I give.
e.g. I search for "mercedes" and then want to get an integer back from twitter that says: "1249". 1249 would mean that there were so many tweets in the last 2 weeks. Twitter only returns data from the last 2 weeks as far as I know. Because of me it's also okay if I get all records back and pull them by means of php or the like. I have already sent some test requests, but always only get arrays back with a maximum of 20 entries.
Anyone have a solution?
And I already looked at similar questions but couldn't find something that helped me. Many answers in the questions I have seen no longer work, as twitter and its api has changed and evolved
Using the public search API, you will get tweets from the last 7 days only and not all tweets. So your results won't be accurate.
If you still want to test, you have to use the standard search API :
https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html
Set the "cout" parameter to 100, and check the "next_results" value in the results to loop 100 others tweets and so on until you get no result.
I couldn't find a solution neither, so I coded it using pieces of code and ideas as the previous #JeffProd one, and avoiding using a lib. I hope it could help you.
PS: You must apply for a Twitter Developer Account and create an app to get your TOKENs and KEYs.
<?php
//Access token & access token secret
define("TOKEN", 'XXXXXXXXXXXXXXXX'); //Access token
define("TOKEN_SECRET", 'XXXXXXXXXXXXXXXX'); //Access token secret
//Consumer API keys
define("CONSUMER_KEY", 'XXXXXXXXXXXXXXXX'); //API key
define("CONSUMER_SECRET", 'XXXXXXXXXXXXXXXX'); //API secret key
$method='GET';
$host='api.twitter.com';
$path='/1.1/search/tweets.json'; //API call path
$url="https://$host$path";
//Query parameters
$query = array(
'q' => 'wordtosearch', /* Word to search */
'count' => '100', /* Specifies a maximum number of tweets you want to get back, up to 100. As you have 100 API calls per hour only, you want to max it */
'result_type' => 'recent', /* Return only the most recent results in the response */
'include_entities' => 'false' /* Saving unnecessary data */
);
//time window in hours
define("WINDOW", 1);
//Authentication
$oauth = array(
'oauth_consumer_key' => CONSUMER_KEY,
'oauth_token' => TOKEN,
'oauth_nonce' => (string)mt_rand(), //A stronger nonce is recommended
'oauth_timestamp' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_version' => '1.0'
);
//Used in Twitter's demo
function add_quotes($str) { return '"'.$str.'"'; }
//Searchs Twitter for a word and get a couple of results
function twitter_search($query, $oauth, $url){
global $method;
$arr=array_merge($oauth, $query); //Combine the values THEN sort
asort($arr); //Secondary sort (value)
ksort($arr); //Primary sort (key)
$querystring=http_build_query($arr,'','&');
//Mash everything together for the text to hash
$base_string=$method."&".rawurlencode($url)."&".rawurlencode($querystring);
//Same with the key
$key=rawurlencode(CONSUMER_SECRET)."&".rawurlencode(TOKEN_SECRET);
//Generate the hash
$signature=rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
//This time we're using a normal GET query, and we're only encoding the query params (without the oauth params)
$url=str_replace("&","&",$url."?".http_build_query($query));
$oauth['oauth_signature'] = $signature; //Don't want to abandon all that work!
ksort($oauth); //Probably not necessary, but twitter's demo does it
$oauth=array_map("add_quotes", $oauth); //Also not necessary, but twitter's demo does this too
//This is the full value of the Authorization line
$auth="OAuth ".urldecode(http_build_query($oauth, '', ', '));
//If you're doing post, you need to skip the GET building above and instead supply query parameters to CURLOPT_POSTFIELDS
$options=array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
//Query Twitter API
$feed=curl_init();
curl_setopt_array($feed, $options);
$json=curl_exec($feed);
curl_close($feed);
//Return decoded response
return json_decode($json);
};
//Initializing
$done = false; //Loop flag
$countTweets=0; //Tweets fetched
$twitter_data = new stdClass();
$now=new DateTime(date('D M j H:i:s O Y')); //Current search time
//Fetching starts
do{
$twitter_data = twitter_search($query,$oauth,$url);
//Partial results, updating the total amount of tweets fetched
$countTweets += count($twitter_data->statuses);
//If not all the tweets have been fetched, then redo...
if(isset($twitter_data->search_metadata->next_results)){
//Parsing information for max_id in tweets fetched
$string="?max_id=";
$parse=explode("&",$twitter_data->search_metadata->next_results);
$maxID=substr($parse[0],strpos($parse[0],$string)+strlen($string));
$query['max_id'] = -1+$maxID; //Returns results with an ID less than (that is, older than) or equal to the specified ID, to avoid getting the same last tweet
//Twitter will be queried again, this time with the addition of 'max_id'
}else{
$done = true;
}
}while(!$done);
//If all the tweets have been fetched, then we are done
echo "<p>query: ".urldecode($query['q'])."</p>";
echo "<p>tweets fetched: ".$countTweets."</p>";
?>

How to add dimensions to Google analytics api requets

The examples given by Google are a very simple query request. however, when I try to add more parameters, it will throw errors and I don't exactly know how to structure the syntax.
This simple query request works:
return $analytics->data_ga->get(
'ga:' . $viewID,
$startDate,
$endDate,
'ga:sessions'
);
I need more information and I've already used Google's Query Explorer to get the Information but I just don't know how to structure my PHP query. The Information I want to request is also ga:pageviews as another metric, ga:pagePath and ga:pageTitle as dimensions and also a filter. I already fail at adding a second metric.
I have tried this:
return $analytics->data_ga->get(
'ga:' . $viewID,
$startDate,
$endDate,
'ga:sessions',
'ga:pageviews'
);
simply adding it doesn't work. Can anyone point me in the correct direction?
Dimensions need to be added as option parms
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12-14", "ga:users,ga:sessions", $params );

Get function in Google Analytics API

I'm trying to fetch some data using the analytics API, the example i have is this:
function getResults(&$analytics, $profileId) {
// Calls the Core Reporting API and queries for the number of sessions
// for the last seven days.
return $analytics->data_ga->get(
'ga:' . $profileId,
'7daysAgo',
'today',
'ga:sessions');
}
and the function in the Analytics.php file is:
public function get($ids, $metrics, $optParams = array())
{
$params = array('ids' => $ids, 'metrics' => $metrics);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "Google_Service_Analytics_RealtimeData");
}
}
How do I adapt that example to return some dimensions along with the sessions, for example, pagePath?
Thanks
So the question is little unclear, but the first part of your question is correct, that example works and is the way to get data from the Google Analytics API. You do NOT need to touch or modify Analytics.php however.
Here is what your code should look like:
$ga_profile_id = xxxxxxx; // insert yours
$from = date('Y-m-d', time()-2*24*60*60); // last 2 days
$to = date('Y-m-d'); // today
$metrics = 'ga:visits,ga:visitors,ga:pageviews';
$dimensions = 'ga:date';
$sort = "-ga:visits";
$data = $service->data_ga->get('ga:'.$ga_profile_id, $from, $to, $metrics, array('dimensions' => $dimensions,'sort'=>$sort));
These are all the basic elements you need to get started. Visit https://developers.google.com/analytics/devguides/reporting/core/v3/common-queries for a list of Common Query recipes. Replace the metrics, dimensions and sort parameters in my example above with the ones listed there to run the common report scenarios they cover.
The Analytics API Query explorer (https://ga-dev-tools.appspot.com/query-explorer/) is a great to play around and discover the metric and dimension names. For example, you'll find that that the dimension for Page Path is: ga:pagePath.
So then, for example, if you want to get visits and pageviews by page path, you simply insert the correct parameters in the code, and you get something that looks like this:
$ga_profile_id = xxxxxx; //insert yours here
$from = date('Y-m-d', time()-2*24*60*60); // last 2 days
$to = date('Y-m-d'); // today
$metrics = 'ga:visits,ga:pageviews';
$dimensions = 'ga:pagePath';
$sort = "-ga:visits";
$data = $service->data_ga->get('ga:'.$ga_profile_id, $from, $to, $metrics, array('dimensions' => $dimensions,'sort'=>$sort));
Which basically means:
Get the metrics visits and pageviews, using page path as the dimension, and sort it by visits - for the last 2 days! Hopefully this all makes sense.
I'm a bit unfamiliar with php syntax but you can specify dimension types in your params when query-ing for example for pagepath you could try
$params = array('ids' => $ids, 'metrics' => $metrics, 'dimensions' => 'rt:pagePath')
See the official dimensions and metrics explorer for more info

(400) Unknown metric(s): ga:socialNetwork'

I need get acquisition->channels info. I think I can get it using "ga:socialNetwork" dimension. But when I use it I get the following error:
(400) Unknown metric(s): ga:socialNetwork
However, ga:socialNetwork dimension exists: https://developers.google.com/analytics/devguides/reporting/core/dimsmets
My service call:
$service->data_ga->get('ga:xxxxx', '2010-01-01', '2015-01-15', 'ga:socialNetwork', $optParams);
ga:socialNetwork is a dimension not a metric. You are attempting pass in a dimension to the parameter that expects a metric.
Attempt the following to correct your code:
$optParams = array(
'dimensions' => 'ga:socialNetwork',
'sort' => '-ga:sessions');
$service->data_ga->get(
'ga:xxxxxx',
'2010-01-01',
'2010-01-15',
'ga:sessions',
$optParams);
ga:sessions is a metric where ga:socialNetwork is a dimension, this help center article should help clarify the difference.

Stripe API: List all Charges

I am using https://stripe.com/docs/api?lang=php#list_charges to get List all Charges but here they specify
count optional — default is 10 A limit on the number of objects to be
returned. Count can range between 1 and 100 items.
and I have thousands of entries, now how can I get all. Though if I set count to 100 it returns 110 records.
You can use the offset argument.
Once you get the 100 transactions, then make another call by adding offset=100 in URL.
This will bring the next 100 transactions, then make offset=200 and so on.
Update:
offset parameter is partly deprecated: API changelog - 2015-09-23
$charges = \Stripe\Charge::all();
foreach ($charges->autoPagingIterator() as $charge) {
// Do something with $charge
}
Reference.
Yes I got it with offset we can get all records.
Here's a PHP example: \Stripe\Charge::all(array("limit" => 3, "offset" => 10));
A Ruby example:
Stripe::Charge.all(limit: 3, offset:3)
As good as the Stripe API docs are, they could be clearer on how to filter.
source: https://stripe.com/docs/api/php#list_charges, https://stripe.com/docs/api/ruby#list_charges
in case offset is deprecated
$result = [];
$created_at = strtotime($request->end_data);
//created_at should be today's date epoch. search google for epoch
$has_more = false;
$a = 0;
do{
print_r($a);
\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$temp = \Stripe\BalanceTransaction::all( array(
'limit' => 100,
'created' => array(
'lte' => $created_at,
)
));
$result = array_merge($temp->data,$result);
$created_at = $temp->data[99]->created_at;
//api returns a parameter has_more(boolean), which means there is more
//data or not so you can also put that in while condition, for ex.
// $has_more = $temp->has_more;
$a++;
}while($a < 5);
dd($result);
this worked for me i was able to get 500 records at once as $a < 5 the api hits 5 times and each time created parameter which is lte (less than equal) changes for each api request and return previous records than current request provide. also i am appending the result of each api call to another result array
Unfortunately you can't.
I can see where such a feature would be nice for accounting purposes or whatever, but it's generally a better user experience to implement some sort of paging when displaying copious amounts of data to the user.
If you need absolute control over how many records to display at a time, I would suggest setting up a webhook on the charge.succeeded event and store your charges locally.

Categories