LoginSignup
22
23

More than 5 years have passed since last update.

[PHP]Google Analytics API v3.0 使い方〜認証編

Posted at

今回は実際にライブラリを読み込み、Client ID等の情報を使ってOAuth2.0認証を行います。

Client IDの作成方法は[PHP]Google Analytics API v3.0 使い方〜前準備編を御覧ください。

記載したソースは要所のみ抜粋していますが、見た目を整えるためBootstrapを使用しています。

■ ライブラリをダウンロードする
https://code.google.com/p/google-api-php-client/
※今回使用しているバージョンは0.6.2です。

ダウンロードしたら、解凍して適当なディレクトリに配置します。

今回はこんな感じ
/www
 /lib
  /google-api-php-client・・・先ほどダウンロードしてきたライブラリ
 signin.php
 index.php

■ 認証画面(signin.php)を作成する
uploading Bootstrap, from Twitter.png...

signin.php
<?php
require('lib/google-api-php-client/src/Google_Client.php');
require('lib/google-api-php-client/src/contrib/Google_AnalyticsService.php');

session_start();
$client = new Google_Client();

// クライアントID
$client->setClientId('1234567890abcdefg.apps.googleusercontent.com');
// クライアントSecret
$client->setClientSecret('ABCDEFG');
// リダイレクトURL
$client->setRedirectUri('http://example.com/index.php');

// 使用するサービスを作成
$service = new Google_AnalyticsService($client);

// 認証用URLを作成
$authURL = $client->createAuthUrl();

?>
<div>
    <h1>Googleアカウントの認証</h1>
    <p>APIを使用するために、Googleアカウントを認証してください</p>
    <p><a href="<?php echo $authURL ?>">Signin</a></p>
</div>

SigninをクリックするとGoogleアカウントの認証画面に遷移します。
uploading 許可のリクエスト.png...

Google Analyticsにログイン出来るアカウントで認証を行うと、設定したURLにリダイレクトされます。

uploading Bootstrap, from Twitter (1).png...

index.php
<div>
  <h1>認証成功</h1>
</div>
22
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
23