You are helping integrate LinkJolt affiliate tracking into a web application using Stripe Checkout.

## Context
- Merchant ID: YOUR_MERCHANT_ID
- Platform: Stripe Checkout
- Webhook Endpoint: https://www.linkjolt.io/api/webhooks/stripe/merchant/YOUR_MERCHANT_ID
- Tracking Script: https://www.linkjolt.io/api/tracking.js?id=YOUR_MERCHANT_ID

## Connecting Stripe (the merchant does this in LinkJolt)
The quickest route: LinkJolt → Integration Hub → Stripe → Step 1, **Set up with Stripe**, then approve once on Stripe's site. Sales, renewals and refunds then reach LinkJolt on their own: there is no webhook to create and no secret to paste. Installing the LinkJolt app from the Stripe App Marketplace for this brand counts too. Only the code changes below are left.

## Or by hand (in the Stripe Dashboard, the merchant does these)
1. Go to https://dashboard.stripe.com/webhooks
2. Click "Add endpoint"
3. Paste this URL: `https://www.linkjolt.io/api/webhooks/stripe/merchant/YOUR_MERCHANT_ID`
4. Select these events:
   - `checkout.session.completed` (required)
   - `invoice.payment_succeeded` (for subscriptions)
   - `customer.subscription.updated` (plan changes)
   - `customer.subscription.deleted` (cancellations)
   - `charge.refunded` + `refund.created` (for refunds)
5. Click "Add endpoint"
6. Copy the "Signing secret" (starts with `whsec_`) and save it in LinkJolt → Settings → Payment Providers (provider: stripe).

---

## Code Integration

### Add Tracking Script

Add this to your website's `<head>` tag:

**HTML:**
```html
<script src="https://www.linkjolt.io/api/tracking.js?id=YOUR_MERCHANT_ID" async></script>
```

**Next.js / React:**
```tsx
import Script from 'next/script'

// Add this in your layout.tsx or _app.tsx
<Script
  src="https://www.linkjolt.io/api/tracking.js?id=YOUR_MERCHANT_ID"
  strategy="afterInteractive"
/>
```

### Pass tracking to Stripe Checkout

**Option A — Frontend redirects directly to Stripe (Stripe.js):**
```typescript
const referral = window.linkjolt?.referral || '';
stripe.redirectToCheckout({
  // ...other options
  clientReferenceId: referral,
});
```

**Option B — Server creates the Checkout Session:**
```typescript
// Frontend
const referral = window.linkjolt?.referral || '';
fetch('/api/create-checkout', {
  method: 'POST',
  body: JSON.stringify({ priceId: 'price_xxx', referral }),
});

// Server (API route)
const session = await stripe.checkout.sessions.create({
  // ...other options
  client_reference_id: req.body.referral || undefined,
});
```

**Option C: Stripe's embedded pricing table (`<stripe-pricing-table>`) or buy button (`<stripe-buy-button>`):**
No code. The tracking script sets `client-reference-id` on both elements, and Stripe passes it to the Checkout Session they open as `client_reference_id`. A `client-reference-id` you set yourself is left alone, so do not set one if you want affiliate tracking. The page with the table or button must load the tracking script.

**client_reference_id constraint**: max 200 chars, alphanumeric + dashes + underscores only. Our referral format fits comfortably.

---

## Tracking Script API Reference

```javascript
// Format: "tc_CAMPAIGN123_aff_AFFILIATE456_cid_CLICK789"
window.linkjolt.referral

// Returns: { trackingCode, affiliateId, clickId }
window.linkjolt.getTrackingInfo()

// Returns boolean
window.linkjolt.isAffiliateVisit()

// Browser-side conversion reporting (used by Squarespace / Teachable / BigCommerce paths)
window.linkjolt.trackPurchase(amount, { orderId: 'ORDER_ID' })
```

---

## Testing

1. Visit your site with test parameters: `https://your-site.com/?tc=TEST123&aff=AFF456`
2. Open browser console and verify:
   ```javascript
   console.log(window.linkjolt.referral);
   // Should output: "tc_TEST123_aff_AFF456"
   ```
3. Complete a real or test purchase in your platform.
4. Check LinkJolt dashboard for the conversion.

## Common issues

- "window.linkjolt is undefined" → script not loaded.
- "referral is null" → visitor didn't arrive via affiliate link. Append `?tc=test&aff=test` and re-check.
- "Webhook not receiving events" → wrong URL in Stripe Dashboard, or webhook is in test mode while site is live.
- "clientReferenceId not set" → make sure you read `window.linkjolt.referral` BEFORE redirecting.
