【GAS】Yahooディスプレイ広告の運用データをスプレッドシートに自動取得する方法(v19対応)
Yahoo!ディスプレイ広告(YDA)のインプレッション・クリック数・コンバージョン数などの運用データを、GAS(Google Apps Script)を使ってスプレッドシートに自動取得する方法を解説します。v19 API対応の最新手順です。
他の広告媒体はこちら
Yahoo広告アプリケーションの登録
Yahoo!広告 API管理ツールにアクセスして、広告運用を行なっているYahoo!ビジネスIDでログインします。
アプリケーションを登録します。登録画面で必要事項を入力して確認を選択します。リダイレクトURIには「oob」を入力してください。
登録が完了したらクライアントIDとクライアントシークレットをメモします。

認証コードの取得
以下のURLを作成してブラウザでアクセスします。
https://biz-oauth.yahoo.co.jp/oauth/v1/authorize?response_type=code
&client_id=CLIENT_ID
&redirect_uri=REDIRECT_URI
&scope=yahooads
&state=任意の文字列
アクセス許可の承認をすると認可コードが表示されます。

アクセストークン・リフレッシュトークンの取得
ターミナルから以下のコマンドを実行します。
curl -X GET \
https://biz-oauth.yahoo.co.jp/oauth/v1/token?grant_type=authorization_code
&client_id=CLIENT_ID
&client_secret=CLIENT_SECRET
&redirect_uri=REDIRECT_URI
&code=AUTH_CODE
アクセストークンとリフレッシュトークンが返されます。アクセストークンは1時間で失効するため、リフレッシュトークンを使って都度新しいアクセストークンを発行する必要があります。
スプレッドシートとGASの作成
スプレッドシートを作成し「db」シートを作成します。「ツール」→「スクリプト」からスクリプトを作成し、以下のコードを記述します。
/**
* Yahoo!広告 ディスプレイ広告 API v19 対応版
* MCCアカウント構成に対応(x-z-base-account-id に MCC ID を指定)
*/
function main() {
const ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('db');
if (!ss) throw new Error("シート 'db' が見つかりません。");
const clientId = "****";
const clientSecret = "****";
const refreshToken = "****";
const mccAccountId = "****"; // MCCアカウントID
const targetAccountId = "****"; // データを取得したい広告アカウントID
// 1. アクセストークン取得
const accessToken = yahooAdLogin(clientId, clientSecret, refreshToken);
// 2. レポート作成ジョブの作成
const createReportResponse = yahooAdCreateDisplayReport(accessToken, mccAccountId, targetAccountId);
const reportJobId = createReportResponse.rval.values[0].reportDefinition.reportJobId;
console.log(`Job Created: ${reportJobId}`);
// 3. レポート完了待機
let isCompleted = false;
for (let i = 0; i < 12; i++) {
isCompleted = yahooAdCheckDisplayReport(accessToken, mccAccountId, targetAccountId, reportJobId);
if (isCompleted) break;
console.log("レポート作成中... (10秒待機)");
Utilities.sleep(10000);
}
if (!isCompleted) throw new Error("レポート作成がタイムアウトしました。");
// 4. レポート取得と書き込み
const reportData = yahooAdDownloadDisplayReport(accessToken, mccAccountId, targetAccountId, reportJobId);
if (reportData && reportData.length > 0) {
const lastRow = ss.getRange("B:B").getValues().filter(String).length;
const targetRow = lastRow + 1;
ss.getRange(targetRow, 1, reportData.length, reportData[0].length).setValues(reportData);
console.log(`${reportData.length}件のデータを書き込みました。`);
} else {
console.log("取得できるデータがありませんでした。");
}
}
function yahooAdLogin(clientId, clientSecret, refreshToken) {
const url = 'https://biz-oauth.yahoo.co.jp/oauth/v1/token';
const params = {
method: 'post',
payload: {
grant_type: 'refresh_token',
client_id: clientId,
client_secret: clientSecret,
refresh_token: refreshToken,
}
};
const response = JSON.parse(UrlFetchApp.fetch(url, params).getContentText());
return response.access_token;
}







ディスカッション
コメント一覧
まだ、コメントがありません