
Referral Viral Loops
- 61 installs
- 41 repo stars
- Updated March 13, 2026
- finsilabs/awesome-ecommerce-skills
Build referral mechanics with dual-sided rewards, unique tracking links, viral-coefficient optimization, and anti-fraud controls.
About
Implements dual-sided referral rewards, tracking links, viral-coefficient tuning, and anti-abuse controls. A developer uses it to engineer viral growth loops and reduce referral fraud.
- Dual-sided rewards tuned for viral coefficient
- Anti-fraud controls against referral abuse
Referral Viral Loops by the numbers
- 61 all-time installs (skills.sh)
- Ranked #534 of 853 Sales & Marketing skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/finsilabs/awesome-ecommerce-skills --skill referral-viral-loopsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 61 |
|---|---|
| repo stars | ★ 41 |
| Last updated | March 13, 2026 |
| Repository | finsilabs/awesome-ecommerce-skills ↗ |
What it does
Build referral mechanics with dual-sided rewards, unique tracking links, viral-coefficient optimization, and anti-fraud controls.
Files
Referral Viral Loops
Overview
Word-of-mouth referral programs are one of the lowest-cost customer acquisition channels — referred customers have 37% higher retention rates and 25% higher LTV than non-referred customers. A dual-sided referral (reward both the referrer and the new customer) typically outperforms one-sided rewards by 2–3×. Dedicated referral apps (ReferralCandy, Friendbuy, Yotpo Loyalty) handle link generation, reward fulfillment, and fraud controls without custom code.
When to Use This Skill
- When CAC is high and word-of-mouth is underutilized
- When existing customers frequently refer friends informally but there is no structured program to track and reward it
- When needing to scale a referral program that has been running manually
- When wanting to calculate K-factor and optimize the program's viral coefficient
Core Instructions
Step 1: Choose the right referral platform
| Platform | Best For | Shopify | WooCommerce | BigCommerce | Price |
|---|---|---|---|---|---|
| ReferralCandy | Simple setup, all major platforms | App Store | Plugin | App Marketplace | $59+/mo |
| Friendbuy | Mid-market DTC, A/B testing rewards | App Store | Via JS | Via JS | $249+/mo |
| Yotpo Loyalty | Brands already using Yotpo | App Store | Limited | App Marketplace | $199+/mo |
| Smile.io Referrals | Already using Smile.io for loyalty | App Store | Plugin | App Marketplace | Included in $49/mo plan |
| Rewardful | SaaS + ecommerce via Stripe | Via Stripe | Via Stripe | Via Stripe | $49+/mo |
| AffiliateWP | WooCommerce-native | — | Plugin | — | $149/yr |
Recommendation: Use ReferralCandy for most stores — quick setup, dual-sided rewards built in, fraud detection included, and competitive pricing. If you are already using Smile.io for loyalty, add their referral module instead of a separate app.
Step 2: Design your referral program structure
Before installing anything, define the reward structure:
Dual-sided reward (recommended):
- Referrer reward: $10 store credit for every successful referral (paid after refund window)
- Referee reward (new customer): 15% off first order, no minimum
Single-sided reward (simpler but lower share rate):
- Referrer reward only: $15 store credit
Minimum order for referral to qualify: $30 (prevents micro-order gaming)
Refund window: Wait 7–14 days after the referee's order before granting the referrer reward — this prevents rewards on returned orders.
Step 3: Set up your referral program
---
Shopify with ReferralCandy
1. Install ReferralCandy from the Shopify App Store 2. Go to ReferralCandy → Program → Rewards and configure:
- Referrer reward: "$10 store credit" (or cash via PayPal)
- Referee reward: "15% off first order" (ReferralCandy creates a unique discount code per referral link)
- Minimum order: $30
3. Go to ReferralCandy → Program → Fraud Settings and enable:
- Block self-referrals
- Flag same-IP conversions for review
- Set maximum referrals per customer per month (10)
4. Go to ReferralCandy → Integrations and connect Klaviyo — this allows referral events to trigger Klaviyo flows 5. ReferralCandy automatically:
- Generates a unique referral link per customer (e.g.,
yourstore.com/?via=sarah123) - Displays the referral widget on the post-purchase page
- Sends referral invitation emails to new customers after purchase
- Tracks clicks, signups, and conversions per referrer
6. Go to ReferralCandy → Promote and add the referral widget to your account dashboard and post-purchase confirmation page
---
Shopify with Smile.io Referrals
1. Go to Smile.io → Programs → Referrals 2. Enable the referral program and configure:
- Referrer reward: points or store credit
- Referee reward: discount code sent automatically when they click the referral link
3. Go to Smile.io → Rewards Panel to customize how the referral link appears in the loyalty widget
---
WooCommerce with AffiliateWP
1. Install AffiliateWP ($149/yr) from the WooCommerce marketplace 2. Go to AffiliateWP → Settings → General and configure:
- Commission rate: fixed amount ($10) or percentage
- Cookie expiration: 30 days (referral attribution window)
3. Go to AffiliateWP → Affiliates → Add Affiliate to manually add customers, or enable self-registration so customers can join as affiliates 4. AffiliateWP generates a unique affiliate link per referrer: yourstore.com/?ref=AFFILIATE_ID 5. For referee discount: create a WooCommerce coupon code and link it to the referral program (AffiliateWP has a coupon integration add-on) 6. For fraud controls: go to AffiliateWP → Settings → Advanced and enable IP address duplicate detection
Alternative: Install ReferralCandy for WooCommerce (plugin) for a simpler dual-sided setup.
---
BigCommerce with ReferralCandy
1. Install ReferralCandy from the BigCommerce App Marketplace 2. Configuration is identical to the Shopify setup above 3. ReferralCandy integrates with BigCommerce's native coupon system to issue referee discount codes
---
Custom / Headless
Use a dedicated referral API platform like Friendbuy or Rewardful rather than building from scratch. These provide:
- Unique referral link generation
- Cookie-based and URL-based attribution
- Webhook events for referral conversions
- Fraud signal APIs
If you must build custom, the core components are:
// Generate a unique referral code per customer
async function generateReferralCode(customerId: string): Promise<string> {
const existing = await db.referralLinks.findOne({ where: { customerId } });
if (existing) return existing.code;
const customer = await db.customers.findById(customerId);
const baseCode = customer.firstName.replace(/[^a-zA-Z]/g, '').toUpperCase().slice(0, 6);
let code = `${baseCode}${Math.floor(100 + Math.random() * 900)}`;
while (await db.referralLinks.findOne({ where: { code } })) {
code = `${baseCode}${Math.floor(100 + Math.random() * 900)}`;
}
await db.referralLinks.create({ customerId, code, clicks: 0, conversions: 0 });
return code;
}
// Attribute referral on order completion — check cookie for referral code
async function attributeReferral(order: Order, referralCode: string | null) {
if (!referralCode) return;
const referralLink = await db.referralLinks.findByCode(referralCode);
if (!referralLink) return;
if (referralLink.customerId === order.customerId) return; // no self-referral
// Check if this email has already been referred (one referral per email per program)
const existing = await db.referralConversions.findOne({ where: { refereeEmail: order.customerEmail } });
if (existing) return;
await db.referralConversions.create({
referralLinkId: referralLink.id,
referrerId: referralLink.customerId,
refereeEmail: order.customerEmail,
orderId: order.id,
orderValue: order.subtotal,
status: 'pending', // set to 'approved' after 7-day refund window
});
// Grant referee discount immediately (e.g., store credit or discount code)
// Schedule referrer reward 7 days after order — after refund window
}Step 4: Promote your referral program
Highest-traffic placements: 1. Post-purchase confirmation page — add a referral widget immediately after checkout (highest-intent moment) 2. Transactional email — add "Give $10, Get $10" block to every order confirmation email in Klaviyo 3. Account dashboard — show the customer's referral link and stats (how many friends referred, how much earned) 4. Packaging insert — include a card with the customer's referral URL printed or handwritten
In ReferralCandy: go to Promote → Post-Purchase Popup to enable the automatic widget and Promote → Emails to configure referral invitation emails.
Step 5: Measure program performance
| Metric | Target | Where to Find |
|---|---|---|
| Share rate (% of customers who refer) | > 5% | ReferralCandy dashboard |
| Referral conversion rate | > 15% of clicks convert | App analytics |
| K-factor (share rate × conversion rate) | 0.3–0.5 = strong; 1.0+ = viral | Calculate from share rate × conversion rate |
| Revenue from referred customers | 10–20% of total new customer revenue | App analytics |
| Cost per acquisition via referral | Usually 40–60% below paid CAC | Reward cost ÷ referred orders |
Best Practices
- Dual-sided rewards outperform one-sided — giving both referrer and referee a reward increases share rates by 2–3× vs. rewarding only the referrer
- Show the referral widget on the post-purchase confirmation page — this is the highest-intent moment; customers who just had a great purchase experience are most likely to share
- Delay referrer reward by 7–14 days — wait until the refund window passes before granting the reward; prevents fraudsters getting rewards on returned orders
- Use store credit over discount codes for referrer rewards — store credit ties the referrer back to your brand; perceived value is higher than a percentage off
- Set a monthly cap per customer — even legitimate customers should not earn unlimited rewards; cap at 5–10 referrals per month
- Add a pre-filled WhatsApp or SMS share button — most customers will not manually copy and paste a link; a one-tap share button doubles share rates
Common Pitfalls
| Problem | Solution |
|---|---|
| Self-referral fraud (customer creates new account to get referee discount) | Enable IP-based duplicate detection; flag same-IP conversions for manual review (ReferralCandy has this built in) |
| Referral codes shared publicly on coupon sites | Make codes unique per referrer so bulk sharing is detectable; ReferralCandy monitors velocity automatically |
| Referrer reward given before order ships | Always delay referrer reward by 7+ days; use the app's built-in reward delay setting |
| Low share rate despite good rewards | Reduce friction — use pre-filled share messages; show the referral widget immediately post-purchase |
| Referred customers do not convert | Increase the referee incentive — 15% off typically outperforms 10% off for first-order conversion |
Related Skills
- @loyalty-program-optimization
- @affiliate-program
- @customer-retention-engine
- @email-marketing-automation
- @first-party-data-collection
{
"context": "Tests whether the agent correctly implements all five fraud detection signals, the correct K-factor formula and interpretation thresholds, and the recommended configuration for anti-abuse limits.",
"type": "weighted_checklist",
"checklist": [
{
"name": "Same-IP flag",
"max_score": 8,
"description": "Fraud check includes a 'same-ip' flag when referrer.lastLoginIp equals referee.lastLoginIp"
},
{
"name": "Instant-account flag",
"max_score": 8,
"description": "Fraud check includes an 'instant-account' flag when the referee account was created less than 1 day before the conversion"
},
{
"name": "Suspicious conversion rate flag",
"max_score": 10,
"description": "Fraud check includes a 'suspicious-conversion-rate' flag when conversions/clicks > 0.20 (20%) AND clicks > 10"
},
{
"name": "Shared-device flag",
"max_score": 8,
"description": "Fraud check includes a 'shared-device' flag based on a device fingerprint check between referrer and referee"
},
{
"name": "Rate-limit flag",
"max_score": 8,
"description": "Fraud check includes a 'rate-limit-exceeded' flag when the referrer's monthly conversion count meets or exceeds maxReferralsPerCustomer"
},
{
"name": "Under-review status on fraud",
"max_score": 8,
"description": "When any fraud flag is detected, the conversion status is updated to 'under-review' (not 'rejected' or 'flagged')"
},
{
"name": "Fraud team notification",
"max_score": 8,
"description": "When fraud is detected, notifyFraudTeam (or equivalent) is called with the conversion ID and the list of flags"
},
{
"name": "K-factor formula",
"max_score": 10,
"description": "K-factor is calculated as shareRate * conversionRate, where shareRate = totalReferrers / totalCustomers and conversionRate = totalConversions / totalReferrers"
},
{
"name": "K-factor thresholds",
"max_score": 10,
"description": "K-factor interpretation uses exactly these thresholds: >= 1.0 = viral/exponential, >= 0.5 = strong, >= 0.2 = moderate, below 0.2 = weak"
},
{
"name": "90-day default lookback",
"max_score": 8,
"description": "The viral coefficient calculation defaults to a 90-day lookback window when no period is specified"
},
{
"name": "Monthly referral cap range",
"max_score": 8,
"description": "Program configuration or documentation specifies a monthly cap of 5–10 referral conversions per customer"
},
{
"name": "Store credit for referrer",
"max_score": 6,
"description": "Recommendation or default configuration uses store_credit as the referrer reward type rather than discount codes"
}
]
}
Referral Program Fraud Detection and Viral Analytics
Problem/Feature Description
Craftly, a marketplace for handmade goods, launched a referral program six months ago and it has grown beyond what anyone expected. Unfortunately, the finance team has started flagging unusual reward payouts — some customers appear to be creating fake accounts or colluding with friends to farm referral rewards. Meanwhile, the growth team has no way to measure whether the program is actually producing viral growth or just giving discounts to people who would have signed up anyway.
The engineering team needs two additions to the existing referral system: a fraud detection function that can identify suspicious conversions before rewards are granted, and an analytics function that calculates the viral coefficient (K-factor) so leadership can track program health over time. The fraud detection needs to catch multiple categories of abuse — not just the obvious cases. The analytics function needs to return a structured result that non-technical stakeholders can interpret.
The fraud detection should integrate into the existing conversion flow, and any suspicious conversions should be escalated rather than silently dropped.
Output Specification
Produce a TypeScript file referral-analytics.ts containing:
- A
checkReferralFraud(conversion)function that returns a boolean indicating whether fraud was detected - A
calculateViralCoefficient(programId, lookbackDays?)function that returns a structured analytics result
Also produce a fraud-and-analytics-design.md that:
- Lists all fraud signals being detected and the rationale for each
- Explains the K-factor formula used and how to interpret the result
- Recommends a sensible value for the monthly per-customer referral cap and preferred reward type for referrers
Assume the following are available: db object with ORM-style access methods, notifyFraudTeam(conversionId, flags) function, and daysBetween(date1, date2) / subDays(date, n) date utilities.
{
"context": "Tests whether the agent correctly implements referral attribution middleware and conversion processing including cookie settings, click tracking, fraud guards, status management, and the timing/format of reward fulfillment.",
"type": "weighted_checklist",
"checklist": [
{
"name": "Cookie name",
"max_score": 6,
"description": "Attribution cookie is named exactly 'referral_code'"
},
{
"name": "Cookie httpOnly flag",
"max_score": 6,
"description": "Cookie is set with httpOnly: true"
},
{
"name": "Cookie sameSite setting",
"max_score": 6,
"description": "Cookie is set with sameSite: 'lax'"
},
{
"name": "Cookie duration",
"max_score": 8,
"description": "Cookie maxAge is set to 30 days expressed as 30 * 86400 * 1000 milliseconds (or equivalent numeric value 2592000000)"
},
{
"name": "Click tracking",
"max_score": 8,
"description": "Middleware increments the click count in the database when a referral code is present in the request"
},
{
"name": "Self-referral prevention",
"max_score": 10,
"description": "Attribution logic checks that the referral link's owner (customerId) is NOT the same as the ordering customer, and skips attribution if they match"
},
{
"name": "Minimum order value check",
"max_score": 8,
"description": "Attribution skips (returns early) if the order subtotal is below the program's minimumOrderValue"
},
{
"name": "One referral per email",
"max_score": 10,
"description": "Code checks for an existing conversion with the same refereeEmail AND programId combination and skips if one exists"
},
{
"name": "Conversion pending status",
"max_score": 8,
"description": "Newly created conversion records are set to status 'pending' (not 'approved' or 'completed')"
},
{
"name": "Referee reward immediate",
"max_score": 10,
"description": "Referee reward is granted synchronously (awaited) immediately when a conversion is recorded"
},
{
"name": "Referrer reward delayed 7 days",
"max_score": 12,
"description": "Referrer reward is scheduled with a delay of 7 days (7 * 86400000 ms or 604800000 ms) via a queue, NOT granted immediately"
},
{
"name": "Discount rewards single-use",
"max_score": 8,
"description": "When creating discount codes (percent_off or fixed_amount rewards), singleUse is set to true"
}
]
}
Implement Referral Attribution and Reward Processing
Problem/Feature Description
Bloom Beauty has launched a referral program where customers can share their personal referral link. The marketing team has set up the program configuration and link generation — now they need the backend logic that actually makes the program work: capturing when a new visitor arrives through a referral link, and processing rewards when that visitor makes a purchase.
The current system has a gap: there's no middleware to record that a visitor arrived via a referral link, and no logic to handle what happens at checkout when a referred customer completes an order. The team needs both pieces built in TypeScript. The system already uses Express for the web layer and BullMQ (or similar) for background jobs. The reward system supports discount codes and store credit.
Key business rules the team has agreed on:
- Not every completed order should earn a referral reward — there are order value thresholds
- The same email address shouldn't be able to trigger multiple rewards for the same program
- The person who referred someone shouldn't be able to refer themselves
- Reward timing matters: not all parties should get their reward at the same moment
Output Specification
Produce a TypeScript file attribution.ts containing:
- An Express middleware function that captures referral attribution from incoming requests
- An
attributeReferral(order, req)function that processes a completed order and handles reward fulfillment
Also produce a attribution-design.md explaining the reward timing strategy and the anti-abuse measures implemented (3–5 bullet points).
Assume the following are available: db object with ORM-style access, referralQueue for scheduling jobs, grantReward(customerId, reward, conversionId, role) function, createUniqueDiscount(params) function, and standard Express Request/Response/NextFunction types.
{
"context": "Tests whether the agent correctly models a referral program with dual-sided rewards and generates unique, shareable referral links using the right code format, idempotency, and URL parameters.",
"type": "weighted_checklist",
"checklist": [
{
"name": "ReferralProgram fields",
"max_score": 8,
"description": "ReferralProgram interface/type includes all 7 required fields: id, name, referrerReward, refereeReward, minimumOrderValue, cookieWindowDays, maxReferralsPerCustomer"
},
{
"name": "Reward type union",
"max_score": 8,
"description": "Reward type field is a union of exactly these 4 values: 'percent_off', 'fixed_amount', 'store_credit', 'free_product'"
},
{
"name": "ReferralLink fields",
"max_score": 8,
"description": "ReferralLink interface/type includes: id, customerId, code, shortUrl, clicks, conversions, revenue, createdAt"
},
{
"name": "Idempotent generation",
"max_score": 12,
"description": "Link generation checks for an existing link (by customerId + programId) and returns it if found, rather than creating a duplicate"
},
{
"name": "Code format",
"max_score": 12,
"description": "Referral code format is: customer's first name (non-alpha chars stripped, uppercased, max 8 chars) concatenated with a 3-digit random number (100–999)"
},
{
"name": "Uniqueness loop",
"max_score": 8,
"description": "Code generation includes a loop to regenerate the code if the generated code already exists in the database"
},
{
"name": "UTM parameters",
"max_score": 12,
"description": "The referral long URL includes all three UTM parameters: utm_source=referral, utm_medium=share, and utm_campaign set to the program ID"
},
{
"name": "Dual-sided reward structure",
"max_score": 10,
"description": "ReferralProgram model includes BOTH a referrerReward field AND a refereeReward field (not just one of them)"
},
{
"name": "Store credit for referrer",
"max_score": 12,
"description": "In any example, default configuration, or documentation: the referrer's reward type is set to 'store_credit' rather than 'percent_off' or 'fixed_amount'"
},
{
"name": "Short shareable code",
"max_score": 10,
"description": "Code field comment or documentation describes the code as short and shareable (e.g., 'SARAH123' format), not a UUID or long random string"
}
]
}
Launch a Customer Referral Program
Problem/Feature Description
Nora Foods is a direct-to-consumer snack brand that has grown mainly through paid social ads, but CAC has been creeping up quarter over quarter. The growth team has noticed that a significant portion of customers mention they "heard about Nora from a friend" in post-purchase surveys — yet there's no mechanism to track or reward these organic referrals. The VP of Growth wants to formalize this into a structured referral program that gives both the person who refers and the person who is referred an incentive to participate, with the goal of turning happy customers into a reliable acquisition channel.
The engineering team needs to build the core TypeScript module for this program. They need proper data models for the program configuration and the referral links themselves, plus a function to generate a referral link for a given customer. The referral links should be memorable and shareable (not random hashes), and each customer should always get the same link rather than accumulating duplicates. Links need to include tracking parameters so the marketing analytics platform can attribute traffic correctly.
Output Specification
Produce a TypeScript file referral.ts that contains:
- Type definitions / interfaces for the referral program and its components
- A
generateReferralLink(customerId, programId)function - A short usage example or inline comment showing what a typical program configuration looks like
Also produce a referral-design.md explaining the key design decisions made (2–4 bullet points).
Assume a db object is available with the same shape shown in typical ORM-style code (e.g., db.referralLinks.findOne, db.referralLinks.create). Assume createShortLink(longUrl, slug) is available. Assume process.env.STORE_URL contains the base store URL.
{
"name": "finsi/referral-viral-loops",
"version": "0.1.0",
"summary": "Build referral mechanics with dual-sided rewards, unique tracking links, viral coefficient optimization, and anti-fraud controls for referral abuse",
"skills": {
"referral-viral-loops": {
"path": "SKILL.md"
}
}
}