Usługa AdSense
Zadbaj o dobrą organizację dzięki kolekcji
Zapisuj i kategoryzuj treści zgodnie ze swoimi preferencjami.
Usługa AdSense umożliwia korzystanie z interfejsu API zarządzania AdSense w Apps Script. Ten interfejs API umożliwia klientom AdSense uzyskiwanie informacji o strukturze konta i generowanie raportów o jego skuteczności.
Dokumentacja
Szczegółowe informacje o tej usłudze znajdziesz w dokumentacji referencyjnej interfejsu AdSense Management API. Podobnie jak wszystkie usługi zaawansowane w Apps Script, usługa AdSense używa tych samych obiektów, metod i parametrów co publiczny interfejs API. Więcej informacji znajdziesz w artykule Jak określane są sygnatury metod.
Aby zgłaszać problemy i uzyskać pomoc, zadaj pytanie na Stack Overflow, używając tagu adsense-api.
Przykładowy kod
Poniższy przykładowy kod korzysta z wersji 2 interfejsu API.
Wyświetlanie listy kont
Ten przykład zawiera listę wszystkich kont dostępnych dla użytkownika. Konta są podawane jako nazwy zasobów, np. accounts/pub-12345
, których można używać w innych metodach, np. wyświetlania klientów reklam. Zwróć uwagę na użycie tokenów strony, aby uzyskać dostęp do pełnej listy wyników.
Wyświetlanie listy klientów reklamowych
Ten przykład zawiera listę wszystkich klientów reklamowych na danym koncie. Określ konto jako nazwę zasobu, np. accounts/pub-12345
. Nazwę zasobu konta możesz uzyskać za pomocą przykładowego kodu List accounts (Wyświetl konta).
Wyświetlanie listy jednostek reklamowych
Ten przykład zawiera listę wszystkich jednostek reklamowych dla danego klienta reklamowego. Określ klienta reklam jako nazwę zasobu, np. accounts/pub-12345/adclients/ca-pub-12345
.
Nazwę zasobu klienta reklamowego możesz uzyskać za pomocą przykładowego kodu List ad clients (Wyświetl klientów reklamowych).
Wygeneruj raport
Ten przykład generuje raport dotyczący Twojego konta AdSense i zapisuje wyniki w arkuszu kalkulacyjnym.
O ile nie stwierdzono inaczej, treść tej strony jest objęta licencją Creative Commons – uznanie autorstwa 4.0, a fragmenty kodu są dostępne na licencji Apache 2.0. Szczegółowe informacje na ten temat zawierają zasady dotyczące witryny Google Developers. Java jest zastrzeżonym znakiem towarowym firmy Oracle i jej podmiotów stowarzyszonych.
Ostatnia aktualizacja: 2025-08-31 UTC.
[null,null,["Ostatnia aktualizacja: 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```"]]