Google Apps Script에서 Google Ad Manager 보고 API를 두드리기

구구도 이것이라고 하는 기사를 찾지 않고, 똑같이 곤란하고 있는 사람들의 도움이 되면과 메모입니다.

목적



Google Apps Scritp에서 Google Ad Manager 보고서 API를 사용하여 비즈니스 효율성을 높이십시오.

사전 준비



서비스 계정 발급



API 요청은 OAuth2에서 인증이 필요하기 때문에
GCP Console 에서 서비스 계정을 발행하고 키를 추가하여 JSON 파일 가져 오기

Google Ad Manager API 활성화 및 서비스 계정 추가



"서비스 계정 사용자 추가"에서 등록하는 이메일 주소는 서비스 계정을 만들 때 발행된 이메일 주소입니다. 확실하지 않으면 검색된 JSON의 client_email 값입니다.


Google Apps Scritp에 라이브러리 oauth2 설치



처리 흐름



  • 저장된 보고서 쿼리 가져오기
    ReportService.getSavedQueriesByStatement
  • 작업 만들기
    ReportService.runReportJob
  • 작업 상태 얻기
    ReportService.getReportJob
  • 보고서 다운로드 URL 받기
    ReportService.getReportDownloadURL
  • 다운로드

  • 저장된 보고서 검색어 검색에 대해 자세히 알아보기



    아래 코드를 실행해도 데이터를 얻을 수 없었습니다. .
    그냥 응답을 확인해도 에러가 아니라는 (ノД`) 시크 시크

    하지만 괜찮아! !
    자세한 것은 코드 기재 후에 기재하므로 설정을 잊지 않고! !
    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

    참고

    좋은 웹페이지 즐겨찾기