Referral System Development with Anti-Cheating and Attribution

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Referral System Development with Anti-Cheating and Attribution
Medium
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Imagine an e-commerce store with 50,000 monthly visitors launching a referral program. A month later, 40% of referral link clicks are unattributed — users came from social media, didn't register immediately, and returned after a week. Without proper attribution, referrals are lost and the program doesn't pay off. According to our data, correct cookie and tracking setup can recover up to 40% of lost profit. That's why we emphasize secure cookies with httpOnly and sameSite: lax, lasting 30 days.

How a referral program solves key business problems?

The main challenges include attribution, cheating, code collisions, and inflexible reward logic. Without a systematic approach, the program loses effectiveness. Our solution addresses each issue: from generating unique codes to automatic bonus accrual.

Why is referral attribution critical?

Without correct attribution, referrals are lost. Our data shows that 80% of referrals come within the first 7 days, but if the cookie lives shorter, up to 30% won't be counted. That's why we use a 30-day cookie with httpOnly and sameSite: lax.

Generating unique codes without collisions

Code collisions are a typical issue with off-the-shelf modules. With thousands of users, short codes repeat. We use the nanoid library with an alphabet that avoids confusing characters (1, l, I, 0, O) and a length of 8 characters. We make up to 5 attempts on collision — the probability of repetition is negligible. To speed up collision checking, we use hashing and cache existing codes in Redis.

import { customAlphabet } from 'nanoid';

const generateCode = customAlphabet('ABCDEFGHJKLMNPQRSTUVWXYZ23456789', 8);

export async function getOrCreateReferralCode(userId: string): Promise<string> {
  const existing = await db.referralCode.findUnique({ where: { userId } });
  if (existing) return existing.code;

  for (let attempt = 0; attempt < 5; attempt++) {
    const code = generateCode();
    try {
      const created = await db.referralCode.create({ data: { userId, code } });
      return created.code;
    } catch (e) { 
      // if collision — try again
    }
  }
  throw new Error('Failed to generate unique referral code');
}

How to prevent referral fraud?

Fraud is another headache. Fraudsters register multiple accounts from the same IP or refer themselves. Our approach includes several layers:

  1. Unique referral check (one user — one referral).
  2. Self-referral prohibition (referrer cannot equal referee).
  3. Verification by first payment.
  4. Time-limited cookie (30 days).
  5. Optionally: CAPTCHA or registration limit per IP.

These measures reduce fraud risk by 90%.

How we do it: stack and real case

We use Next.js, Prisma, and PostgreSQL. All critical operations are wrapped in transactions. Consider a typical case from our practice: an e-commerce store with 50,000 products and seasonal promotions. They needed different bonuses for different categories: 10% on electronics, 5% on clothing, fixed amount on new items. Flexible business logic is implemented through custom rules in a separate RewardRules table. Our client noted that after implementing correct attribution, the referral program generated 40% more orders.

Tracking with cookies

Next.js middleware reads the ?ref= parameter from the URL and sets a cookie for 30 days, even if the user doesn't register. On registration, the code from the cookie is read and a referral relationship is created.

// middleware.ts
export function middleware(request: NextRequest) {
  const response = NextResponse.next();
  const ref = request.nextUrl.searchParams.get('ref');
  if (ref && !request.cookies.get('referral_code')) {
    response.cookies.set('referral_code', ref, {
      maxAge: 60 * 60 * 24 * 30,
      httpOnly: true,
      sameSite: 'lax',
    });
  }
  return response;
}

On registration, we extract the code from the cookie and verify that the referrer is not the same as the referee. If the code is valid, we create a Referral record with status PENDING.

Reward accrual

After the first successful payment (e.g., via Stripe), a webhook calls the handleFirstPayment function. It finds the associated referral, calculates the reward amount (e.g., 20% of the payment), and in a transaction updates the status and credits the referrer's balance. Notification is sent automatically.

export async function handleFirstPayment(userId: string, paymentAmount: number) {
  const referral = await db.referral.findFirst({
    where: { referredUserId: userId, status: 'PENDING' },
    include: { referralCode: true }
  });
  if (!referral) return;

  const rewardAmount = Math.floor(paymentAmount * 0.20);
  await db.$transaction([
    db.referral.update({
      where: { id: referral.id },
      data: { status: 'QUALIFIED', rewardAmount }
    }),
    db.userBalance.upsert({
      where: { userId: referral.referralCode.userId },
      create: { userId: referral.referralCode.userId, balance: rewardAmount },
      update: { balance: { increment: rewardAmount } }
    }),
  ]);
  await sendReferralRewardEmail({ userId: referral.referralCode.userId, amount: rewardAmount });
}

User dashboard

Each user sees their referral link, statistics on invited users (how many pending, qualified, rewarded) and total bonuses earned. A conversion chart and payout history can be added. The dashboard is implemented as a Next.js server component, data fetched via server-side Prisma queries.

Comparison of custom vs. off-the-shelf modules

Criteria Our solution Off-the-shelf (e.g., AffiliateWP)
Business logic flexibility Absolute — any scenario Limited by fixed rules
Backend integration Full data ownership Relies on third-party API
Security Control at each level Possible plugin vulnerabilities
Total cost Tailored development License + customizations

A custom system is justified if you have non-standard reward rules, multiple currencies, or deep ERP integration. A pre-built plugin is faster to implement but rarely offers the needed flexibility.

Process and timeline

Stage Duration Outcome
Analysis 1–2 days Technical specification
Design 1–2 days Data model, API specification
Implementation 3–5 days Working code
Testing 1–2 days Test report
Deployment 1 day Production launch
Implementation details
  • Prisma schema includes models: User, ReferralCode, Referral, RewardRule, UserBalance.
  • All database operations are wrapped in transactions for consistency.
  • To avoid race conditions during code generation, we use a unique index and a retry loop.

What's included in development

  • Prisma migration schema
  • Middleware for referral tracking (30-day cookie)
  • Unique code generator with 5 retry attempts
  • API routes: code creation, registration, payment webhook, dashboard
  • Payment gateway integration (Stripe, YooKassa) — webhook setup
  • User dashboard with link copying and statistics
  • Email notifications for bonus accrual
  • API documentation (Swagger/OpenAPI)
  • 2 weeks of technical support after launch

Why choose us

We have over 5 years of experience developing complex web systems, having implemented 20+ referral programs for e-commerce, SaaS, and info-products. We guarantee correct attribution and scalability — handling up to 100,000 referrals per day without performance loss. All code is open and documented.

Order a referral system development that will deliver real results. Get a consultation — we'll assess your project and offer the best solution. Contact us to discuss the details.

Website Marketing Tools: From Plugin Chaos to Production-Ready Mechanics

A typical scenario: a marketer installs a free referral plugin, launches a promo code campaign, and within two weeks 40% of payouts go to emulated devices and burner emails. Promo codes leak via Open Graph previews and spread to coupon aggregators within hours. Attribution reports show first‑click from the marketing dashboard, last‑click from the product team, and the two numbers differ by 35% – budget decisions become a guessing game. We solve this architecturally, not with duct tape.

Referral Links with Anti‑Cheat Protection — website marketing tools

A referral system built on honest server‑side cookies, conversion confirmation via server‑to‑server API, and multi‑factor limits – IP, device fingerprint, time window. Self‑referrals are blocked at the backend, multi‑account attempts are detected by pattern analysis (same IP + different User‑Agent + identical time gap). Payouts are frozen until source verification passes automated checks. Integration with CRM (Bitrix24, amoCRM, HubSpot) gives the manager a single pane: source, inviter, conversion value, and rejection reason if any.

Promo Codes and Partner Programs

Personal and mass codes with granular limits – quantity, date range, minimum order value, one‑use per customer. Multi‑level partner program (invite‑your‑invitee) with automatic bonus accrual and withdrawal via a personal cabinet. Analytics per code: conversion rate, average order value, ROI. We log every usage event to a dedicated table (PostgreSQL + Redis for counters), so fraud patterns become visible within minutes.

Precise Conversion Attribution – Why Last‑Click Is Not Enough

UTM tagging with strict validation (case‑sensitive, forbidden characters filter), micro‑conversion events (CTA click, scroll to form, add to cart), dual‑stream integration: client‑side (GA4 + Yandex.Metrica) and server‑side (own tracker via Segment or custom endpoint). Multi‑touch attribution distributes weight across touchpoints using a configurable decay model – linear, time‑decay, or position‑based. The result: marketing and product teams see the same numbers.

How Do We Prevent Fraud Without Breaking User Experience?

Static rules block legitimate users too. Instead we apply a scoring system: each click gets a risk score (0‑100) based on device fingerprint, referral chain depth, and time between referral and conversion. Only scores above 85 freeze payout pending manual review. This cuts false positives from typical 15% down to 2% while catching 98% of bot‑generated referrals.

Stage Deliverable
Audit of existing mechanics Report with bottlenecks: where attribution is lost, which channels are underestimated, which fraud vectors are open
System design Flow diagrams, tracking points, anti‑cheat limits, fallback scenarios
Development Referral links, promo codes, partner cabinet, server API, scoring engine
Integration CRM (Bitrix24, amoCRM, HubSpot), GA4, Yandex.Metrica, email/SMS notifications
Testing Load test (1000 concurrent referrals), fraud simulation, unit + e2e tests

What Does Multi‑Touch Attribution Actually Change?

In a recent e‑commerce project (180 000 users/month) we replaced last‑click with a linear model. The previously undervalued social channel jumped from 4% attributed revenue to 18%, and the team reallocated budget accordingly – overall ROAS grew by 22% within two months. Numbers like that don’t appear when you only look at the final click.

Common Implementation Pitfalls (and How We Avoid Them)

What we always check
  • Cookie lifetime expiry: too short loses organic referrals, too long inflates cross‑session counts – we set 30 days with reset on conversion.
  • Self‑referral detection: naive IP check blocks office colleagues – we add device fingerprint and referral chain depth.
  • Attribution refresh: if a user re‑enters via a different source before converting, weight distribution must be recalculated – we store all touchpoints with timestamps.
  • Promo code idempotency: without it, double‑clicking the Apply button applies the discount twice – idempotency key solves it.
Approach Setup time Fraud resistance Attribution accuracy
Plugin 1–2 hours Low (basic IP check) Last‑click only
Custom built 3–4 weeks High (scoring + server‑side) Multi‑touch, configurable

How We Work and What It Costs

Our team has delivered marketing mechanics for over 150 projects – e‑commerce, SaaS platforms, content portals. We work under a fixed‑deadline contract with a guaranteed milestone schedule. First version (referral links + promo codes + basic attribution) is ready in 3–4 weeks. Full release with anti‑fraud, multi‑touch attribution, and partner cabinet takes 6–8 weeks. Cost is calculated individually based on complexity – get a free estimate by contacting us. We also offer an audit of your current mechanics; the report includes concrete numbers and a roadmap to fix the biggest leaks.

Need a reliable marketing tools system that doesn’t leak money? Order a consultation – we’ll analyse your case and propose an architecture that scales.