Jiniya

WEB

구글 API로 Analytics정보를 이용해보자! (Google Analytics API PHP)

 

http://blog.upgle.com/upgletyle/8381


1. 기본설정

기본 API 사용을 위해 필요한 과정은 다음과 같다.

 

  1. 먼저 Google APIs Console에 가서 새로은 프로젝트를 만든다
    https://code.google.com/apis/console/
  2. 새 프로젝트를 만들었다면 Services메뉴에 가서 Analytics API 서비스를 사용함으로 변경한다.
  3. API Access 메뉴에 가서 Create an Oauth 2.0 Client-ID... 버튼을 클릭한다.
  4. Product name, Home Page URL 등 정보를 입력한다.
  5. Application type은 web application으로 선택한다.

*Service accounts 부분은 Open ssl이 필요한 부분으로 생략합니다. 해당 내용이 궁금하시면 Github를 접속하시기 바랍니다.

2. 다운로드

위의 API등록 과정을 마쳤으면 아래의 주소에가서 GoogleAnalyticsAPI.class.php 파일을 다운받는다.

 

https://github.com/wanze/Google-Analytics-API-PHP 


3. API 권한 부분 설정하기

3-1. Web applications 일때 (요청부분)

 

1
2
3
4
5
6
7
8
9
include('GoogleAnalyticsAPI.class.php');
 
$ga = new GoogleAnalyticsAPI();
$ga->auth->setClientId('your_client_id'); // From the APIs console
$ga->auth->setClientSecret('your_client_secret'); // From the APIs console
$ga->auth->setRedirectUri('redirect_uri'); // Url to your app, must match one in the APIs console
 
// Get the Auth-Url
$url = $ga->auth->buildAuthUrl();

 

3-2. Redirect 부분 :: Google 서버는 요청된 redirect_url에 Code를 보내주며 redirect받은 페이지에서는 해당 코드를 토큰으로 만들어 저장하게 된다. 토큰의 유효시간은 3600초로 1시간동안 유지되며 해당 시간이 지나면 $ga->auth->refreshAccessToken($refreshToken); 로 다시 토큰을 받아야한다. 토큰을 받아온 후에는 Session이나 Database에 저장하여 해당 정보를 유지시켜주는것이 좋다.(불필요한 토큰 재요청 방지)

 

1
2
3
4
5
6
7
8
9
10
11
12
$code = $_GET['code'];
$auth = $ga->auth->getAccessToken($code);
 
// Try to get the AccessToken
if ($auth['http_code'] == 200) {
    $accessToken = $auth['access_token'];
    $refreshToken = $auth['refresh_token'];
    $tokenExpires = $auth['expires_in'];
    $tokenCreated = time();
} else {
    // error...
}

 

3-3. 토큰을 재발급 받는 예제. 토큰이 만료되었을때 재발급을 받도록 요청한다.

 

1
2
3
4
5
// Check if the accessToken is expired
if ((time() - $tokenCreated) >= $tokenExpires) {
    $auth = $ga->auth->refreshAccessToken($refreshToken);
    // Get the accessToken as above and save it into the Database / Session
}

 

4. Analytics API를 통해 계정 찾기

구글 API를 요청한 계정에는 하나의 사이트만 연결하여 사용하시는분도 계실 수 있고 두세게에서 많으면 수십개의 사이트를 연결해서 사용하는 유저도 있기때문에 Analytics 구글계정에 연동된 정보를 얻어와야한다. 여기서 필요한 사이트의 ID를 메모해두도록 한다. (ga:000000 형식)

 

1
2
3
4
5
6
7
8
9
10
11
// Set the accessToken and Account-Id
$ga->setAccessToken($accessToken);
$profiles = $ga->getProfiles();
$accounts = array();
foreach ($profiles['items'] as $item) {
    $id = "ga:{$item['id']}";
    $name = $item['name'];
    $accounts[$id] = $name;
}
// Print out the Accounts with Id => Name, the array-key of one Account is the ID you have to remember
print_r($accounts);

 

 

5. 필요한 정보 API QUERY를 날려 얻어오기

구글에서 제공하는 Metrics & Dimensions 레퍼런스를 통해 필요한 정보를 API를 통해 Query를 날려 정보를 얻어올 수 있다. Query뿐만 아니라 Analytics Class에서 제공하는 함수를 통해서도 데이터에 쉽게 접근할수가 있다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Set the accessToken and Account-Id
$ga->setAccessToken($accessToken);
$ga->setAccountId('ga:xxxxxxx');
 
// Set the default params. For example the start/end dates and max-results
$defaults = array(
    'start-date' => date('Y-m-d', strtotime('-1 month')),
    'end-date' => date('Y-m-d'),
);
$ga->setDefaultQueryParams($defaults);
 
// Example1: Get visits by date
$params = array(
    'metrics' => 'ga:visits',
    'dimensions' => 'ga:date',
);
$visits = $ga->query($params);
 
// Example2: Get visits by country
$params = array(
    'metrics' => 'ga:visits',
    'dimensions' => 'ga:country',
    'sort' => '-ga:visits',
    'max-results' => 30,
    'start-date' => '2013-01-01' //Overwrite this from the defaultQueryParams
);
$visitsByCountry = $ga->query($params);
 
// Example3: Same data as Example1 but with the built in method:
$visits = $ga->getVisitsByDate();
 
// Example4: Get visits by Operating Systems and return max. 100 results
$visitsByOs = $ga->getVisitsBySystemOs(array('max-results' => 100));
 
// Example5: Get referral traffic
$referralTraffic = $ga->getReferralTraffic();
 
// Example6: Get visits by languages
$visitsByLanguages = $ga->getVisitsByLanguages();

 

Metrics & Dimensions Reference:

https://developers.google.com/analytics/devguides/reporting/core/dimsmets 


 

Google Analytics Query Explorer for testing queries and results:

(쿼리를 테스트해볼 수 있는 좋은 사이트가 여기 있네요~)

 

http://ga-dev-tools.appspot.com/explorer/