【问题标题】:How do I request the AdWords API without client authentication in Google Apps Script?如何在 Google Apps 脚本中请求 AdWords API 而无需客户端身份验证?
【发布时间】:2018-05-21 14:44:30
【问题描述】:

我有一个绑定到需要读取 AdWords 数据的电子表格的 Google Apps 脚本。我避免使用用户权限 OAuth2 程序,因为它是一个完全服务器到服务器的脚本,可以自动将每日数据更新到工作表中。

在大量浏览文档之后,我创建了一个服务帐户,并按照本指南为其授予了必要的权限: https://developers.google.com/adwords/api/docs/guides/authentication#oauth2_service_accounts

我还没有完全理解下一步,即如何实际发出请求,特别是在 Apps 脚本中。这个代码是什么?

还接受更好的建议,以最优雅的方式在无需客户端许可的情况下在 Apps 脚本上请求 AdWords API。我设法获得了一个似乎是正确轨道的刷新令牌,但无法用它生成 OAuth2 令牌。

【问题讨论】:

    标签: google-apps-script oauth-2.0 google-oauth google-ads-api


    【解决方案1】:

    我发现不需要服务帐户,最好的方法是遵循已安装的应用流程。

    这是在 Google Apps 脚本上请求 AdWords API 的最简单方法:

    1. 创建 客户端 ID客户端密码,如 here. 所述
    2. 按照here 所述,按照 OAuth2 Playground 流程获取 刷新令牌
    3. 关注this process,获取您的开发者令牌。注意:您必须创建/使用单独的经理帐户,申请令牌并等待其批准。您也可以使用测试帐户。
    4. 找到您的客户客户 ID here - 登录后,它会以 XXX-XXX-XXXX 形式显示在右上角。
    5. 创建您的AWQL query(不确定本指南是否同样适用于 XML)。

    function getGoogleAccessToken() {
    
        // This is also a general method to fetch an access token using a refresh token in GAS.
    
        var params = {
            client_id: YOUR_CLIENT_ID,
            client_secret: YOUR_CLIENT_SECRET,
            refresh_token: YOUR_REFRESH_TOKEN,
            grant_type: 'refresh_token'
        }
    
        const options = {
            contentType: 'application/x-www-form-urlencoded',
            method: 'post',
            muteHttpExceptions: true, // To see the whole response in case of errors
            payload: params
        }
    
        var url = "https://www.googleapis.com/oauth2/v4/token";
    
        var data = UrlFetchApp.fetch(url, options);
        return (JSON.parse(data).access_token);
    }
    
    function getAdwordsData() {
    
        var adwordsParams = {
            "__fmt": "CSV",
            "__rdquery": YOUR_VALID_AWQL_QUERY
        }
    
        var adwordsOptions = {
            contentType: "application/x-www-form-urlencoded",
            method: 'post',
            muteHttpExceptions: true,
            payload: adwordsParams
        };
    
        adwordsOptions.headers = {
            "Authorization": "Bearer " + getGoogleAccessToken(),
            "developerToken": YOUR_DEVELOPER_TOKEN,
            "clientCustomerId": YOUR_CLIENT_CUSTOMER_ID",
            "includeZeroImpressions": true,
            "Expect": "100-continue",
            "User-Agent": "curl, gzip",
            "Accept": "*/*",
            "Accept-Encoding": "gzip"
        };
    
        var url = 'https://adwords.google.com/api/adwords/reportdownload/v201710';
        var res = UrlFetchApp.fetch(url, options);
        Logger.log(res);
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 2017-07-22
      相关资源
      最近更新 更多