# Generate and redeem a referral code

> For the complete documentation index, see [llms.txt](https://docs.talon.one/llms.txt).

Let's create a [promotion rule](/docs/product/rules/overview.md#promotion-rules) that automatically creates a referral code when a customer registers.
When this code is redeemed by a referred friend, the friend gets 50 loyalty points, and the advocate gets 100 points.

## Create the promotion

In the current scenario, let's use two rules:

1. Generate a referral code
1. Friend redeems referral code

### Rule 1: Generate a referral code

We want to check when a customer registers, we should give them a referral code they can
share with their friends.

- Condition: **Check for event types and custom event values** and select **Customer Profile Registration**.
- Effect: **Create referral code** and select **In the current campaign**.

A customer profile registration is a
[built-in event](/docs/dev/concepts/entities/events.md#built-in-events) that happens when
a new customer profile is created via the [Update customer profile][cp] endpoint.

This customer is known as an **Advocate** because the referral code was generated in their session.

### Rule 2: Friend redeems referral code

We want to find a valid referral code, and when we find one, give 100 loyalty points to
the advocate and 50 to the friend.

A referral code always contains the information about the customer related to the creation of the code.

- Conditions:
  - **Referral code is valid**.
  - **Check for default event: Customer Session Closing**.

- Effects:
  1. **Add loyalty points**:
     - **Loyalty program**: **Sample wallet**.
     - **Recipient**: **Advocate**.
     - **Reason**: `100 Bonus points for Advocate`
     - **Amount of points**: `100`
  1. **Add loyalty points**:
     - **Loyalty program**: **Sample wallet**.
     - **Recipient**: **Current Customer (Friend)**.
     - **Reason**: `50 Bonus points for Friend`
     - **Amount of points**: `50`

## Run the campaign

To run the whole campaign, we need two requests to simulate the different stages.

### A customer registers

When a customer registers, they should get a referral code. The customer registration
event is triggered by the [Update Customer Profile][cp] endpoint with a new integration ID
passed as a path parameter.

<Tabs
  defaultValue="req"
  values={[
    {label: '🚀 Request', value: 'req'},
    {label: '✅ Response', value: 'res'},
  ]}>

<TabItem value="req">

Let's assume the `NEWCUSTOMER` id doesn't exist yet and let's call the
**Update customer profile endpoint** with it.

The payload can remain empty, we only need an `integrationId` and the `runRuleEngine` query parameter set to `true`.

```json title="Creating a new profile" {1} showLineNumbers
CURL -X PUT https://mycompany.europe-west1.talon.one/v2/customer_profiles/NEWCUSTOMER?runRuleEngine=true -d
'{
  "attributes": {},
  "audiencesChanges": {
    "adds": [],
    "deletes": []
  },
  "responseContent": []
}'
```

</TabItem>
<TabItem value="res">

We receive this response, which confirms the profile is created and triggers our
first rule:

- Lines 21 and 23: The `referralCreated` generated a referral code shown in `value`.
- Lines 3 and 11: A referral object lists the customer considered as an advocate and the code generated by the effect.

```json title="Response" {9,11,21,23} showLineNumbers
{
  "createdCoupons": [],
  "createdReferrals": [
    {
      "id": 2,
      "created": "2022-12-02T19:05:13.250464045Z",
      "usageLimit": 100,
      "campaignId": 4,
      "advocateProfileIntegrationId": "talonone-ajvrdoy5kv8",
      "attributes": {},
      "code": "JY9P-HYL8",
      "usageCounter": 0
    }
  ],
  "effects": [
    {
      "campaignId": 4,
      "rulesetId": 3,
      "ruleIndex": 0,
      "ruleName": "Generate a referral code",
      "effectType": "referralCreated",
      "props": {
        "value": "JY9P-HYL8"
      }
    }
  ]
}
```

</TabItem>
</Tabs>

Let's imagine that our customer received their referral code and gave it to a friend.

### A friend places an order

Our first customer's friend places an order containing the referral code. Let's test creating
this session, using the [Update customer session][cs] endpoint:

<Tabs
  defaultValue="req"
  values={[
    {label: '🚀 Request', value: 'req'},
    {label: '✅ Response', value: 'res'},
  ]}>

<TabItem value="req">

To trigger the rule, we must send a valid referral code.

```json title="Sending a session update" {21} showLineNumbers
CURL -X PUT https://mycompany.europe-west1.talon.one/v2/customer_sessions/68476946 -d
'{
  "customerSession": {
    "profileId": "673TGNRP35",
    "state": "open",
    "cartItems": [
      {
        "name": "ProductC",
        "sku": "sku-00004",
        "quantity": 1,
        "price": 100,
        "Category": "Accessories",
        "weight": 0,
        "position": 0,
        "attributes": {}
      }
    ],
    "couponCodes": [
      ""
    ],
    "referralCode": "JY9P-HYL8",
    "attributes": {},
    "additionalCosts": {}
  },
  "responseContent": []
}'
```

</TabItem>
<TabItem value="res">

We receive this response:

- Lines 10 and 12: `acceptReferral` means the referral code found in the session is valid.
- Lines 20, 25, and 26: `addLoyaltyPoints` represents the 100 points given to the advocate.
- Lines 35, 40 and 45: `addLoyaltyPoints` represents the 50 points given to the friend.

```json title="Response" {10,12,20,25,26,35,40,41} showLineNumbers
{
  "createdCoupons": [],
  "createdReferrals": [],
  "effects": [
    {
      "campaignId": 246,
      "rulesetId": 491,
      "ruleIndex": 1,
      "ruleName": "Friend redeems referral code: 100 bonus points for advocate and 50 bonus points for friend",
      "effectType": "acceptReferral",
      "props": {
        "value": "JY9P-HYL8"
      }
    },
    {
      "campaignId": 246,
      "rulesetId": 491,
      "ruleIndex": 1,
      "ruleName": "Friend redeems referral code: 100 bonus points for advocate and 50 bonus points for friend",
      "effectType": "addLoyaltyPoints",
      "props": {
        "name": "100 Bonus points for Advocate",
        "programId": 1,
        "subLedgerId": "",
        "value": 100,
        "recipientIntegrationId": "talonone-ajvrdoy5kv8",
        "transactionUUID": "5b6c55d0-0f65-4bd0-9f50-ffaea62162ef"
      }
    },
    {
      "campaignId": 246,
      "rulesetId": 491,
      "ruleIndex": 1,
      "ruleName": "Friend redeems referral code: 100 bonus points for advocate and 50 bonus points for friend",
      "effectType": "addLoyaltyPoints",
      "props": {
        "name": "50 bonus points for friend",
        "programId": 1,
        "subLedgerId": "",
        "value": 50,
        "recipientIntegrationId": "talonone-2wv1mr9vlw6",
        "transactionUUID": "0c822264-ca42-4d22-b39a-83e8fd40c16d"
      }
    }
  ]
}
```

</TabItem>
</Tabs>

:::tip Key Takeaways

- A referral consists of an advocate who refers a friend.
- You can use many rules in one campaign. A request can trigger several rules at
  once, or you might need specific requests. This depends on your conditions.
- You can trigger the rules with the [Update customer profile][cp] endpoint, as well as the
  [Update customer session][cs] endpoint.

:::

## Related pages

- [Referrals](/docs/product/campaigns/referrals/referral-overview.md)
- [Referral campaign tutorials](/docs/product/tutorials/referrals.md)
- [Update customer session endpoint][cs]
- [Use conditions](/docs/product/rules/conditions/overview.md) and [effects](/docs/product/rules/effects/overview.md)

[cs]: /integration-api#tag/Customer-sessions/operation/updateCustomerSessionV2
[cp]: /integration-api#tag/Customer-profiles/operation/updateCustomerProfileV2
