|
1 | | -import { defineAffiliate, tokenSetup } from '@profullstack/sh1pt-core'; |
| 1 | +import { defineAffiliate, tokenSetup, type AffiliateConnectContext } from '@profullstack/sh1pt-core'; |
2 | 2 |
|
3 | 3 | interface Config { |
4 | 4 | accountId?: string; |
| 5 | + adId?: string; |
| 6 | + baseUrl?: string; |
| 7 | + clickRef?: string; |
| 8 | + clickRef2?: string; |
| 9 | + currency?: string; |
| 10 | + trackingBaseUrl?: string; |
5 | 11 | } |
6 | 12 |
|
| 13 | +const DEFAULT_API_BASE = 'https://api.tradedoubler.com'; |
| 14 | +const DEFAULT_TRACKING_BASE = 'https://clk.tradedoubler.com'; |
| 15 | +const PRODUCT_TOKEN_KEY = 'TRADEDOUBLER_API_TOKEN'; |
| 16 | +const PUBLISHER_ID_KEY = 'TRADEDOUBLER_PUBLISHER_ID'; |
| 17 | + |
7 | 18 | export default defineAffiliate<Config>({ |
8 | | - id: "affiliate-tradedoubler", |
9 | | - label: "Tradedoubler", |
10 | | - side: "both", |
| 19 | + id: 'affiliate-tradedoubler', |
| 20 | + label: 'Tradedoubler', |
| 21 | + side: 'publisher', |
11 | 22 |
|
12 | 23 | async connect(ctx, config) { |
13 | | - const token = ctx.secret("TRADEDOUBLER_API_TOKEN"); |
14 | | - if (!token) throw new Error("TRADEDOUBLER_API_TOKEN not in vault — run `sh1pt promote affiliates setup`"); |
15 | | - return { accountId: config.accountId ?? "affiliate-tradedoubler" }; |
16 | | - }, |
17 | | - |
18 | | - async createProgram(ctx, program) { |
19 | | - ctx.log(`[stub] ${"affiliate-tradedoubler"} createProgram name=${program.name} commission=${program.commissionRate}${program.commissionType === 'percentage' ? '%' : ''}`); |
| 24 | + const feeds = await tradedoublerGet(ctx, config, '/1.0/productFeeds.json'); |
| 25 | + const firstFeed = collectItems(feeds, ['feeds'])[0]; |
20 | 26 | return { |
21 | | - programId: `stub-${Date.now()}`, |
22 | | - marketplaceUrl: "https://www.tradedoubler.com", |
| 27 | + accountId: |
| 28 | + config.accountId |
| 29 | + ?? ctx.secret(PUBLISHER_ID_KEY) |
| 30 | + ?? stringField(firstFeed, ['siteId', 'publisherId']) |
| 31 | + ?? 'affiliate-tradedoubler', |
23 | 32 | }; |
24 | 33 | }, |
25 | 34 |
|
26 | | - async getTrackingLink(ctx, programId, destinationUrl) { |
27 | | - ctx.log(`[stub] ${"affiliate-tradedoubler"} getTrackingLink program=${programId}`); |
28 | | - return { url: destinationUrl }; |
| 35 | + async getTrackingLink(ctx, programId, destinationUrl, config) { |
| 36 | + ctx.log(`tradedoubler tracking link · program=${programId}`); |
| 37 | + const publisherId = config.accountId ?? ctx.secret(PUBLISHER_ID_KEY); |
| 38 | + if (!publisherId) throw new Error('Tradedoubler accountId / publisher id is required'); |
| 39 | + if (!destinationUrl) throw new Error('Tradedoubler destinationUrl is required'); |
| 40 | + try { |
| 41 | + new URL(destinationUrl); |
| 42 | + } catch { |
| 43 | + throw new Error('Tradedoubler destinationUrl must be an absolute URL'); |
| 44 | + } |
| 45 | + const parts = [ |
| 46 | + matrixPart('a', publisherId), |
| 47 | + matrixPart('p', programId), |
| 48 | + ]; |
| 49 | + if (config.adId) parts.push(matrixPart('g', config.adId)); |
| 50 | + if (config.clickRef) parts.push(matrixPart('epi', config.clickRef)); |
| 51 | + if (config.clickRef2) parts.push(matrixPart('epi2', config.clickRef2)); |
| 52 | + parts.push(matrixPart('url', destinationUrl, true)); |
| 53 | + return { |
| 54 | + url: `${trimSlash(config.trackingBaseUrl ?? DEFAULT_TRACKING_BASE)}/click?${parts.join('')}`, |
| 55 | + }; |
29 | 56 | }, |
30 | 57 |
|
31 | | - async stats(ctx, programId) { |
32 | | - ctx.log(`[stub] ${"affiliate-tradedoubler"} stats program=${programId}`); |
33 | | - return { publishers: 0, clicks: 0, conversions: 0, revenue: 0, commissionsPaid: 0, currency: 'USD' }; |
| 58 | + async stats(ctx, programId, config) { |
| 59 | + ctx.log(`tradedoubler product-feed stats · program=${programId}`); |
| 60 | + const data = await tradedoublerGet(ctx, config, '/1.0/productFeeds.json', { programId }); |
| 61 | + const feeds = collectItems(data, ['feeds']); |
| 62 | + const matchingFeeds = feeds.filter((feed) => feedMatchesProgram(feed, programId)); |
| 63 | + const scopedFeeds = matchingFeeds.length > 0 ? matchingFeeds : feeds; |
| 64 | + return { |
| 65 | + publishers: scopedFeeds.length > 0 ? 1 : 0, |
| 66 | + clicks: 0, |
| 67 | + conversions: 0, |
| 68 | + revenue: 0, |
| 69 | + commissionsPaid: 0, |
| 70 | + currency: |
| 71 | + firstString(scopedFeeds, ['currencyISOCode', 'currency']) |
| 72 | + ?? config.currency |
| 73 | + ?? 'EUR', |
| 74 | + }; |
34 | 75 | }, |
35 | 76 |
|
36 | 77 | setup: tokenSetup<Config>({ |
37 | | - secretKey: "TRADEDOUBLER_API_TOKEN", |
38 | | - label: "Tradedoubler", |
39 | | - vendorDocUrl: "https://www.tradedoubler.com", |
| 78 | + secretKey: PRODUCT_TOKEN_KEY, |
| 79 | + label: 'Tradedoubler', |
| 80 | + vendorDocUrl: 'https://dev.tradedoubler.com/products/publisher/', |
40 | 81 | steps: [ |
41 | | - "Log into tradedoubler.com → My Account → API", |
42 | | - "Generate a token", |
43 | | - "Paste below", |
| 82 | + 'Open the Tradedoubler publisher interface and create a Products API token', |
| 83 | + 'Paste the Products API token below', |
| 84 | + 'Optionally store TRADEDOUBLER_PUBLISHER_ID or set accountId for direct click tracking links', |
| 85 | + ], |
| 86 | + fields: [ |
| 87 | + { |
| 88 | + key: 'accountId', |
| 89 | + message: 'Optional Tradedoubler publisher id used in click tracking URLs:', |
| 90 | + }, |
| 91 | + { |
| 92 | + key: 'clickRef', |
| 93 | + message: 'Optional EPI value to attach to tracking links:', |
| 94 | + }, |
| 95 | + { |
| 96 | + key: 'clickRef2', |
| 97 | + message: 'Optional EPI2 value to attach to tracking links:', |
| 98 | + }, |
44 | 99 | ], |
45 | 100 | }), |
46 | 101 | }); |
| 102 | + |
| 103 | +type TdRecord = Record<string, unknown>; |
| 104 | + |
| 105 | +async function tradedoublerGet( |
| 106 | + ctx: AffiliateConnectContext, |
| 107 | + config: Config, |
| 108 | + path: string, |
| 109 | + matrix: Record<string, string | number | undefined> = {}, |
| 110 | +): Promise<unknown> { |
| 111 | + const token = ctx.secret(PRODUCT_TOKEN_KEY); |
| 112 | + if (!token) throw new Error(`${PRODUCT_TOKEN_KEY} not in vault`); |
| 113 | + const url = new URL(`${trimSlash(config.baseUrl ?? DEFAULT_API_BASE)}${withMatrix(path, matrix)}`); |
| 114 | + url.searchParams.set('token', token); |
| 115 | + const res = await fetch(url, { |
| 116 | + headers: { |
| 117 | + accept: 'application/json', |
| 118 | + }, |
| 119 | + }); |
| 120 | + if (!res.ok) { |
| 121 | + const text = await res.text(); |
| 122 | + throw new Error(`Tradedoubler ${res.status}: ${redact(text, token).slice(0, 200)}`); |
| 123 | + } |
| 124 | + return res.json(); |
| 125 | +} |
| 126 | + |
| 127 | +function withMatrix(path: string, matrix: Record<string, string | number | undefined>): string { |
| 128 | + const suffix = Object.entries(matrix) |
| 129 | + .filter(([, value]) => value !== undefined && String(value).length > 0) |
| 130 | + .map(([key, value]) => `;${key}=${encodeURIComponent(String(value))}`) |
| 131 | + .join(''); |
| 132 | + return `${path}${suffix}`; |
| 133 | +} |
| 134 | + |
| 135 | +function matrixPart(key: string, value: string, encodeFullUrl = false): string { |
| 136 | + return `${key}(${encodeFullUrl ? encodeURIComponent(value) : encodeMatrixValue(value)})`; |
| 137 | +} |
| 138 | + |
| 139 | +function encodeMatrixValue(value: string): string { |
| 140 | + return encodeURIComponent(value).replace(/%2F/gi, '/'); |
| 141 | +} |
| 142 | + |
| 143 | +function feedMatchesProgram(feed: TdRecord, programId: string): boolean { |
| 144 | + if (stringField(feed, ['programId', 'id']) === programId) return true; |
| 145 | + const programs = feed.programs; |
| 146 | + if (!Array.isArray(programs)) return false; |
| 147 | + return programs |
| 148 | + .filter(isRecord) |
| 149 | + .some((program) => stringField(program, ['programId', 'id']) === programId); |
| 150 | +} |
| 151 | + |
| 152 | +function collectItems(data: unknown, keys: string[]): TdRecord[] { |
| 153 | + if (Array.isArray(data)) return data.filter(isRecord); |
| 154 | + if (!isRecord(data)) return []; |
| 155 | + for (const key of keys) { |
| 156 | + const value = data[key]; |
| 157 | + if (Array.isArray(value)) return value.filter(isRecord); |
| 158 | + } |
| 159 | + if (Array.isArray(data.items)) return data.items.filter(isRecord); |
| 160 | + if (Array.isArray(data.data)) return data.data.filter(isRecord); |
| 161 | + return [data]; |
| 162 | +} |
| 163 | + |
| 164 | +function isRecord(value: unknown): value is TdRecord { |
| 165 | + return typeof value === 'object' && value !== null; |
| 166 | +} |
| 167 | + |
| 168 | +function stringField(item: TdRecord | undefined, keys: string[]): string | undefined { |
| 169 | + if (!item) return undefined; |
| 170 | + for (const key of keys) { |
| 171 | + const value = item[key]; |
| 172 | + if (typeof value === 'string' && value.length > 0) return value; |
| 173 | + if (typeof value === 'number' && Number.isFinite(value)) return String(value); |
| 174 | + } |
| 175 | + return undefined; |
| 176 | +} |
| 177 | + |
| 178 | +function firstString(items: TdRecord[], keys: string[]): string | undefined { |
| 179 | + for (const item of items) { |
| 180 | + const value = stringField(item, keys); |
| 181 | + if (value) return value; |
| 182 | + } |
| 183 | + return undefined; |
| 184 | +} |
| 185 | + |
| 186 | +function redact(text: string, ...values: Array<string | undefined>): string { |
| 187 | + let redacted = text; |
| 188 | + for (const value of values) { |
| 189 | + if (value) redacted = redacted.split(value).join('[redacted]'); |
| 190 | + } |
| 191 | + return redacted; |
| 192 | +} |
| 193 | + |
| 194 | +function trimSlash(value: string): string { |
| 195 | + return value.replace(/\/+$/, ''); |
| 196 | +} |
0 commit comments