在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):Opteo/google-ads-api开源软件地址(OpenSource Url):https://github.com/Opteo/google-ads-api开源编程语言(OpenSource Language):TypeScript 100.0%开源软件介绍(OpenSource Introduction):Google Ads API Unofficial Google Ads API client library for Node.js Features
HiringWe're currently hiring full-stack engineers at Opteo! If you're interested in working on this library and other exciting projects, say hello at [email protected] Installationnpm install google-ads-api Usage
Create a clientimport { GoogleAdsApi } from "google-ads-api";
const client = new GoogleAdsApi({
client_id: "<CLIENT-ID>",
client_secret: "<CLIENT-SECRET>",
developer_token: "<DEVELOPER-TOKEN>",
}); Create a customer instanceconst customer = client.Customer({
customer_id: "1234567890",
refresh_token: "<REFRESH-TOKEN>",
});
// Also supports login & linked customer ids
const customer = client.Customer({
customer_id: "1234567890",
login_customer_id: "<LOGIN-CUSTOMER-ID>",
linked_customer_id: "<LINKED-CUSTOMER-ID>",
refresh_token: "<REFRESH-TOKEN>",
}); List accessible customersThis is a special client method for listing the accessible customers for a given refresh token, and is equivalent to CustomerService.listAccessibleCustomers. It returns the resource names of available customer accounts. const client = new GoogleAdsApi({
client_id: "<CLIENT-ID>",
client_secret: "<CLIENT-SECRET>",
developer_token: "<DEVELOPER-TOKEN>",
});
const refreshToken = "<REFRESH-TOKEN">
const customers = await client.listAccessibleCustomers(refreshToken); Retrieve Campaigns with metricsimport { enums } from "google-ads-api";
const campaigns = await customer.report({
entity: "campaign",
attributes: [
"campaign.id",
"campaign.name",
"campaign.bidding_strategy_type",
"campaign_budget.amount_micros",
],
metrics: [
"metrics.cost_micros",
"metrics.clicks",
"metrics.impressions",
"metrics.all_conversions",
],
constraints: {
"campaign.status": enums.CampaignStatus.ENABLED,
},
limit: 20,
}); Retrieve Campaigns using GAQLIf you prefer to use the Google Ads Query Language (GAQL) the const campaigns = await customer.query(`
SELECT
campaign.id,
campaign.name,
campaign.bidding_strategy_type,
campaign_budget.amount_micros,
metrics.cost_micros,
metrics.clicks,
metrics.impressions,
metrics.all_conversions,
FROM
campaign
WHERE
campaign.status = "ENABLED"
LIMIT 20
`); Retrieve Ad Group metrics by dateimport { enums } from "google-ads-api";
const campaigns = await customer.report({
entity: "ad_group",
metrics: [
"metrics.cost_micros",
"metrics.clicks",
"metrics.impressions",
"metrics.all_conversions",
],
segments: ["segments.date"],
from_date: "2021-01-01",
to_date: "2021-02-01",
}); Retrieve Keywords with an async iteratorCalls searchStream internally but returns the rows one by one in an async iterator. import { enums } from "google-ads-api";
const stream = customer.reportStream({
entity: "ad_group_criterion",
attributes: [
"ad_group_criterion.keyword.text",
"ad_group_criterion.status",
],
constraints: {
"ad_group_criterion.type": enums.CriterionType.KEYWORD,
},
});
// Rows are streamed in one by one
for await (const row of stream) {
// Break the loop to stop streaming
if (someLogic) {
break
}
} Retrieve Keywords with a raw streamReturns the raw stream so that events can be handled manually. For more information on Google's stream methods please consult their docs. import { enums, parse } from "google-ads-api";
const reportOptions = {
entity: "ad_group_criterion",
attributes: [
"ad_group_criterion.keyword.text",
"ad_group_criterion.status",
],
constraints: {
"ad_group_criterion.type": enums.CriterionType.KEYWORD,
},
};
const stream = customer.reportStreamRaw(reportOptions);
// Rows are streamed in 10,000 row chunks
stream.on("data", (chunk) => {
const parsedResults = parse({
results: chunk.results,
reportOptions,
});
});
stream.on("error", (error) => {
throw new Error(error);
});
stream.on("end", () => {
console.log("stream has finished");
}); Create an expanded text adimport { resources, enums, ResourceNames } from "google-ads-api";
const ad = new resources.Ad({
expanded_text_ad: {
headline_part1: "Cruise to Mars",
headline_part2: "Best Space Cruise Line",
description: "Buy your tickets now!",
path1: "cruises",
path2: "mars",
},
final_urls: ["https://example.com"],
type: enums.AdType.EXPANDED_TEXT_AD,
});
const adGroup = ResourceNames.adGroup(cus.credentials.customerId, "123");
const adGroupAd = new resources.AdGroupAd({
status: enums.AdGroupAdStatus.PAUSED,
ad_group,
ad,
});
// Returns an array of newly created resource names if successful
const { results } = await cus.adGroupAds.create([adGroupAd]); Create a Campaign & Budget atomicallyimport {
resources,
enums,
toMicros,
ResourceNames,
MutateOperation,
} from "google-ads-api";
// Create a resource name with a temporary resource id (-1)
const budgetResourceName = ResourceNames.campaignBudget(
customer.credentials.customer_id,
"-1"
);
const operations: MutateOperation<
resources.ICampaignBudget | resources.ICampaign
>[] = [
{
entity: "campaign_budget",
operation: "create",
resource: {
// Create a budget with the temporary resource id
resource_name: budgetResourceName,
name: "Planet Express Budget",
delivery_method: enums.BudgetDeliveryMethod.STANDARD,
amount_micros: toMicros(500),
},
},
{
entity: "campaign",
operation: "create",
resource: {
name: "Planet Express",
advertising_channel_type: enums.AdvertisingChannelType.SEARCH,
status: enums.CampaignStatus.PAUSED,
manual_cpc: {
enhanced_cpc_enabled: true,
},
// Use the temporary resource id which will be created in the previous operation
campaign_budget: budgetResourceName,
network_settings: {
target_google_search: true,
target_search_network: true,
},
},
},
];
const result = await customer.mutateResources(operations); Summary RowIf a summary row is requested in the const [summaryRow, ...response] = await customer.report({
entity: "campaign",
metrics: ["metrics.clicks", "metrics.all_conversions"],
summary_row_setting: enums.SummaryRowSetting.SUMMARY_ROW_WITH_RESULTS,
}); If a summery row is requested in the const stream = customer.reportStream({
entity: "campaign",
metrics: ["metrics.clicks", "metrics.all_conversions"],
summary_row_setting: enums.SummaryRowSetting.SUMMARY_ROW_WITH_RESULTS,
});
const accumulator = [];
for await (const row of stream) {
accumulator.push(row);
}
const summaryRow = accumulator.slice(-1)[0]; Total Results CountThe const totalRows = await customer.reportCount({
entity: "search_term_view",
attributes: ["search_term_view.resource_name"],
}); Report Results OrderThere are 2 methods of sorting the results of report. The prefered method is to use the const response = await customer.report({
entity: "campaign",
attributes: ["campaign.id"],
metrics: ["metrics.clicks"],
segments: ["segments.date"],
order: [
{ field: "metrics.clicks", sort_order: "DESC" },
{ field: "segments.date", sort_order: "ASC" },
{ field: "campaign.id" }, // default sort_order is descending
],
}); The other method is to use the const response = await customer.report({
entity: "campaign",
attributes: ["campaign.id"],
metrics: ["metrics.clicks"],
segments: ["segments.date"],
order_by: "metrics.clicks",
sort_order: "DESC",
}); Resource NamesThe library provides a set of helper methods under the import { ResourceNames } from "google-ads-api";
const customerId = "1234567890";
const campaignId = "3218318373";
ResourceNames.campaign(customerId, campaignId);
// "customers/1234567890/campaigns/3218318373"
ResourceNames.adGroup(123, 123);
// "customers/123/adGroups/123"
ResourceNames.adGroupAd("1", "2", "3");
// "customers/1/adGroupAds/2~3"
const amsterdamLocationId = 1010543;
ResourceNames.geoTargetConstant(amsterdamLocationId);
// "geoTargetConstants/1010543"
ResourceNames.accountBudget(customer.credentials.customer_id, 123);
// "customers/1234567890/accountBudgets/123" HooksThe library provides hooks that can be executed before, after or on error of a query, stream or a mutation. Query/stream hooks:
These hooks have access to the These hooks also have access to the These hooks also have access the the |