AdSense 服务
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
借助 AdSense 服务,您可以在 Apps 脚本中使用 AdSense Management API。借助此 API,AdSense 客户可以获取有关其账号结构的信息,并运行报告来了解账号的效果。
参考
有关此服务的详细信息,请参阅 AdSense 管理 API 的参考文档。与 Apps 脚本中的所有高级服务一样,AdSense 服务使用的对象、方法和参数均与公共 API 相同。如需了解详情,请参阅方法签名是如何确定的。
如需报告问题并寻求其他支持,请在 Stack Overflow 上使用 adsense-api 标记提问。
示例代码
以下示例代码使用 API 的版本 2。
列出账号
此示例列出了用户可用的所有账号。账号以资源名称(例如 accounts/pub-12345
)的形式指定,可用于其他方法,例如列出广告客户。请注意,您可以使用页面令牌来访问完整的结果列表。
列出广告客户
此示例会列出指定账号的所有广告客户。以资源名称的形式指定账号,例如 accounts/pub-12345
。您可以使用列出账号示例代码获取账号资源名称。
列出广告单元
此示例会列出指定广告客户的所有广告单元。将广告客户指定为资源名称,例如 accounts/pub-12345/adclients/ca-pub-12345
。
您可以使用列出广告客户示例代码获取广告客户资源名称。
生成报告
此示例会生成有关您的 AdSense 账号的报告,并将结果输出到电子表格中。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-31。
[null,null,["最后更新时间 (UTC):2025-08-31。"],[[["\u003cp\u003eThe AdSense Management API allows you to programmatically access your AdSense account data within Google Apps Script.\u003c/p\u003e\n"],["\u003cp\u003eYou can retrieve information about your account structure, including accounts, ad clients, and ad units.\u003c/p\u003e\n"],["\u003cp\u003eThis API enables you to generate reports on your AdSense performance and export them to a Google Sheet.\u003c/p\u003e\n"],["\u003cp\u003eThis is an advanced service that needs to be enabled before use, offering functionality similar to the public AdSense Management API.\u003c/p\u003e\n"]]],[],null,["# AdSense Service\n\nThe AdSense service allows you to use the\n[AdSense Management API](/adsense/management) in Apps Script. This API\ngives AdSense customers the ability to get information about the structure\nof their account and run reports on how it is performing.\n| **Note:** This is an advanced service that must be [enabled before use](/apps-script/guides/services/advanced).\n\nReference\n---------\n\nFor detailed information on this service, see the\n[reference documentation](/adsense/management/reference/rest) for the AdSense\nManagement API. Like all advanced services in Apps Script, the AdSense service\nuses the same objects, methods, and parameters as the public API. For more information, see [How method signatures are determined](/apps-script/guides/services/advanced#how_method_signatures_are_determined).\n\nTo report issues and find other support, please ask on Stack Overflow using the\n[adsense-api](https://stackoverflow.com/questions/tagged/adsense-api)\ntag.\n\nSample code\n-----------\n\nThe sample code below uses [version 2](/adsense/management/reference/rest) of\nthe API.\n\n### List accounts\n\nThis sample lists all of the accounts available to the user. The accounts are\nspecified as resource names, for example, `accounts/pub-12345`, that can be used\nin other methods, such as [listing ad clients](#list_ad_clients). Notice the use\nof page tokens to access the full list of results. \nadvanced/adsense.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/adsense.gs) \n\n```javascript\n/**\n * Lists available AdSense accounts.\n */\nfunction listAccounts() {\n let pageToken;\n do {\n const response = AdSense.Accounts.list({pageToken: pageToken});\n if (!response.accounts) {\n console.log('No accounts found.');\n return;\n }\n for (const account of response.accounts) {\n console.log('Found account with resource name \"%s\" and display name \"%s\".',\n account.name, account.displayName);\n }\n pageToken = response.nextPageToken;\n } while (pageToken);\n}\n```\n\n### List ad clients\n\nThis sample lists all of the ad clients for a given account. Specify the account\nas a resource name, for example, `accounts/pub-12345`. You can get the account\nresource name by using the [List accounts](#list_accounts) sample code. \nadvanced/adsense.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/adsense.gs) \n\n```javascript\n/**\n * Logs available Ad clients for an account.\n *\n * @param {string} accountName The resource name of the account that owns the\n * collection of ad clients.\n */\nfunction listAdClients(accountName) {\n let pageToken;\n do {\n const response = AdSense.Accounts.Adclients.list(accountName, {\n pageToken: pageToken\n });\n if (!response.adClients) {\n console.log('No ad clients found for this account.');\n return;\n }\n for (const adClient of response.adClients) {\n console.log('Found ad client for product \"%s\" with resource name \"%s\".',\n adClient.productCode, adClient.name);\n console.log('Reporting dimension ID: %s',\n adClient.reportingDimensionId ?? 'None');\n }\n pageToken = response.nextPageToken;\n } while (pageToken);\n}\n```\n\n### List ad units\n\nThis sample lists all of the ad units for a given ad client. Specify the ad\nclient as a resource name, such as `accounts/pub-12345/adclients/ca-pub-12345`.\nYou can get the ad client resource name by using the\n[List ad clients](#list_ad_clients) sample code. \nadvanced/adsense.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/adsense.gs) \n\n```javascript\n/**\n * Lists ad units.\n * @param {string} adClientName The resource name of the ad client that owns the collection\n * of ad units.\n */\nfunction listAdUnits(adClientName) {\n let pageToken;\n do {\n const response = AdSense.Accounts.Adclients.Adunits.list(adClientName, {\n pageSize: 50,\n pageToken: pageToken\n });\n if (!response.adUnits) {\n console.log('No ad units found for this ad client.');\n return;\n }\n for (const adUnit of response.adUnits) {\n console.log('Found ad unit with resource name \"%s\" and display name \"%s\".',\n adUnit.name, adUnit.displayName);\n }\n\n pageToken = response.nextPageToken;\n } while (pageToken);\n}\n```\n\n### Generate a report\n\nThis sample generates a report over your AdSense account and outputs the\nresults to a spreadsheet. \nadvanced/adsense.gs \n[View on GitHub](https://github.com/googleworkspace/apps-script-samples/blob/main/advanced/adsense.gs) \n\n```javascript\n/**\n * Generates a spreadsheet report for a specific ad client in an account.\n * @param {string} accountName The resource name of the account.\n * @param {string} adClientReportingDimensionId The reporting dimension ID\n * of the ad client.\n */\nfunction generateReport(accountName, adClientReportingDimensionId) {\n // Prepare report.\n const today = new Date();\n const oneWeekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000);\n\n const report = AdSense.Accounts.Reports.generate(accountName, {\n // Specify the desired ad client using a filter.\n filters: ['AD_CLIENT_ID==' + escapeFilterParameter(adClientReportingDimensionId)],\n metrics: ['PAGE_VIEWS', 'AD_REQUESTS', 'AD_REQUESTS_COVERAGE', 'CLICKS',\n 'AD_REQUESTS_CTR', 'COST_PER_CLICK', 'AD_REQUESTS_RPM',\n 'ESTIMATED_EARNINGS'],\n dimensions: ['DATE'],\n ...dateToJson('startDate', oneWeekAgo),\n ...dateToJson('endDate', today),\n // Sort by ascending date.\n orderBy: ['+DATE']\n });\n\n if (!report.rows) {\n console.log('No rows returned.');\n return;\n }\n const spreadsheet = SpreadsheetApp.create('AdSense Report');\n const sheet = spreadsheet.getActiveSheet();\n\n // Append the headers.\n sheet.appendRow(report.headers.map((header) =\u003e header.name));\n\n // Append the results.\n sheet.getRange(2, 1, report.rows.length, report.headers.length)\n .setValues(report.rows.map((row) =\u003e row.cells.map((cell) =\u003e cell.value)));\n\n console.log('Report spreadsheet created: %s',\n spreadsheet.getUrl());\n}\n\n/**\n * Escape special characters for a parameter being used in a filter.\n * @param {string} parameter The parameter to be escaped.\n * @return {string} The escaped parameter.\n */\nfunction escapeFilterParameter(parameter) {\n return parameter.replace('\\\\', '\\\\\\\\').replace(',', '\\\\,');\n}\n\n/**\n * Returns the JSON representation of a Date object (as a google.type.Date).\n *\n * @param {string} paramName the name of the date parameter\n * @param {Date} value the date\n * @return {object} formatted date\n */\nfunction dateToJson(paramName, value) {\n return {\n [paramName + '.year']: value.getFullYear(),\n [paramName + '.month']: value.getMonth() + 1,\n [paramName + '.day']: value.getDate()\n };\n}\n```"]]