Google Apps Script で Google Ad Manager のレポートAPIをたたく


ググってもこれだという記事がみつからず、同じように困っている人たちのお役に立てればとメモです。

目的

Google Apps Scritp で Google Ad Manager のレポートAPIをたたいて業務の効率化を図る

事前準備

サービスアカウントを発行

APIのリクエストはOAuth2で認証が必要であるため
GCP Console にてサービスアカウントを発行し、鍵を追加してJSONファイルを取得

「サービスアカウントユーザーを追加」で登録するメールアドレスはサービスアカウント作成時に発行されたメールアドレスです。不明な場合は取得したJSONのclient_emailの値になります。

Google Apps Scritp にライブラリ oauth2 をインストール

処理の流れ

  1. 保存済みのレポートクエリを取得
    ReportService.getSavedQueriesByStatement
  2. ジョブ作成
    ReportService.runReportJob
  3. ジョブの状態を取得
    ReportService.getReportJob
  4. レポートのダウンロード用URLを取得
    ReportService.getReportDownloadURL
  5. ダウンロードする

保存済みのレポートクエリを取得の詳細

下記コードを実行してもデータは取得できなかった。。
ただレスポンスを確認してもエラーではないという(ノД`)シクシク

でも大丈夫!!
詳細はコード記載の後に記載するので設定を忘れずに!!

function getSavedQueries() {
  const keyJson = {
    "type": "service_account",
    "project_id": "****",
    "private_key_id": "****",
    "private_key": "-----BEGIN PRIVATE KEY----- **** -----END PRIVATE KEY-----\n",
    "client_email": "****@****.iam.gserviceaccount.com",
    "client_id": "****",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://oauth2.googleapis.com/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/****"
  };

  const soapXml = '<?xml version=\"1.0\" encoding=\"UTF-8\"?>' +
          '<soapenv:Envelope ' +
            'xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" ' +
            'xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ' +
            'xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">' +
            '<soapenv:Header>' +
              '<ns1:RequestHeader ' + 
                'soapenv:actor=\"http://schemas.xmlsoap.org/soap/actor/next\" ' +
                'soapenv:mustUnderstand=\"0\" ' +
                'xmlns:ns1=\"https://www.google.com/apis/ads/publisher/v202105\">' +
                '<ns1:networkCode>' + {管理者 -> 全般設定 -> ネットワーク設定 タブのネットワークコード} + '</ns1:networkCode>' + 
                '<ns1:applicationName>' + keyJson.project_id + '</ns1:applicationName>' + 
              '</ns1:RequestHeader>' +  
            '</soapenv:Header>' +
            '<soapenv:Body>' + 
              '<getSavedQueriesByStatement xmlns=\"https://www.google.com/apis/ads/publisher/v202105\">' + 
                '<filterStatement>' + 
                  '<query>LIMIT 10</query>' + // 適宜変更してください
                '</filterStatement>' + 
              '</getSavedQueriesByStatement>' + 
            '</soapenv:Body>' + 
          '</soapenv:Envelope>';

  const service = OAuth2.createService('report')
      .setAuthorizationBaseUrl(keyJson.auth_uri)
      .setTokenUrl(keyJson.token_uri)
      .setClientId(keyJson.client_id)
      .setPrivateKey(keyJson.private_key)
      .setPropertyStore(PropertiesService.getScriptProperties())
      .setScope([
        'https://www.googleapis.com/auth/dfp',
        'https://www.googleapis.com/auth/analytics.readonly'
      ]);

    if (!service.hasAccess()) {          
      Logger.log(service.getLastError());
      return;
    }

    const url = 'https://ads.google.com/apis/ads/publisher/v202105/ReportService?wsdl';
    const response = UrlFetchApp.fetch(url, {
      headers: {
        Authorization: 'Bearer ' + service.getAccessToken()
      },
      method: 'post',
      contentType: 'text/xml; charset=utf-8',
      payload: soapXml,
      muteHttpExceptions: true
    });
    Logger.log(response);
}

追加の設定

「サービスアカウントユーザーを追加」で選択した「役割」次第では追加設定の必要はないかもしれないが、私は役割を「レポートの作成と表示」としたため、レポート詳細の編集者にサービスアカウント作成時に発行されたメールアドレスを登録することで上記スクリプト実行でデータの取得ができるようになった。

他処理

まだ作ってないのでいつか...www

参考