PHP の回答を追加しています。調整したり、garb / ruby コードに変換したりできる場合があります。
これで、サービス アカウントで Analytics を使用できるようになります。実際には、アクセス トークンの代わりに秘密鍵を使用する必要があります。
API コンソールでアプリを作成する
基本的には、Google API コンソールに移動してアプリを作成します。
[サービス] タブで Google アナリティクスを有効にします。
[API アクセス] タブで、新しい OAuth ID を作成し (別のクライアント ID を作成... ボタン)、サービス アカウントを選択して秘密鍵をダウンロードします (新しいキーを生成... リンク)。後でキーを Web サーバーにアップロードする必要があります。
[API アクセス] ページの [サービス アカウント] セクションで、メール アドレス (@developer.gserviceaccount.com) をコピーし、このメール アドレスを持つ新しいユーザーを Google アナリティクス プロファイルに追加します。これを行わないと、いくつかの素敵なエラーが発生します
コード
SVN から最新の Google PHP クライアントをダウンロードします (コマンド ラインからsvn checkout http://google-api-php-client.googlecode.com/svn/trunk/ google-api-php-client-read-only
)。
コードで Analytics API にアクセスできるようになりました。
require_once 'Google_Client.php';
require_once 'contrib/Google_AnalyticsService.php';
$keyfile = 'dsdfdss0sdfsdsdfsdf44923dfs9023-privatekey.p12';
// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('Your product name');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'11122233344@developer.gserviceaccount.com',
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyfile)
)
);
// Get this from the Google Console, API Access page
$client->setClientId('11122233344.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
// We have finished setting up the connection,
// now get some data and output the number of visits this week.
// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'ga:1234';
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}