I'm developing module for obtaining additional data from google analytics account. To get this data Google requires access_token. This is what I've managed so far
if (isset($_GET['code'])) {
// try to get an access token
$code = $_GET['code'];
$url = 'https://accounts.google.com/o/oauth2/token';
$params = array(
"code" => $code,
"client_id" => "559825975819-881lg83vs8feo70v5unqa8kfoijuvfnn.apps.googleusercontent.com",
"client_secret" => "vj4UNNItAJocX4RkNaD_3DQ4",
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"access_type" => "offline",
"grant_type" => "authorization_code"
);
$ch = curl_init();
curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$data = (json_decode($output, true));
$access_token_var = $data['access_token'];
echo $access_token_var;
} else {
$url = "https://accounts.google.com/o/oauth2/auth";
$params = array(
"response_type" => "code",
"client_id" => "559825975819-881lg83vs8feo70v5unqa8kfoijuvfnn.apps.googleusercontent.com",
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"scope" => "https://www.googleapis.com/auth/analytics",
"access_type" => "offline",
"approval_prompt" => "force"
);
$request_to = $url . '?' . http_build_query($params);
header("Location: " . $request_to);
}
And I'm getting access_token, it is echoing in needed variable. But I want to obtain analytics additional data in background process (for example, while client making order and clicking order button), but everytime I need new access_token, i need to authorize with my google account, and therefore, every client on web site needs to do this, despite the fact, that I set up "access_type" => "offline". What's wrong? Or is it something wrong with my API app?