> ## Documentation Index
> Fetch the complete documentation index at: https://docs.letterby.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Building referrals and rewards

> Learn how to implement viral referral systems and reward mechanisms that drive engagement and growth

# Building referrals and rewards

Referrals and rewards are the heart of any successful waitlist. They create
viral loops that drive organic growth while keeping users engaged. This guide
will show you how to implement both systems using Letterby.

## Understanding the referral system

Letterby automatically generates unique referral links for each contact. When
someone signs up using a referral link, both the referrer and referee benefit:

* **Referrer**: Gets points and moves up in the waitlist
* **Referee**: May get bonus points for being referred
* **You**: Get organic growth and higher conversion rates

### How referrals work

1. Each contact gets a unique `referralLink` when they join
2. When someone clicks their referral link and signs up, the referrer's
   `referrals` count increases
3. You can reward the referrer with points using the Actions API
4. The system tracks everything automatically

## Setting up referral rewards

### 1. Track referral events

When a new user signs up through a referral link, Letterby automatically:

* Increments the referrer's `referrals` count
* Tracks the connection between referrer and referee

You can then award points to the referrer for successful referrals:

<CodeGroup>
  ```javascript Node.js theme={null}
  // Award points to a referrer for successful referral
  async function rewardReferral(referrerContactId, referredEmail) {
  	try {
  		// Award points to the referrer
  		const response = await fetch('https://letterby.com/api/v4/actions', {
  			method: 'POST',
  			headers: {
  				'Content-Type': 'application/json',
  				apiKey: 'YOUR_API_KEY',
  			},
  			body: JSON.stringify({
  				contactId: referrerContactId,
  				name: `Referred ${referredEmail}`,
  				increase: 50, // 50 points for successful referral
  			}),
  		})

  		const result = await response.json()
  		console.log('Referral reward added:', result)
  	} catch (error) {
  		console.error('Failed to reward referral:', error)
  	}
  }
  ```

  ```python Python theme={null}
  import requests

  def reward_referral(referrer_contact_id, referred_email):
      """Award points to a referrer for successful referral"""
      try:
          response = requests.post(
              'https://letterby.com/api/v4/actions',
              headers={
                  'Content-Type': 'application/json',
                  'apiKey': 'YOUR_API_KEY'
              },
              json={
                  'contactId': referrer_contact_id,
                  'name': f'Referred {referred_email}',
                  'increase': 50  # 50 points for successful referral
              }
          )

          result = response.json()
          print('Referral reward added:', result)
      except Exception as error:
          print('Failed to reward referral:', error)
  ```
</CodeGroup>

### 2. Reward the referee

You can also give bonus points to new users who were referred:

<CodeGroup>
  ```javascript Node.js theme={null}
  // Give bonus points to someone who was referred
  async function rewardReferee(newContactId, referrerName) {
  	try {
  		const response = await fetch('https://letterby.com/api/v4/actions', {
  			method: 'POST',
  			headers: {
  				'Content-Type': 'application/json',
  				apiKey: 'YOUR_API_KEY',
  			},
  			body: JSON.stringify({
  				contactId: newContactId,
  				name: `Referred by ${referrerName}`,
  				increase: 10, // 10 bonus points for being referred
  			}),
  		})

  		const result = await response.json()
  		console.log('Referee bonus added:', result)
  	} catch (error) {
  		console.error('Failed to reward referee:', error)
  	}
  }
  ```

  ```bash cURL theme={null}
  curl --request POST \
    --url https://letterby.com/api/v4/actions \
    --header 'Content-Type: application/json' \
    --header 'apiKey: YOUR_API_KEY' \
    --data '{
      "contactId": "new_contact_123",
      "name": "Referred by John Doe",
      "increase": 10
    }'
  ```
</CodeGroup>

## Building a comprehensive reward system

### Common reward scenarios

Here are effective reward strategies that drive engagement:

#### Social sharing rewards

<CodeGroup>
  ```javascript Social Media Shares theme={null}
  // Reward users for sharing on social media
  const socialRewards = {
  	twitter: { points: 15, name: 'Shared on Twitter' },
  	linkedin: { points: 15, name: 'Shared on LinkedIn' },
  	facebook: { points: 10, name: 'Shared on Facebook' },
  	instagram: { points: 20, name: 'Shared on Instagram Story' },
  }

  async function rewardSocialShare(contactId, platform) {
  	const reward = socialRewards[platform]
  	if (!reward) return

  	await fetch('https://letterby.com/api/v4/actions', {
  		method: 'POST',
  		headers: {
  			'Content-Type': 'application/json',
  			apiKey: 'YOUR_API_KEY',
  		},
  		body: JSON.stringify({
  			contactId,
  			name: reward.name,
  			increase: reward.points,
  		}),
  	})
  }
  ```

  ```javascript Profile Completion theme={null}
  // Reward users for completing their profile
  async function rewardProfileCompletion(contactId, completedFields) {
  	const rewards = {
  		name: 5,
  		phone: 10,
  		company: 15,
  		social_links: 20,
  	}

  	for (const field of completedFields) {
  		if (rewards[field]) {
  			await fetch('https://letterby.com/api/v4/actions', {
  				method: 'POST',
  				headers: {
  					'Content-Type': 'application/json',
  					apiKey: 'YOUR_API_KEY',
  				},
  				body: JSON.stringify({
  					contactId,
  					name: `Completed ${field}`,
  					increase: rewards[field],
  				}),
  			})
  		}
  	}
  }
  ```
</CodeGroup>

#### Engagement rewards

<CodeGroup>
  ```javascript Daily Check-ins theme={null}
  // Reward daily engagement
  async function rewardDailyCheckin(contactId) {
  	await fetch('https://letterby.com/api/v4/actions', {
  		method: 'POST',
  		headers: {
  			'Content-Type': 'application/json',
  			apiKey: 'YOUR_API_KEY',
  		},
  		body: JSON.stringify({
  			contactId,
  			name: 'Daily check-in',
  			increase: 2, // Small daily reward
  		}),
  	})
  }
  ```

  ```javascript Newsletter Subscription theme={null}
  // Reward newsletter signups
  async function rewardNewsletterSignup(contactId) {
  	await fetch('https://letterby.com/api/v4/actions', {
  		method: 'POST',
  		headers: {
  			'Content-Type': 'application/json',
  			apiKey: 'YOUR_API_KEY',
  		},
  		body: JSON.stringify({
  			contactId,
  			name: 'Subscribed to newsletter',
  			increase: 25,
  		}),
  	})
  }
  ```
</CodeGroup>

### Milestone rewards

Create special rewards for reaching certain milestones:

```javascript theme={null}
async function checkAndRewardMilestones(contactId) {
	// Get contact details to check current stats
	const contact = await fetch(
		`https://letterby.com/api/v4/contacts/${contactId}`,
		{
			headers: { apiKey: 'YOUR_API_KEY' },
		},
	).then(res => res.json())

	const { referrals, points } = contact.data.contact

	// Referral milestones
	const referralMilestones = [
		{ count: 5, reward: 100, name: 'First 5 referrals bonus' },
		{ count: 10, reward: 250, name: 'First 10 referrals bonus' },
		{ count: 25, reward: 500, name: 'Super referrer bonus' },
	]

	// Point milestones
	const pointMilestones = [
		{ count: 100, reward: 50, name: 'First 100 points milestone' },
		{ count: 500, reward: 100, name: 'Power user milestone' },
		{ count: 1000, reward: 200, name: 'Elite member milestone' },
	]

	// Check and award milestone rewards
	// (You'd need to track which milestones were already awarded)
}
```

## Advanced referral strategies

### Tiered referral rewards

Create increasing rewards for multiple referrals:

```javascript theme={null}
const referralTiers = [
	{ min: 1, max: 2, points: 25, name: 'Referral reward' },
	{ min: 3, max: 4, points: 35, name: 'Active referrer bonus' },
	{ min: 5, max: 9, points: 50, name: 'Super referrer bonus' },
	{ min: 10, max: Infinity, points: 75, name: 'Elite referrer bonus' },
]

async function getRewardForReferralCount(referralCount) {
	const tier = referralTiers.find(
		t => referralCount >= t.min && referralCount <= t.max,
	)
	return tier || referralTiers[0]
}
```

### Limited-time bonus campaigns

Create urgency with temporary bonus rewards:

```javascript theme={null}
async function applyBonusCampaign(contactId, actionName, basePoints) {
	const now = new Date()
	const isWeekend = now.getDay() === 0 || now.getDay() === 6
	const isHappyHour = now.getHours() >= 18 && now.getHours() <= 20

	let multiplier = 1
	let bonusName = actionName

	if (isWeekend) {
		multiplier = 1.5
		bonusName += ' (Weekend Bonus)'
	}

	if (isHappyHour) {
		multiplier *= 1.2
		bonusName += ' (Happy Hour)'
	}

	const finalPoints = Math.floor(basePoints * multiplier)

	await fetch('https://letterby.com/api/v4/actions', {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
			apiKey: 'YOUR_API_KEY',
		},
		body: JSON.stringify({
			contactId,
			name: bonusName,
			increase: finalPoints,
		}),
	})
}
```

## Retrieving referral data

### Get a contact's referral information

You can retrieve referral stats for any contact:

<CodeGroup>
  ```javascript Get Referral Stats theme={null}
  async function getReferralStats(contactId) {
  	try {
  		const response = await fetch(
  			`https://letterby.com/api/v4/contacts/${contactId}`,
  			{
  				headers: {
  					apiKey: 'YOUR_API_KEY',
  				},
  			},
  		)

  		const result = await response.json()
  		const contact = result.data.contact

  		return {
  			referralLink: contact.referralLink,
  			referralCount: contact.referrals,
  			totalPoints: contact.points,
  			position: contact.position,
  		}
  	} catch (error) {
  		console.error('Failed to get referral stats:', error)
  	}
  }
  ```

  ```python Get Referral Stats theme={null}
  def get_referral_stats(contact_id):
      """Get referral statistics for a contact"""
      try:
          response = requests.get(
              f'https://letterby.com/api/v4/contacts/{contact_id}',
              headers={'apiKey': 'YOUR_API_KEY'}
          )

          result = response.json()
          contact = result['data']['contact']

          return {
              'referralLink': contact['referralLink'],
              'referralCount': contact['referrals'],
              'totalPoints': contact['points'],
              'position': contact['position']
          }
      except Exception as error:
          print('Failed to get referral stats:', error)
  ```
</CodeGroup>

### Track action history

See all rewards a contact has earned:

```javascript theme={null}
async function getContactActions(contactId) {
	try {
		const response = await fetch(
			`https://letterby.com/api/v4/actions?contactId=${contactId}`,
			{
				headers: {
					apiKey: 'YOUR_API_KEY',
				},
			},
		)

		const result = await response.json()
		return result.data.actions
	} catch (error) {
		console.error('Failed to get actions:', error)
	}
}
```

## Best practices for referrals and rewards

### Design effective reward structures

1. **Make referrals valuable**: Offer meaningful rewards (25-100 points) for
   successful referrals
2. **Reward both parties**: Give bonuses to both referrer and referee
3. **Create urgency**: Use limited-time bonuses and campaigns
4. **Gamify progression**: Create milestones and achievement levels

### Technical implementation tips

1. **Validate actions**: Ensure users can't game the system
2. **Rate limiting**: Prevent abuse with reasonable limits
3. **Clear communication**: Always tell users what they earned and why
4. **Analytics**: Track which rewards drive the most engagement

### Common reward values

Based on successful Waitlist campaigns:

* **Referral completion**: 25-100 points
* **Social media shares**: 10-25 points
* **Profile completion**: 5-50 points (based on complexity)
* **Daily check-ins**: 1-5 points
* **Newsletter signup**: 15-30 points
* **Milestone bonuses**: 50-500 points

## Measuring success

Track these key metrics to optimize your referral and reward system:

* **Referral conversion rate**: Percentage of referral link clicks that convert
* **Average referrals per user**: How viral is your waitlist?
* **Point distribution**: Which rewards are most popular?
* **Engagement over time**: Are rewards keeping users active?

<Info>
  Want to see this in action? Check out our [complete integration
  example](/guides/implementing-letterby) for a full implementation that
  includes referrals and rewards.
</Info>

## Troubleshooting

### Common issues

**Referral links not working**

* Ensure contacts are verified before their referral links become active
* Check that the referring contact exists and is valid

**Points not being awarded**

* Verify the contact ID is correct
* Ensure the action name is descriptive and unique
* Check that your API key has the proper permissions

**Duplicate rewards**

* Implement checks to prevent duplicate rewards for the same action
* Use unique action names that include timestamps or unique identifiers

Remember: A well-designed referral and reward system can increase your waitlist
signups by 3-5x while keeping users highly engaged throughout their journey!
