|
1 | | -import { defineAffiliate, tokenSetup } from '@profullstack/sh1pt-core'; |
| 1 | +import { createHash, createHmac } from 'node:crypto'; |
| 2 | +import { defineAffiliate, tokenSetup, type AffiliateConnectContext } from '@profullstack/sh1pt-core'; |
2 | 3 |
|
3 | 4 | interface Config { |
| 5 | + accessKey?: string; |
4 | 6 | accountId?: string; |
| 7 | + apiHost?: string; |
| 8 | + marketplace?: string; |
| 9 | + marketplaceHost?: string; |
| 10 | + partnerTag?: string; |
| 11 | + region?: string; |
| 12 | + subtag?: string; |
5 | 13 | } |
6 | 14 |
|
| 15 | +const DEFAULT_API_HOST = 'webservices.amazon.com'; |
| 16 | +const DEFAULT_MARKETPLACE_HOST = 'www.amazon.com'; |
| 17 | +const DEFAULT_REGION = 'us-east-1'; |
| 18 | +const SERVICE = 'ProductAdvertisingAPI'; |
| 19 | + |
7 | 20 | export default defineAffiliate<Config>({ |
8 | | - id: "affiliate-amazon-associates", |
9 | | - label: "Amazon Associates / PAAPI", |
10 | | - side: "publisher", |
| 21 | + id: 'affiliate-amazon-associates', |
| 22 | + label: 'Amazon Associates / PA-API', |
| 23 | + side: 'publisher', |
11 | 24 |
|
12 | 25 | async connect(ctx, config) { |
13 | | - const token = ctx.secret("AMAZON_PAAPI_SECRET"); |
14 | | - if (!token) throw new Error("AMAZON_PAAPI_SECRET not in vault — run `sh1pt promote affiliates setup`"); |
15 | | - return { accountId: config.accountId ?? "affiliate-amazon-associates" }; |
16 | | - }, |
17 | | - |
18 | | - async createProgram(ctx, program) { |
19 | | - ctx.log(`[stub] ${"affiliate-amazon-associates"} createProgram name=${program.name} commission=${program.commissionRate}${program.commissionType === 'percentage' ? '%' : ''}`); |
20 | | - return { |
21 | | - programId: `stub-${Date.now()}`, |
22 | | - marketplaceUrl: "https://affiliate-program.amazon.com", |
23 | | - }; |
24 | | - }, |
25 | | - |
26 | | - async getTrackingLink(ctx, programId, destinationUrl) { |
27 | | - ctx.log(`[stub] ${"affiliate-amazon-associates"} getTrackingLink program=${programId}`); |
28 | | - return { url: destinationUrl }; |
| 26 | + const partnerTag = requirePartnerTag(config); |
| 27 | + await paapiRequest(ctx, config, 'SearchItems', { |
| 28 | + Keywords: 'sh1pt', |
| 29 | + SearchIndex: 'All', |
| 30 | + ItemCount: 1, |
| 31 | + PartnerTag: partnerTag, |
| 32 | + PartnerType: 'Associates', |
| 33 | + Marketplace: marketplace(config), |
| 34 | + Resources: ['ItemInfo.Title'], |
| 35 | + }); |
| 36 | + return { accountId: config.accountId ?? partnerTag }; |
29 | 37 | }, |
30 | 38 |
|
31 | | - async stats(ctx, programId) { |
32 | | - ctx.log(`[stub] ${"affiliate-amazon-associates"} stats program=${programId}`); |
33 | | - return { publishers: 0, clicks: 0, conversions: 0, revenue: 0, commissionsPaid: 0, currency: 'USD' }; |
| 39 | + async getTrackingLink(ctx, programId, destinationUrl, config) { |
| 40 | + const partnerTag = requirePartnerTag(config); |
| 41 | + ctx.log(`amazon associates link · asin=${programId}`); |
| 42 | + const url = new URL(destinationUrl || `https://${marketplaceHost(config)}/dp/${encodeURIComponent(programId)}`); |
| 43 | + if (!url.searchParams.has('tag')) url.searchParams.set('tag', partnerTag); |
| 44 | + const subtag = cleanSubtag(config.subtag); |
| 45 | + if (subtag && !url.searchParams.has('ascsubtag')) url.searchParams.set('ascsubtag', subtag); |
| 46 | + return { url: url.toString() }; |
34 | 47 | }, |
35 | 48 |
|
36 | 49 | setup: tokenSetup<Config>({ |
37 | | - secretKey: "AMAZON_PAAPI_SECRET", |
38 | | - label: "Amazon Associates / PAAPI", |
39 | | - vendorDocUrl: "https://affiliate-program.amazon.com", |
| 50 | + secretKey: 'AMAZON_PAAPI_SECRET', |
| 51 | + label: 'Amazon Associates / PA-API', |
| 52 | + vendorDocUrl: 'https://webservices.amazon.com/paapi5/documentation/', |
40 | 53 | steps: [ |
41 | | - "Join affiliate-program.amazon.com (per region)", |
42 | | - "Apply for the Product Advertising API (requires 3 sales)", |
43 | | - "Generate access key + secret in IAM; paste the secret below", |
| 54 | + 'Join Amazon Associates for the target marketplace', |
| 55 | + 'Apply for Product Advertising API access and create access credentials', |
| 56 | + 'Paste the PA-API secret key below; enter the access key and partner tag as fields', |
| 57 | + ], |
| 58 | + fields: [ |
| 59 | + { |
| 60 | + key: 'accessKey', |
| 61 | + message: 'Amazon PA-API access key:', |
| 62 | + }, |
| 63 | + { |
| 64 | + key: 'partnerTag', |
| 65 | + message: 'Amazon Associates partner tag, for example example-20:', |
| 66 | + }, |
| 67 | + { |
| 68 | + key: 'marketplaceHost', |
| 69 | + message: 'Marketplace host for tagged links (default: www.amazon.com):', |
| 70 | + }, |
44 | 71 | ], |
45 | 72 | }), |
46 | 73 | }); |
| 74 | + |
| 75 | +async function paapiRequest( |
| 76 | + ctx: AffiliateConnectContext, |
| 77 | + config: Config, |
| 78 | + operation: 'SearchItems' | 'GetItems', |
| 79 | + payload: Record<string, unknown>, |
| 80 | +): Promise<unknown> { |
| 81 | + const accessKey = requireValue(config.accessKey, 'Amazon PA-API accessKey is required'); |
| 82 | + const secretKey = requireValue(ctx.secret('AMAZON_PAAPI_SECRET'), 'AMAZON_PAAPI_SECRET not in vault'); |
| 83 | + const apiHost = config.apiHost ?? DEFAULT_API_HOST; |
| 84 | + const region = config.region ?? DEFAULT_REGION; |
| 85 | + const path = `/paapi5/${operation.toLowerCase()}`; |
| 86 | + const body = JSON.stringify(payload); |
| 87 | + const now = new Date(); |
| 88 | + const amzDate = amzTimestamp(now); |
| 89 | + const dateStamp = amzDate.slice(0, 8); |
| 90 | + const target = `com.amazon.paapi5.v1.ProductAdvertisingAPIv1.${operation}`; |
| 91 | + const headers = signedHeaders({ |
| 92 | + accessKey, |
| 93 | + apiHost, |
| 94 | + amzDate, |
| 95 | + body, |
| 96 | + dateStamp, |
| 97 | + path, |
| 98 | + region, |
| 99 | + secretKey, |
| 100 | + target, |
| 101 | + }); |
| 102 | + const res = await fetch(`https://${apiHost}${path}`, { |
| 103 | + method: 'POST', |
| 104 | + headers, |
| 105 | + body, |
| 106 | + }); |
| 107 | + if (!res.ok) { |
| 108 | + const text = await res.text(); |
| 109 | + throw new Error(`Amazon PA-API ${res.status}: ${redact(text, [accessKey, secretKey]).slice(0, 200)}`); |
| 110 | + } |
| 111 | + return res.json(); |
| 112 | +} |
| 113 | + |
| 114 | +function signedHeaders(input: { |
| 115 | + accessKey: string; |
| 116 | + apiHost: string; |
| 117 | + amzDate: string; |
| 118 | + body: string; |
| 119 | + dateStamp: string; |
| 120 | + path: string; |
| 121 | + region: string; |
| 122 | + secretKey: string; |
| 123 | + target: string; |
| 124 | +}): Record<string, string> { |
| 125 | + const canonicalHeaders = [ |
| 126 | + 'content-encoding:amz-1.0', |
| 127 | + 'content-type:application/json; charset=utf-8', |
| 128 | + `host:${input.apiHost}`, |
| 129 | + `x-amz-date:${input.amzDate}`, |
| 130 | + `x-amz-target:${input.target}`, |
| 131 | + '', |
| 132 | + ].join('\n'); |
| 133 | + const signedHeaderNames = 'content-encoding;content-type;host;x-amz-date;x-amz-target'; |
| 134 | + const canonicalRequest = [ |
| 135 | + 'POST', |
| 136 | + input.path, |
| 137 | + '', |
| 138 | + canonicalHeaders, |
| 139 | + signedHeaderNames, |
| 140 | + sha256(input.body), |
| 141 | + ].join('\n'); |
| 142 | + const credentialScope = `${input.dateStamp}/${input.region}/${SERVICE}/aws4_request`; |
| 143 | + const stringToSign = [ |
| 144 | + 'AWS4-HMAC-SHA256', |
| 145 | + input.amzDate, |
| 146 | + credentialScope, |
| 147 | + sha256(canonicalRequest), |
| 148 | + ].join('\n'); |
| 149 | + const signature = hmacHex(signingKey(input.secretKey, input.dateStamp, input.region), stringToSign); |
| 150 | + return { |
| 151 | + accept: 'application/json', |
| 152 | + 'content-encoding': 'amz-1.0', |
| 153 | + 'content-type': 'application/json; charset=utf-8', |
| 154 | + host: input.apiHost, |
| 155 | + 'x-amz-date': input.amzDate, |
| 156 | + 'x-amz-target': input.target, |
| 157 | + authorization: [ |
| 158 | + `AWS4-HMAC-SHA256 Credential=${input.accessKey}/${credentialScope}`, |
| 159 | + `SignedHeaders=${signedHeaderNames}`, |
| 160 | + `Signature=${signature}`, |
| 161 | + ].join(', '), |
| 162 | + }; |
| 163 | +} |
| 164 | + |
| 165 | +function signingKey(secretKey: string, dateStamp: string, region: string): Buffer { |
| 166 | + const kDate = hmac(Buffer.from(`AWS4${secretKey}`, 'utf8'), dateStamp); |
| 167 | + const kRegion = hmac(kDate, region); |
| 168 | + const kService = hmac(kRegion, SERVICE); |
| 169 | + return hmac(kService, 'aws4_request'); |
| 170 | +} |
| 171 | + |
| 172 | +function hmac(key: Buffer | string, data: string): Buffer { |
| 173 | + return createHmac('sha256', key).update(data, 'utf8').digest(); |
| 174 | +} |
| 175 | + |
| 176 | +function hmacHex(key: Buffer | string, data: string): string { |
| 177 | + return createHmac('sha256', key).update(data, 'utf8').digest('hex'); |
| 178 | +} |
| 179 | + |
| 180 | +function sha256(value: string): string { |
| 181 | + return createHash('sha256').update(value, 'utf8').digest('hex'); |
| 182 | +} |
| 183 | + |
| 184 | +function amzTimestamp(date: Date): string { |
| 185 | + return date.toISOString().replace(/[:-]|\.\d{3}/g, ''); |
| 186 | +} |
| 187 | + |
| 188 | +function marketplace(config: Config): string { |
| 189 | + return `www.${marketplaceHost(config).replace(/^www\./, '')}`; |
| 190 | +} |
| 191 | + |
| 192 | +function marketplaceHost(config: Config): string { |
| 193 | + return config.marketplaceHost ?? config.marketplace ?? DEFAULT_MARKETPLACE_HOST; |
| 194 | +} |
| 195 | + |
| 196 | +function requirePartnerTag(config: Config): string { |
| 197 | + return requireValue(config.partnerTag ?? config.accountId, 'Amazon Associates partnerTag is required'); |
| 198 | +} |
| 199 | + |
| 200 | +function requireValue(value: string | undefined, message: string): string { |
| 201 | + if (!value) throw new Error(message); |
| 202 | + return value; |
| 203 | +} |
| 204 | + |
| 205 | +function cleanSubtag(value: string | undefined): string | undefined { |
| 206 | + if (!value) return undefined; |
| 207 | + return value.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 100); |
| 208 | +} |
| 209 | + |
| 210 | +function redact(value: string, secrets: string[]): string { |
| 211 | + return secrets.reduce((text, secret) => text.split(secret).join('[redacted]'), value); |
| 212 | +} |
0 commit comments