Referral Program Implementation
Complete guide to building viral referral programs with automatic rewards for both referrers and referees.
Overview
Reward users for bringing friends, family, and colleagues to your platform. Typical implementations:
- Referrer reward: 100-500 LTZ per successful referral
- Referee reward: 50-100 LTZ for signing up
- Bonus rewards: Extra LTZ for milestones (5 referrals, 10 referrals, etc.)
Quick Implementation
1. Generate Referral Codes
// Generate unique code for each user
function generateReferralCode(userEmail) {
return btoa(userEmail).slice(0, 8).toUpperCase();
}
// Example: "[email protected]" → "dGVzdEBl"
const code = generateReferralCode('[email protected]');
2. Track Referral Signups
// On signup page
const urlParams = new URLSearchParams(window.location.search);
const referralCode = urlParams.get('ref');
document.getElementById('signup-form').addEventListener('submit', async (e) => {
e.preventDefault();
const newUserEmail = e.target.email.value;
// Create account
await createAccount(newUserEmail);
// Reward new user
await LoyalteezAutomation.track('account_creation', {
userEmail: newUserEmail,
metadata: {
referred_by: referralCode || 'organic'
}
});
// Reward referrer if exists
if (referralCode) {
const referrerEmail = await getReferrerEmail(referralCode);
await LoyalteezAutomation.track('referral_success', {
userEmail: referrerEmail,
metadata: {
referred_user: newUserEmail,
referral_code: referralCode
}
});
}
});
3. Display Referral Link
// User dashboard
const referralCode = generateReferralCode(userEmail);
const referralLink = `https://yoursite.com/signup?ref=${referralCode}`;
document.getElementById('referral-link').textContent = referralLink;
// Copy to clipboard
document.getElementById('copy-link').addEventListener('click', () => {
navigator.clipboard.writeText(referralLink);
alert('Referral link copied!');
});
Complete Example: React
import { useState, useEffect } from 'react';
export function ReferralDashboard({ userEmail }: { userEmail: string }) {
const [referralCode, setReferralCode] = useState('');
const [referralLink, setReferralLink] = useState('');
const [referrals, setReferrals] = useState([]);
const [copied, setCopied] = useState(false);
useEffect(() => {
// Generate user's referral code
const code = btoa(userEmail).slice(0, 8).toUpperCase();
setReferralCode(code);
setReferralLink(`${window.location.origin}/signup?ref=${code}`);
// Load user's referrals
loadReferrals(userEmail).then(setReferrals);
}, [userEmail]);
const copyLink = () => {
navigator.clipboard.writeText(referralLink);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const shareOnSocial = (platform: string) => {
const text = 'Join me on this awesome platform and get 50 LTZ!';
const urls = {
twitter: `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(referralLink)}`,
facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(referralLink)}`,
linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(referralLink)}`,
};
window.open(urls[platform], '_blank', 'width=600,height=400');
};
return (
<div className="referral-dashboard">
<h2>Refer Friends & Earn 100 LTZ</h2>
<p>Share your unique link and earn rewards when friends sign up!</p>
<div className="referral-link-box">
<input
type="text"
value={referralLink}
readOnly
onClick={(e) => e.target.select()}
/>
<button onClick={copyLink}>
{copied ? '✓ Copied!' : 'Copy Link'}
</button>
</div>
<div className="social-share">
<button onClick={() => shareOnSocial('twitter')}>Share on Twitter</button>
<button onClick={() => shareOnSocial('facebook')}>Share on Facebook</button>
<button onClick={() => shareOnSocial('linkedin')}>Share on LinkedIn</button>
</div>
<div className="referral-stats">
<div className="stat">
<h3>{referrals.length}</h3>
<p>Total Referrals</p>
</div>
<div className="stat">
<h3>{referrals.length * 100}</h3>
<p>LTZ Earned</p>
</div>
</div>
<div className="referral-list">
<h3>Your Referrals</h3>
{referrals.map((referral) => (
<div key={referral.id} className="referral-item">
<span>{referral.email}</span>
<span>{referral.status}</span>
<span>+100 LTZ</span>
</div>
))}
</div>
</div>
);
}
Backend Implementation
Node.js Server
const express = require('express');
const app = express();
// Store referral codes in database
const referralCodes = new Map(); // Use database in production
// Generate and save referral code
app.post('/api/referral/generate', async (req, res) => {
const { userEmail } = req.body;
const code = Buffer.from(userEmail).toString('base64').slice(0, 8).toUpperCase();
// Save to database
await db.referralCodes.insert({
code: code,
userEmail: userEmail,
createdAt: new Date()
});
res.json({ code, link: `https://yoursite.com/signup?ref=${code}` });
});
// Handle referral signup
app.post('/api/signup', async (req, res) => {
const { email, referralCode } = req.body;
// Create account
const newUser = await createUser(email);
// Reward new user
await fetch('https://api.loyalteez.app/loyalteez-api/manual-event', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
brandId: process.env.LOYALTEEZ_BRAND_ID,
eventType: 'account_creation',
userEmail: email,
domain: 'yourdomain.com',
metadata: {
referred_by: referralCode || 'organic'
}
})
});
// If referral code exists, reward referrer
if (referralCode) {
const referrer = await db.referralCodes.findOne({ code: referralCode });
if (referrer) {
await fetch('https://api.loyalteez.app/loyalteez-api/manual-event', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
brandId: process.env.LOYALTEEZ_BRAND_ID,
eventType: 'referral_success',
userEmail: referrer.userEmail,
domain: 'yourdomain.com',
metadata: {
referred_user: email,
referral_code: referralCode,
reward_amount: 100
}
})
});
// Track referral in database
await db.referrals.insert({
referrer: referrer.userEmail,
referee: email,
code: referralCode,
status: 'completed',
createdAt: new Date()
});
}
}
res.json({ success: true, user: newUser });
});
// Get user's referrals
app.get('/api/referrals/:userEmail', async (req, res) => {
const referrals = await db.referrals.find({
referrer: req.params.userEmail
});
res.json(referrals);
});
Advanced Features
Milestone Bonuses
// Reward for reaching referral milestones
async function checkReferralMilestones(referrerEmail) {
const referralCount = await db.referrals.count({ referrer: referrerEmail });
const milestones = {
5: { bonus: 250, badge: 'Bronze Recruiter' },
10: { bonus: 500, badge: 'Silver Recruiter' },
25: { bonus: 1500, badge: 'Gold Recruiter' },
50: { bonus: 5000, badge: 'Platinum Recruiter' }
};
if (milestones[referralCount]) {
await LoyalteezAutomation.track('referral_milestone', {
userEmail: referrerEmail,
metadata: {
milestone: referralCount,
bonus: milestones[referralCount].bonus,
badge: milestones[referralCount].badge
}
});
}
}
Two-Tier Referrals
// Reward for referrals of referrals
app.post('/api/signup', async (req, res) => {
const { email, referralCode } = req.body;
// ... existing signup logic ...
if (referralCode) {
const referrer = await db.referralCodes.findOne({ code: referralCode });
// Tier 1: Direct referrer
await rewardUser(referrer.userEmail, 'referral_tier1', { amount: 100 });
// Tier 2: Referrer's referrer
const referrerOfReferrer = await db.referrals.findOne({
referee: referrer.userEmail
});
if (referrerOfReferrer) {
await rewardUser(referrerOfReferrer.referrer, 'referral_tier2', {
amount: 25
});
}
}
});
Conditional Rewards
// Only reward if referee completes specific action
app.post('/api/purchase', async (req, res) => {
const { userEmail, amount } = req.body;
// Check if user was referred
const referral = await db.referrals.findOne({
referee: userEmail,
status: 'pending' // Not yet rewarded
});
if (referral && amount >= 50) { // First purchase over $50
// Reward referrer NOW
await rewardUser(referral.referrer, 'qualified_referral', {
amount: 200, // Higher reward
referee: userEmail,
purchase_amount: amount
});
// Update referral status
await db.referrals.update(
{ _id: referral._id },
{ status: 'rewarded', rewardedAt: new Date() }
);
}
});
Expiring Codes
// Generate time-limited referral codes
function generateExpiringCode(userEmail, daysValid = 30) {
const expiry = Date.now() + (daysValid * 24 * 60 * 60 * 1000);
const payload = { email: userEmail, exp: expiry };
return jwt.sign(payload, process.env.JWT_SECRET);
}
// Validate code on signup
function validateReferralCode(code) {
try {
const payload = jwt.verify(code, process.env.JWT_SECRET);
if (payload.exp < Date.now()) {
return { valid: false, reason: 'expired' };
}
return { valid: true, referrer: payload.email };
} catch (error) {
return { valid: false, reason: 'invalid' };
}
}
Gamification
Leaderboard
// Get top referrers
app.get('/api/referral/leaderboard', async (req, res) => {
const topReferrers = await db.referrals.aggregate([
{ $group: { _id: '$referrer', count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 10 }
]);
res.json(topReferrers);
});
Referral Contests
// Monthly referral contest
async function checkMonthlyWinner() {
const startOfMonth = new Date();
startOfMonth.setDate(1);
startOfMonth.setHours(0, 0, 0, 0);
const topReferrer = await db.referrals.aggregate([
{ $match: { createdAt: { $gte: startOfMonth } } },
{ $group: { _id: '$referrer', count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 1 }
]);
if (topReferrer.length > 0) {
await rewardUser(topReferrer[0]._id, 'monthly_contest_winner', {
referrals: topReferrer[0].count,
bonus: 5000 // 5000 LTZ bonus!
});
}
}
// Run monthly
cron.schedule('0 0 1 * *', checkMonthlyWinner); // First day of month
Anti-Fraud Measures
Prevent Self-Referrals
// Check IP and device fingerprint
app.post('/api/signup', async (req, res) => {
const { email, referralCode } = req.body;
const ip = req.ip;
const fingerprint = req.headers['x-device-fingerprint'];
if (referralCode) {
const referrer = await db.users.findOne({ referralCode });
// Check if same IP or device
const suspicious = await db.users.findOne({
email: referrer.email,
$or: [
{ lastIP: ip },
{ fingerprint: fingerprint }
]
});
if (suspicious) {
return res.status(400).json({
error: 'Self-referral detected'
});
}
}
// Proceed with signup...
});
Limit Referrals Per Period
// Max 10 referrals per month
async function checkReferralLimit(referrerEmail) {
const startOfMonth = new Date();
startOfMonth.setDate(1);
const monthlyReferrals = await db.referrals.count({
referrer: referrerEmail,
createdAt: { $gte: startOfMonth }
});
if (monthlyReferrals >= 10) {
throw new Error('Monthly referral limit reached');
}
}
Email Templates
Referral Invitation
<html>
<body>
<h1>{{referrer_name}} Invited You!</h1>
<p>Your friend {{referrer_name}} wants to share something special with you.</p>
<div style="background: #f5f5f5; padding: 20px; border-radius: 8px;">
<h3>Sign Up & Get 50 LTZ Free!</h3>
<p>Use this exclusive link to join:</p>
<a href="{{referral_link}}" style="background: #6C33EA; color: white; padding: 12px 24px; text-decoration: none; border-radius: 6px;">
Join Now & Claim Reward
</a>
</div>
<p><small>Note: {{referrer_name}} will receive 100 LTZ when you sign up!</small></p>
</body>
</html>
Analytics & Tracking
Track these metrics:
- Referral Conversion Rate: % of clicks that become signups
- Top Referrers: Who's bringing the most users?
- Referral Channels: Twitter vs Email vs Direct link
- Lifetime Value: Do referred users have higher LTV?
- Viral Coefficient: How many new users does each user bring?
Next Steps
- Newsletter Signup Rewards - Reward subscribers
- Purchase Loyalty - Reward purchases
- Webhooks Guide - Get notified of events
- Custom Events - Create custom reward rules
Support
- Examples: github.com/Alpha4-Labs/loyalteez-examples
- Email: [email protected]
- Docs: docs.loyalteez.app