Bonjour,
Voici mon approche de l'API Google Analytics avec Curl.
Je suis étudiant, ce qui suit est le fruit de mes recherches et est déjà exposé sur mon site perso.
I - AuthentificationIl faut être authentifié pour utiliser cette API, Google offre, comme pour ses autres services, plusieurs possibilités. Je passerais les explications lourdes sur les différents modes d'authentification (
lire ici). Ce qu'il faut au final, c'est récupéré un Token qui permettra d'utiliser le service Google Analytics par la suite.
Je voulais un système d'authentification où l'on ai juste à renseigner ses identifiants Google.
$email = '*********@*********';
$passwd = '********';
$ids = '********';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = array('accountType' => 'GOOGLE',
'Email' => $email,
'Passwd' => $passwd,
'source'=>'CLI_GAnalytics',
'service'=>'analytics');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$hasil = curl_exec($ch);
$hasil = @split("Auth=", $hasil);
$auth = $hasil[1];
curl_close($ch);
Donc j'ai utilisé Curl, ce qui a nécessité l'activation du module PHP (dans WAMP).
$ids représente l'identifiant du site concerné. Il est à récupérer dans Google Analytics, il suffit d'ouvrir le dashboard du site et de regarder l'identifiant dans l'url qui se présente ainsi :
https://www.google.com/analytics/reporting/?id=xxxxxxxxx.
On passe ensuite les données dans un tableau, en sachant que vous pouvez mettre ce que vous voulez dans 'source'.
$auth est mon Token d'authentification auprès du service Google Analytics.
II - Récupération des informationsJe désire afficher, pour le jour courant (oui parce que l'API permet de récupérer les informations de son site en direct), le nombre de visites par navigateur.
$current_date = date('Y-m-d', time());
$ch1 = curl_init("https://www.google.com/analytics/feeds/data?ids=ga:" . $ids . "&metrics=ga:visits&dimensions=ga:browser&start-date=" . $current_date . "&end-date=" . $current_date);
$header[] = 'Authorization: GoogleLogin auth=' . $auth;
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch1, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HEADER, false);
$response = curl_exec($ch1);
curl_close($ch1);
$XML_response = @str_replace('dxp:','',$response);
$XML_object = simplexml_load_string($XML_response);
echo '<ul>';
foreach($XML_object->entry as $m)
{
$tmp = @split('ga:browser=', $m->title);
echo '<li>' . $tmp[1];
echo ' : ';
echo $m->metric['value'];
echo ' visits</li>';
}
echo '</ul>';
Lorsqu'on veut utiliser l'API il faut indiquer que l'on est authentifié, c'est le but des lignes :
$header[] = 'Authorization: GoogleLogin auth=' . $auth;
curl_setopt($ch1, CURLOPT_HTTPHEADER, $header);
Ensuite, il est obligatoire de renseigner les paramètres
ids,
start-date et
end-date. Sinon on obtient une belle erreur... Ici, je cherche à récupérer le nombre de visites (qui est le
metric) en fonction du navigateur qui est la
dimension.
https://www.google.com/analytics/feeds/data?ids=ga:" . $ids . "&metrics=ga:visits&dimensions=ga:browser&start-date=" . $current_date . "&end-date=" . $current_date);
Les
metrics et
dimensions sont disponibles
ici.
On récupère un flux XML, que j'ai d'abord épuré :
$XML_response = @str_replace('dxp:','',$response);
Puis je charge un objet XML pour récupérer les résultats que je souhaite.
Ce code produit le résultat suivant :
* Chrome : 1 visits
* Firefox : 15 visits
* Internet Explorer : 3 visits
Youpi ! Je suis riche, 19 visites aujourd'hui...
Pour récupérer le nombre de visiteurs, il suffit de modifier les
metrics et
dimensions :
https://www.google.com/analytics/feeds/data?ids=ga:" . $ids . "&metrics=ga:visits&start-date=" . $current_date . "&end-date=" . $current_date);
et de changer l'accès au résultat :
echo $XML_object->entry->metric['value'] . ' visits';
Pour récupérer le nombre de pages vues, on modifie comme ceci (l'accès au résultat est le même) :
https://www.google.com/analytics/feeds/data?ids=ga:" . $ids . "&metrics=ga:pageviews&start-date=" . $current_date . "&end-date=" . $current_date);
III - Graphique avec l'API Google ChartL'API Google Chart est une API qui permet de créer des graphiques (format image) assez simplement. Le lien qui m'a été utile est le suivant :
http://code.google.com/intl/fr/apis/chart/basics.html. J'avais commencé avec Yahoo UI que j'utilise régulièrement au travail, mais l'intérêt était moindre et je voulais consommer le moins de ressources possibles. Cependant YUI permet d'avoir des graphiques live, ce qui peut avoir son utilité.
Donc j'ai repris le code précédent, je l'ai modifié un petit peu et voilà le résultat :
<?php
$email = '*******@*******';
$passwd = '*******';
$ids = '*******';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = array('accountType' => 'GOOGLE',
'Email' => $email,
'Passwd' => $passwd,
'source'=>'CLI_GAnalytics',
'service'=>'analytics');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$hasil = curl_exec($ch);
$hasil = @split("Auth=", $hasil);
$auth = $hasil[1];
curl_close($ch);
$current_date = date('Y-m-d', time());
$ch1 = curl_init("https://www.google.com/analytics/feeds/data?ids=ga:" . $ids . "&metrics=ga:visits&dimensions=ga:browser&start-date=" . $current_date . "&end-date=" . $current_date);
$header[] = 'Authorization: GoogleLogin auth=' . $auth;
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch1, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HEADER, false);
$response = curl_exec($ch1);
curl_close($ch1);
$XML_response = @str_replace('dxp:','',$response);
$XML_object = simplexml_load_string($XML_response);
$data = '';
$label = '';
foreach($XML_object->entry as $m)
{
$tmp = @split('ga:browser=', $m->title);
if($label == "")
{
$label .= $tmp[1] . ' (' . $m->metric['value'] . ')';
$data .= $m->metric['value'];
}
else
{
$label .= '|' . $tmp[1] . ' (' . $m->metric['value'] . ')';
$data .= ',' . $m->metric['value'];
}
}
echo '
<img src="http://chart.apis.google.com/chart?
chs=400x150
&chd=t:' . $data . '
&cht=p3
&chdl=' . $label . '"
alt="Sample chart" />
';
?>
Ce qui permet d'obtenir ce genre de graphique :
|Firefox%20(9)|Opera%20(1))
|Internet%20Explorer%20(2)|LG%20(1)|Safari%20(1))
Résultat très honorable pour la très faible complexité de ce code. J'ai donc mon graphique des navigateurs sur la journée. Le nombre entre parenthèses correspond au nombre de visites avec le dit navigateur.
IV - Statistiques par pageJe voulais pouvoir voir mes statistiques par page, en administrateur seulement. C'est-à-dire avoir à côté de mes liens d'édition et pour chaque article, le nombre de fois que mon article a été vu aujourd'hui et combien il y a eu de visites uniques.
C'est maintenant chose faite, et c'est facile !
<?php
$email = '********@********';
$passwd = '********';
$ids = '********';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = array('accountType' => 'GOOGLE',
'Email' => $email,
'Passwd' => $passwd,
'source'=>'CLI_GAnalytics',
'service'=>'analytics');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$hasil = curl_exec($ch);
$hasil = @split("Auth=", $hasil);
$auth = $hasil[1];
curl_close($ch);
$uri = $_SERVER['REQUEST_URI'];
$current_date = date('Y-m-d', time());
$ch1 = curl_init("https://www.google.com/analytics/feeds/data?ids=ga:" . $ids . "&metrics=ga:pageviews&dimensions=ga:pagePath&filters=ga:pagePath%3D%3D" . $uri . "&start-date=" . $current_date . "&end-date=" . $current_date);
$header[] = 'Authorization: GoogleLogin auth=' . $auth;
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch1, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_HEADER, false);
$response = curl_exec($ch1);
curl_close($ch1);
$XML_response = @str_replace('dxp:','',$response);
$XML_object = simplexml_load_string($XML_response);
$pv = $XML_object->entry->metric['value'] ? $XML_object->entry->metric['value'] : 0;
echo 'Vue ' . $pv . ' fois aujourd\'hui.';
?>
J'ai donc mon résultat de la forme :
Vue 10 fois aujourd'hui.
Ce qu'il fallait faire pour récupérer les informations de la page courante :
$ch1 = curl_init("https://www.google.com/analytics/feeds/data?ids=ga:" . $ids . "&metrics=ga:pageviews&dimensions=ga:pagePath&filters=ga:pagePath%3D%3D" . $uri . "&start-date=" . $current_date . "&end-date=" . $current_date);
Ou plus exactement ajouter la
dimension pagePath et filtrer sur cette dimension comme ceci :
&filters=ga:pagePath%3D%3D" . $uri . "
L'URI de la page se récupère avec :
$_SERVER['REQUEST_URI']
On récupère par exemple :
/index.html.
Pour avoir la même chose avec les visites uniques, il suffit de modifier le
metrics en
uniquepageviews.
L'utilisation des filtres c'est par
ici. Tous les metrics et dimensions sont par
là.
V - Une classe PHP5Pour intégrer Google Analytics à mon système de blog je me suis constitué une petite classe PHP5. Cette classe est implémentée selon le design pattern Singleton. Le constructeur dispose des identifiants de connexion en dur mais on peut très bien utiliser des constantes.
<?php
class GAnalytics
{
private $email;
private $passwd;
private $ids;
private $auth;
private static $instance;
private function __construct()
{
$this->login('********@********', '********', '********');
}
private function __clone()
{}
public static function instance()
{
if(!isset(self::$instance))
{
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
private function login($email, $passwd, $ids)
{
$this->email = $email;
$this->passwd = $passwd;
$this->ids = $ids;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = array('accountType' => 'GOOGLE',
'Email' => $this->email,
'Passwd' => $this->passwd,
'source'=>'CLI_GAnalytics',
'service'=>'analytics');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$hasil = curl_exec($ch);
$hasil = @split("Auth=", $hasil);
curl_close($ch);
$this->auth = $hasil[1];
}
public function getDimensionByMetric($metrics, $dimensions, $date_1, $date_2 = null)
{
if(!$date_2)
$date_2 = $date_1;
$ch = curl_init("https://www.google.com/analytics/feeds/data?ids=ga:" . $this->ids . "&metrics=ga:" . $metrics . "&dimensions=ga:" . $dimensions . "&start-date=" . $date_1 . "&end-date=" . $date_2);
$header[] = 'Authorization: GoogleLogin auth=' . $this->auth;
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
$infos = curl_getinfo($ch);
curl_close($ch);
if($infos['http_code'] != 200)
throw new Exception("[EXCEPTION] (" . $info['http_code'] . ") " . $response);
$XML_response = @str_replace('dxp:','',$response);
$XML_object = simplexml_load_string($XML_response);
$data = '';
$label = '';
foreach($XML_object->entry as $m)
{
$tmp = @split('ga:' . $dimensions . '=', $m->title);
if($label == "")
{
$label .= $tmp[1] . ' (' . $m->metric['value'] . ')';
$data .= $m->metric['value'];
}
else
{
$label .= '|' . $tmp[1] . ' (' . $m->metric['value'] . ')';
$data .= ',' . $m->metric['value'];
}
}
return array('label' => $label, 'data' => $data);
}
public function getMetric($metric, $date_1, $date_2 = null)
{
if(!$date_2)
$date_2 = $date_1;
$ch = curl_init("https://www.google.com/analytics/feeds/data?ids=ga:" . $this->ids . "&metrics=ga:" . $metric . "&start-date=" . $date_1 . "&end-date=" . $date_2);
$header[] = 'Authorization: GoogleLogin auth=' . $this->auth;
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
$infos = curl_getinfo($ch);
curl_close($ch);
if($infos['http_code'] != 200)
throw new Exception("[EXCEPTION] (" . $info['http_code'] . ") " . $response);
$XML_response = @str_replace('dxp:','',$response);
$XML_object = simplexml_load_string($XML_response);
return $XML_object->entry->metric['value'] ? $XML_object->entry->metric['value'] : 0;
}
public function getMetricURI($metric, $uri, $date_1, $date_2 = null)
{
if(!$date_2)
$date_2 = $date_1;
$ch = curl_init("https://www.google.com/analytics/feeds/data?ids=ga:" . $this->ids . "&metrics=ga:" . $metric . "&dimensions=ga:pagePath&filters=ga:pagePath%3D%3D" . $uri . "&start-date=" . $date_1 . "&end-date=" . $date_2);
$header[] = 'Authorization: GoogleLogin auth=' . $this->auth;
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
$response = curl_exec($ch);
$infos = curl_getinfo($ch);
curl_close($ch);
if($infos['http_code'] != 200)
throw new Exception("[EXCEPTION] (" . $info['http_code'] . ") " . $response);
$XML_response = @str_replace('dxp:','',$response);
$XML_object = simplexml_load_string($XML_response);
return $XML_object->entry->metric['value'] ? $XML_object->entry->metric['value'] : 0;
}
}
?>
Pour récupérer une instance de cette classe on appelle la méthode statique instance() :
$ga = GAnalytics::instance();
Ensuite on peut utiliser les méthodes comme dans l'exemple ci-dessous :
$navigateurs = $ga->getDimensionByMetric('visits', 'browser', date('Y-m-d', time()));
$countries = $ga->getDimensionByMetric('visits', 'country', date('Y-m-d', time()));
$visits = $ga->getMetric('visits', date('Y-m-d', time()));
$unique_visits = $ga->getMetric('visitors', date('Y-m-d', time()));
$page_views = $ga->getMetric('pageviews', date('Y-m-d', time()));
*
getDimensionByMetric() permet d'effectuer une requête avec un metric et une dimension.
*
getMetric() permet d'effectuer une requête avec un metric uniquement.
*
getMetricURI() permet d'effectuer une requête avec un metric par rapport à une URI précise.
Les résultats sont visibles à cette adresse :
http://www.willdurand.fr/posts/22/api-google-analytics-une-classe-php5-et-des-resultats-d-integration.htmlSources : http://google-data-api.blogspot.com/2008/05/clientlogin-with-php-curl.html pour l'utilisation de Curl, et l'API Google pour le reste.
http://www.willdurand.fr/posts/20/api-google-analytics-decouverte-par-l-exemple.htmlhttp://www.willdurand.fr/posts/21/api-google-analytics-round-2-graphiques-et-statistiques-par-page.htmlhttp://www.willdurand.fr/posts/22/api-google-analytics-une-classe-php5-et-des-resultats-d-integration.htmlWilliam DURAND.