Layanan AdSense
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Layanan AdSense memungkinkan Anda menggunakan
AdSense Management API di Apps Script. API ini memberi pelanggan AdSense kemampuan untuk mendapatkan informasi tentang struktur akun mereka dan menjalankan laporan tentang performanya.
Referensi
Untuk mengetahui informasi mendetail tentang layanan ini, lihat dokumentasi referensi untuk AdSense Management API. Seperti semua layanan lanjutan di Apps Script, layanan AdSense menggunakan objek, metode, dan parameter yang sama dengan API publik. Untuk mengetahui informasi selengkapnya, lihat Cara menentukan tanda tangan metode.
Untuk melaporkan masalah dan menemukan dukungan lainnya, ajukan pertanyaan di Stack Overflow menggunakan tag
adsense-api.
Kode contoh
Contoh kode di bawah menggunakan versi 2
API.
Mencantumkan akun
Contoh ini mencantumkan semua akun yang tersedia untuk pengguna. Akun ditentukan sebagai nama resource, misalnya, accounts/pub-12345
, yang dapat digunakan dalam metode lain, seperti mencantumkan klien iklan. Perhatikan penggunaan token halaman untuk mengakses daftar lengkap hasil.
Mencantumkan klien iklan
Contoh ini mencantumkan semua klien iklan untuk akun tertentu. Tentukan akun
sebagai nama resource, misalnya, accounts/pub-12345
. Anda bisa mendapatkan nama resource akun menggunakan contoh kode List accounts.
Mencantumkan unit iklan
Contoh ini mencantumkan semua unit iklan untuk klien iklan tertentu. Tentukan klien iklan sebagai nama resource, seperti accounts/pub-12345/adclients/ca-pub-12345
.
Anda bisa mendapatkan nama resource klien iklan menggunakan kode contoh
List ad clients.
Membuat laporan
Contoh ini membuat laporan tentang akun AdSense Anda dan menampilkan
hasilnya ke spreadsheet.
Kecuali dinyatakan lain, konten di halaman ini dilisensikan berdasarkan Lisensi Creative Commons Attribution 4.0, sedangkan contoh kode dilisensikan berdasarkan Lisensi Apache 2.0. Untuk mengetahui informasi selengkapnya, lihat Kebijakan Situs Google Developers. Java adalah merek dagang terdaftar dari Oracle dan/atau afiliasinya.
Terakhir diperbarui pada 2025-08-31 UTC.
[null,null,["Terakhir diperbarui pada 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```"]]