Google Analytics API Reference 에 따르면 OAuth뿐만 아니라 액세스 토큰을 사용하여 페이지의 통계에 액세스 할 수 있습니다. OAuth를 사용하는 것은 꽤 복잡하거나 적어도 PHP에서 그런 것처럼 보입니다. 그러나 문서에 따르면 access_code를 get 매개 변수로 사용할 수도 있습니다.
Google 개발자 콘솔 에서 access_token을 얻기 위해 여러 가지 방법을 시도 했지만 둘 다 작동하지 않고 항상 다음 오류가 반환됩니다.
{"error":{"errors":[{"domain":"global","reason":"required","message":"Login Required","locationType":"header","location":"Authorization"}],"code":401,"message":"Login Required"}}
따라서 Google 애널리틱스 페이지 속성에 만료되지 않는 API 액세스 코드를 얻는 방법이 궁금합니다. 가능하다면?
먼저 Google 개발자 콘솔 에 애플리케이션을 등록해야합니다 . Oauth2를 사용하여 액세스 토큰을 얻는 문제입니다. 먼저 사용자에게 데이터 액세스 권한을 요청하여 액세스 토큰을 얻습니다. 권한이 부여되면 액세스 토큰을 얻는 데 사용할 수있는 새로 고침 토큰을 받게됩니다.
다음 예제는 GitHub 에있는 Google PHP 클라이언트 라이브러리를 사용합니다 . 코드는 내 Google Oauth2 PHP 튜토리얼 튜토리얼 에서 복사되었습니다 .
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("{devkey}");
$client->setClientId('{clientid}.apps.googleusercontent.com');
$client->setClientSecret('{clientsecret}');
$client->setRedirectUri('http://www.daimto.com/Tutorials/PHP/Oauth2.php');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Analytics($client);
// request user accounts
$accounts = $service->management_accountSummaries->listManagementAccountSummaries();
foreach ($accounts->getItems() as $item) {
echo "Account: ",$item['name'], " " , $item['id'], "<br /> \n";
foreach($item->getWebProperties() as $wp) {
echo ' WebProperty: ' ,$wp['name'], " " , $wp['id'], "<br /> \n";
$views = $wp->getProfiles();
if (!is_null($views)) {
foreach($wp->getProfiles() as $view) {
// echo ' View: ' ,$view['name'], " " , $view['id'], "<br /> \n";
}
}
}
} // closes account summaries
}
print "<br><br><br>";
print "Access from google: " . $_SESSION['token'];
?>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다