AdSense サービス
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
AdSense サービスを使用すると、Apps Script で AdSense Management API を使用できます。この API を使用すると、AdSense のお客様はアカウントの構造に関する情報を取得し、アカウントのパフォーマンスに関するレポートを実行できます。
リファレンス
このサービスの詳細については、AdSense Management API のリファレンス ドキュメントをご覧ください。Apps Script のすべての高度なサービスと同様に、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 Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2025-08-31 UTC。
[null,null,["最終更新日 2025-08-31 UTC。"],[[["\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```"]]