Referral System Development: Codes, Attribution, Payouts
Imagine: you launch a referral program, and a week later you see hundreds of registrations from a single IP with the same referral code. Without proper attribution and fraud protection, such abuse eats your budget and demotivates real users. We design and implement referral programs that turn your customers into acquisition agents — with unique code generation, reliable cookie-based attribution, and multi‑layer fraud protection. Over five years we have built more than 30 such solutions for e‑commerce, SaaS, and educational platforms. Here is how the technical implementation looks.
Data Model and Code Generation
The database schema includes four key tables: referral_codes, referral_clicks, referrals, and referral_rewards. Each unique code is generated for a user once and remains unchanged. We use readable codes based on name or a mix of letters and digits — so users easily remember and share them. For fast lookup we add indexes on code and user_id.
CREATE TABLE referral_codes (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT REFERENCES users(id),
code VARCHAR(32) UNIQUE NOT NULL,
type VARCHAR(32) DEFAULT 'personal',
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE referral_clicks (
id BIGSERIAL PRIMARY KEY,
code_id BIGINT REFERENCES referral_codes(id),
ip INET,
user_agent TEXT,
landed_at TIMESTAMPTZ DEFAULT NOW(),
converted BOOLEAN DEFAULT FALSE
);
CREATE TABLE referrals (
id BIGSERIAL PRIMARY KEY,
referrer_id BIGINT REFERENCES users(id),
referred_id BIGINT REFERENCES users(id),
code_id BIGINT REFERENCES referral_codes(id),
status VARCHAR(32) DEFAULT 'pending',
qualified_at TIMESTAMPTZ,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE TABLE referral_rewards (
id BIGSERIAL PRIMARY KEY,
referral_id BIGINT REFERENCES referrals(id),
recipient_id BIGINT REFERENCES users(id),
type VARCHAR(32),
amount DECIMAL(14,2),
currency CHAR(3) DEFAULT 'RUB',
status VARCHAR(32) DEFAULT 'pending',
paid_at TIMESTAMPTZ
);
How Referral Attribution Works
Attribution starts with a middleware that intercepts the GET parameter ?ref=CODE and stores it in the session. Even if the user does not register immediately, the code remains tied to the session for the entire visit. Upon registration we check the code and create a record in referrals with status pending. Next, we log the click and mark it as converted. The session lifetime is configurable — by default 24 hours for accurate attribution.
// Middleware: ReferralTracker
class ReferralTrackerMiddleware {
public function handle(Request $request, Closure $next): Response {
$code = $request->query('ref');
if ($code && !session()->has('referral_code')) {
$referralCode = ReferralCode::where('code', $code)->first();
if ($referralCode) {
session(['referral_code' => $code]);
ReferralClick::create([
'code_id' => $referralCode->id,
'ip' => $request->ip(),
'user_agent' => $request->userAgent(),
]);
}
}
return $next($request);
}
}
// In UserRegistrationService
public function register(array $data): User {
$user = User::create($data);
$referralCode = session()->pull('referral_code');
if ($referralCode) {
$code = ReferralCode::where('code', $referralCode)->first();
if ($code && $code->user_id !== $user->id) {
Referral::create([
'referrer_id' => $code->user_id,
'referred_id' => $user->id,
'code_id' => $code->id,
'status' => 'pending',
]);
ReferralClick::where('code_id', $code->id)
->where('converted', false)
->latest('landed_at')
->first()
?->update(['converted' => true]);
}
}
return $user;
}
Qualification Conditions and Reward Types
A referral is considered qualified only after performing a target action — for example, first payment or profile completion. We implement this through an event system. Comparison of reward types:
| Type |
Description |
When Suitable |
| Fixed |
Fixed amount per qualification, e.g., $10 |
Low average order value, simple products |
| Percentage |
Percentage of the referral's purchase amount, e.g., 10% |
High average order value, subscriptions |
| Points |
Bonus points |
Ecosystems with internal currency |
Fixed rewards are simpler to implement, but percentage rewards scale with average order value. A two‑sided program (bonus to both referrer and new user) gives an extra push to registrations. In practice, percentage schemes are 2x better than fixed rewards for attracting active referrers.
How to Choose Reward Type?
It all depends on the average order value and monetization model. If the product is low‑priced, a fixed amount of a few hundred works well. For subscriptions with high LTV, percentage is more advantageous — for instance, 10% of the first payment motivates more than a one‑time bonus. We always analyze the economics and propose an optimized scheme. In one project, switching from fixed to percentage bonus cut the CPA almost by half (from $15 to $8) while maintaining referrer motivation.
Why Fraud Protection Matters
Without protection, the referral program becomes an easy target for abuse. We implement basic checks: self‑referral prohibition, limit on registrations from one IP (no more than three in seven days), and flags for manual review of suspicious chains. Session validity is also configured to prevent attribution months after a click. According to our data, fraud protection reduces losses by 80% compared to having none, saving clients $5,000–$15,000 annually.
What's Included in the Work
- Documentation of the data schema and description of API endpoints for the referrer dashboard.
- Admin interface to manage referral programs and view statistics.
- Unit tests for attribution and reward accrual.
- Deployment on a server or in a container (Docker).
- Integration with a payment system for batch payouts.
- Connection to CRM via REST API for partner data sync.
Process Overview
- Analysis — we examine the target audience, monetization model, qualification conditions.
- Design — choose topography (single‑level/MLM), draw ERD, agree on attribution logic.
- Implementation — write code on Laravel 11 / Next.js 14 (React), configure queues for deferred payouts.
- Testing — verify chains: click → registration → purchase → accrual → payout.
- Deployment — push to staging, perform load testing (guarantee 10k concurrent clicks), then launch to production.
Timeline
| Version |
Time |
| Basic (codes, attribution, fixed reward) |
1–1.5 wk |
| Two‑sided + percentage bonuses |
2–2.5 wk |
| Multi‑level (MLM) |
+1–2 wk |
The cost is calculated individually: it depends on scheme complexity, CRM integration needs, and fraud protection requirements. Typical budgets range from $5,000 to $20,000. Contact us to discuss your referral program — we'll find the optimal solution. Get a consultation on reward scheme selection, based on our experience with thirty projects. Source: Referral marketing effectiveness study, 2023.
Website CRM Integration: Bitrix24, amoCRM, Salesforce, HubSpot
A sales manager manually copies leads from email into the CRM. Half of them never make it. Follow‑up calls are missed. This isn’t a people problem — it’s an architectural gap between the website and the company’s core system. We close that gap with a direct site‑to‑CRM connection: leads land in the pipeline within 30 seconds after form submission, duplication is blocked, and status changes flow both ways automatically. Request a free integration audit to identify the bottlenecks in your current flow.
Integration isn’t just a POST to an API endpoint. It’s a battle against timeouts, duplicate records, data loss, and desynchronised states. We handle three core problems at once: asynchronous delivery (so the user never waits for the CRM), deduplication by email (one address – one lead), and two‑way feedback (a status change in the CRM instantly appears on the site). Below is how we tackle each.
Bitrix24: REST API and Event Handlers
Bitrix24 dominates the Russian B2B space. Its REST API works via OAuth 2.0 or an incoming webhook (webhook is simpler but less secure for production). Main entities are lead, deal, contact, and company.
Creating a lead requires POST /rest/crm.lead.add with the correct field set. Attaching it to a funnel means passing SOURCE_ID. Adding a timeline comment uses crm.timeline.comment.add. Real‑time tracking is done through Event Handlers: register a hook with event.bind; Bitrix24 pushes a POST to your endpoint when any deal status changes.
The real complexity lies in custom fields. Every Bitrix24 installation has its own set, and their IDs must be fetched via crm.lead.fields. Mapping those fields between the site and the CRM can be done manually or automatically — we use an automatic detection mechanism that works even in non‑standard configurations (proven on 20+ projects). We guarantee correct matching, so no lead arrives without the right pipeline stage or source tag.
amoCRM: Clean REST with Predictable Endpoints
amoCRM (now Kommo for international markets) offers a cleaner API. OAuth 2.0 with refresh token, JSON API, and well‑structured endpoints. Pipelines are pipelines, deals are leads, contacts are contacts.
A common mistake: when creating a deal you must supply pipeline_id and status_id explicitly. Without them the deal lands in the default pipeline – often the wrong one. Tags for source classification go into _embedded.tags. Incoming webhooks are configured in the admin panel; they support add, update, delete, status, and note events. We always verify the webhook signature using the API key and make sure the endpoint responds with 200 OK in under 5 seconds – otherwise the CRM marks delivery as failed.
Salesforce and HubSpot: Enterprise‑Grade Integration
Salesforce is the enterprise standard. It offers REST API, SOQL for complex queries, and Apex for server‑side logic. Integration can be direct via Salesforce REST API or through middleware like Zapier or MuleSoft. For PHP projects we use phpforce/soap-client or the Force.com‑Toolkit. The main challenge is mapping hundreds of custom objects and fields; we solve it with Describe Global to collect metadata automatically – cutting setup time by three‑quarters compared to reading documentation manually (Salesforce Developer Guide).
HubSpot is popular among SaaS companies and international B2B. Its API v3 provides a REST interface with solid SDKs for PHP and Node.js (@hubspot/api-client). Contacts, Companies, Deals are standard objects. The Forms API lets you send data from any custom form directly to HubSpot without using the native widget. One pitfall: the access_token must include the right scopes; a misconfigured token returns 403 Forbidden with a vague message. We include error_logging that captures the error code – debugging takes minutes instead of hours.
Which CRM fits your business: Bitrix24, amoCRM, or HubSpot?
| Criteria |
Bitrix24 |
amoCRM |
HubSpot |
| API complexity |
Medium (REST + webhooks, custom fields) |
Low (clean JSON API) |
Medium (REST + SDK, OAuth 2.0) |
| Typical synchronous latency |
200‑600 ms |
100‑300 ms |
150‑400 ms |
| Built‑in deduplication by email |
crm.duplicate.findByComm |
Contact search |
contacts/search |
| Webhook events |
Event Handlers (push) |
Admin panel configuration |
Webhook + Automations |
| Best suited for |
Russian B2B, government, custom fields |
Small‑ to medium‑sized business |
International B2B, SaaS |
Why is asynchronous sending important?
Calling a CRM API synchronously from the form handler is a mistake. The API may respond in 2 seconds – or time out. The user sits waiting. The correct pattern: form submission → save to database → queue a job → return 200 to the user immediately. A background worker then pushes the lead to the CRM. If the CRM is down, the worker retries with exponential backoff. We use Redis + Bull on Node.js or Laravel Queue on PHP – this guarantees delivery even during temporary outages.
Deduplication – how we stop duplicate leads
The same contact may fill the form twice. Without deduplication the CRM ends up with two identical leads. Before creating a new lead we search by email: for Bitrix24 we call crm.duplicate.findByComm, for HubSpot we use contacts/search. If a match is found we attach a task or comment to the existing lead instead of creating a new one. In our projects this cuts duplicate entries by 95%.
Two‑way synchronization – what happens when a manager changes a deal status
If a manager updates a deal status in the CRM, the website needs to reflect that change – especially if the client has a personal account. We configure webhooks from the CRM to an endpoint on the site, then update the local database and notify the client. Critical details: verify the webhook signature and respond with 200 OK within 5 seconds, otherwise the CRM assumes delivery failed. We guarantee that the delay between a status change in the CRM and its appearance on the site never exceeds 3 seconds.
How do we conduct integration in 5 steps?
- Audit of data flows – analyse current lead transfer, CRM field structure, and performance bottlenecks. Deliverable: “as‑is” and “to‑be” data flow diagrams.
- Architecture design – choose the queue mechanism (Redis Bull or Laravel Queue), define the deduplication method, and prepare a field mapping specification.
- Implementation on staging – write code on Laravel or Node.js, configure webhooks, and test with real data: lead creation, status updates, and error handling.
- Load testing – simulate peak traffic (e.g. 500 requests per minute) and adjust retry policies and timeout settings.
- Deployment and documentation – push to production, train the team on monitoring and retry cleanup, and deliver full endpoint documentation.
What is included in the work
- Audit report with current data flow diagrams and typical error patterns.
- Architecture design document specifying queue, deduplication, and mapping.
- Production‑ready integration code on Laravel or Node.js.
- Webhook configuration and signature verification.
- Team training on support tasks and retry cleanup.
- 30‑day warranty support for bug fixes and mapping adjustments.
Real‑world case: real‑estate agency with 400 leads per month
Click to expand
A real‑estate agency processed every incoming lead manually – 400 leads per month. Each lead took 3 minutes to enter, and 15% were lost because emails were missed. We integrated their site with amoCRM using asynchronous queue delivery and automatic deduplication. Leads now appear in the pipeline within 5 seconds, and leftover tasks are automatically assigned to the next available agent. Result: 30% increase in conversion and $12,000 saved annually in administrative overhead.
Timelines
| Scenario |
Duration |
| One CRM, lead transfer from forms |
1‑2 weeks |
| Two‑way synchronization + statuses |
3‑5 weeks |
| Multiple CRM + custom field mapping |
4‑8 weeks |
The exact cost is calculated after an audit of your current processes and CRM data structure. Contact us for a project estimate – we will send a commercial proposal within one business day. With 5+ years of experience and more than 20 completed integrations, you get a solution that works from day one. Get an engineer consultation to see how your sales funnel can run without manual lead transfer.
Additional sources: Customer relationship management (Wikipedia) · REST API (Wikipedia)