Skip to content

Affonso API

github-actions[bot] edited this page Dec 2, 2026 · 1 revision

Affonso API

Client configuration and endpoint methods for @tundraconnect/affonso.

Configuration

import { Affonso } from '@tundraconnect/affonso';

const client = new Affonso({
  auth: { type: 'BEARER', token: 'sk_live_your_api_key' },
});
Option Type Required Default Description
auth AffonsoAuth yes — { type: 'BEARER', token, prefix? }; prefix defaults to Bearer.
baseURL string no https://api.affonso.io/v1 A proxy or test server.
timeout number no 30 Request timeout in seconds.
maxRetryWait number no — Opt into one wait-and-retry on a 429 (see Errors).
defaultRetryWait number no — The wait for a 429 that carries no hint.

Generate the API key in the Affonso dashboard under the affiliate program's Connect → API page. It is shown once. The key selects the program — there is no program-id option — and carries permissions (read:affiliates, write:affiliates, read:referrals, write:referrals, create:clicks, read:commissions, write:commissions, read:payouts, write:payouts); a call the key is not scoped for fails with FORBIDDEN.

Affonso has no sandbox yet: sk_dev_ keys are documented as "coming soon", so every write reaches your real program.

Getters

Getter Type Description
vendor string Always 'Affonso'.

Conventions

  • Validation. Every request body is checked before it is sent and fails with REQUEST_VALIDATION_ERROR. Unknown fields are rejected, not dropped, and numbers and booleans must not arrive as strings. Blank path ids and out-of-range page/limit values are rejected the same way.
  • Amounts are decimal numbers in major units: 99 is $99.00.
  • Field names follow the wire format. Most resources are snake_case; payouts and clicks are camelCase. Statuses are lowercase on the REST API and UPPERCASE in webhooks.
  • The { success, data } envelope is unwrapped: methods return data.

Pagination

Affiliates, commissions, payouts and coupons are page-numbered (page from 1, limit up to 200, default 50). Their list* method returns { data, pagination }, where pagination is an AffonsoPageInfo: { page, limit, total, totalPages, hasNextPage, hasPrevPage }. Affonso spells this block camelCase on some endpoints and snake_case on commissions; the client normalizes both, and derives totalPages and the flags from total/limit if they are missing.

Referrals are cursor-paginated (limit up to 100, default 10): listReferrals returns { data, hasMore }; pass the last referral's id as startingAfter for the next page.

Every list has a listAll* async iterator that walks all pages, stopping when the vendor reports no next page, a page is empty, or maxPages (default 1000) pages have been read. Without limit it requests 100 per page.

import { Affonso } from '@tundraconnect/affonso';

const client = new Affonso({
  auth: { type: 'BEARER', token: 'sk_live_your_api_key' },
});

const pending = await Array.fromAsync(
  client.listAllAffiliates({ partnershipStatus: 'pending' }),
);
console.log(pending.length);

Affiliates

Method Endpoint Result
listAffiliates(options?) GET /affiliates AffonsoPage<AffiliateSchema>
listAllAffiliates(options?) GET /affiliates, every page AsyncGenerator<AffiliateSchema>
getAffiliate(id, { expand? }) GET /affiliates/{id} AffiliateSchema
createAffiliate(request) POST /affiliates AffiliateSchema
updateAffiliate(id, update) PUT /affiliates/{id} AffiliateSchema
deleteAffiliate(id) DELETE /affiliates/{id} void
createPortalToken(id) POST /affiliates/{id}/portal-token PortalTokenSchema

listAffiliates filters: partnershipStatus (pending/approved/ rejected), search (name, email or tracking id), groupId, sort (createdAt|updatedAt|name|partnershipStatus + :asc|:desc), createdGte, createdLte, and expand.

expand takes any of promoCodes, commissionOverrides, invoiceDetails and payoutMethod; the extra data appears on the affiliate under those keys.

createAffiliate approves the affiliate unless status says otherwise, and generates tracking_id from the name when none is given (a taken one is a CONFLICT). updateAffiliate sends only what you pass; null clears a nullable field. Sending payout_method without payout_details changes only the method — stored credentials stay.

deleteAffiliate is irreversible: the affiliate's referrals, commissions and partnerships are deleted with it.

createPortalToken returns { token, portalUrl, expiresAt }: redirect the affiliate to portalUrl to sign them into the hosted portal. The token is single-use and valid for 5 minutes; mint one per redirect. The affiliate must be active.

Server-side tracking

Method Endpoint Result
trackClick(request) POST /clicks ClickSchema
recordSignup(request) POST /signups ReferralSchema
createConversion(request) POST /conversions ConversionSchema
refundConversion(id, request?) POST /conversions/{id}/refund ConversionSchema

The flow without the browser pixel: trackClick when a visitor arrives on an affiliate link (keep the returned id), recordSignup with that id when they sign up, and createConversion when they pay.

  • trackClick is camelCase (trackingId, utmSource, userAgent, gclid, ...). The click id is also a valid referral_id for a conversion. This endpoint has its own burst rate limit.
  • recordSignup needs click_id and at least one of email / external_user_id (checked locally). It is idempotent per click. A fraud rule in BLOCK mode still succeeds, with status: 'rejected' — check it.
  • createConversion needs sale_amount, an external_event_id idempotency key, and at least one of referral_id (or affonso_id), customer_id or external_user_id (checked locally). Affonso tries external_user_id, then referral_id, then customer_id. Reusing an external_event_id returns the existing conversion rather than a duplicate. A sale that earns nothing still succeeds, with commission_created: false and activity_outcome: 'sale_recorded'.
  • refundConversion without amount refunds the whole remaining sale and marks the commission refunded; with one, the commission shrinks proportionally and sales_status becomes partial_refunded.

Referrals

Method Endpoint Result
listReferrals(options?) GET /referrals AffonsoCursorPage<ReferralSchema>
listAllReferrals(options?) GET /referrals, every page AsyncGenerator<ReferralSchema>
getReferral(id, options?) GET /referrals/{id} ReferralSchema
createReferral(request) POST /referrals ReferralSchema
updateReferral(id, update) PUT /referrals/{id} ReferralSchema
deleteReferral(id) DELETE /referrals/{id} void

listReferrals filters: affiliateId, externalUserId, status, order (asc/desc, newest first by default), createdGte, createdLte, and expandAffiliate. Clicks are not listed. getReferral takes expandAffiliate and includeStats (revenue, commission and order totals).

createReferral can convert an existing click via click_id. A status other than lead sets converted_at. A referral email must be unique in the program (CONFLICT otherwise).

deleteReferral is irreversible and deletes the referral's commission transactions too.

Commissions

Method Endpoint Result
listCommissions(options?) GET /commissions AffonsoPage<CommissionSchema>
listAllCommissions(options?) GET /commissions, every page AsyncGenerator<CommissionSchema>
getCommission(id, { expand? }) GET /commissions/{id} CommissionSchema
createCommission(request) POST /commissions CommissionSchema
createBonus(request) POST /commissions/bonus BonusSchema
updateCommission(id, update) PUT /commissions/{id} CommissionSchema
deleteCommission(id) DELETE /commissions/{id} void

listCommissions filters: affiliateId, referralId, status, salesStatus, createdGte, createdLte, and expand (affiliate, affiliate_program, referral).

createCommission records a sale commission by hand — you give the commission amount. Prefer createConversion, which calculates it. createBonus credits an affiliate with no sale or referral behind it; the bonus is ready_for_payment at once.

Status values you may set: pending, pending_manual_approval, ready_for_payment, paid, declined. Affonso may also report processing_payout, refunded and dispute. A paid commission cannot be deleted.

Payouts

Method Endpoint Result
listPayouts(options?) GET /payouts AffonsoPage<PayoutSchema>
listAllPayouts(options?) GET /payouts, every page AsyncGenerator<PayoutSchema>
getPayout(id) GET /payouts/{id} PayoutSchema
updatePayout(id, update) PUT /payouts/{id} PayoutSchema

Payouts are camelCase. listPayouts filters: status, affiliateId, sort (createdAt|updatedAt|amount|processedAt + :asc|:desc), dateFrom, dateTo (dates, YYYY-MM-DD). getPayout includes the payout's transactions.

updatePayout requires status. Affonso validates the transition: pending → processing | cancelled, processing → completed | failed | cancelled, failed → pending | cancelled, cancelled → pending; completed is final. Completing a payout marks every commission in it paid.

Coupons

Method Endpoint Result
listCoupons(options?) GET /coupons AffonsoPage<CouponSchema>
listAllCoupons(options?) GET /coupons, every page AsyncGenerator<CouponSchema>
getCoupon(id, { expandAffiliate? }) GET /coupons/{id} CouponSchema
createCoupon(request) POST /coupons CouponSchema
deleteCoupon(id) DELETE /coupons/{id} void

A coupon is created at your payment provider too and linked to the affiliate. createCoupon checks locally that repeating comes with duration_in_months, fixed with currency, and a percentage is at most 100. Provider rules Affonso enforces: Dodo supports only percentages; Creem needs a product_ids entry. A provider failure is a 502 (SERVICE_UNAVAILABLE). deleteCoupon removes it at the provider as well and frees the code.

Program

getProgram() — GET /program — returns the program the key belongs to, with its plan (tier, postbacks, groups_limit).

Webhooks

verifyWebhook({ payload, headers, secret, toleranceSeconds?, nowMs? }) checks a delivery and returns the parsed WebhookEventSchema ({ id, type, createdAt, data }).

Affonso sends X-Affonso-Timestamp (Unix seconds) and X-Affonso-Signature, the lowercase hex HMAC-SHA256 of <timestamp>.<rawBody> keyed by the endpoint's signing secret. The secret is a 64-character hex string used as-is as the key — do not hex-decode it. Deliveries more than 5 minutes from now (either direction) are rejected. Pass the raw body (await req.text()), never re-serialized JSON.

data is left open because its shape depends on the event, and its casing differs by family: camelCase for affiliate, referral, transaction and payout events; snake_case for coupon events. WEBHOOK_EVENT_TYPES lists the documented types. A full refund arrives as transaction.rejected, a partial one as transaction.updated. Deliveries are retried for up to 48 hours (11 attempts), so dedupe on event.id.

Affonso.webhookSignedContent(timestamp, payload) returns the exact string that is signed.

Not covered

This connect wraps what a backend integration needs, not Affonso's whole API. Not wrapped: affiliate analytics, the Risk Center (fraud events), the normalized POST /events endpoint and the Segment adapter, the embedded dashboard, Affiliate Finder, program settings beyond GET /program (payment terms, tracking, restrictions, portal, fraud rules, notifications, groups, promotion URLs, creatives), campaigns and retainers, onboarding forms, and the marketplace.

See Errors for failure handling and Schemas for request/response validation.


← Back to Affonso

Clone this wiki locally