@blossu/ui
v0.16.0
Published
Blossu UI SDK - Client-side tracking for affiliate/referral programs
Maintainers
Readme
@blossu/ui
Client-side tracking SDK for Blossu - the affiliate and referral tracking platform.
Installation
npm install @blossu/ui
# or
yarn add @blossu/ui
# or
pnpm add @blossu/uiQuick Start
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 attributionUsage
Automatic Tracking
By default, the SDK automatically:
- Detects referral codes in the URL (e.g.,
?ref=PARTNER123) - Saves the referral info in a cookie
- Tracks the click event
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 Signup
Track when a user signs up after being referred:
import { getClient } from '@blossu/ui';
const blossu = getClient();
// After user signs up
await blossu.signup({
customerExternalId: 'user_123',
customerEmail: '[email protected]',
customerName: 'John Doe',
});Track Sale (Client-Side)
Track a purchase/conversion from the frontend:
import { Currency, SaleProvider } from '@blossu/ui';
await blossu.sale({
customerExternalId: 'user_123',
customerEmail: '[email protected]',
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/serverSDK 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.
Stripe Integration
Get the referral ID for Stripe Checkout:
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(),
});Recommended: Server-Side Sale Tracking
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:
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.
Access Referral Info
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);Manual Click Tracking
If you need to manually track a click:
await blossu.trackClick('PARTNER123');Clear Referral
Clear the stored referral info:
blossu.clearReferral();Usage with React
Option 1: Pre-built Components (Recommended)
The easiest way to add referral functionality to your React app:
import { ReferralWidget } from '@blossu/ui/react';
function MyApp() {
const user = useUser(); // Your user hook
return (
<ReferralWidget
workspaceId="wks_xxx"
email={user.email}
signature={user.blossuSignature} // HMAC signature from your backend
theme="light"
primaryColor="#3b82f6"
/>
);
}Option 2: Individual Components
Use individual components for more control:
import { ReferralLink, ReferralStats } from '@blossu/ui/react';
function MyReferralPage() {
return (
<div>
<h2>My Referral Program</h2>
<ReferralStats
clicks={120}
conversions={45}
revenue={450000} // in cents
/>
<ReferralLink
code="FRIEND10"
destinationUrl="https://myapp.com"
label="Share your referral link"
showCopyButton={true}
/>
</div>
);
}Option 3: Custom UI with Hook
Build completely custom UIs using the usePartner hook:
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 <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
return (
<div>
<h2>Welcome, {partner?.firstName}!</h2>
<p>You've earned: ${(partner?.totalEarned || 0) / 100}</p>
<div>
<h3>Stats</h3>
<p>Clicks: {stats?.clicks}</p>
<p>Conversions: {stats?.conversions}</p>
</div>
<div>
<h3>Your Codes</h3>
{codes.map((code) => (
<div key={code.id}>
<span>{code.code}</span>
<button onClick={() => copyLink(code.code)}>Copy Link</button>
</div>
))}
</div>
<button onClick={() => createCode('newcode123', 'My New Code')}>Create New Code</button>
</div>
);
}Option 4: ReferralTracker Wrapper
For tracking only (no UI):
import { ReferralTracker } from '@blossu/ui/react';
export default function RootLayout({ children }) {
return (
<html>
<body>
<ReferralTracker publishableKey={process.env.NEXT_PUBLIC_BLOSSU_KEY!}>{children}</ReferralTracker>
</body>
</html>
);
}Then in your components:
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 <form>...</form>;
}Generating HMAC Signature (Backend)
For the widget and usePartner hook, you need to generate an HMAC signature on your backend:
// 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:
function MyApp() {
const [auth, setAuth] = useState(null);
useEffect(() => {
fetch('/api/blossu-token')
.then((res) => res.json())
.then(setAuth);
}, []);
if (!auth) return <div>Loading...</div>;
return <ReferralWidget workspaceId="wks_xxx" email={auth.email} signature={auth.signature} />;
}Usage with React (Manual Hook)
// hooks/useBlossu.ts
import { useEffect, useState } from 'react';
import { init, getClient, BlossuClient } from '@blossu/ui';
export function useBlossu() {
const [client, setClient] = useState<BlossuClient | null>(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 <form>...</form>;
}Usage with Script Tag
You can also load the SDK via a script tag:
<script src="https://cdn.blossu.com/blossu.min.js"></script>
<script>
Blossu.init({
apiKey: 'your-api-key',
});
// Later...
if (window.blossu.hasReferral()) {
console.log('Referred by:', window.blossu.getCode());
}
</script>Configuration Options
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
init(config)
Initialize the SDK and returns a BlossuClient instance.
getClient()
Get the current BlossuClient instance (after calling init).
BlossuClient
| 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
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 Blossu
When the user converts (signup, purchase):
- Use the SDK to track the event
- The
blossu_ref_idlinks the conversion to the original click
For Stripe payments:
- Pass
getStripeClientReferenceId()asclient_reference_idin Checkout - Blossu's webhook handler will automatically attribute the payment
- Pass
TypeScript Support
This SDK is written in TypeScript and provides full type definitions:
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
};License
MIT
