SDK integration
Add consent-gated browser attribution, Stripe metadata, and manual conversion tracking.
The RefCampaign browser SDK is passive until your consent-management platform (CMP) sends the visitor's attribution choice. Loading the script alone does not create an attribution session or capture a visit.
Quickstart
- 1
Load the passive SDK
<script src="https://sdk.refcampaign.com/v4.js?s=rcst_PUBLIC_SITE_TOKEN" async></script> - 2
Forward the CMP decision
Call the SDK once after the CMP resolves its persisted choice, then after every grant or withdrawal:
async function applyAttributionConsent(granted) { return window.RefCampaignBrowser.setConsent({ attribution: granted }) }A grant sends one install heartbeat from the configured merchant origin. Attribution readiness is confirmed separately from the authenticated merchant checklist in RefCampaign. On a URL such as
https://merchant.example/?ref=fabrice, the grant also creates a first-party_rc_sidsession for 180 days, the longest campaign attribution window. A refusal sends no browser request. A later withdrawal deletes the session. - 3
Send the consented session to checkout
const sessionId = window.RefCampaignBrowser.getSessionId() await fetch('/api/checkout', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ priceId, sessionId }), })On the server, attach
refcampaign_sessionmetadata only whensessionIdis present. Checkout must continue normally without it.
npm installation
pnpm add @refcampaign/sdkimport { RefCampaignBrowser } from '@refcampaign/sdk/browser'
RefCampaignBrowser.configure({
siteToken: 'rcst_PUBLIC_SITE_TOKEN',
debug: true,
})
await RefCampaignBrowser.setConsent({ attribution: cmpChoice === 'granted' })Choose one browser path: CDN or npm. The public site token is safe for browser use; never expose a RefCampaign secret key there.
Import from the subpath that matches the runtime: @refcampaign/sdk/browser in browser code, @refcampaign/sdk/server on the server, and @refcampaign/sdk/webhooks (or @refcampaign/sdk/webhooks/edge) to verify webhooks. The root @refcampaign/sdk import still works, but it also references the Node-only webhook verifier, which browser bundlers may warn about.
If a visitor lands on a referral link while no siteToken is configured, the SDK logs a console warning: the visit cannot be attributed.
Consent lifecycle
Your CMP remains the source of truth. RefCampaign does not store the consent choice.
- Initial grant or persisted grant: call
setConsent({ attribution: true }). - Initial refusal: call
setConsent({ attribution: false }). - Reload: replay the persisted CMP decision.
- Withdrawal: call the false branch immediately.
The merchant is responsible for obtaining consent and retaining any evidence required by applicable law. If consent is refused, the browser visit is not attributed automatically. You may still attribute a conversion using information independently known by your server, such as a coupon, an explicit referral code, or an affiliate code already attached to the order.
Stripe attribution
For a Checkout subscription, preserve the metadata on both the Checkout Session and Subscription:
const metadata = sessionId ? { refcampaign_session: sessionId } : {}
const checkout = await stripe.checkout.sessions.create({
mode: 'subscription',
line_items: [{ price: priceId, quantity: 1 }],
metadata,
subscription_data: { metadata },
success_url: 'https://merchant.example/success',
cancel_url: 'https://merchant.example/pricing',
})For a one-time payment, add the same metadata to the Payment Intent.
Server-set session cookie
Safari caps cookies written by JavaScript to 7 days. A cookie your own server sets in an HTTP response is not capped this way, so a Safari visitor can still be attributed after a week. After a consented capture, send the sessionId to your backend and re-issue _rc_sid there:
const result = await RefCampaignBrowser.setConsent({ attribution: true })
if (result.status === 'captured') {
await fetch('/api/refcampaign/session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId: result.sessionId }),
})
}// app/api/refcampaign/session/route.ts (Next.js App Router)
import { NextResponse } from 'next/server'
const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
export async function POST(request: Request) {
// Refuse cross-site requests: another site must not be able to replace
// your visitor's session with its own (an HTML form can post text/plain).
if (
!request.headers.get('content-type')?.startsWith('application/json') ||
request.headers.get('sec-fetch-site') === 'cross-site'
) {
return new NextResponse(null, { status: 403 })
}
const body = await request.json().catch(() => null)
const sessionId = body?.sessionId
if (typeof sessionId !== 'string' || !SESSION_ID.test(sessionId)) {
return new NextResponse(null, { status: 400 })
}
const response = new NextResponse(null, { status: 204 })
response.cookies.set('_rc_sid', sessionId, {
maxAge: 15552000, // 180 days
path: '/',
domain: '.merchant.example', // your registrable domain
secure: true,
sameSite: 'lax',
httpOnly: false, // the SDK reads it, and deletes it on withdrawal
})
return response
}Keep Path=/, your registrable domain, and no HttpOnly: the SDK must read the cookie and delete it when consent is withdrawn.
- Accept only same-site JSON requests, as above. Otherwise any website could post its own session ID to your endpoint and take the visitor's attribution.
- Call the endpoint only after a grant. It re-issues the consented cookie and stores nothing before consent.
- Serve it from your own site. Safari also caps server-set cookies to 7 days when the responding server's IP address does not match the website's, for example behind a CNAME to a third-party host.
- Re-issue only on
captured, not on every visit: RefCampaign applies the attribution window from the click date anyway.
identify() (deprecated)
RefCampaignBrowser.identify(email) has no effect since SDK 4.1: it sends nothing and resolves immediately. The browser email hash it used to send was not used for attribution, because a browser can claim any email. Remove the call. For a visitor whose consented session is gone, attribute from facts your server knows: a coupon, a submitted referral code, or an affiliateCode.
Manual conversions
Use the server client for non-Stripe payments or independently known attribution:
import { RefCampaignServer } from '@refcampaign/sdk/server'
const rc = new RefCampaignServer(process.env.REFCAMPAIGN_SECRET_KEY!)
await rc.trackConversion({
orderId: 'ord_42',
sessionId,
// Or affiliateCode when your server already knows the partner.
amount: 4900,
currency: 'EUR',
metadata: { payment_method: 'paypal' },
})Amounts are integer cents. orderId is the idempotence key.
To attribute by customer email, pass customerEmailHash built with hashEmail(). It applies the normalization RefCampaign matches (trimmed, lowercased, SHA-256). It needs Web Crypto (Node.js 20+ or an edge runtime):
import { hashEmail } from '@refcampaign/sdk/server'
await rc.trackConversion({
orderId: 'ord_43',
customerEmailHash: await hashEmail(order.customerEmail),
amount: 4900,
currency: 'EUR',
})Report a full or partial refund with the same order id:
await rc.refundConversion({ orderId: 'ord_42' })
await rc.refundConversion({
orderId: 'ord_42',
amount: 1000,
reason: 'partial return',
})Verification checklist
- Refuse on
?ref=fabrice: no capture request and no attribution session. - Grant: one capture request and
_rc_sidavailable to the consented checkout flow. - Reload: replayed CMP grant exposes the existing session.
- Withdraw: the session is deleted.
- Complete checkout without a session: the purchase still succeeds.
Once visit tracking and conversion attribution are configured, Settings → SDK setup offers an optional server simulation. It sends an internal test click through the tracking Worker, then records a synthetic conversion and commission. If click processing is still pending, retry with the same click.
The result shows the test amount, commission, and conversion reference. No Stripe payment is created. Synthetic records are excluded from real statistics, affiliate activation, and payouts. This simulation does not verify the SDK on your site, your CMP, or Stripe webhooks. Validate your integration with the consent checks above and a separate Stripe test-mode checkout.