> For the complete documentation index, see [llms.txt](https://native-app-co.gitbook.io/stork-credit/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://native-app-co.gitbook.io/stork-credit/getting-started/setting-up-referrals.md).

# Setting up referrals

Set up a referral program in three parts: create referral codes, add an automatic reward rule, and add a Referral Code block to your cart, checkout or Thank you page.

Referrals take three parts: a code, an automatic reward rule and a Referral Code block. It works like this:

1. A shopper enters a code in your cart, at checkout, or on the Thank you page after ordering.
2. Stork Credit tags the customer with that code, for example `referral:SUMMER25`. This happens once the order is placed, or straight away on the Thank you page.
3. Your reward rule sees the tag and issues store credit for the order. For a code entered on the Thank you page after the order is already paid, the rule runs again so the order is still rewarded.

This works for guest checkouts as well as logged-in customers.

{% hint style="info" %}
Referral codes are available on the **Grow** and **Pro** plans. On the Free plan, the Referral Code blocks in your cart and checkout reject every code, and the Thank you page block is hidden. See [Plans & billing](/stork-credit/reference/plans-and-billing.md).
{% endhint %}

## Part 1: Set up referral codes

Create one code for each influencer or partner.

1. Open Stork Credit and click **Referral codes** in the app menu.
2. Under **New code**, fill in the fields below.
3. Click **Create code**.

| Field               | What it does                                                                                                              |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| **Code**            | What shoppers type in the Referral Code block, for example `SUMMER25`. It isn't case-sensitive and can't be changed later |
| **Label**           | Optional. A note for you, such as the influencer's name                                                                   |
| **Success message** | Shown in the Referral Code block when the code is accepted. Defaults to *Code Successfully Applied*                       |

Each code gets a customer tag, shown in **Your codes**, for example `referral:SUMMER25`. The reward rule in Part 2 looks for this tag.

* **Edit** changes a code's label or success message.
* **Disable** stops the code being accepted without deleting it.
* **Delete** removes the code permanently.

## Part 2: Create the automatic reward

A code on its own issues nothing. The reward comes from an [order-value automation](/stork-credit/automations/order-value-automations.md) that only applies to customers carrying the code's tag. The reward is store credit on the customer's account, not a discount at checkout.

On the **Referral codes** page, pick one of two shortcuts:

| Button                               | Where                 | Use it to                                                                              |
| ------------------------------------ | --------------------- | -------------------------------------------------------------------------------------- |
| **Create reward rule**               | Next to a code        | Reward one code differently, for example a bigger reward for one influencer's audience |
| **Create reward rule for all codes** | Beside **Your codes** | Use one rule for every code, matching any tag that starts with `referral:`             |

Either button opens a new order-value rule with these settings already filled in:

* **Customer eligibility:** Customers with specific tags, set to the code's tag.
* **Uses per customer:** Once per customer.
* **Credit type:** Fixed amount.

Then finish the rule:

1. Enter the reward **Amount**, or switch **Credit type** to a percentage of the order.
2. Set anything else you need, such as a minimum order value or an expiry for the credit.
3. **Save** the rule, then **activate** it.

{% hint style="warning" %}
An inactive rule credits nobody. Make sure the rule is active before you share your codes.
{% endhint %}

You can also start from the **Referral reward** [template](/stork-credit/automations/templates.md) under **Automations**.

## Part 3: Add the Referral Code block

Shoppers need somewhere to enter a code. There are three places to add a Referral Code block. Use any of them, or all of them:

* **Theme block**: for your cart page or anywhere else in your theme. Works on every Shopify plan.
* **Thank you page block**: for the page shoppers see after ordering. Works on every Shopify plan.
* **Checkout block**: for your checkout. Needs a store on **Shopify Plus**.

The quickest way to add the theme and checkout blocks is from the app. On the **Referral codes** page, under **Add the Referral Code block**, click **Add to theme** or **Add to checkout**. Each button opens the right Shopify editor in a new tab. **Add to checkout** only appears on stores on Shopify Plus.

### In your cart (any Shopify plan)

1. On the **Referral codes** page, click **Add to theme**. The theme editor opens on your **Cart** page with the **Referral Code** block already added.
2. Optional: drag the block to where you want it, and change the heading, button text, messages and colours in the block's settings.
3. Click **Save**.

To add the block to a different page, or to add it by hand:

1. In Shopify admin, go to **Online Store → Themes** and click **Customize**.
2. Open your **Cart** page, or whichever page you want it on.
3. Click **Add block → Apps → Referral Code**.
4. Click **Save**.

#### Adding it with HTML and Liquid instead

If you can't add the block in the theme editor, paste the code below into your theme instead. This helps if:

* **Apps** doesn't appear under **Add block** on your cart page. This is common on older themes.
* You want the code field in a cart drawer or pop-up cart.
* You want to match your theme's design exactly.

The code works the same way as the block. It checks the code with Stork Credit, shows your success message, and saves the code on the cart so it reaches the order.

{% hint style="info" %}
**On a newer theme? Try Custom Liquid first.** In the theme editor, open your **Cart** page and click **Add section → Custom Liquid**, or **Add block → Custom Liquid** if your theme offers it. Paste the code below into the **Liquid code** box and click **Save**. You don't need to edit any theme files.
{% endhint %}

To add it to your theme files:

1. In Shopify admin, go to **Online Store → Themes**. Click **⋯ → Duplicate** to make a backup first.
2. On your live theme, click **⋯ → Edit code**.
3. Under **Snippets**, click **Add a new snippet**. Name it `stork-referral` and click **Done**.
4. Paste the code below into the new snippet and click **Save**.
5. Open the file for your cart and paste this line where the code field should appear:

   ```liquid
   {%- render 'stork-referral' -%}
   ```

   File names vary by theme. On Dawn and other Shopify themes, the cart page is `sections/main-cart-footer.liquid` and the cart drawer is `snippets/cart-drawer.liquid`.
6. Click **Save**, then check your cart on the live store.

```liquid
{%- assign stork_referral = cart.attributes['Referral code'] -%}

<div class="stork-referral" data-stork-referral>
  <p class="stork-referral__heading">Have a referral code?</p>

  <div class="stork-referral__form"{%- if stork_referral != blank %} hidden{%- endif %}>
    <input
      type="text"
      class="stork-referral__input"
      placeholder="Referral code"
      aria-label="Referral code"
      autocomplete="off"
      autocapitalize="characters"
      spellcheck="false"
    >
    <button type="button" class="stork-referral__apply">Apply</button>
  </div>

  <div class="stork-referral__message" role="status" aria-live="polite">
    {%- if stork_referral != blank -%}
      Referral code applied: <strong>{{ stork_referral | escape }}</strong>
      <button type="button" class="stork-referral__remove">Remove</button>
    {%- endif -%}
  </div>
</div>

<style>
  .stork-referral { margin: 16px 0; }
  .stork-referral__heading { margin: 0 0 8px; font-weight: 600; }
  .stork-referral__form { display: flex; gap: 8px; }
  .stork-referral__form[hidden] { display: none; }
  .stork-referral__input { flex: 1; min-width: 0; padding: 10px 12px; }
  .stork-referral__message:not(:empty) { margin-top: 8px; }
  .stork-referral__remove { background: none; border: 0; padding: 0; text-decoration: underline; cursor: pointer; }
</style>

<script>
  (function () {
    // Runs once per page, even if the snippet appears more than once.
    if (window.storkReferralLoaded) return;
    window.storkReferralLoaded = true;

    const cartUpdateUrl = ((window.Shopify && Shopify.routes && Shopify.routes.root) || '/') + 'cart/update.js';

    // Saves the code on the cart. It must be called "Referral code" to reach the order.
    async function saveCode(value) {
      const response = await fetch(cartUpdateUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ attributes: { 'Referral code': value } })
      });
      if (!response.ok) throw new Error('Cart update failed');
    }

    function showMessage(root, text, code) {
      const message = root.querySelector('.stork-referral__message');
      message.replaceChildren(text);
      if (!code) return;

      const strong = document.createElement('strong');
      strong.textContent = code;
      const remove = document.createElement('button');
      remove.type = 'button';
      remove.className = 'stork-referral__remove';
      remove.textContent = 'Remove';
      message.append(' ', strong, ' ', remove);
    }

    async function applyCode(root) {
      const form = root.querySelector('.stork-referral__form');
      const input = root.querySelector('.stork-referral__input');
      const button = root.querySelector('.stork-referral__apply');
      const code = input.value.trim();
      if (!code) return;

      button.disabled = true;
      showMessage(root, '');

      try {
        // Stork Credit checks the code is real and active.
        const response = await fetch('/apps/stork-credit/proxy/referral', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ code: code })
        });
        const data = await response.json();

        if (!data.success) {
          showMessage(root, data.error || 'Invalid referral code');
        } else if (!data.applied) {
          showMessage(root, 'A referral code has already been applied to your account.');
        } else {
          await saveCode(data.code);
          form.hidden = true;
          showMessage(root, data.message || 'Referral code applied:', data.code);
        }
      } catch (error) {
        showMessage(root, "We couldn't apply that referral code. Please try again.");
      } finally {
        button.disabled = false;
      }
    }

    async function removeCode(root) {
      try {
        await saveCode('');
      } catch (error) {
        return;
      }
      root.querySelector('.stork-referral__input').value = '';
      root.querySelector('.stork-referral__form').hidden = false;
      showMessage(root, '');
    }

    document.addEventListener('click', function (event) {
      const root = event.target.closest('[data-stork-referral]');
      if (!root) return;
      if (event.target.closest('.stork-referral__apply')) applyCode(root);
      if (event.target.closest('.stork-referral__remove')) removeCode(root);
    });

    // Pressing Enter applies the code instead of submitting the cart.
    document.addEventListener('keydown', function (event) {
      if (event.key !== 'Enter' || !event.target.matches('.stork-referral__input')) return;
      event.preventDefault();
      applyCode(event.target.closest('[data-stork-referral]'));
    });
  })();
</script>
```

To change the wording, edit the text in the code. That includes the heading, the placeholder, the button labels and the messages. The success message comes from the code's own **Success message** in Stork Credit. The code field inherits your theme's fonts and button styles. You can restyle it with the `stork-referral` classes in the `<style>` section.

{% hint style="warning" %}
Leave two parts of the code as they are. `'Referral code'` is the name the code is saved under, and Stork Credit looks for that exact name on the order. `/apps/stork-credit/proxy/referral` is where the code is checked. If either one changes, codes won't reach your orders and no one is credited.
{% endhint %}

{% hint style="info" %}
Some cart drawers load their contents after the page has opened, so the code's script never starts. If **Apply** does nothing in your drawer, cut everything from `<script>` to `</script>` out of the snippet. Paste it into `layout/theme.liquid`, just above `</body>`. If it still doesn't work, [get in touch](/stork-credit/reference/support.md) and we'll help you place it.
{% endhint %}

Theme updates can replace edited files. After you update your theme, check the code field is still in your cart.

### On the Thank you page (any Shopify plan)

1. In Shopify admin, go to **Settings → Checkout** and click **Customize**.
2. From the page menu at the top of the editor, choose **Thank you**.
3. Click **Add app block** and choose **Referral Code**.
4. Place it where shoppers will see it, for example near the top of the page.
5. Click **Save**.

The block asks *Have a referral code?* and shows a code field with an **Apply** button. When a code is accepted, shoppers see your success message and the store credit their order earned. If the order isn't paid yet, they see what they'll earn once it is. Codes can be entered for 24 hours after the order is placed, and can't be removed once applied.

### In your checkout (Shopify Plus)

1. On the **Referral codes** page, click **Add to checkout**. You can also get there from Shopify admin: go to **Settings → Checkout** and click **Customize**.
2. Click **Add app block** and choose **Referral Code**.
3. Place it where shoppers will see it, for example near the order summary.
4. Optional: add the **Automatic Store Credit** block the same way.
5. Click **Save**.

| Block                      | What shoppers see                                                                                                                     |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| **Referral Code**          | A code field and an **Apply** button. When the code is accepted, they see your success message, the code and a **Remove** link        |
| **Automatic Store Credit** | The store credit this order will earn. It updates as soon as a code is applied or removed, so shoppers see their reward before paying |

{% hint style="info" %}
The Referral Code checkout block doesn't appear in accelerated checkouts that skip the checkout page, or on draft order invoices. No code can be entered there.
{% endhint %}

A code accepted in the cart or checkout block is saved on the order, and shows under **Additional details** on the order as **Referral code**. A code entered on the Thank you page is added to the customer's tags instead, because the order has already been placed.

For more on the blocks, see [Cart & checkout widgets](/stork-credit/integrations/storefront-and-checkout.md).

## Test it

Place a test order with a code. The customer is tagged after the order is placed, not when the code is applied.

* [ ] The code is accepted in the Referral Code block and shows your success message
* [ ] The order shows **Referral code** under **Additional details**
* [ ] The customer has the `referral:` tag for the code once the order is placed
* [ ] Once the order is paid, the reward rule's **Runs** tab shows the credit issued

If something's missing, check these:

| What you see                      | What to check                                                                                                                                                                                                             |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| *Invalid referral code*           | The code exists, is active, and your store is on a paid plan                                                                                                                                                              |
| *Referral code already applied*   | The customer already has a referral tag. The first code wins                                                                                                                                                              |
| No **Referral code** on the order | A Referral Code block was added and saved in the theme editor or checkout editor. The checkout block needs Shopify Plus. Codes entered on the Thank you page never appear on the order. Check the customer's tags instead |
| Code on the order but no tag      | The code was disabled before the order was placed, or the order has no customer                                                                                                                                           |
| Tag but no credit                 | The rule is active and its tag matches. Check the reason in the rule's **Runs** tab. See [Run history](/stork-credit/automations/run-history.md)                                                                          |

For how codes behave in detail, such as guests, first-code-wins and removing tags, see [Referral codes](/stork-credit/automations/referral-codes.md).
