API de Google Analytics o una excepción "invalid_grant" con cuenta de servicio. Mismo código en dos servidores. Solo una trabaja
Estoy consultando la API de Analytics a través deCuenta de servicio.
He escrito el código en el servidor dev y funciona sin problemas. Cuando ejecuta el mismo código en el servidor de producción, lanza esto:
Google_AuthException: error al actualizar el token OAuth2, mensaje: '{"error": "invalid_grant"}'
He intentado crear otra cuenta de servicio, y el comportamiento es el mismo.
El borrador oAuth IETF (http://tools.ietf.org/html/draft-ietf-oauth-v2-31) dice esto sobre el error:
invalid_grant
The provided authorization grant (e.g. authorization
code, resource owner credentials) or refresh token is
invalid, expired, revoked, does not match the redirection
URI used in the authorization request, or was issued to
another client.
Aquí está el código que he escrito:
$GA_CLIENT_ID = 'XX.apps.googleusercontent.com';
$GA_APP_EMAIL = '[email protected]';
$GA_APP_NAME = 'XX';
$GA_KEY_FILE = 'XX';
// create client object and set app name
$client = new Google_Client();
$client->setApplicationName($GA_APP_NAME); // name of your app
// set assertion credentials
$client->setAssertionCredentials(
new Google_AssertionCredentials(
$GA_APP_EMAIL, // email you added to GA
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($GA_KEY_FILE) // keyfile you downloaded
));
// other settings
$client->setClientId($GA_CLIENT_ID); // from API console
$client->setAccessType('offline_access'); // this may be unnecessary?
// create service and get data
$service = new Google_AnalyticsService($client);
$result = $service->data_ga->get($ids, $startDate, $endDate, $metrics, $optParams);
return $result;
También he intentado una solución sugerida aquí (https://groups.google.com/forum/?fromgroups#!topic/gs-discussion/3y_2XVE2q7U%5B1-25%5D) usando authenticatedRequest () en lugar de Google_AnalyticsService:
$req = new Google_HttpRequest($apiUrl);
$resp = $client::getIo()->authenticatedRequest($req);
$result = json_decode($resp->getResponseBody(), true);
Esta alternativa también funciona en el servidor dev, pero no en el servidor de producción.
Estoy totalmente despistado en este caso. ¿Alguien lo ha visto / arreglado?
¡Gracias!