【发布时间】:2017-11-09 18:33:50
【问题描述】:
这是我从中获取 GA 数据的代码,但它总是在浏览器中询问帐户选择。如何在 PHP 脚本中定义默认帐户。
我错过了什么?
这等于 GA 文档中的 index.php,但我使用 Symfony 框架并决定更改此路线
/**
* @Route("/get-google-analytics-data")
*/
public function getGoogleAnalyticsData () {
$ga = $this->get('google_analytics_service');
$client = new \Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Create an authorized analytics service object.
$analytics = new \Google_Service_AnalyticsReporting($client);
// Call the Analytics Reporting API V4.
$response = $ga->getReport($analytics);
// Print the response.
return new \Symfony\Component\HttpFoundation\Response($ga->printResults($response));
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
return $this->redirect($redirect_uri);
}
这等于 GA 文档中的 oauth2callback.php。
}
/**
* @Route("/oauth2callback", name="gaOA2callback")
*/
public function gaOA2callback () {
$client = new \Google_Client();
$client->setAuthConfig(__DIR__ .'/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER["HTTP_HOST"] . '/oauth2callback');
$client->addScope(\Google_Service_Analytics::ANALYTICS_READONLY);
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
return $this->redirect($auth_url);
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/get-google-analytics-data';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
return $this->redirect($redirect_uri);
}
}
【问题讨论】:
标签: php symfony oauth-2.0 google-analytics-api