情報科学屋さんを目指す人のメモ

方法・手順・解説を書き残すブログ。私と同じことを繰り返さずに済むように。

AdSense Management APIを使用したサービス作成時のメモ(WordPressプラグイン作成)

AdSense (3) AdSense Management API (1) WordPress (80) WordPressプラグイン (26) did2 A/B Testing (1)

AdSense Management APIを使用して、AdSense連携するWordPressプラグインを作成した時の作業メモを公開します。生メモで整理されていませんが、Web上の情報が少ないので、役に立つ場面があるかと思います。リンク先の完成品(WordPressプラグイン)のソースコードも参考にしてください。

作成したWordPressプラグイン

AdSenseの収益に応じて、WordPressテーマを自動的に切り替えます。

詳細:「AdSenseの収益最大化を支援するWordPressプラグインを開発しました

最終的には↑のソースコードを読むことがお勧めです。

ただ、Google Developer Consoleまわりの設定はさすがにソースコードからはわからないので、このエントリを参考にしてください。

とはいうものの、失敗した時の設定も混ざっているかもしれないので、そのつもりでお願いします。

今更下手に編集すると、もともとの情報を損なうだけな気がするので、生メモのまま設置します。

重要資料

Google Accounts Authentication and Authorization Using OAuth 2.0 for Web Server Applications
https://developers.google.com/accounts/docs/OAuth2WebServer

https://developers.google.com/accounts/docs/OAuth2InstalledApp?hl=ja
こっちだった。
これが、Google AdSense Dashboard for WPの動作と一緒。

「When creating a client ID, you specify that your application is an Installed application」
なので、「クライアントIDを作成」では「Installed aapplication」を選択して、「インストールされているアプリケーションの種類」では「その他」を選択。

「In this context, the client secret is obviously not treated as a secret.」

AdSense Management API スタートガイド
https://developers.google.com/adsense/management/getting_started

参考になるプラグイン

https://deconf.com/earnings-dashboard-google-adsense-wordpress/

プラグインのOAuth用URL例

https://accounts.google.com/o/oauth2/auth
?scope=https://www.googleapis.com/auth/adsense.readonly
&response_type=code
&access_type=offline
&redirect_uri=urn:ietf:wg:oauth:2.0:oob
&approval_prompt=auto
&client_id=123456789012.apps.googleusercontent.com
&hl=ja
&from_login=1
&as=1234567890abcdef
&pli=1
&authuser=0

リダイレクトURLを作る

https://deconf.com/earnings-dashboard-google-adsense-wordpress/

プラグインのOAuth用URL例

https://accounts.google.com/o/oauth2/auth
?scope=https://www.googleapis.com/auth/adsense.readonly
&response_type=code
&access_type=offline
&redirect_uri=urn:ietf:wg:oauth:2.0:oob
&approval_prompt=auto
&client_id=
123456789012-1234567890abcdefghijklmnopqrstuv.apps.googleusercontent.com
&hl=ja
&from_login=1
&as=
&pli=1
&authuser=0

「did2 AB Testing が次の許可をリクエストしています:」

Google Developers Console登録

https://console.developers.google.com/project

設定を変更する

左のAccount Settingsから、Languageを「日本語」に変更。これで、日本語化される。

プロジェクトを作成する

プロジェクト(ここでは、AdSense連携をしたいアプリケーションのこと)を作成して、登録する。

「プロジェクトを作成」から、「プロジェクト名」と「プロジェクト ID」を設定する。

ここでは「did2 AB Testing」と「did2-ab-testing」を指定。

作成には少し時間がかかるので待つ。すると、プロジェクトダッシュボードが表示される。

APIと認証にある「認証情報」で「新しいクライアントIDを作成」を実行。

「The consent screen requires a product name.」と表示されてしまったので、「Configure consent screen」ボタンから同意画面の設定へ。

使うべきは「AdSense Management API」 https://developers.google.com/adsense/management/?csw=1 AdSense Host API ではないので注意。

https://developers.google.com/api-client-library/php/guide/aaa_apikeys の「Acquiring an API key」

Google Developers Console のプロジェクトの「APIと認証」→「API」の「AdSense Management API」の右の「OFF」をクリックする。

「AdSense Management API を有効にする際にエラーが発生しました 表示しない」と表示されてしまう(Error Enabling Adsense Management API)。 AdBlockが原因だった

「AdSense Management APIの有効化」が表示されたら 「AdSense Management API の利用規約とGoogle APIsの利用規約を読んだうえで内容に同意します」にチェックを入れて「同意する」。

「有効なAPI」に「AdSense Management API」が追加される。

「APIと認証>認証情報>公開APIへのアクセス>新しいキーを作成」をクリック。

「新しいキーの作成」で「Google Developers Console に表示される API では、固有のプロジェクト ID をリクエストに含める必要があります。 これによりリクエストを特定のプロジェクトに関連付けることができ、トラフィックの監視、割り当ての実施、 請求の処理が可能になります。」が表示されるので、今回はクライアント側で動作するので「ブラウザキー」をクリック。

「ブラウザキーの作成と許可対象リファラーの設定」が出たら、このキーはクライアントのアプリケーションでデプロイできます。 API リクエストはクライアントのブラウザから直接 Google に送信されます。 詳細

下の HTTP リファラー(ウェブサイト)からのリクエストを受け入れるURL またはパターンを 1 行に 1 つずつ入力してください。例: *.example.com/* と表示されるのですが、特に限定したくない(するべきだけど)。ただ、ここではとりあえず「*.did2memo.net/*」にしておきました。そして、「作成」をクリックします。

APIキーが表示されるので、それをコピーします。

エラー対策

$adSense->reports->generate で exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/adsense/v1.4/reports?startDate=2015-01-01&endDate=2015-01-31&metric=EARNINGS&dimension=DATE&sort=DATE&useTimezoneReporting=true&key=xxxxxxxxxxxxxxxxxxxxxxxxx: (403) There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.' が帰ってきてしまったので、許可対象リファラを「did2memo.net/*」に変更。

参考(ちょっと違った、的なのも含む)

利用時メモ

(ここから別のメモを結合しておきます)

AdSense Management APIをPHPから使用して、データを取得する方法についてのメモを載せておきます。

accountId

「$accounts = $adsense->accounts->listAccounts();」で取得可能。

object(Google_Service_AdSense_Accounts)#1234 (9) {
["collection_key":protected]=> string(5) "items"
["etag"]=> string(52) ""xxxxx""
["itemsType":protected]=> string(30) "Google_Service_AdSense_Account"
["itemsDataType":protected]=> string(5) "array"
["kind"]=> string(16) "adsense#accounts"
["nextPageToken"]=> NULL
["internal_gapi_mappings":protected]=> array(0) { }
["modelData":protected]=> array(1) {
	["items"]=> array(1) {
		[0]=> array(5) {
			["kind"]=> string(15) "adsense#account"
			["id"]=> string(20) "pub-xxxxx"
			["name"]=> string(12) "情報太郎"
			["premium"]=> bool(false)
			["timezone"]=> string(10) "Asia/Tokyo"
		}
	}
}
["processed":protected]=> array(0) { }
}

var_dumpで確認してみると、取得できるデータは上記のような構造なので、accountIdは「$accountId = $accounts['modelData']['items'][0]['id']」または「$accounts['items'][0]['id']」で取得できました。

adClientId

adClientIdは、「$adClients = $adSense->accounts_adclients->listAccountsAdclients($accountId)」で一覧取得できるので、これまた「$adClients['items'][0]['id']」で取得できるのですが、これで取得できるのは「ca-mb-pub」で始まるIDでした。

このIDを使ってAPIを使用しても、この後「Accounts.customchannels: list(phpクライアントでは$adSense->accounts_adclients->listAccountsAdclients($accountId))」を使用したところ、取得できたカスタムチャネルの一覧は空でした。

試しに「ca-pub」にIDを変更してみると、うまく情報が取得できました。

ということなので、どうやら標準的には、「ca-pub」でよいようです。この「ca-pub-xxxx」というバージョンのID(xxxxは、accountIdのpub以降と同じ)は、「$adClients['items'][1]['id']」で、[2]にすると、「partner-pub-xxxx」でした。人によって異なるかもしれませんが、調べようがないので、自分の場合の話を載せておきます。

カスタムチャネル一覧を取得する

カスタムチャネルの一覧をAdSense Management APIで取得するには、

  • 「$customChannels = $adSense->accounts_customchannels->listAccountsCustomchannels($accountId, $adClientId);」
  • 「$customChannels = $adSense->customchannels->listCustomchannels($adClientId);」

のどちらでも良さそうです。

コメント(0)

新しいコメントを投稿