Blossu UI SDK - Client-side tracking for affiliate/referral programs
npm install @blossu/uiClient-side tracking SDK for Blossu - the affiliate and referral tracking platform.
``bash`
npm install @blossu/uior
yarn add @blossu/uior
pnpm add @blossu/ui
`javascript
import { init } from '@blossu/ui';
// Initialize the SDK with your publishable key (starts with pk_)
const blossu = init({
publishableKey: 'pk_your_publishable_key',
});
// The SDK automatically tracks referral codes from the URL (e.g., ?ref=PARTNER123)
// and stores them in a cookie for attribution
`
By default, the SDK automatically:
1. Detects referral codes in the URL (e.g., ?ref=PARTNER123)
2. Saves the referral info in a cookie
3. Tracks the click event
`javascript
import { init } from '@blossu/ui';
init({
publishableKey: 'pk_your_publishable_key',
trackingParam: 'ref', // URL parameter to look for (default: 'ref')
autoTrack: true, // Enable automatic tracking (default: true)
});
`
Track when a user signs up after being referred:
`javascript
import { getClient } from '@blossu/ui';
const blossu = getClient();
// After user signs up
await blossu.signup({
customerExternalId: 'user_123',
customerEmail: 'customer@example.com',
customerName: 'John Doe',
});
`
Track a purchase/conversion from the frontend:
`javascript
import { Currency, SaleProvider } from '@blossu/ui';
await blossu.sale({
customerExternalId: 'user_123',
customerEmail: 'customer@example.com',
customerName: 'John Doe',
amount: 9900, // $99.00 in cents
currency: Currency.USD,
provider: SaleProvider.STRIPE,
});
`
> Important: Sales tracked from the frontend are marked as pending and require backend validation. For production use cases, we strongly recommend tracking sales server-side using the @blossu/server SDK or via payment provider integrations (Stripe, Paddle, Lemon Squeezy webhooks).
>
> Why?
> - Frontend tracking can be manipulated by users
> - Sales should be confirmed by your payment provider
> - Webhook-based tracking is more reliable
>
> See the Server SDK documentation for backend sale tracking.
Get the referral ID for Stripe Checkout:
`javascript
import { getClient } from '@blossu/ui';
const blossu = getClient();
// For Stripe Checkout - pass as client_reference_id
const checkoutSession = await stripe.checkout.sessions.create({
// ... other options
client_reference_id: blossu.getStripeClientReferenceId(),
metadata: blossu.getStripeMetadata(),
});
`
For production applications, we recommend tracking sales server-side for reliability and security:
Option 1: Payment Provider Webhooks (Recommended)
Configure Blossu integrations with Stripe, Paddle, or Lemon Squeezy. Sales are automatically tracked when payments are confirmed via webhooks.
Option 2: Server SDK
Use the @blossu/server SDK to track sales from your backend:
`typescript
import { Blossu, Currency, SaleProvider } from '@blossu/server';
const blossu = new Blossu(process.env.BLOSSU_API_KEY);
// Track sale after payment confirmation
await blossu.track.sale({
customerExternalId: 'user_123',
amount: 9900,
currency: Currency.USD,
provider: SaleProvider.STRIPE,
providerData: {
invoiceId: 'in_xxx',
paymentIntentId: 'pi_xxx',
},
});
`
See the integration documentation for setup guides.
`javascript
import { getClient } from '@blossu/ui';
const blossu = getClient();
// Check if user was referred
if (blossu.hasReferral()) {
console.log('Referral code:', blossu.getCode());
console.log('Referral ID:', blossu.getRefId());
}
// Get full referral info
const info = blossu.getReferralInfo();
// { code: 'partner123', refId: 'bls_abc123_xyz789', timestamp: 1704067200000 }
// Access globally
console.log(window.blossu_ref_id);
`
If you need to manually track a click:
`javascript`
await blossu.trackClick('PARTNER123');
Clear the stored referral info:
`javascript`
blossu.clearReferral();
The easiest way to add referral functionality to your React app:
`tsx
import { ReferralWidget } from '@blossu/ui/react';
function MyApp() {
const user = useUser(); // Your user hook
return (
email={user.email}
signature={user.blossuSignature} // HMAC signature from your backend
theme="light"
primaryColor="#3b82f6"
/>
);
}
`
Use individual components for more control:
`tsx
import { ReferralLink, ReferralStats } from '@blossu/ui/react';
function MyReferralPage() {
return (
conversions={45}
revenue={450000} // in cents
/>
destinationUrl="https://myapp.com"
label="Share your referral link"
showCopyButton={true}
/>
$3
Build completely custom UIs using the
usePartner hook:`tsx
import { usePartner } from '@blossu/ui/react';function CustomReferralUI() {
const { partner, codes, stats, isLoading, error, referralLink, copyLink, createCode } =
usePartner({
workspaceId: 'wks_xxx',
email: user.email,
signature: user.blossuSignature,
});
if (isLoading) return
Loading...;
if (error) return Error: {error}; return (
Welcome, {partner?.firstName}!
You've earned: ${(partner?.totalEarned || 0) / 100}
Stats
Clicks: {stats?.clicks}
Conversions: {stats?.conversions}
Your Codes
{codes.map((code) => (
{code.code}
))}
);
}
`$3
For tracking only (no UI):
`tsx
import { ReferralTracker } from '@blossu/ui/react';export default function RootLayout({ children }) {
return (
{children}
);
}
`Then in your components:
`tsx
import { getClient } from '@blossu/ui';function SignupForm() {
const blossu = getClient();
const handleSignup = async (email: string, userId: string) => {
// ... create user
// Track signup with Blossu
if (blossu?.hasReferral()) {
await blossu.signup({
customerExternalId: userId,
customerEmail: email,
});
}
};
return
;
}
`$3
For the widget and
usePartner hook, you need to generate an HMAC signature on your backend:`typescript
// app/api/blossu-token/route.ts
import crypto from 'crypto';
import { NextResponse } from 'next/server';export async function GET(req: Request) {
const user = await getCurrentUser(req); // Your auth logic
const signature = crypto
.createHmac('sha256', process.env.BLOSSU_SECRET_KEY!)
.update(user.email)
.digest('hex');
return NextResponse.json({
email: user.email,
signature,
});
}
`Then fetch it in your component:
`tsx
function MyApp() {
const [auth, setAuth] = useState(null); useEffect(() => {
fetch('/api/blossu-token')
.then((res) => res.json())
.then(setAuth);
}, []);
if (!auth) return
Loading...; return ;
}
`Usage with React (Manual Hook)
`jsx
// hooks/useBlossu.ts
import { useEffect, useState } from 'react';
import { init, getClient, BlossuClient } from '@blossu/ui';export function useBlossu() {
const [client, setClient] = useState(null);
useEffect(() => {
const blossu = init({
apiKey: process.env.NEXT_PUBLIC_BLOSSU_API_KEY!,
});
setClient(blossu);
}, []);
return client;
}
// Usage in component
function SignupForm() {
const blossu = useBlossu();
const handleSubmit = async (email: string, userId: string) => {
// ... create user
// Track signup with Blossu
if (blossu?.hasReferral()) {
await blossu.signup({
customerExternalId: userId,
customerEmail: email,
});
}
};
return
;
}
`Usage with Script Tag
You can also load the SDK via a script tag:
`html
`Configuration Options
`javascript
init({
// Required
publishableKey: 'pk_your_publishable_key', // Get from Blossu dashboard // Optional
programSlug: 'my-program', // Program slug (optional)
apiUrl: 'https://api.blossu.com', // API endpoint
trackingParam: 'ref', // URL parameter for referral codes
cookieName: 'blossu_ref', // Cookie name for storing referral info
cookieExpiryDays: 30, // How long to remember the referral
autoTrack: true, // Auto-track referral codes from URL
debug: false, // Enable debug logging
});
`API Reference
$3
Initialize the SDK and returns a
BlossuClient instance.$3
Get the current
BlossuClient instance (after calling init).$3
| Method | Description |
| ------------------------------ | ------------------------------- |
|
trackClick(code) | Track a referral link click |
| signup(data?) | Track a signup/lead |
| sale(data) | Track a sale/conversion |
| pageview() | Track a page view |
| hasReferral() | Check if user has referral info |
| getCode() | Get the referral code |
| getRefId() | Get the unique referral ID |
| getReferralInfo() | Get full referral info object |
| clearReferral() | Clear stored referral info |
| getStripeClientReferenceId() | Get refId for Stripe checkout |
| getStripeMetadata() | Get metadata object for Stripe |How It Works
1. When a user visits your site with a referral link (e.g.,
?ref=PARTNER123), the SDK: - Extracts the referral code
- Generates a unique
blossu_ref_id
- Stores both in a cookie
- Sends a click event to Blossu2. When the user converts (signup, purchase):
- Use the SDK to track the event
- The
blossu_ref_id links the conversion to the original click3. For Stripe payments:
- Pass
getStripeClientReferenceId() as client_reference_id in Checkout
- Blossu's webhook handler will automatically attribute the paymentTypeScript Support
This SDK is written in TypeScript and provides full type definitions:
`typescript
import type { BlossuConfig, ReferralInfo, TrackSignupData, TrackSaleData } from '@blossu/ui';
import { Currency, SaleProvider } from '@blossu/ui';// Only customerExternalId, amount, and currency are required
const saleData: TrackSaleData = {
customerExternalId: 'user_123',
amount: 9900,
currency: Currency.USD,
// Optional: customerEmail, customerName, provider, metadata
};
``MIT