@hermoso/ads 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +105 -2
- package/docs/bring-your-own-app.md +391 -0
- package/package.json +66 -4
- package/src/core.js +20 -0
- package/src/credentials.js +53 -0
- package/src/errors.js +29 -0
- package/src/hash.js +30 -0
- package/src/http.js +148 -0
- package/src/index.js +103 -0
- package/src/money.js +25 -0
- package/src/oauth.js +34 -0
- package/src/ops.js +49 -0
- package/src/platform.js +56 -0
- package/src/platforms/amazon-ads.js +218 -0
- package/src/platforms/apple-ads.js +236 -0
- package/src/platforms/applovin-ads.js +182 -0
- package/src/platforms/google-ads.js +435 -0
- package/src/platforms/index.js +21 -0
- package/src/platforms/linkedin-ads.js +297 -0
- package/src/platforms/meta.js +518 -0
- package/src/platforms/microsoft-ads.js +381 -0
- package/src/platforms/openai-ads.js +246 -0
- package/src/platforms/outbrain-ads.js +128 -0
- package/src/platforms/pinterest-ads.js +271 -0
- package/src/platforms/reddit-ads.js +259 -0
- package/src/platforms/snapchat-ads.js +276 -0
- package/src/platforms/taboola-ads.js +57 -0
- package/src/platforms/tiktok-ads.js +348 -0
- package/src/platforms/trade-desk.js +111 -0
- package/src/platforms/x-ads.js +274 -0
- package/src/safety.js +96 -0
- package/src/tools.js +81 -0
- package/src/zip.js +47 -0
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
import { definePlatform, row, pickLevel, dateRange } from '../platform.js';
|
|
2
|
+
import { AdsError } from '../errors.js';
|
|
3
|
+
import { assertBornPaused, gateStatus, gateBudget, gateDelete, checkLength, STATUS } from '../safety.js';
|
|
4
|
+
import { toMajor } from '../money.js';
|
|
5
|
+
import { oauth2Refresh } from '../oauth.js';
|
|
6
|
+
import { decompress, parseCsv } from '../zip.js';
|
|
7
|
+
import { hashEmailCanonical } from '../hash.js';
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
const TOKEN_URL = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
|
|
11
|
+
const HOSTS = {
|
|
12
|
+
CampaignManagement: ['campaign.api.bingads.microsoft.com', 'campaign.api.sandbox.bingads.microsoft.com'],
|
|
13
|
+
CustomerManagement: ['clientcenter.api.bingads.microsoft.com', 'clientcenter.api.sandbox.bingads.microsoft.com'],
|
|
14
|
+
Reporting: ['reporting.api.bingads.microsoft.com', 'reporting.api.sandbox.bingads.microsoft.com'],
|
|
15
|
+
AdInsight: ['adinsight.api.bingads.microsoft.com', 'adinsight.api.sandbox.bingads.microsoft.com'],
|
|
16
|
+
};
|
|
17
|
+
const ids = (v) => String(v).replace(/\D/g, '');
|
|
18
|
+
const AD_TYPES = ['AppInstall', 'DynamicSearch', 'ExpandedText', 'Hotel', 'Image', 'Product', 'ResponsiveAd', 'ResponsiveSearch', 'Text'];
|
|
19
|
+
|
|
20
|
+
function allErrors(body) {
|
|
21
|
+
const fault = body?.ApplicationFault ?? body;
|
|
22
|
+
const out = [...(fault?.OperationErrors ?? []), ...(fault?.BatchErrors ?? [])];
|
|
23
|
+
return { list: out, tracking: fault?.TrackingId };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function parseError(status, body) {
|
|
27
|
+
const { list, tracking } = allErrors(body);
|
|
28
|
+
if (!list.length) return body?.Message ? { message: body.Message } : null;
|
|
29
|
+
const e = list[0];
|
|
30
|
+
const code = Number(e.Code);
|
|
31
|
+
const message = list.map((x) => `${x.Message ?? x.ErrorCode}${x.Details ? ` (${x.Details})` : ''}${x.FieldPath ? ` [${x.FieldPath}]` : ''}`).join('; ') + (tracking ? ` (tracking ${tracking})` : '');
|
|
32
|
+
if (code === 105) return { kind: 'auth', code, message, userMessage: `Microsoft Advertising rejected the credentials: the token or developer token is invalid, or belongs to the other environment (sandbox vs production). ${message}` };
|
|
33
|
+
if (code === 106) return { kind: 'permission', code, message, userMessage: `Microsoft Advertising: this user has no access to that customer/account pair. ${message}` };
|
|
34
|
+
if (code === 2204) return { kind: 'refused', code, message, userMessage: `Microsoft Advertising: the account's payment method is missing or declined. ${message}` };
|
|
35
|
+
if (code === 3412) return { kind: 'validation', code, message, userMessage: 'Microsoft Advertising wants a language NAME such as "English", not a code.' };
|
|
36
|
+
return { kind: status === 401 ? 'auth' : 'validation', code, message };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function checkBody(body) {
|
|
40
|
+
const partial = (body?.PartialErrors ?? []).filter(Boolean);
|
|
41
|
+
const nested = (body?.NestedPartialErrors ?? []).flatMap((n) => n?.BatchErrors ?? []).filter(Boolean);
|
|
42
|
+
const all = [...partial, ...nested];
|
|
43
|
+
if (!all.length) return null;
|
|
44
|
+
return { kind: 'validation', code: all[0].Code, message: all.map((x) => `${x.Message ?? x.ErrorCode}${x.FieldPath ? ` [${x.FieldPath}]` : ''}`).join('; ') };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** One call: service + verb + resource. CustomerManagement must NOT get the customer headers. */
|
|
48
|
+
function msa(ctx, service, method, resource, body, accountId) {
|
|
49
|
+
return ctx.creds().then((c) => {
|
|
50
|
+
const host = HOSTS[service][c.sandbox === 'true' || c.sandbox === true ? 1 : 0];
|
|
51
|
+
const headers = {};
|
|
52
|
+
if (service !== 'CustomerManagement') {
|
|
53
|
+
if (c.customerId) headers.CustomerId = ids(c.customerId);
|
|
54
|
+
if (accountId) headers.CustomerAccountId = ids(accountId);
|
|
55
|
+
}
|
|
56
|
+
return ctx.request({ method, base: `https://${host}/${service}/v13`, path: `/${resource}`, json: body, headers });
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const acct = (a) => ids(a.accountId);
|
|
61
|
+
|
|
62
|
+
export default definePlatform({
|
|
63
|
+
id: 'microsoft_ads',
|
|
64
|
+
label: 'Microsoft Advertising',
|
|
65
|
+
money: 'major',
|
|
66
|
+
credentials: [
|
|
67
|
+
{ name: 'clientId', required: true, env: 'MICROSOFT_ADS_CLIENT_ID', desc: 'Entra (Azure AD) app registration client id.' },
|
|
68
|
+
{ name: 'clientSecret', env: 'MICROSOFT_ADS_CLIENT_SECRET', desc: 'Client secret (web apps); omit for public clients.' },
|
|
69
|
+
{ name: 'refreshToken', required: true, env: 'MICROSOFT_ADS_REFRESH_TOKEN' },
|
|
70
|
+
{ name: 'developerToken', required: true, env: 'MICROSOFT_ADS_DEVELOPER_TOKEN', desc: 'From Microsoft Advertising > Settings > Developer settings.' },
|
|
71
|
+
{ name: 'customerId', required: true, env: 'MICROSOFT_ADS_CUSTOMER_ID', desc: 'Manager/customer id that owns the accounts.' },
|
|
72
|
+
{ name: 'sandbox', env: 'MICROSOFT_ADS_SANDBOX', desc: '"true" to use the sandbox hosts.' },
|
|
73
|
+
],
|
|
74
|
+
baseUrl: 'https://campaign.api.bingads.microsoft.com/CampaignManagement/v13',
|
|
75
|
+
authHeaders: (c) => ({ authorization: `Bearer ${c.accessToken}`, DeveloperToken: c.developerToken }),
|
|
76
|
+
refresh: (c, ctx) => oauth2Refresh(ctx, c, { tokenUrl: TOKEN_URL, extra: { scope: 'https://ads.microsoft.com/msads.manage offline_access' } }),
|
|
77
|
+
parseError,
|
|
78
|
+
checkBody,
|
|
79
|
+
notes: [
|
|
80
|
+
'With no locations a campaign serves worldwide; createCampaign says so loudly.',
|
|
81
|
+
'Campaign types are a flags enum sent as a comma-separated string.',
|
|
82
|
+
'A shared budget makes a campaign\'s DailyBudget read-only; setBudget refuses it.',
|
|
83
|
+
'Reports are submitted, polled and downloaded as a zipped CSV; a pending report returns reportRequestId to resume.',
|
|
84
|
+
],
|
|
85
|
+
setup: {
|
|
86
|
+
app: 'An app registration in Microsoft Entra ID (Azure portal) with a redirect URI, plus a developer token requested in Microsoft Advertising (Settings > Developer settings).',
|
|
87
|
+
scopes: ['https://ads.microsoft.com/msads.manage', 'offline_access', 'openid'],
|
|
88
|
+
review: 'A multi-tenant app needs publisher verification for other organisations to consent. The developer token is issued per user; a universal sandbox token exists for testing.',
|
|
89
|
+
hosted: { connect: 'app', note: 'Hosted Hermoso connects with one click where supported, with no developer app of your own.' },
|
|
90
|
+
docs: 'https://learn.microsoft.com/advertising/guides/get-started',
|
|
91
|
+
},
|
|
92
|
+
ops: {
|
|
93
|
+
listAccounts: {
|
|
94
|
+
run: async (ctx, a) => {
|
|
95
|
+
const user = await msa(ctx, 'CustomerManagement', 'POST', 'User/Query', { UserId: null });
|
|
96
|
+
const customers = [...new Set((user.CustomerRoles ?? []).map((r) => r.CustomerId))].slice(0, 25);
|
|
97
|
+
const items = []; const seen = new Set();
|
|
98
|
+
for (const customerId of customers) {
|
|
99
|
+
try {
|
|
100
|
+
const r = await msa(ctx, 'CustomerManagement', 'POST', 'AccountsInfo/Query', { CustomerId: customerId, OnlyParentAccounts: false });
|
|
101
|
+
for (const x of r.AccountsInfo ?? []) {
|
|
102
|
+
if (seen.has(x.Id)) continue; seen.add(x.Id);
|
|
103
|
+
items.push(row(x, { id: String(x.Id), name: x.Name, number: x.Number, status: x.AccountLifeCycleStatus, customerId: String(customerId) }, a));
|
|
104
|
+
}
|
|
105
|
+
} catch (e) { items.push({ customerId: String(customerId), error: e.message }); }
|
|
106
|
+
}
|
|
107
|
+
return { items };
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
listCampaigns: {
|
|
111
|
+
params: { accountId: { required: true }, campaignTypes: { type: 'string', desc: 'Comma-separated flags; default Search,Shopping,DynamicSearchAds,Audience,PerformanceMax.' } },
|
|
112
|
+
run: async (ctx, a) => {
|
|
113
|
+
const types = a.campaignTypes ?? 'Search,Shopping,DynamicSearchAds,Audience,PerformanceMax';
|
|
114
|
+
let r; let complete = true;
|
|
115
|
+
try {
|
|
116
|
+
r = await msa(ctx, 'CampaignManagement', 'POST', 'Campaigns/QueryByAccountId', { AccountId: acct(a), CampaignType: types, ReturnAdditionalFields: 'LifetimeBudgetFields,CpvCpmBiddingScheme' }, acct(a));
|
|
117
|
+
} catch (e) {
|
|
118
|
+
if (e.kind !== 'validation') throw e;
|
|
119
|
+
r = await msa(ctx, 'CampaignManagement', 'POST', 'Campaigns/QueryByAccountId', { AccountId: acct(a), CampaignType: types }, acct(a));
|
|
120
|
+
complete = false;
|
|
121
|
+
}
|
|
122
|
+
return { items: (r.Campaigns ?? []).map((c) => row(c, { id: String(c.Id), name: c.Name, status: c.Status, type: c.CampaignType, dailyBudget: c.DailyBudget, budgetType: c.BudgetType, sharedBudgetId: c.BudgetId > 0 ? String(c.BudgetId) : undefined }, a)),
|
|
123
|
+
...(complete ? {} : { complete: false, note: 'Campaigns with lifetime budgets or CPV/CPM bidding may be missing from this list.' }) };
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
getCampaign: {
|
|
127
|
+
params: { accountId: { required: true }, id: { required: true } },
|
|
128
|
+
run: async (ctx, a) => {
|
|
129
|
+
const r = await msa(ctx, 'CampaignManagement', 'POST', 'Campaigns/QueryByIds', { AccountId: acct(a), CampaignIds: [ids(a.id)], CampaignType: 'Search,Shopping,DynamicSearchAds,Audience,PerformanceMax' }, acct(a));
|
|
130
|
+
const c = (r.Campaigns ?? []).filter(Boolean)[0];
|
|
131
|
+
if (!c) throw new AdsError('not_found', `Campaign ${a.id} not found.`);
|
|
132
|
+
return row(c, { id: String(c.Id), name: c.Name, status: c.Status, type: c.CampaignType, dailyBudget: c.DailyBudget, budgetType: c.BudgetType, timeZone: c.TimeZone, sharedBudgetId: c.BudgetId > 0 ? String(c.BudgetId) : undefined }, a);
|
|
133
|
+
},
|
|
134
|
+
},
|
|
135
|
+
createCampaign: {
|
|
136
|
+
params: {
|
|
137
|
+
accountId: { required: true }, name: { required: true }, dailyBudget: { required: true },
|
|
138
|
+
campaignType: { type: 'string', enum: ['Search', 'Shopping', 'DynamicSearchAds', 'Audience', 'PerformanceMax'], desc: 'Default Search.' },
|
|
139
|
+
budgetType: { type: 'string', enum: ['DailyBudgetStandard', 'DailyBudgetAccelerated'] },
|
|
140
|
+
locations: { type: 'array', desc: 'Location ids from searchTargeting type "locations". None = worldwide.' },
|
|
141
|
+
languages: { type: 'array', desc: 'Language names (e.g. "English") or ["All"]. Default ["All"].' },
|
|
142
|
+
biddingScheme: { type: 'object', desc: 'e.g. {"Type":"MaxClicks"}; default EnhancedCpc.' },
|
|
143
|
+
timeZone: { type: 'string', desc: 'Default: the account\'s own time zone.' },
|
|
144
|
+
},
|
|
145
|
+
run: async (ctx, a) => {
|
|
146
|
+
assertBornPaused(a, 'campaign');
|
|
147
|
+
checkLength('name', a.name, 128);
|
|
148
|
+
const amount = toMajor(a.dailyBudget, 'dailyBudget');
|
|
149
|
+
if (amount > 1e6) throw new AdsError('validation', 'dailyBudget looks too large (over 1,000,000).', { field: 'dailyBudget' });
|
|
150
|
+
let timeZone = a.timeZone;
|
|
151
|
+
if (!timeZone) {
|
|
152
|
+
try { timeZone = (await msa(ctx, 'CustomerManagement', 'POST', 'Account/Query', { AccountId: acct(a) })).Account?.TimeZone; } catch { }
|
|
153
|
+
timeZone ??= 'PacificTimeUSCanadaTijuana';
|
|
154
|
+
}
|
|
155
|
+
const type = a.campaignType ?? 'Search';
|
|
156
|
+
const campaign = { Name: a.name, Status: 'Paused', DailyBudget: amount, BudgetType: a.budgetType ?? 'DailyBudgetStandard', TimeZone: timeZone, CampaignType: type,
|
|
157
|
+
Languages: a.languages ?? ['All'], ...(a.biddingScheme ? { BiddingScheme: a.biddingScheme } : {}), ...(a.fields ?? {}) };
|
|
158
|
+
const r = await msa(ctx, 'CampaignManagement', 'POST', 'Campaigns', { AccountId: acct(a), Campaigns: [campaign] }, acct(a));
|
|
159
|
+
const id = String((r.CampaignIds ?? [])[0]);
|
|
160
|
+
const out = { id, status: STATUS.PAUSED, timeZone };
|
|
161
|
+
if (a.locations?.length) {
|
|
162
|
+
if (a.locations.length > 100) throw new AdsError('validation', 'At most 100 locations per call.', { field: 'locations' });
|
|
163
|
+
await msa(ctx, 'CampaignManagement', 'POST', 'CampaignCriterions', {
|
|
164
|
+
CampaignCriterions: a.locations.map((l) => ({ CampaignId: id, Type: 'BiddableCampaignCriterion', Criterion: { Type: 'LocationCriterion', LocationId: ids(l) } })),
|
|
165
|
+
CriterionType: 'Targets',
|
|
166
|
+
}, acct(a));
|
|
167
|
+
out.locations = a.locations.length;
|
|
168
|
+
} else {
|
|
169
|
+
out.warning = 'No locations given: Microsoft serves this campaign worldwide. Add locations before activating.';
|
|
170
|
+
}
|
|
171
|
+
return out;
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
listAdGroups: {
|
|
175
|
+
params: { accountId: { required: true }, campaignId: { required: true } },
|
|
176
|
+
run: async (ctx, a) => {
|
|
177
|
+
const r = await msa(ctx, 'CampaignManagement', 'POST', 'AdGroups/QueryByCampaignId', { CampaignId: ids(a.campaignId) }, acct(a));
|
|
178
|
+
return { items: (r.AdGroups ?? []).map((g) => row(g, { id: String(g.Id), name: g.Name, status: g.Status, cpcBid: g.CpcBid?.Amount, campaignId: String(a.campaignId) }, a)) };
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
createAdGroup: {
|
|
182
|
+
params: {
|
|
183
|
+
accountId: { required: true }, campaignId: { required: true }, name: { required: true }, cpcBid: { type: 'number' },
|
|
184
|
+
keywords: { type: 'array', desc: 'Optional [{text, matchType: Exact|Phrase|Broad, bid}] or strings (Phrase).' },
|
|
185
|
+
},
|
|
186
|
+
run: async (ctx, a) => {
|
|
187
|
+
assertBornPaused(a, 'ad group');
|
|
188
|
+
checkLength('name', a.name, 256);
|
|
189
|
+
const kws = (a.keywords ?? []).map((k) => (typeof k === 'string' ? { text: k } : k));
|
|
190
|
+
kws.forEach((k, i) => checkLength(`keywords[${i}]`, k.text, 100));
|
|
191
|
+
const r = await msa(ctx, 'CampaignManagement', 'POST', 'AdGroups', { CampaignId: ids(a.campaignId), AdGroups: [{ Name: a.name, Status: 'Paused', ...(a.cpcBid != null ? { CpcBid: { Amount: toMajor(a.cpcBid, 'cpcBid') } } : {}), ...(a.fields ?? {}) }] }, acct(a));
|
|
192
|
+
const id = String((r.AdGroupIds ?? [])[0]);
|
|
193
|
+
let keywordIds = [];
|
|
194
|
+
if (kws.length) {
|
|
195
|
+
const k = await msa(ctx, 'CampaignManagement', 'POST', 'Keywords', { AdGroupId: id, Keywords: kws.map((x) => ({ Text: x.text, MatchType: x.matchType ?? 'Phrase', Status: 'Paused', ...(x.bid != null ? { Bid: { Amount: toMajor(x.bid, 'bid') } } : {}) })) }, acct(a));
|
|
196
|
+
keywordIds = (k.KeywordIds ?? []).map(String);
|
|
197
|
+
}
|
|
198
|
+
return { id, status: STATUS.PAUSED, keywordIds };
|
|
199
|
+
},
|
|
200
|
+
},
|
|
201
|
+
listAds: {
|
|
202
|
+
params: { accountId: { required: true }, adGroupId: { required: true } },
|
|
203
|
+
run: async (ctx, a) => {
|
|
204
|
+
const r = await msa(ctx, 'CampaignManagement', 'POST', 'Ads/QueryByAdGroupId', { AdGroupId: ids(a.adGroupId), AdTypes: AD_TYPES }, acct(a));
|
|
205
|
+
return { items: (r.Ads ?? []).map((x) => row(x, { id: String(x.Id), type: x.Type, status: x.Status, editorialStatus: x.EditorialStatus, finalUrls: x.FinalUrls, headlines: x.Headlines?.map((h) => h.Asset?.Text) }, a)) };
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
createAd: {
|
|
209
|
+
params: {
|
|
210
|
+
accountId: { required: true }, adGroupId: { required: true }, finalUrl: { type: 'string', required: true },
|
|
211
|
+
headlines: { type: 'array', required: true, desc: 'Responsive search ad: 3-15 headlines, 30 characters each.' },
|
|
212
|
+
descriptions: { type: 'array', required: true, desc: '2-4 descriptions, 90 characters each.' }, path1: { type: 'string' }, path2: { type: 'string' },
|
|
213
|
+
},
|
|
214
|
+
run: async (ctx, a) => {
|
|
215
|
+
assertBornPaused(a, 'ad');
|
|
216
|
+
if (a.headlines.length < 3 || a.headlines.length > 15) throw new AdsError('validation', 'A responsive search ad needs 3 to 15 headlines.', { field: 'headlines' });
|
|
217
|
+
if (a.descriptions.length < 2 || a.descriptions.length > 4) throw new AdsError('validation', 'A responsive search ad needs 2 to 4 descriptions.', { field: 'descriptions' });
|
|
218
|
+
a.headlines.forEach((h, i) => checkLength(`headlines[${i}]`, h, 30));
|
|
219
|
+
a.descriptions.forEach((d, i) => checkLength(`descriptions[${i}]`, d, 90));
|
|
220
|
+
for (const p of ['path1', 'path2']) { checkLength(p, a[p], 15); if (a[p]?.includes('/')) throw new AdsError('validation', `${p} cannot contain "/".`, { field: p }); }
|
|
221
|
+
if (a.path2 && !a.path1) throw new AdsError('validation', 'path2 needs path1.', { field: 'path2' });
|
|
222
|
+
if (!/^https?:\/\//i.test(a.finalUrl)) throw new AdsError('validation', 'finalUrl must be an http(s) URL.', { field: 'finalUrl' });
|
|
223
|
+
const asset = (t) => ({ Asset: { Type: 'TextAsset', Text: t } });
|
|
224
|
+
const r = await msa(ctx, 'CampaignManagement', 'POST', 'Ads', { AdGroupId: ids(a.adGroupId), Ads: [{ Type: 'ResponsiveSearch', Status: 'Paused', FinalUrls: [a.finalUrl], Headlines: a.headlines.map(asset), Descriptions: a.descriptions.map(asset), Path1: a.path1, Path2: a.path2, ...(a.fields ?? {}) }] }, acct(a));
|
|
225
|
+
return { id: String((r.AdIds ?? [])[0]), status: STATUS.PAUSED };
|
|
226
|
+
},
|
|
227
|
+
},
|
|
228
|
+
listAudiences: {
|
|
229
|
+
params: { accountId: { required: true }, types: { type: 'string', desc: 'Comma-separated audience type flags (default CustomerList).' } },
|
|
230
|
+
run: async (ctx, a) => {
|
|
231
|
+
const r = await msa(ctx, 'CampaignManagement', 'POST', 'Audiences/QueryByIds', { AudienceIds: null, Type: a.types ?? 'CustomerList' }, acct(a));
|
|
232
|
+
return { items: (r.Audiences ?? []).map((x) => row(x, { id: String(x.Id), name: x.Name, type: x.Type, scope: x.Scope, searchSize: x.SearchSize, networkSize: x.AudienceNetworkSize }, a)) };
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
createAudience: {
|
|
236
|
+
params: {
|
|
237
|
+
accountId: { required: true }, name: { required: true }, emails: { type: 'array', desc: 'Emails, hashed here (SHA-256) after Microsoft\'s normalisation.' },
|
|
238
|
+
acceptTerms: { type: 'boolean', required: true, desc: 'You accept Microsoft\'s Customer Match terms for this data.' }, membershipDays: { type: 'number', desc: '1-390, or -1 for no expiry.' },
|
|
239
|
+
},
|
|
240
|
+
run: async (ctx, a) => {
|
|
241
|
+
if (a.acceptTerms !== true) throw new AdsError('validation', 'Customer lists require acceptTerms: true (Microsoft\'s Customer Match terms).', { field: 'acceptTerms' });
|
|
242
|
+
checkLength('name', a.name, 128);
|
|
243
|
+
const r = await msa(ctx, 'CampaignManagement', 'POST', 'Audiences', { Audiences: [{ Type: 'CustomerList', Name: a.name, ParentId: acct(a), Scope: 'Account', MembershipDuration: a.membershipDays ?? 30 }] }, acct(a));
|
|
244
|
+
const id = String((r.AudienceIds ?? [])[0]);
|
|
245
|
+
let added = 0;
|
|
246
|
+
const hashed = (a.emails ?? []).map(hashEmailCanonical).filter(Boolean);
|
|
247
|
+
for (let i = 0; i < hashed.length; i += 1000) {
|
|
248
|
+
await msa(ctx, 'CampaignManagement', 'POST', 'CustomerListUserData/Apply', { CustomerListUserData: { AcceptCustomerMatchTerm: true, ActionType: 'Add', AudienceId: id, CustomerListItemSubType: 'Email', CustomerListItems: hashed.slice(i, i + 1000) } }, acct(a));
|
|
249
|
+
added += Math.min(1000, hashed.length - i);
|
|
250
|
+
}
|
|
251
|
+
return { id, added };
|
|
252
|
+
},
|
|
253
|
+
},
|
|
254
|
+
setStatus: {
|
|
255
|
+
params: { accountId: { required: true }, id: { required: true }, level: {}, status: { required: true }, campaignId: { desc: 'Required for level adGroup.' }, adGroupId: { desc: 'Required for level ad.' } },
|
|
256
|
+
run: async (ctx, a) => {
|
|
257
|
+
const status = gateStatus(a);
|
|
258
|
+
if (status === STATUS.ARCHIVED) throw new AdsError('validation', 'Microsoft Advertising has no archive; use deleteObject.', { field: 'status' });
|
|
259
|
+
const s = status === STATUS.ACTIVE ? 'Active' : 'Paused';
|
|
260
|
+
const level = pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform);
|
|
261
|
+
if (level === 'campaign') await msa(ctx, 'CampaignManagement', 'PUT', 'Campaigns', { AccountId: acct(a), Campaigns: [{ Id: ids(a.id), Status: s }] }, acct(a));
|
|
262
|
+
else if (level === 'adGroup') {
|
|
263
|
+
if (!a.campaignId) throw new AdsError('validation', 'Ad group status needs campaignId.', { field: 'campaignId' });
|
|
264
|
+
await msa(ctx, 'CampaignManagement', 'PUT', 'AdGroups', { CampaignId: ids(a.campaignId), AdGroups: [{ Id: ids(a.id), Status: s }] }, acct(a));
|
|
265
|
+
} else {
|
|
266
|
+
if (!a.adGroupId) throw new AdsError('validation', 'Ad status needs adGroupId.', { field: 'adGroupId' });
|
|
267
|
+
const r = await msa(ctx, 'CampaignManagement', 'POST', 'Ads/QueryByIds', { AdGroupId: ids(a.adGroupId), AdIds: [ids(a.id)], AdTypes: AD_TYPES }, acct(a));
|
|
268
|
+
const type = (r.Ads ?? []).filter(Boolean)[0]?.Type;
|
|
269
|
+
if (!type) throw new AdsError('not_found', `Ad ${a.id} not found.`);
|
|
270
|
+
await msa(ctx, 'CampaignManagement', 'PUT', 'Ads', { AdGroupId: ids(a.adGroupId), Ads: [{ Id: ids(a.id), Type: type, Status: s }] }, acct(a));
|
|
271
|
+
}
|
|
272
|
+
return { id: String(a.id), status };
|
|
273
|
+
},
|
|
274
|
+
},
|
|
275
|
+
setBudget: {
|
|
276
|
+
params: { accountId: { required: true }, id: { required: true, desc: 'Campaign id.' }, amount: { required: true } },
|
|
277
|
+
run: async (ctx, a) => {
|
|
278
|
+
const r = await msa(ctx, 'CampaignManagement', 'POST', 'Campaigns/QueryByIds', { AccountId: acct(a), CampaignIds: [ids(a.id)], CampaignType: 'Search,Shopping,DynamicSearchAds,Audience,PerformanceMax' }, acct(a));
|
|
279
|
+
const c = (r.Campaigns ?? []).filter(Boolean)[0];
|
|
280
|
+
if (!c) throw new AdsError('not_found', `Campaign ${a.id} not found.`);
|
|
281
|
+
if (c.BudgetId > 0) throw new AdsError('refused', `This campaign uses shared budget ${c.BudgetId}; change the shared budget instead.`);
|
|
282
|
+
gateBudget(a, c.DailyBudget);
|
|
283
|
+
await msa(ctx, 'CampaignManagement', 'PUT', 'Campaigns', { AccountId: acct(a), Campaigns: [{ Id: ids(a.id), DailyBudget: toMajor(a.amount) }] }, acct(a));
|
|
284
|
+
return { id: String(a.id), dailyBudget: toMajor(a.amount), previous: c.DailyBudget };
|
|
285
|
+
},
|
|
286
|
+
},
|
|
287
|
+
deleteObject: {
|
|
288
|
+
params: { accountId: { required: true }, id: { required: true }, level: { required: true }, campaignId: { desc: 'Required for level adGroup.' }, adGroupId: { desc: 'Required for level ad.' }, confirm: {}, confirmName: {}, confirmChildren: {} },
|
|
289
|
+
run: async (ctx, a) => {
|
|
290
|
+
const level = pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform);
|
|
291
|
+
const radius = { what: level, children: [] };
|
|
292
|
+
if (level === 'campaign') {
|
|
293
|
+
const c = await ctx.platform.ops.getCampaign.run(ctx, a);
|
|
294
|
+
const groups = (await msa(ctx, 'CampaignManagement', 'POST', 'AdGroups/QueryByCampaignId', { CampaignId: ids(a.id) }, acct(a))).AdGroups ?? [];
|
|
295
|
+
Object.assign(radius, { name: c.name, live: c.status === 'Active' });
|
|
296
|
+
radius.children.push({ label: 'ad groups', count: groups.length });
|
|
297
|
+
gateDelete(a, radius);
|
|
298
|
+
await msa(ctx, 'CampaignManagement', 'DELETE', 'Campaigns', { AccountId: acct(a), CampaignIds: [ids(a.id)] }, acct(a));
|
|
299
|
+
} else if (level === 'adGroup') {
|
|
300
|
+
if (!a.campaignId) throw new AdsError('validation', 'Deleting an ad group needs campaignId.', { field: 'campaignId' });
|
|
301
|
+
const ads = (await msa(ctx, 'CampaignManagement', 'POST', 'Ads/QueryByAdGroupId', { AdGroupId: ids(a.id), AdTypes: AD_TYPES }, acct(a))).Ads ?? [];
|
|
302
|
+
radius.children.push({ label: 'ads', count: ads.length });
|
|
303
|
+
gateDelete(a, radius);
|
|
304
|
+
await msa(ctx, 'CampaignManagement', 'DELETE', 'AdGroups', { CampaignId: ids(a.campaignId), AdGroupIds: [ids(a.id)] }, acct(a));
|
|
305
|
+
} else {
|
|
306
|
+
if (!a.adGroupId) throw new AdsError('validation', 'Deleting an ad needs adGroupId.', { field: 'adGroupId' });
|
|
307
|
+
gateDelete(a, radius);
|
|
308
|
+
await msa(ctx, 'CampaignManagement', 'DELETE', 'Ads', { AdGroupId: ids(a.adGroupId), AdIds: [ids(a.id)] }, acct(a));
|
|
309
|
+
}
|
|
310
|
+
return { deleted: { level, id: String(a.id) } };
|
|
311
|
+
},
|
|
312
|
+
},
|
|
313
|
+
report: {
|
|
314
|
+
params: {
|
|
315
|
+
accountId: { required: true }, since: {}, until: {},
|
|
316
|
+
reportType: { type: 'string', desc: 'Default CampaignPerformanceReportRequest.' }, aggregation: { type: 'string', desc: 'Summary (default), Daily, Weekly, Monthly...' },
|
|
317
|
+
columns: { type: 'array' }, reportRequestId: { type: 'string', desc: 'Resume a pending report.' },
|
|
318
|
+
maxPolls: { type: 'number', desc: 'Default 15.' }, pollMs: { type: 'number', desc: 'Default 6000.' },
|
|
319
|
+
},
|
|
320
|
+
run: async (ctx, a) => {
|
|
321
|
+
let reqId = a.reportRequestId;
|
|
322
|
+
if (!reqId) {
|
|
323
|
+
const { since, until } = dateRange(a);
|
|
324
|
+
const d = (s) => { const [Y, M, D] = s.split('-').map(Number); return { Year: Y, Month: M, Day: D }; };
|
|
325
|
+
const columns = a.columns ?? ['AccountName', 'AccountId', 'CampaignName', 'CampaignId', 'CampaignStatus', 'Impressions', 'Clicks', 'Ctr', 'AverageCpc', 'Spend', 'Conversions', 'ConversionRate', 'CostPerConversion'];
|
|
326
|
+
const r = await msa(ctx, 'Reporting', 'POST', 'GenerateReport/Submit', { ReportRequest: { Type: a.reportType ?? 'CampaignPerformanceReportRequest', Format: 'Csv', ReportName: 'report', ReturnOnlyCompleteData: false, Aggregation: a.aggregation ?? 'Summary', Columns: columns, Scope: { AccountIds: [acct(a)] }, Time: { CustomDateRangeStart: d(since), CustomDateRangeEnd: d(until) } } }, acct(a));
|
|
327
|
+
reqId = r.ReportRequestId;
|
|
328
|
+
}
|
|
329
|
+
const maxPolls = a.maxPolls ?? 15; const pollMs = a.pollMs ?? 6000;
|
|
330
|
+
for (let i = 0; i < maxPolls; i++) {
|
|
331
|
+
const p = await msa(ctx, 'Reporting', 'POST', 'GenerateReport/Poll', { ReportRequestId: reqId }, acct(a));
|
|
332
|
+
const st = p.ReportRequestStatus ?? {};
|
|
333
|
+
if (st.Status === 'Error') throw new AdsError('vendor', 'Microsoft Advertising could not build the report.');
|
|
334
|
+
if (st.Status !== 'Pending') {
|
|
335
|
+
if (!st.ReportDownloadUrl) return { rows: [], note: 'No data for this period.' };
|
|
336
|
+
const res = await ctx.fetch(st.ReportDownloadUrl);
|
|
337
|
+
const text = decompress(Buffer.from(await res.arrayBuffer())).toString('utf8').replace(/^/, '');
|
|
338
|
+
return { rows: csvRows(text) };
|
|
339
|
+
}
|
|
340
|
+
if (i < maxPolls - 1) await new Promise((r) => setTimeout(r, pollMs));
|
|
341
|
+
}
|
|
342
|
+
return { pending: true, reportRequestId: reqId, note: 'Still building; call report again with reportRequestId.' };
|
|
343
|
+
},
|
|
344
|
+
},
|
|
345
|
+
searchTargeting: {
|
|
346
|
+
params: { type: { required: true, enum: ['locations'] }, query: { required: true } },
|
|
347
|
+
run: async (ctx, a) => {
|
|
348
|
+
if (a.type !== 'locations') throw new AdsError('validation', 'type must be "locations".', { field: 'type' });
|
|
349
|
+
const idx = await geoIndex(ctx);
|
|
350
|
+
const q = String(a.query).toLowerCase();
|
|
351
|
+
return { items: idx.filter((g) => g.name.toLowerCase().includes(q)).slice(0, a.limit ?? 25) };
|
|
352
|
+
},
|
|
353
|
+
},
|
|
354
|
+
},
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
/** The report CSV carries a preamble and a footer; find the header row by a known column. */
|
|
358
|
+
function csvRows(text) {
|
|
359
|
+
const rows = parseCsv(text);
|
|
360
|
+
const h = rows.findIndex((r) => r.includes('Impressions') || r.includes('Spend') || r.includes('AccountId') || r.includes('CampaignId'));
|
|
361
|
+
if (h < 0) return [];
|
|
362
|
+
const header = rows[h];
|
|
363
|
+
return rows.slice(h + 1)
|
|
364
|
+
.filter((r) => r.length === header.length && !/^(Total|©)/.test(r[0] ?? ''))
|
|
365
|
+
.map((r) => Object.fromEntries(header.map((k, i) => [k, r[i]])));
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
let GEO_CACHE = null;
|
|
369
|
+
async function geoIndex(ctx) {
|
|
370
|
+
if (GEO_CACHE && Date.now() - GEO_CACHE.at < 7 * 86400000) return GEO_CACHE.rows;
|
|
371
|
+
const r = await msa(ctx, 'CampaignManagement', 'POST', 'GeoLocationsFileUrl/Query', { Version: '2.0', LanguageLocale: 'en', CompressionType: 'GZip' });
|
|
372
|
+
const res = await ctx.fetch(r.FileUrl);
|
|
373
|
+
const rows = parseCsv(decompress(Buffer.from(await res.arrayBuffer())).toString('utf8').replace(/^/, ''));
|
|
374
|
+
const header = rows[0] ?? [];
|
|
375
|
+
const col = (n) => header.indexOf(n);
|
|
376
|
+
const [iId, iName, iType, iStatus] = ['Location Id', 'Bing Display Name', 'Location Type', 'Status'].map(col);
|
|
377
|
+
const out = rows.slice(1).filter((x) => x[iStatus] === 'Active' || iStatus < 0).map((x) => ({ id: x[iId], name: x[iName], type: x[iType] }));
|
|
378
|
+
GEO_CACHE = { at: Date.now(), rows: out };
|
|
379
|
+
return out;
|
|
380
|
+
}
|
|
381
|
+
export const _resetGeoCache = () => { GEO_CACHE = null; };
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { definePlatform, row, pickLevel, dateRange } from '../platform.js';
|
|
3
|
+
import { AdsError } from '../errors.js';
|
|
4
|
+
import { assertBornPaused, gateStatus, gateBudget, gateDelete, checkLength, requireConfirm, STATUS } from '../safety.js';
|
|
5
|
+
import { toMicros, fromMicros } from '../money.js';
|
|
6
|
+
import { hashEmail, hashPhoneDigits } from '../hash.js';
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
const BASE = 'https://api.ads.openai.com/v1';
|
|
10
|
+
const PATH = { campaign: 'campaigns', adGroup: 'ad_groups', ad: 'ads' };
|
|
11
|
+
const GRANULARITY = ['hourly', 'daily', 'monthly', 'none'];
|
|
12
|
+
|
|
13
|
+
function arrayQuery(path, params) {
|
|
14
|
+
const parts = [];
|
|
15
|
+
for (const [k, v] of Object.entries(params)) {
|
|
16
|
+
if (v == null) continue;
|
|
17
|
+
if (Array.isArray(v)) for (const x of v) parts.push(`${encodeURIComponent(k)}[]=${encodeURIComponent(typeof x === 'object' ? JSON.stringify(x) : x)}`);
|
|
18
|
+
else parts.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
|
|
19
|
+
}
|
|
20
|
+
return parts.length ? `${path}?${parts.join('&')}` : path;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const scrub = (s) => (s == null ? s : String(s).replace(/sk-[A-Za-z0-9_*-]{8,}/g, '[key]'));
|
|
24
|
+
|
|
25
|
+
function parseError(status, body) {
|
|
26
|
+
const e = body?.error ?? body;
|
|
27
|
+
const message = scrub(e?.message ?? body?.detail?.map?.((d) => `${d.loc?.join('.')}: ${d.msg}`).join('; ') ?? body?.message);
|
|
28
|
+
if ((status === 401 || status === 403) && !/not enabled|admins/i.test(message ?? '')) {
|
|
29
|
+
return { kind: status === 401 ? 'auth' : 'permission', message, userMessage: `ChatGPT Ads refused the key. It must be an Advertiser API key from Ads Manager > Settings, not a platform API key. ${message ?? ''}`.trim() };
|
|
30
|
+
}
|
|
31
|
+
if (status === 403 && /not enabled/i.test(message ?? '')) return { kind: 'permission', message, userMessage: `ChatGPT Ads: this feature is not switched on for the ad account (the key is fine). ${message}` };
|
|
32
|
+
if (status === 409) return { kind: 'validation', message, userMessage: 'ChatGPT Ads: the object changed before the update applied; nothing changed. Read it again and retry.' };
|
|
33
|
+
return message ? { message, code: e?.code } : null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const post = (ctx, path, json, idempotent = false) => ctx.request({ method: 'POST', path, json, headers: idempotent ? { 'Idempotency-Key': randomUUID() } : {} });
|
|
37
|
+
|
|
38
|
+
export default definePlatform({
|
|
39
|
+
id: 'openai_ads',
|
|
40
|
+
label: 'ChatGPT Ads',
|
|
41
|
+
money: 'micros',
|
|
42
|
+
credentials: [{ name: 'apiKey', required: true, env: 'OPENAI_ADS_API_KEY', desc: 'Advertiser API key from ChatGPT Ads Manager > Settings > API keys (one key = one ad account).' }],
|
|
43
|
+
baseUrl: BASE,
|
|
44
|
+
authHeaders: (c) => ({ authorization: `Bearer ${c.apiKey}` }),
|
|
45
|
+
parseError,
|
|
46
|
+
notes: [
|
|
47
|
+
'One key is one ad account; accountId is not needed.',
|
|
48
|
+
'Creative: a text + image card. Title 3-50 characters, body 1-100. There is no video.',
|
|
49
|
+
'`targeting` and `bidding_config` are REPLACED wholesale on update: send the complete object.',
|
|
50
|
+
'There is no delete: deleteObject archives, which is irreversible.',
|
|
51
|
+
],
|
|
52
|
+
setup: {
|
|
53
|
+
app: 'No developer app: create an Advertiser API key in ChatGPT Ads Manager > Settings > API keys.',
|
|
54
|
+
scopes: ['(API keys carry the ad account\'s permissions; no scopes)'],
|
|
55
|
+
review: 'The ad account itself must be approved to advertise. Some features (target CPA/CPC bidding, daily spend limits) are switched on per account.',
|
|
56
|
+
hosted: { connect: 'own', note: 'ChatGPT Ads issues API keys per ad account.' },
|
|
57
|
+
docs: 'https://developers.openai.com/ads/',
|
|
58
|
+
},
|
|
59
|
+
ops: {
|
|
60
|
+
listAccounts: {
|
|
61
|
+
run: async (ctx, a) => {
|
|
62
|
+
const x = await ctx.request({ path: '/ad_account' });
|
|
63
|
+
return { items: [row(x, { id: x.id, name: x.name ?? x.account_name ?? x.brand_name, status: x.status, currency: x.currency_code, timezone: x.timezone, review: x.review?.status }, a)] };
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
listCampaigns: {
|
|
67
|
+
run: async (ctx, a) => {
|
|
68
|
+
const r = await ctx.request({ path: arrayQuery('/campaigns', { limit: Math.min(a.limit ?? 100, 100), after: a.cursor, include: ['serving_issues'] }) });
|
|
69
|
+
return { items: (r.data ?? []).map((c) => row(c, { id: c.id, name: c.name, status: c.status, objective: c.objective, biddingType: c.bidding_type, dailyBudget: fromMicros(c.budget?.daily_spend_limit_micros), lifetimeBudget: fromMicros(c.budget?.lifetime_spend_limit_micros), servingIssues: c.serving_issues }, a)), next: r.has_more ? r.last_id : null };
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
getCampaign: {
|
|
73
|
+
params: { id: { required: true } },
|
|
74
|
+
run: async (ctx, a) => { const c = await ctx.request({ path: arrayQuery(`/campaigns/${a.id}`, { include: ['serving_issues'] }) }); return row(c, { id: c.id, name: c.name, status: c.status, dailyBudget: fromMicros(c.budget?.daily_spend_limit_micros), servingIssues: c.serving_issues }, a); },
|
|
75
|
+
},
|
|
76
|
+
createCampaign: {
|
|
77
|
+
params: {
|
|
78
|
+
name: { required: true }, dailyBudget: { desc: 'Minimum 25.' }, lifetimeBudget: {}, biddingType: { type: 'string', enum: ['impressions', 'clicks', 'conversions'], desc: 'Default clicks.' },
|
|
79
|
+
conversionEventId: { type: 'string', desc: 'Required for conversions bidding; cannot change later.' }, targeting: { type: 'object', desc: '{locations:{include:[ids]}, platforms:{included:[...]}}' },
|
|
80
|
+
},
|
|
81
|
+
run: async (ctx, a) => {
|
|
82
|
+
assertBornPaused(a, 'campaign');
|
|
83
|
+
if (String(a.name).length < 3) throw new AdsError('validation', 'name needs at least 3 characters.', { field: 'name' });
|
|
84
|
+
if (a.dailyBudget == null && a.lifetimeBudget == null) throw new AdsError('validation', 'Give dailyBudget (minimum 25) or lifetimeBudget.', { field: 'dailyBudget' });
|
|
85
|
+
if (a.dailyBudget != null && Number(a.dailyBudget) < 25) throw new AdsError('validation', 'ChatGPT Ads requires a daily budget of at least 25.', { field: 'dailyBudget' });
|
|
86
|
+
const bidding = a.biddingType ?? 'clicks';
|
|
87
|
+
if (!['impressions', 'clicks', 'conversions'].includes(bidding)) throw new AdsError('validation', 'biddingType must be impressions, clicks or conversions.', { field: 'biddingType' });
|
|
88
|
+
if (bidding === 'conversions' && !a.conversionEventId) throw new AdsError('validation', 'Conversions bidding needs conversionEventId.', { field: 'conversionEventId' });
|
|
89
|
+
const body = { name: a.name, status: 'paused', bidding_type: bidding,
|
|
90
|
+
budget: a.dailyBudget != null ? { daily_spend_limit_micros: toMicros(a.dailyBudget, 'dailyBudget') } : { lifetime_spend_limit_micros: toMicros(a.lifetimeBudget, 'lifetimeBudget') },
|
|
91
|
+
...(a.conversionEventId ? { conversion_event_setting_ids: [a.conversionEventId] } : {}), ...(a.targeting ? { targeting: a.targeting } : {}), ...(a.fields ?? {}) };
|
|
92
|
+
const c = await post(ctx, '/campaigns', body, true);
|
|
93
|
+
return { id: c.id, status: STATUS.PAUSED, stored: c.status };
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
listAdGroups: {
|
|
97
|
+
params: { campaignId: {} },
|
|
98
|
+
run: async (ctx, a) => {
|
|
99
|
+
const r = await ctx.request({ path: arrayQuery('/ad_groups', { campaign_id: a.campaignId, limit: 100, after: a.cursor, include: ['serving_issues'] }) });
|
|
100
|
+
return { items: (r.data ?? []).map((g) => row(g, { id: g.id, name: g.name, status: g.status, campaignId: g.campaign_id, bidding: g.bidding_config, servingIssues: g.serving_issues }, a)), next: r.has_more ? r.last_id : null };
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
createAdGroup: {
|
|
104
|
+
params: {
|
|
105
|
+
campaignId: { required: true }, name: { required: true }, billingEvent: { type: 'string', enum: ['impression', 'click'], desc: 'Default click.' },
|
|
106
|
+
strategy: { type: 'string', desc: 'fixed_bid, maximize_clicks, maximize_conversions, target_cpc, target_cpa.' }, maxBid: { type: 'number' }, target: { type: 'number' },
|
|
107
|
+
contextHints: { type: 'array', desc: 'Topics/questions this ad should appear near (up to 2000).' },
|
|
108
|
+
},
|
|
109
|
+
run: async (ctx, a) => {
|
|
110
|
+
assertBornPaused(a, 'ad group');
|
|
111
|
+
if (String(a.name).length < 3) throw new AdsError('validation', 'name needs at least 3 characters.', { field: 'name' });
|
|
112
|
+
if ((a.contextHints ?? []).length > 2000) throw new AdsError('validation', 'At most 2000 context hints.', { field: 'contextHints' });
|
|
113
|
+
const camp = await ctx.request({ path: `/campaigns/${a.campaignId}` });
|
|
114
|
+
const billing = a.billingEvent ?? (camp.bidding_type === 'impressions' ? 'impression' : 'click');
|
|
115
|
+
const strategy = a.strategy ?? (camp.bidding_type === 'impressions' ? 'fixed_bid' : camp.budget?.daily_spend_limit_micros ? `maximize_${camp.bidding_type}` : 'fixed_bid');
|
|
116
|
+
if (strategy === 'fixed_bid' && a.maxBid == null) throw new AdsError('validation', 'A fixed bid needs maxBid.', { field: 'maxBid' });
|
|
117
|
+
if (strategy.startsWith('target_') && a.target == null) throw new AdsError('validation', `${strategy} needs target.`, { field: 'target' });
|
|
118
|
+
const bidding = { billing_event_type: billing, strategy, ...(a.maxBid != null && strategy === 'fixed_bid' ? { max_bid_micros: toMicros(a.maxBid, 'maxBid') } : {}), ...(a.target != null ? { target_micros: toMicros(a.target, 'target') } : {}) };
|
|
119
|
+
const g = await post(ctx, '/ad_groups', { campaign_id: a.campaignId, name: a.name, status: 'paused', bidding_config: bidding, ...(a.contextHints ? { context_hints: a.contextHints } : {}), ...(a.fields ?? {}) }, true);
|
|
120
|
+
const stored = g.bidding_config ?? {};
|
|
121
|
+
const drift = ['strategy', 'max_bid_micros', 'target_micros'].filter((k) => bidding[k] != null && String(stored[k]) !== String(bidding[k]));
|
|
122
|
+
return { id: g.id, status: STATUS.PAUSED, ...(drift.length ? { warning: `ChatGPT Ads stored a different ${drift.join(', ')} than requested.`, stored } : {}) };
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
listAds: {
|
|
126
|
+
params: { adGroupId: {} },
|
|
127
|
+
run: async (ctx, a) => {
|
|
128
|
+
const r = await ctx.request({ path: arrayQuery('/ads', { ad_group_id: a.adGroupId, limit: 100, after: a.cursor, include: ['serving_issues'] }) });
|
|
129
|
+
return { items: (r.data ?? []).map((x) => row(x, { id: x.id, name: x.name, status: x.status, review: x.review?.status, adGroupId: x.ad_group_id, title: x.creative?.title }, a)), next: r.has_more ? r.last_id : null };
|
|
130
|
+
},
|
|
131
|
+
},
|
|
132
|
+
uploadAsset: {
|
|
133
|
+
params: { url: { type: 'string', required: true, desc: 'Public image URL (no video on this channel).' } },
|
|
134
|
+
run: async (ctx, a) => {
|
|
135
|
+
if (/\.(mp4|mov|webm|m4v)(\?|$)/i.test(a.url)) throw new AdsError('validation', 'ChatGPT Ads has no video format; use an image.', { field: 'url' });
|
|
136
|
+
const r = await post(ctx, '/upload', { image_url: a.url });
|
|
137
|
+
return { fileId: r.file_id ?? r.id };
|
|
138
|
+
},
|
|
139
|
+
},
|
|
140
|
+
createAd: {
|
|
141
|
+
params: {
|
|
142
|
+
adGroupId: { required: true }, name: { required: true }, title: { type: 'string', required: true, desc: '3-50 characters.' }, body: { type: 'string', required: true, desc: '1-100 characters.' },
|
|
143
|
+
targetUrl: { type: 'string', required: true }, fileId: { type: 'string', required: true, desc: 'Image from uploadAsset.' },
|
|
144
|
+
},
|
|
145
|
+
run: async (ctx, a) => {
|
|
146
|
+
assertBornPaused(a, 'ad');
|
|
147
|
+
checkLength('title', a.title, 50);
|
|
148
|
+
if (String(a.title).length < 3) throw new AdsError('validation', 'title needs at least 3 characters.', { field: 'title' });
|
|
149
|
+
checkLength('body', a.body, 100);
|
|
150
|
+
checkLength('targetUrl', a.targetUrl, 2048);
|
|
151
|
+
checkLength('name', a.name, 1000);
|
|
152
|
+
if (!/^https?:\/\//i.test(a.targetUrl)) throw new AdsError('validation', 'targetUrl must be http(s).', { field: 'targetUrl' });
|
|
153
|
+
const ad = await post(ctx, '/ads', { ad_group_id: a.adGroupId, name: a.name, status: 'paused', creative: { type: 'chat_card', title: a.title, body: a.body, target_url: a.targetUrl, file_id: a.fileId }, ...(a.fields ?? {}) }, true);
|
|
154
|
+
return { id: ad.id, status: STATUS.PAUSED, review: ad.review?.status, note: 'Creative enhancements are on by default for this channel and may adjust the copy at serving time.' };
|
|
155
|
+
},
|
|
156
|
+
},
|
|
157
|
+
listAudiences: {
|
|
158
|
+
run: async (ctx, a) => {
|
|
159
|
+
const r = await ctx.request({ path: '/custom_audiences', query: { limit: 100, after: a.cursor } });
|
|
160
|
+
return { items: (r.data ?? []).map((x) => row(x, { id: x.id, name: x.name, size: x.size, status: x.status }, a)), next: r.has_more ? r.last_id : null };
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
createAudience: {
|
|
164
|
+
params: { name: { required: true }, description: { type: 'string' }, emails: { type: 'array' }, phones: { type: 'array' } },
|
|
165
|
+
run: async (ctx, a) => {
|
|
166
|
+
const aud = await post(ctx, '/custom_audiences', { name: a.name, ...(a.description ? { description: a.description } : {}) }, true);
|
|
167
|
+
const identifiers = [
|
|
168
|
+
...(a.emails ?? []).map(hashEmail).filter(Boolean).map((h) => ({ identifier_type: 'email_sha256', identifier: h })),
|
|
169
|
+
...(a.phones ?? []).map(hashPhoneDigits).filter(Boolean).map((h) => ({ identifier_type: 'phone_number_sha256', identifier: h })),
|
|
170
|
+
];
|
|
171
|
+
let op;
|
|
172
|
+
if (identifiers.length) op = await post(ctx, `/custom_audiences/${aud.id}/add`, { identifiers }, true);
|
|
173
|
+
return { id: aud.id, added: identifiers.length, ...(op ? { operationId: op.id } : {}) };
|
|
174
|
+
},
|
|
175
|
+
},
|
|
176
|
+
setStatus: {
|
|
177
|
+
params: { id: { required: true }, level: {}, status: { required: true } },
|
|
178
|
+
run: async (ctx, a) => {
|
|
179
|
+
const status = gateStatus(a);
|
|
180
|
+
const path = PATH[pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform)];
|
|
181
|
+
if (status === STATUS.ARCHIVED) return ctx.platform.ops.deleteObject.run(ctx, a);
|
|
182
|
+
await post(ctx, `/${path}/${a.id}/${status === STATUS.ACTIVE ? 'activate' : 'pause'}`, {});
|
|
183
|
+
return { id: a.id, status, note: 'Reads can lag a status change by a few seconds.' };
|
|
184
|
+
},
|
|
185
|
+
},
|
|
186
|
+
setBudget: {
|
|
187
|
+
params: { id: { required: true, desc: 'Campaign id.' }, amount: { required: true } },
|
|
188
|
+
run: async (ctx, a) => {
|
|
189
|
+
const c = await ctx.request({ path: `/campaigns/${a.id}` });
|
|
190
|
+
const daily = c.budget?.daily_spend_limit_micros != null;
|
|
191
|
+
if (daily && Number(a.amount) < 25) throw new AdsError('validation', 'ChatGPT Ads requires a daily budget of at least 25.', { field: 'amount' });
|
|
192
|
+
gateBudget(a, fromMicros(daily ? c.budget.daily_spend_limit_micros : c.budget?.lifetime_spend_limit_micros));
|
|
193
|
+
await post(ctx, `/campaigns/${a.id}`, { budget: daily ? { daily_spend_limit_micros: toMicros(a.amount) } : { lifetime_spend_limit_micros: toMicros(a.amount) } });
|
|
194
|
+
return { id: a.id, [daily ? 'dailyBudget' : 'lifetimeBudget']: Number(a.amount) };
|
|
195
|
+
},
|
|
196
|
+
},
|
|
197
|
+
updateAdGroup: {
|
|
198
|
+
params: { id: { required: true }, name: {}, contextHints: { type: 'array' }, biddingConfig: { type: 'object', desc: 'The COMPLETE bidding_config (it is replaced wholesale).' } },
|
|
199
|
+
run: async (ctx, a) => {
|
|
200
|
+
const cur = await ctx.request({ path: `/ad_groups/${a.id}` });
|
|
201
|
+
const body = { ...(a.name ? { name: a.name } : {}), ...(a.contextHints ? { context_hints: a.contextHints } : {}), ...(a.fields ?? {}) };
|
|
202
|
+
if (a.biddingConfig) {
|
|
203
|
+
if (!a.biddingConfig.strategy || !a.biddingConfig.billing_event_type) throw new AdsError('validation', 'biddingConfig is replaced wholesale: include billing_event_type and strategy (and the bid fields you want to keep).', { field: 'biddingConfig' });
|
|
204
|
+
if (cur.status === 'active') requireConfirm(a, 'Changing bidding on a live ad group');
|
|
205
|
+
body.bidding_config = a.biddingConfig;
|
|
206
|
+
}
|
|
207
|
+
return { id: a.id, adGroup: await post(ctx, `/ad_groups/${a.id}`, body) };
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
deleteObject: {
|
|
211
|
+
params: { id: { required: true }, level: { required: true }, confirm: {}, confirmName: {}, confirmChildren: {} },
|
|
212
|
+
run: async (ctx, a) => {
|
|
213
|
+
const level = pickLevel(a, { campaign: 'campaign', adGroup: 'adGroup', ad: 'ad' }, ctx.platform);
|
|
214
|
+
const cur = await ctx.request({ path: `/${PATH[level]}/${a.id}` });
|
|
215
|
+
const children = [];
|
|
216
|
+
if (level === 'campaign') children.push({ label: 'ad groups', count: ((await ctx.request({ path: `/ad_groups?campaign_id=${a.id}&limit=100` })).data ?? []).filter((g) => g.status !== 'archived').length });
|
|
217
|
+
if (level === 'adGroup') children.push({ label: 'ads', count: ((await ctx.request({ path: `/ads?ad_group_id=${a.id}&limit=100` })).data ?? []).filter((x) => x.status !== 'archived').length });
|
|
218
|
+
gateDelete(a, { what: level, name: cur.name, children, live: cur.status === 'active', note: 'Archiving is irreversible on ChatGPT Ads.' });
|
|
219
|
+
await post(ctx, `/${PATH[level]}/${a.id}/archive`, {});
|
|
220
|
+
return { id: a.id, status: STATUS.ARCHIVED };
|
|
221
|
+
},
|
|
222
|
+
},
|
|
223
|
+
report: {
|
|
224
|
+
params: {
|
|
225
|
+
level: { type: 'string', enum: ['ad_account', 'campaign', 'ad_group', 'ad'], desc: 'Row level (default campaign).' }, id: { desc: 'Report on one campaign/ad group/ad.' },
|
|
226
|
+
since: {}, until: {}, granularity: { type: 'string', enum: GRANULARITY }, metrics: { type: 'array' }, segments: { type: 'array', desc: 'country, device, platform or product.' },
|
|
227
|
+
},
|
|
228
|
+
run: async (ctx, a) => {
|
|
229
|
+
const { since, until } = dateRange(a);
|
|
230
|
+
if (a.granularity && !GRANULARITY.includes(a.granularity)) throw new AdsError('validation', `granularity must be one of ${GRANULARITY.join(', ')}`, { field: 'granularity' });
|
|
231
|
+
const level = a.level ?? 'campaign';
|
|
232
|
+
const scope = a.id ? `/${{ campaign: 'campaigns', ad_group: 'ad_groups', ad: 'ads' }[level] ?? 'campaigns'}/${a.id}/insights` : '/ad_account/insights';
|
|
233
|
+
const range = JSON.stringify({ type: 'unix_range', start: Date.parse(`${since}T00:00:00Z`) / 1000, end: Date.parse(`${until}T00:00:00Z`) / 1000 + 86400 });
|
|
234
|
+
const r = await ctx.request({ path: arrayQuery(scope, { time_granularity: a.granularity ?? 'none', aggregation_level: level, fields: a.metrics ?? ['impressions', 'clicks', 'spend', 'ctr', 'cpc', 'cpm'], segments: a.segments, time_ranges: [range], limit: Math.min(a.limit ?? 500, 2000), after: a.cursor }) });
|
|
235
|
+
return { rows: r.data ?? [], next: r.has_more ? r.last_id : null, note: 'Time ranges align to the ad account\'s own time zone.' };
|
|
236
|
+
},
|
|
237
|
+
},
|
|
238
|
+
searchTargeting: {
|
|
239
|
+
params: { type: { required: true, enum: ['locations'] }, query: { required: true } },
|
|
240
|
+
run: async (ctx, a) => {
|
|
241
|
+
const r = await ctx.request({ path: '/geo_lookup/search', query: { q: a.query, limit: Math.min(a.limit ?? 25, 50) } });
|
|
242
|
+
return { items: (r.data ?? []).map((x) => ({ id: x.id, name: x.canonical_name ?? x.name, type: x.type, countryCode: x.country_code })) };
|
|
243
|
+
},
|
|
244
|
+
},
|
|
245
|
+
},
|
|
246
|
+
});
|