# Kwik Developer Docs

> **Coming soon.** Kwik's public API and MCP server are coming soon. These docs are an early preview, in the beginning stages: endpoints, fields and examples are samples and will change before launch. Brands on Kwik today can ask their account manager about integrations.

Source: https://kwik.com/docs/ (this file is every docs page in one place). Generated from the live site.

Contents: 1. Overview · 2. How Kwik works · 3. How the app works · 4. How the modules work together · 5. Reward modules · 6. API reference (preview) · 7. MCP server (coming soon) · 8. Storefront integration

## 1. Overview

Kwik helps online brands keep customers buying and get them to share. These docs explain how the platform works under the hood: the building blocks, each reward module, and a preview of the public API and MCP server Kwik is building.

### Quickstart (planned)

1. **Get your API key.** Coming soon. Keys will be per brand, and you will keep them on your server.
2. **Install the Kwik Pixel.** Add one script to your store theme. It records first-party clicks, codes and orders.

```html
<script async src="https://cdn.kwik.com/pixel.js"
  data-store="YOUR_STORE_ID"></script>
```

3. **Make your first request.** Find a customer by email (sample).

```bash
curl "https://api.kwik.com/v1/customers?email=jane@example.com" \
  -H "Authorization: Bearer $KWIK_API_KEY"
```

4. **Listen for events.** Add a webhook URL to hear when customers earn, redeem and refer (see Webhooks below).

### Key ideas

- **Customer:** A shopper on your store. One Kwik login holds their rewards from every brand.
- **Wallet:** Where a customer's cashback, store credit and commissions live, pending or available.
- **Reward:** What a customer earns: cashback, points, entries, credit or a commission.
- **Program:** Your mix of modules and rules, set up for your store.
- **Attribution:** How Kwik ties an order to the code, link or person that drove it, for life.
- **Wave:** A referral of a referral. Waves let rewards travel past the first share.

## 2. How Kwik works

Kwik is a small set of building blocks: brands run campaigns, customers earn rewards, ambassadors share codes, and every sale is credited to the people who drove it.

### The building blocks

| Block | Id prefix | What it is |
| --- | --- | --- |
| Brand | `brand` | Your business on Kwik. Everything below belongs to one brand. |
| Campaign | `cmp_` | A set of rewards for a group of people, like "VIP referrals" or "Creators". A customer can be in many campaigns; one is active. |
| Customer | `cus_` | A shopper at your brand. Can be created with just an email, even before they make a Kwik account. |
| Ambassador | `cus_` | A customer who can earn when friends buy. Status can be verified, unverified or paid promotion. |
| Share code | `code` | An ambassador's personal code and link. Orders that use it are credited to them. |
| Loyalty program | `lp_` | Points customers earn and spend. Each customer has a balance and a history in each program. |
| Giveaway | `gw_` | A prize customers earn entries toward. Runs in weeks, each with its own ways to earn. |
| Revenue report | `report` | The sales Kwik drove, split by program: referral, retention or influencer. |

How they connect: a **brand** runs **campaigns**. **Customers** join campaigns. Customers who share become **ambassadors** with a **share code**. Customers earn in **loyalty programs** and **giveaways**. Every order is credited to the right people and shows up in **revenue reports**.

### How an order flows through Kwik

1. **A customer shops.** The Kwik Pixel and store widget show what each product and the cart will earn.
2. **They buy.** Kwik reads the order and finds who to credit: the share code or link used, and the people before them (waves).
3. **Rewards are earned.** Cashback, points and giveaway entries are added right away, as pending.
4. **The return window closes.** Pending rewards become available. If the order is refunded, the rewards are taken back.
5. **They spend or share.** Customers spend points and credit at checkout, or share their code so friends buy, and the loop starts again.

Waves: when a friend who bought with a share code shares their own code, the first ambassador can earn on those sales too. The brand sets how many waves pay and how much.

### Where Kwik shows up on a store

| Place | What the customer sees |
| --- | --- |
| Product pages | What each product earns: points, cashback or entries. |
| Cart | The total reward for the order, and products that unlock a bonus. |
| Thank-you page | Everything the order earned, the customer's share link, and a button to claim it. |
| Order emails | The share link and reward balance, added to emails you already send. |
| No-password tracker | Customers check their balance with just their email, before they make an account. |
| Rewards widget | A branded panel on your store to see rewards, share and redeem. |
| Branded sign-up page | A page on your site, in your words, where customers join and get a share link. |
| The Kwik app | One login where shoppers see their rewards from every Kwik brand. |

Most of this works without any code from the brand. The API is for when you want Kwik data in your own app, emails, CRM or support tools.

### Integration flow

1. **Get a key.** The public API will use a secret key per brand.
2. **Create the customer.** POST /customers with their email. Save the customer id.
3. **Find the campaign.** GET /campaigns and pick the one they should join.
4. **Add them to it.** POST /campaigns/{id}/members.
5. **Show their share code.** GET /customers/{id}/share-code.
6. **Show their points.** GET their balance and history in your loyalty program.
7. **Show their giveaway entries.** GET their entry balance in the current giveaway.
8. **Report results.** GET /reports/revenue for sales by program.

## 3. How the app works

### The five parts of Kwik

| Part | Who uses it | What it does |
| --- | --- | --- |
| **Kwik Admin** | Brands | The brand dashboard: campaigns, giveaways and weekly promos, loyalty programs, cashback, commissions, ambassadors, reports and payouts. |
| **Kwik Shopify app** | Shoppers on the brand's store | Syncs products and orders, shows rewards in theme blocks and widgets, carries share codes through the cart, and handles post-purchase sign-up. |
| **Rewards engine** | Runs in the background | Reads each synced order, works out who to credit, and calculates entries, points, cashback, commissions and Waves under the brand's rules. |
| **Kwik app** (app.kwik.com) | Shoppers and ambassadors | One login for rewards from every Kwik brand: balances, share links, redemption and payouts. |
| **Messaging and integrations** | Brands and their tools | Automated emails, Klaviyo, and webhooks (triggers) that tell other systems when something happens. |

### What happens to an order

1. **The shopper arrives.** A share link carries a `waveLink` code. The Shopify app keeps it and saves it on the cart, so it reaches the order.
2. **The order syncs to Kwik.** Orders come in from Shopify as they are paid, with a regular full sync as a backup. Re-syncing an order never awards rewards twice.
3. **Kwik finds who to credit.** It reads the share code, the cart attribute or order tag, and any promo code used, then finds the referrer and the people before them (Waves).
4. **The engine calculates rewards.** Entries, points, cashback and commissions are each worked out from the brand's active settings. See the giveaway math below.
5. **Rewards are recorded as pending.** Each reward gets its own history line, tied to the order and the person who earned it.
6. **Holds clear, or rewards are taken back.** After the return window, rewards become available. If an order is refunded, its points and other rewards can be retracted.
7. **Brands can recalculate.** If settings were wrong, the admin can re-roll (recalculate) orders for a giveaway week or for cashback, and see an order calculation breakdown that shows the math.

### How brand settings reach the store

Brands change settings in Kwik Admin, like a giveaway week's multipliers. The Shopify app reads them, so product badges, entry counts and countdowns on the store stay current. A saved week shows up in Shopify within about 20 seconds, and a full sync runs every few hours as a backup.

Theme developers can place Kwik values, like a product's entries or the current multiplier, into their theme with Kwik's blocks and placeholders, instead of hard-coding numbers or relying on product tags.

### The giveaway math, as built

Each giveaway week has its own **ways to earn**. For a paid order, Kwik works line by line:

1. **Buy a product.** The amount paid for the line, times the "buy a product" percent (usually 100%), times the base ratio. The default base ratio is $1 = 1 entry. A brand can set its own, like $1 = 10.
2. **Product or sitewide multiplier.** If the product is in a custom multiplier group, use that multiplier only. If not, use the default sitewide multiplier for the week. If neither is on, the base ratio stands.
3. **Product bonus.** A fixed number of bonus entries on one product. Depending on the setting, it is added before multipliers (and gets multiplied) or after.
4. **Order multiplier (doubler).** Doubles (or multiplies) the subtotal of eligible product entries only.
5. **Lump sums last.** Promo-code entries, free entries and sign-up bonuses are added at the end. No multiplier touches them.

**Referrals.** A referral multiplier can boost a referred buyer's entries. With **Referral Point Match**, the person who referred them earns the same entries the buyer earns from buying, product and sitewide multipliers, product bonuses, promo codes and free entries. Point Match, the referral multiplier and refer-a-friend rewards are set together on one referral settings screen.

**Promo code bonus.** A brand can tie a fixed reward to a discount code: for example, `WELCOME100` gives 100 entries, or `VIP25` gives 25 loyalty points. The code is matched when the order syncs.

**Free entries.** Customers can collect free entries (for example, daily) without buying, so a giveaway is never pay-to-enter. Show the free-entry instructions with the official rules.

### Feature status (as of November 24, 2026)

Live = in production. Building = in development, testing or scoping. Planned = backlog or proposed.

#### Giveaways

| Feature | Status | Notes |
| --- | --- | --- |
| Weekly ways to earn, base ratio and buy-a-product % | Live | Each week sets how entries are earned. |
| Product multipliers and default sitewide multiplier | Live | Product groups override the sitewide fallback. |
| Product bonus entries | Live | Fixed bonus on one product, before or after multipliers. |
| Order multiplier (doubler) | Live | Multiplies eligible product entries only. |
| Promo code bonus entries or points | Live | Fixed reward tied to a discount code. |
| Free entries | Live | A free way to enter. |
| Referral multiplier and Referral Point Match | Live | Combined into one referral settings screen. |
| Duplicate a week | Live | Copy a week's setup to the next. |
| Recalculate (re-roll) orders | Live | Re-run the math after a settings fix. |
| Order calculation breakdown | Live | Shows the math for one order. |
| Participants search | Live | Find anyone with entries. |
| Giveaway landing page | Building | A Kwik-hosted page for a giveaway. |

#### Loyalty points

| Feature | Status | Notes |
| --- | --- | --- |
| Ways to earn and loyalty CMS | Live | Name points, set rates and copy. |
| Product bonus points | Live | Extra points on a chosen product. |
| Retract points on refunds, history by order number | Live | Keeps balances right after returns. |
| Ways to redeem: dynamic discount, alternate point, repeat-order offer | Live | Spend points as a discount, another point type or an offer. |
| Double points on next order, double balance | Planned | Proposed ways to earn. |
| Auto redeem and automatic product rewards | Planned | Redeem without a code. |
| Ways to earn: next order, subscriptions, upload content, visit a link | Building | At different stages. |

#### Cashback and payouts

| Feature | Status | Notes |
| --- | --- | --- |
| Cashback page in Kwik Admin | Live | Set up and manage cashback. |
| Recalculate cashback | Live | Re-runs cashback only. |
| Venmo payouts, "Delivered" payout status | Live | More ways to get paid, clearer status. |
| Cashback redesign and text reminders | Live | The updated cashback experience. |
| Payout eligibility tied to brand billing | Planned | Commissions and cash become eligible once the brand is billed. |

#### Referrals, commissions and Waves

| Feature | Status | Notes |
| --- | --- | --- |
| Commission screen, commission by SKU | Live | Set different commissions per product. |
| Wave percent and level settings | Live | How deep Waves pay and how much. |
| Change a customer's referrer | Live | Fix who gets credit. |
| Ambassador details and sorting | Live | See and sort ambassadors. |
| Unique promo code per brand, auto-generated codes | Building | No two people share a code. |
| Referral reports | Planned | Deeper referral reporting. |

#### Shopify app and storefront

| Feature | Status | Notes |
| --- | --- | --- |
| Post-purchase sign-up | Live | Claim rewards right after checkout. |
| Share codes on cart attributes and order tags | Live | Carries attribution to the order. |
| Giveaway settings synced to the store | Live | A saved week appears in about 20 seconds. |
| Point balance and ways-to-earn widgets | Building | Store widgets. |
| Shopify app refactor: app blocks, discount logic, multiple campaigns, SSO to Kwik Admin, translations | Building | Being scoped as one project. |
| Integration with Shopify customer accounts | Planned |  |

#### Campaigns and statuses

| Feature | Status | Notes |
| --- | --- | --- |
| Multiple campaigns per customer | Building | In development. Today most brands run one campaign. |
| Statuses and segments (segments from Shopify, Klaviyo or CSV) | Building | Gifts on reaching a status come later. |

#### Messaging and integrations

| Feature | Status | Notes |
| --- | --- | --- |
| Webhooks (triggers) from Kwik | Live | Tell other systems when something happens. |
| Automated emails: claim your rewards, rewards expiring, share-link reminder, give and get, friends-and-family code, successful earn | Live |  |
| Klaviyo integration | Building | Kwik events and properties in Klaviyo. |
| Public triggers for Mailchimp, Zapier and others | Building |  |
| Custom way to earn by webhook | Planned | A brand's own action triggers a reward. |
| Hero banner images by API | Planned | Brand images served to the store from Kwik. |
| Public API and MCP server | Planned | See the API and MCP pages. |

## 4. How the modules work together

### One order, three outcomes

A shopper opens a friend's link, buys a hoodie and earns giveaway entries. The friend earns a referral reward. If the shopper later shares their own link, the original friend may earn again through Waves. All three outcomes can come from the same brand program. Each has its own recipient, qualifying action and record in Kwik.

Use this guide to decide what to show on a storefront, which rules to read from the brand's configuration, and how to check the result of an order.

### Start with the campaign

A **brand** owns the program. A **campaign** groups the audience, the rules for joining and the reward rules for one experience, such as a creator program or a VIP referral program. A **module** handles one part of that experience: Giveaways counts a buyer's entries, Referrals identifies who introduced the buyer, and Cashback can give the buyer money back.

A giveaway has its own prize, dates and earning periods inside the program. Ending a giveaway and ending someone's membership are different operations.

> **Note:** Multiple campaigns per customer are being built now. Today most brands run one campaign per customer. The API preview is written for the multi-campaign model.

In the API preview, a customer can belong to several campaigns and has one **active** campaign. Read the active membership when showing personal benefits. Being in two campaigns does not give a customer both sets of rates. For a referred order, check the buyer's offer and the ambassador's earning terms separately: a shopper can get a friend offer without qualifying for the ambassador's commission.

| When configuring a campaign | Example decision | Where the customer sees it |
| --- | --- | --- |
| Who can join? | Open enrollment, invitation, or a rule based on purchases | Branded sign-up page or an invitation in the rewards widget |
| What earns a reward? | Eligible spend, a completed referral order or a set action | Product page, cart estimate or ways-to-earn list |
| Who receives it? | The buyer earns entries, the referring customer earns points | Each person's own tracker or rewards history |
| Which offer applies now? | This week's giveaway rate, a product override or a member benefit | Product badge, referral offer or Mini Cart |
| When can they use it? | Points reach a redemption level, or cashback clears its hold and is claimed | Rewards widget, claim page or wallet |

### Statuses, segments, tags and gifts

> **Note:** Statuses are a newer design that is rolling out by brand. The API preview uses active campaign membership instead. Confirm which model a brand uses before building enrollment or showing a tier.

In the Status design, personal benefits come from one **active status** inside the brand program.

- **Segment** answers "who qualifies?" A customer can be in several segments, such as repeat buyers, subscribers and an imported VIP list.
- **Tag** labels a customer for targeting or export.
- **Status** decides what that person can earn or access. When several match, the configured priority wins.

Qualifying can depend on purchases in a period, a subscription, a sign-up form or an invitation. The design also allows a manual override, and a fallback status when someone stops qualifying.

A **gift** is given once, when someone reaches a status. An **ongoing benefit** applies to their later qualifying activity. For example, a new VIP might get 500 points once and a member discount on every future purchase. Showing the VIP badge on each visit must never give the welcome gift again. Gift options in the design include points, entries, cashback, commissions, a free product and free shipping. What is available depends on the brand's rollout.

### Where the pieces meet on a Shopify store

| Surface | What to show | What to read |
| --- | --- | --- |
| Product card or page | Entries, points or cashback for this item, plus any referral offer | Current promotion, eligible price, product rule and customer context |
| Cart drawer or cart page | Order-level estimate and any optional upgrade | All eligible lines, quantities, selected tier and qualifying bonuses |
| Thank-you page or claim email | Reward earned on this order, claim action and share link if eligible | Completed order, recipient, reward state and claim deadline |
| Entry tracker | Entries for the selected giveaway and how they were earned | Customer, giveaway and entry history |
| Branded widget or customer account | Balances, next loyalty reward, share tools and ways to redeem | Selected brand and program, membership and available rewards |
| Klaviyo email or SMS | A timely reminder, like an unclaimed reward or progress to a reward | The Kwik metric, event properties, profile data and channel consent |

In Klaviyo, use the order event's award for "you earned 200 points on this purchase." Use an up-to-date balance for "you have 2,450 points available." A later purchase or redemption can make those two numbers differ. Use the metric and property names in the connected account.

### Custom storefronts (Hydrogen)

Share links arrive with a `waveLink` code, for example `/products/hoodie?waveLink=ABC123`. Keep the exact case of `waveLink`.

1. Capture the code when the shopper arrives.
2. Carry it across navigation.
3. Save it as a cart attribute before checkout, keeping any attributes already on the cart.
4. Test every path to checkout: the cart drawer, direct-to-checkout, quick-add and bundles.

On a completed test order, check the exact field the brand's Kwik integration reads. Some setups also need an order tag next to the cart attribute. Then confirm Kwik credited the right referrer.

The documented Hydrogen setup uses a 30-day attribution cookie and a separate 24-hour cache for the rep's profile. Confirm the store's attribution policy before reusing those durations.

Step-by-step code for all of this, plus timers, multiplier badges and cart entry estimates, is in [Storefront integration](/docs/storefront/).

For an optional "Shopping with Ava" banner, Kwik provides a share-link lookup that returns the rep's name and photo. Ask your Kwik contact for its address. Hide old profile data when a new link can't be looked up, and never block checkout if the lookup fails. A profile lookup only checks the display. A completed test order checks attribution.

### API access today, and the preview

Brands integrating today should get the supported operations, credentials and setup details for their store from their Kwik contact. The self-serve REST API, public webhooks and MCP server in these docs are previews. Their sample URLs, payloads and tool names may change before launch.

| Preview area | What it is for |
| --- | --- |
| Customers and ambassadors | Find a customer by email, keep the customer id, and see or set ambassador status |
| Campaigns and share codes | Read membership and performance, manage enrollment, or get a customer's share link |
| Loyalty | Pick a loyalty program, then read the customer's balance and transactions in it |
| Giveaways | Pick a campaign, giveaway and earning period, then read ways to earn, participants or one customer's entries |
| Reporting | Read attributed revenue by program and period, or revenue-share amounts |
| Webhooks and MCP | Get notified, or ask an AI assistant about program data, once those ship |

For a custom account page, start with the shopper's brand-specific customer record. Pick the loyalty program before showing points, and the giveaway before showing entries. Get the shopper's share link if they can refer. Keep brand credentials on the server, and return only the fields the signed-in customer is allowed to see.

## 5. Reward modules

Seven modules, one platform. Each one: how it works, the settings, the events it sends and an example request.

### Giveaways

Turn purchases and actions into giveaway entries. Set multipliers by week, campaign or product, track every customer's entries, and offer a free method of entry (AMOE).

**How it works**

1. **Create a giveaway.** Name it, set the prize, the dates and the official rules.
2. **Set up each week.** Each week (round) has its own ways to earn: buy a product, multipliers, bonuses, promo codes and free entries. Duplicate a week to reuse it.
3. **Show entries everywhere.** Product cards, cart, entry tracker and emails show what each order earns. Saved weeks sync to the store in about 20 seconds.
4. **Check and draw.** Use the order calculation breakdown and recalculate if needed, then pick winners from the final entries.

**Settings**

| Field | Type | What it does |
| --- | --- | --- |
| `base_ratio` | number | Entries per $1 for buy a product. Default 1. |
| `buy_product_percent` | percent | Share of the line amount that earns entries. Usually 100%. |
| `sitewide_multiplier` | number | Default multiplier for products not in a multiplier group. |
| `product_multipliers` | Group[] | Custom multipliers for product groups. These override the sitewide default. |
| `product_bonuses` | Bonus[] | Fixed bonus entries on one product, before or after multipliers. |
| `order_multiplier` | number | Multiplies eligible product entries on the order. |
| `promo_code_rules` | Rule[] | Fixed entries (or points) when a discount code is used. |
| `free_entries` | Rule | A free way to enter, so no purchase is needed. |
| `referral_point_match` | boolean | The referrer earns the same entries as the buyer. |

**Events**

| Event | When it fires |
| --- | --- |
| `entry.created` | A customer earned entries from an order or action. |
| `giveaway.ended` | The giveaway closed and entries are final. |
| `winner.selected` | A winner was drawn. |

**In practice**

Entries belong to one giveaway. The brand sets the prize, dates, official rules and ways to enter. A giveaway can run in weekly rounds, each with its own earning schedule. The store can show entries next to a product, update the estimate as the cart changes, and link to a tracker of entries already recorded. An email-based tracker works for customers before they make a Kwik login. Always show the official rules and free-entry instructions next to the offer.

##### How an order earns entries

1. For each eligible line, take the amount actually paid (including quantity), times the "buy a product" percent, times the base ratio. The default base ratio is $1 = 1 entry.
2. Apply that product's custom multiplier if it is in a multiplier group. Otherwise use the week's default sitewide multiplier. Only one of the two counts on each line.
3. Add any product bonus entries. Depending on the setting, they are added before multipliers (and get multiplied) or after.
4. Add the lines together and apply the order multiplier (doubler). It only multiplies eligible product entries.
5. For a referred order, apply the referral multiplier when the week has one.
6. Add lump sums last: promo-code entries, free entries and sign-up bonuses. No multiplier touches them.

**Example.** One entry per eligible dollar. A $40 hoodie has a 5× product multiplier. A $20 cap uses the 2× sitewide multiplier. The order also gets a 2× order upgrade, a 3× referral multiplier and 100 promo-code bonus entries.

| Step | Calculation | Entries |
| --- | --- | --- |
| Hoodie | $40 × 1 × 5 | 200 |
| Cap | $20 × 1 × 2 | 40 |
| After order upgrade | (200 + 40) × 2 | 480 |
| After referral multiplier | 480 × 3 | 1,440 |
| Final order award | 1,440 + 100 | 1,540 |

Kwik Admin shows an **order calculation breakdown** with the exact steps for a real order. Use it to check the math when a tracker and a cart disagree. If settings were wrong, the admin can **recalculate (re-roll)** the week's orders.

With **Referral Point Match** on, the person who referred the buyer earns the same entries the buyer earns from buying, multipliers, product bonuses, promo codes and free entries.

Show the customer a breakdown when a cart mixes rates. "25 entries per dollar" is already an effective rate; a true 25× multiplier means something different when the base is 10 entries per dollar. Use the campaign's definition the same way on badges, bundles, countdowns and upsells. Some Shopify themes read a product tag such as `kwik10` to show a badge. A product with no tag can still earn base or sitewide entries.

The tracker should name the giveaway, the order or action, and the entries awarded. A referral order, a sign-up bonus or a free entry can each be its own history line. When a new giveaway starts, select its id and earning period on purpose. For a closed giveaway, use the final reconciled entry file. Any credit offered after a giveaway needs its own conversion terms.

**Example:** `GET /customers/{customer_id}/entries`: Read a customer's entry balance and where it came from.

```json
{
  "customer_id": "cus_8f2a",
  "giveaway_id": "gw_lambo_2026",
  "entries": 8970,
  "history": [
    { "source": "product_multiplier", "label": "Trail Runner 30x", "entries": 3600 },
    { "source": "order", "label": "Order #1042", "entries": 450 },
    { "source": "amoe", "label": "Free entry", "entries": 1 }
  ]
}
```

### Mini Cart

Offer tier upgrades in the cart (standard, plus and premium) with rewards matched to each customer type. Upgrades add profit to the same order.

**How it works**

1. **Pick the tiers.** Choose what each tier adds: entries, cashback, points or perks.
2. **Match customers.** Show first-time buyers and loyal customers different offers.
3. **Show it in the cart.** The upgrade appears before checkout, one tap to add.

**Settings**

| Field | Type | What it does |
| --- | --- | --- |
| `tiers` | Tier[] | Upgrade options with a price and the rewards they add. |
| `segments` | string[] | Customer types each tier is shown to. |
| `placement` | enum | Where the upgrade shows: cart drawer, cart page or checkout. |

**Events**

| Event | When it fires |
| --- | --- |
| `upgrade.added` | A customer added an upgrade to their cart. |
| `upgrade.purchased` | An order with an upgrade was paid. |

**In practice**

The giveaway Mini Cart lets shoppers upgrade the order they are already building. A product or offer page can show Standard, Plus and Premium packages. The cart then shows the chosen package, its price, the entries it adds, and any further upgrade before checkout. Tier names, prices and entry awards come from the brand's offer.

For a "Double your entries" offer, label which entries double and show the new order total. In the Giveaways example, removing the 2× order upgrade changes the award from 1,540 to 820 entries, while the 100 bonus entries stay at 100. Update the estimate whenever a shopper changes quantity, switches packages or removes the upgrade. Count an upgrade only when the completed order includes it.

##### VIP offer pages

A VIP offer page shows a bundle or membership to the audience it is meant for: the products included, the price or subscription terms, and the entries or benefits for each option. The chosen item then goes into the store's cart. For a subscription offer, keep the selected selling plan. A package called "VIP" only gives a customer a status if the enrollment rules say so.

**Example:** `GET /carts/{cart_id}/upgrades`: Get the upgrade offers for a cart, matched to the customer.

```json
{
  "cart_id": "cart_51c",
  "segment": "first_time",
  "tiers": [
    { "id": "plus", "price": 4.99, "adds": ["2x entries"] },
    { "id": "premium", "price": 9.99, "adds": ["5x entries", "10% cashback"] }
  ]
}
```

### Cashback

Pay customers back after they buy instead of discounting up front. Cashback lands in the Kwik wallet once the return window clears, as cash or store credit.

**How it works**

1. **Set the rate.** A percentage back, by product, collection or customer type.
2. **Hold through returns.** Cashback stays pending until the return window closes.
3. **Customer chooses.** Store credit for the next order, or cash out.

**Settings**

| Field | Type | What it does |
| --- | --- | --- |
| `rate` | percent | Cashback rate on eligible spend. |
| `pending_days` | number | Days to hold before cashback is available. |
| `payout_options` | enum[] | store_credit, cash or both. |

**Events**

| Event | When it fires |
| --- | --- |
| `cashback.pending` | Cashback was earned on an order. |
| `cashback.available` | The return window closed and it can be spent. |
| `cashback.redeemed` | The customer used it or cashed out. |

**In practice**

Cashback gives the buyer value after a qualifying purchase. A campaign can apply it to a first order or to repeat orders, as a fixed amount or a percent of eligible spend. On the product page or in the cart, tell the shopper what the order should earn. After purchase, show the amount earned, what they must do to claim it, and any claim deadline.

A **hold** controls when the money becomes available, for example after the return window. A **claim deadline** controls how long the customer has to act. Show both dates when both apply. A shopper who sees "$5 pending" needs to know whether to claim now, wait, or come back later. Use the real transaction state and the brand's claim flow to pick the message.

Kwik Cash can be withdrawn where cash payout is turned on. Store credit is spent with the brand that issued it, under its terms. Show only the options that apply to that reward. A refund or adjustment can change the amount available, so use the wallet history for the current amount. The buyer's cashback and an ambassador's commission can come from the same order, but they belong to different people.

**Example:** `GET /customers/{customer_id}/wallet`: Read a customer's pending and available cashback.

```json
{
  "customer_id": "cus_8f2a",
  "cashback": { "pending": 12.00, "available": 18.40 },
  "currency": "USD"
}
```

### Loyalty Points

Points customers can see, earn and spend. Set points per dollar and per action, add tiers and milestone rewards, and show how far each customer is from a free reward.

**How it works**

1. **Set earning rules.** Points per dollar, plus actions like reviews, referrals and birthdays.
2. **Add rewards.** Free products, discounts or entries at set point levels.
3. **Show progress.** Customers see their balance, history and the next reward.

**Settings**

| Field | Type | What it does |
| --- | --- | --- |
| `points_per_dollar` | number | Points earned per dollar spent. |
| `actions` | Action[] | Extra ways to earn and what each is worth. |
| `rewards` | Reward[] | What points unlock, and at how many points. |

**Events**

| Event | When it fires |
| --- | --- |
| `points.earned` | A customer earned points. |
| `reward.unlocked` | A customer reached a reward level. |
| `points.redeemed` | Points were spent. |

**In practice**

Loyalty Points gives a customer a spendable balance in one brand loyalty program. Brands can name their points, set an earning rate and define what points can be spent on. A purchase can earn points and giveaway entries at different rates. A giveaway's weekly multiplier only changes the points estimate if the loyalty program also has a points promotion.

The widget can show ways to earn, recent activity, available points and progress to a reward. Depending on setup, purchases, sign-up, birthdays, referrals and confirmed newsletter or social actions can earn points. For an opt-in reward, award it once, on the confirmed subscription. A form submission can come before confirmation.

**Example.** A shopper with 2,450 points sees "550 points to a free hoodie" when the reward costs 3,000. At 3,000, they can redeem. When they do, show the points spent and what they got: a product, a discount, free shipping or entries in a named giveaway. Read the balance for the selected loyalty program, and show pending points separately when they are supplied.

**Example:** `GET /customers/{customer_id}/points`: Read a balance, the next reward and recent history.

```json
{
  "customer_id": "cus_8f2a",
  "balance": 2450,
  "next_reward": { "name": "Wireless Headphones", "points": 3000, "away": 550 },
  "history": [
    { "label": "Order #1042", "points": 240 },
    { "label": "Product review", "points": 100 }
  ]
}
```

### Referrals

Give your best customers a share link with its own unique code, credit every order they bring in, and reward both people with cashback, points, entries, commissions or waves.

**How it works**

1. **Invite the right customers.** Top spenders, at the right order, not a sitewide banner.
2. **Unique code per link.** Every share link creates its own code, so codes cannot leak.
3. **Credit and reward.** Orders are tied to the referrer for life. Both sides get rewarded.

**Settings**

| Field | Type | What it does |
| --- | --- | --- |
| `eligibility` | Rule[] | Which customers can refer, by order count or spend. |
| `reward_referrer` | Reward | What the person who shared earns. |
| `reward_friend` | Reward | What the new customer gets. |
| `unique_codes` | boolean | Generate a code per share link. |

**Events**

| Event | When it fires |
| --- | --- |
| `referral.link_created` | A customer created a share link. |
| `referral.converted` | A referred friend placed an order. |
| `reward.paid` | A referral reward was paid out. |

**In practice**

An eligible customer or creator gets a share link or personal code. The brand chooses who to invite, which page the link opens, what the friend gets and what the referrer earns. The invite can appear after an eligible purchase, on a branded sign-up page or in the rewards widget. The landing page can show the rep's name, photo and offer, so the shopper knows whose link they followed.

| Part of the referral | Example | What to record or show |
| --- | --- | --- |
| Share | Ava sends Ben her product link | The destination and the Kwik link code |
| Buyer offer | Ben gets extra entries or a checkout discount | The offer Ben can use and its conditions |
| Direct referral reward | Ben's order earns Ava points or a commission | Ava's reward, the order it came from and its state |
| Lifetime attribution | Ben comes back later and buys directly | Credit under the brand's repeat-order attribution terms |

A promo code can identify a referrer, give a discount, or both. A share link can carry attribution without the buyer typing a code. Check how the store handles a shopper who arrives through one rep's link and then types another rep's code. A personal code can be copied and passed around, so showing it does not prove who qualified for a payout.

**Discounts.** A brand can set up a link offer, a promo-code offer or a member benefit: a product or order discount, free shipping or buy-X-get-Y. In the Status design, Kwik decides who is eligible for a status-based offer and Shopify applies the discount. Read the real checkout result before describing the price paid or estimating rewards on discounted items.

**Example:** `POST /referrals/links`: Create a share link with its own coupon code.

```json
{
  "customer_id": "cus_8f2a",
  "destination": "/products/trail-runner"
}
```

```json
{
  "url": "https://yourstore.com/products/trail-runner?waveLink=AVA7HK2",
  "code": "AVA7HK2",
  "unique": true
}
```

### Waves

Rewards that ripple past the first referral: when a referred friend refers someone, the original customer earns too. You set the depth and the percent for each wave.

**How it works**

1. **Set the depth.** How many waves deep rewards go.
2. **Set the percent.** What each wave pays, usually less with each step.
3. **Track every wave.** Lifetime attribution across the whole chain.

**Settings**

| Field | Type | What it does |
| --- | --- | --- |
| `depth` | number | How many waves pay out. |
| `percent_by_wave` | percent[] | Payout for wave 1, wave 2 and on. |
| `bonuses` | Bonus[] | Extra rewards when a wave hits a target. |

**Events**

| Event | When it fires |
| --- | --- |
| `wave.order` | An order was attributed to a wave. |
| `wave.reward` | A wave reward was earned. |

**In practice**

Waves tracks introductions past the first referral. Say Ava introduces Ben, and Ben later introduces Cara. When Cara buys, Ben is the direct referrer and Ava is one step further up. The brand sets how many levels it rewards and the amount at each level. Show each person the order or wave that explains what they earned.

Repeat purchases and wave depth answer different questions. If Ben buys again months later, that is another purchase by Ava's original referral. When Cara buys for the first time, that is a new buyer one level deeper in Ava's network. A brand can keep the lasting customer relationship while paying each order under different rules. Keep the original order total intact when reporting several rewards from one order.

**Example:** `GET /customers/{customer_id}/waves`: See how far a customer's referrals have spread.

```json
{
  "customer_id": "cus_8f2a",
  "waves": [
    { "wave": 1, "customers": 3, "earned": 45.00 },
    { "wave": 2, "customers": 9, "earned": 22.50 },
    { "wave": 3, "customers": 27, "earned": 11.25 }
  ]
}
```

### Data And Tracking

First-party tracking with the Kwik Pixel, attribution by code, link and redirect, and reporting on true lifetime value by customer, ambassador type and campaign.

**How it works**

1. **Install the pixel.** One script on your store, first-party data from day one.
2. **Attribute every order.** Codes, links, redirects and lifetime credit.
3. **Read the reports.** Who carries your revenue, and when to reward them.

**Settings**

| Field | Type | What it does |
| --- | --- | --- |
| `attribution_window` | days | How long a click or code keeps credit. |
| `ltv_mode` | enum | personal, referred or true (both). |
| `group_by` | enum[] | ambassador_type, campaign, module. |

**Events**

| Event | When it fires |
| --- | --- |
| `order.attributed` | An order was tied to a source. |
| `fraud.flagged` | An order or account was flagged for review. |

**In practice**

Kwik connects storefront activity, Shopify orders and the customer or ambassador tied to each transaction. First-party tracking captures referral signals like a link or code. The paid order supplies the purchase details. The customer's reward history explains the outcome. Use each record for the question it answers.

| Question | What to check |
| --- | --- |
| Why does a shopper see this offer? | Active campaign or status, current giveaway round, product and referral eligibility |
| Why is the tracker different from the cart? | Cart estimate vs. paid lines, final discounts, quantities, bonus rules, refunds and the selected giveaway |
| Why did this ambassador earn money? | Order attribution, direct or upstream relationship, campaign terms and commission state |
| How much business did this customer drive? | Their own purchases plus attributed referred sales, with the period and depth stated |
| How did the Mini Cart perform? | Completed upsell orders, opt-in rate, and order value with and without the upgrade |

One order can count toward a giveaway, a loyalty program and a referral report. If Cara spends $60 and two people earn commissions, the store still has one $60 order. Use order ids to reconcile revenue, and reward transactions to reconcile what customers earned. Report referral, retention and influencer sales using the report's attribution definitions.

**Example:** `GET /reports/ltv?group_by=campaign`: True lifetime value by campaign.

```json
{
  "group_by": "campaign",
  "rows": [
    { "campaign": "spring_vip", "customers": 412, "true_ltv": 286.40 },
    { "campaign": "giveaway_lambo", "customers": 1290, "true_ltv": 174.10 }
  ]
}
```

## 6. API reference (preview)

A sample of the REST API Kwik is building. Customers join campaigns, earn points and giveaway entries, share a code, and every sale they drive shows up in revenue reports.

### Basics

- **Base URL (sample):** `https://api.kwik.com/v1`
- **Format:** JSON in and out. Send `Content-Type: application/json` with a body.
- **Ids:** prefixes `cus_` customer, `cmp_` campaign, `lp_` loyalty program, `gw_` giveaway, `wk_` giveaway week. Ids in these docs are made up.
- **Dates:** ISO 8601, in UTC.
- **Lists:** use `page` and `page_size`. Every list comes back in the same wrapper:

```json
{
  "data": [ ... ],
  "page": 1,
  "page_size": 10,
  "has_more": true
}
```

### Authentication

The public API will use a secret key per brand, sent as a bearer token (`Authorization: Bearer $KWIK_API_KEY`). Keep it on your server, never in browser code. Keys are not available yet.

### Customers

A customer is a shopper at your brand. You can create one with just an email. Keep the customer id: points, entries and share codes all hang off it.

#### `POST /customers`

Create a customer.

| Field | Type | Required | What it is |
| --- | --- | --- | --- |
| `email` | string | Yes | Customer email |
| `share_code` | string | No | A custom share code to give them, like JANE10 |

Request body:

```json
{
  "email": "jane@example.com",
  "share_code": "JANE10"
}
```

Response (200):

```json
{
  "id": "cus_50001",
  "email": "jane@example.com",
  "share_code": "JANE10",
  "ambassador": false,
  "created_at": "2026-11-24T18:02:11Z"
}
```

#### `GET /customers?email=jane@example.com`

Find a customer by email.

#### `POST /customers/{customer_id}/ambassador`

Make a customer an ambassador, so they earn when friends buy.

| Field | Type | Required | What it is |
| --- | --- | --- | --- |
| `campaign_ids` | string[] | Yes | Campaigns they can earn in |
| `status` | enum | No | verified, unverified or paid_promotion |

Request body:

```json
{
  "campaign_ids": ["cmp_301"],
  "status": "verified"
}
```

### Campaigns

A campaign is a set of rewards you run for a group of people, like a VIP referral program or a creator program. Customers join campaigns, and a customer's active campaign decides what they earn.

#### `GET /campaigns`

List your campaigns.

| Field | Type | Required | What it is |
| --- | --- | --- | --- |
| `status` | enum | No | active, inactive, unverified_purchaser, paid_promotion or sponsorship |
| `search` | string | No | Filter by name |
| `page` | number | No | Default 1 |
| `page_size` | number | No | Default 10 |

#### `POST /campaigns/{campaign_id}/members`

Add customers to a campaign, by id or by email.

| Field | Type | Required | What it is |
| --- | --- | --- | --- |
| `customer_ids` | string[] | One of the two | Customer ids |
| `emails` | string[] | One of the two | Customer emails |

Request body:

```json
{
  "customer_ids": ["cus_50001"],
  "emails": ["sam@example.com"]
}
```

Response (200):

```json
{
  "campaign_id": "cmp_301",
  "added": 2
}
```

#### `DELETE /campaigns/{campaign_id}/members`

Remove customers from a campaign. Same body as adding.

#### `GET /campaigns/{campaign_id}/members`

List a campaign's members.

#### `GET /customers/{customer_id}/campaigns`

The campaigns a customer belongs to. The one marked active is their current campaign.

#### `GET /campaigns/{campaign_id}/performance?period=this_month`

How a campaign is doing.

| Field | Type | Required | What it is |
| --- | --- | --- | --- |
| `period` | enum | No | this_week, this_month (default), last_month, this_year or all_time |

Response (200):

```json
{
  "campaign_id": "cmp_301",
  "period": "this_month",
  "members": 412,
  "orders": 268,
  "sales": 21480.50
}
```

### Share codes

Every ambassador gets a personal share code and link. Friends who buy with it are credited to the ambassador, and can be credited to the people before them too (waves).

#### `GET /customers/{customer_id}/share-code`

One customer's share code and link.

Response (200):

```json
{
  "customer_id": "cus_50001",
  "code": "JANE10",
  "url": "https://yourstore.com/?waveLink=JANE10"
}
```

#### `GET /share-codes?campaign_id=cmp_301`

Every ambassador's code, for one campaign or all of them.

### Loyalty points

A brand can run one or more loyalty programs. Each customer has a point balance in each program, plus a history of every point earned and spent.

#### `GET /loyalty-programs`

List your loyalty programs and their ids.

#### `GET /loyalty-programs/{program_id}/customers/{customer_id}`

A customer's point balance.

Response (200):

```json
{
  "program_id": "lp_12",
  "customer_id": "cus_50001",
  "balance": 2450,
  "pending": 240
}
```

#### `GET /loyalty-programs/{program_id}/transactions?customer_id=cus_50001`

Point history for one customer, or for the whole program if you leave out customer_id.

Response (200):

```json
{
  "data": [
    { "type": "earn", "points": 240, "reason": "Order #1042", "at": "2026-11-20T18:02:11Z" },
    { "type": "spend", "points": -500, "reason": "Free shipping", "at": "2026-11-22T09:14:00Z" }
  ],
  "page": 1,
  "has_more": false
}
```

### Giveaways

A giveaway belongs to a campaign and runs in weeks (rounds). Each week has its own ways to earn and spend entries, like multiplier weekends. Every customer has an entry balance and history.

#### `GET /campaigns/{campaign_id}/giveaways`

The giveaways in a campaign.

#### `GET /giveaways/{giveaway_id}`

One giveaway: prize, dates and status.

#### `GET /giveaways/{giveaway_id}/weeks`

The weeks (rounds) of a giveaway.

#### `GET /giveaways/{giveaway_id}/weeks/{week_id}/ways-to-earn`

How people earn and spend entries that week.

Response (200):

```json
{
  "week_id": "wk_3",
  "earn": [
    { "action": "purchase", "entries_per_dollar": 15 },
    { "action": "email_signup", "entries": 50 },
    { "action": "referral_order", "entries": 500 }
  ],
  "multiplier": 2
}
```

#### `GET /giveaways/{giveaway_id}/participants`

Everyone with entries, with search and sorting.

#### `GET /giveaways/{giveaway_id}/customers/{customer_id}`

One customer's entry balance and history.

Response (200):

```json
{
  "giveaway_id": "gw_88",
  "customer_id": "cus_50001",
  "entries": 8970,
  "history": [
    { "source": "order", "label": "Order #1042", "entries": 450 },
    { "source": "referral", "label": "Friend's order", "entries": 500 }
  ]
}
```

### Orders

For stores that are not on Shopify. Shopify orders sync to Kwik on their own. Send each paid order, refund and cancellation from your server. The full field list, and where the share code goes, is under Storefront integration, in What Kwik needs on every order.

#### `POST /orders`

Send a paid order, or update one. The same order_id never counts twice.

| Field | Type | Required | What it is |
| --- | --- | --- | --- |
| `order_id` | string | Yes | Your order id |
| `created_at` | string | Yes | ISO 8601, UTC |
| `status` | enum | Yes | paid, partially_refunded, refunded or cancelled |
| `currency` | string | Yes | Like USD |
| `customer` | object | Yes | At least email |
| `line_items` | object[] | Yes | product_id, quantity, unit_price, amount_paid |
| `discount_codes` | object[] | If used | Codes on the order |
| `attribution` | object | If present | wave_link: the share code, exactly as captured |

Request body:

```json
{
  "order_id": "1042",
  "created_at": "2026-12-03T22:14:05Z",
  "status": "paid",
  "currency": "USD",
  "customer": { "email": "jane@example.com" },
  "line_items": [
    { "line_id": "1", "product_id": "8100000000001", "quantity": 1, "unit_price": 40.00, "amount_paid": 40.00 }
  ],
  "discount_codes": [],
  "attribution": { "wave_link": "ABC123" }
}
```

Response (200):

```json
{
  "order_id": "1042",
  "received": true,
  "referrer_id": "cus_50001",
  "rewards": "pending"
}
```

#### `POST /orders/{order_id}/refunds`

Report a full or partial refund. Kwik takes back the rewards for the refunded lines.

Request body:

```json
{
  "refund_id": "r-7781",
  "refunded_at": "2026-12-09T15:30:00Z",
  "line_items": [{ "line_id": "1", "quantity": 1, "amount": 40.00 }]
}
```

### Revenue reports

Kwik reports the sales it drives, across all programs or by program: referral, retention or influencer. Leave out the dates for all-time numbers.

#### `GET /reports/revenue?start=2026-10-01&end=2026-10-31`

Sales across all programs, with a split by program.

| Field | Type | Required | What it is |
| --- | --- | --- | --- |
| `start` | date | No | Start of the range |
| `end` | date | No | End of the range |
| `program` | enum | No | referral, retention or influencer |

Response (200):

```json
{
  "start": "2026-10-01",
  "end": "2026-10-31",
  "total_sales": 48250.75,
  "by_program": [
    { "program": "referral", "sales": 21480.50 },
    { "program": "retention", "sales": 19110.25 },
    { "program": "influencer", "sales": 7660.00 }
  ]
}
```

#### `GET /reports/revenue-share?program=referral`

What was paid out in revenue share for one program.

### Webhooks

Planned: add an HTTPS URL and Kwik sends a POST for each event, signed with a `Kwik-Signature` header.

```json
{
  "id": "evt_31c9",
  "type": "referral.converted",
  "created_at": "2026-11-20T18:02:11Z",
  "data": {
    "referrer_id": "cus_50001",
    "customer_id": "cus_50002",
    "order_id": "ord_1042",
    "code": "JANE10"
  }
}
```

| Event | When it fires | Module |
| --- | --- | --- |
| `entry.created` | A customer earned entries from an order or action. | Giveaways |
| `giveaway.ended` | The giveaway closed and entries are final. | Giveaways |
| `winner.selected` | A winner was drawn. | Giveaways |
| `upgrade.added` | A customer added an upgrade to their cart. | Mini Cart |
| `upgrade.purchased` | An order with an upgrade was paid. | Mini Cart |
| `cashback.pending` | Cashback was earned on an order. | Cashback |
| `cashback.available` | The return window closed and it can be spent. | Cashback |
| `cashback.redeemed` | The customer used it or cashed out. | Cashback |
| `points.earned` | A customer earned points. | Loyalty Points |
| `reward.unlocked` | A customer reached a reward level. | Loyalty Points |
| `points.redeemed` | Points were spent. | Loyalty Points |
| `referral.link_created` | A customer created a share link. | Referrals |
| `referral.converted` | A referred friend placed an order. | Referrals |
| `reward.paid` | A referral reward was paid out. | Referrals |
| `wave.order` | An order was attributed to a wave. | Waves |
| `wave.reward` | A wave reward was earned. | Waves |
| `order.attributed` | An order was tied to a source. | Data And Tracking |
| `fraud.flagged` | An order or account was flagged for review. | Data And Tracking |

### Errors

Errors return a status code and a JSON body with a `code` and a `message`.

| Status | Code | Meaning |
| --- | --- | --- |
| 400 | `bad_request` | A field is missing or the wrong type. |
| 401 | `unauthorized` | The API key is missing or wrong. |
| 404 | `not_found` | That customer, campaign or giveaway does not exist. |
| 409 | `conflict` | That already happened, like adding a member twice. |
| 429 | `rate_limited` | Too many requests. Wait and retry. |

## 7. MCP server (coming soon)

MCP (Model Context Protocol) is an open standard that lets AI assistants, like Claude, safely use tools. The Kwik MCP server will give an assistant a small set of tools that use the Kwik API on the brand's behalf, with its key and permissions. It is in the beginning stages: tool names and details are a plan, not a final list.

### Planned tools

| Tool | Type | What it does |
| --- | --- | --- |
| `find_customer` | Read | Look up a customer by email, with their campaigns and ambassador status. |
| `get_share_code` | Read | A customer's share code and link. |
| `get_points` | Read | A customer's point balance and recent history. |
| `get_giveaway_entries` | Read | A customer's entries in a giveaway, and where they came from. |
| `list_campaigns` | Read | Your campaigns and their status. |
| `campaign_performance` | Read | Members, orders and sales for a campaign over a period. |
| `revenue_report` | Read | Sales Kwik drove, by program, for a date range. |
| `add_to_campaign` | Write | Add customers to a campaign. Asks you to confirm first. |

Tools that change data, like adding customers to a campaign, will always ask the user to confirm first.

### What you could ask

| You ask | Tools it uses |
| --- | --- |
| "How many points does jane@example.com have, and what is her share code?" | find_customer, get_points, get_share_code |
| "Which campaign brought in the most sales this month?" | list_campaigns, campaign_performance |
| "What did referrals make us in October compared with retention?" | revenue_report |
| "Add these 20 VIP customers to the VIP referral campaign." | add_to_campaign (after you confirm) |

### Connecting (sample)

When it ships, brands will add Kwik to their assistant's MCP settings with an API key. The address and key below do not work yet.

```json
{
  "mcpServers": {
    "kwik": {
      "url": "https://mcp.kwik.com/sse",
      "headers": { "Authorization": "Bearer YOUR_KWIK_API_KEY" }
    }
  }
}
```

## 8. Storefront integration

Integrating Kwik with your storefront, on a Shopify theme, Hydrogen or any other website: track share links, send the right order data, show the referring rep, and keep giveaway timers, multiplier badges and cart entry estimates in sync.

| Task | Shopify theme | Hydrogen or headless Shopify | Any other website |
| --- | --- | --- | --- |
| Track share links | Turn on the Referral Attribution app embed | Your code: cookie, cart attribute, every checkout path | The copy-paste snippet, then save the code on your order |
| Get orders to Kwik | Automatic | Automatic | Send each order in the order body shape |
| Show the referring rep | An app proxy, or a browser call if Kwik allows it | A server route proxies the lookup | Your own server route |
| Countdown timers | Native Giveaway Countdown block, or Liquid plus a script | Storefront API (needs confirmation) | Schedule from your server, same script |
| Badges and estimates | Metafields in Liquid plus a script | Storefront API data plus your code | Rates from your server, same script |

### Track Kwik Share Links Through Checkout

Keep the referral code from the shopper's first visit all the way to the finished order, so Kwik credits the right rep. Works on a Shopify theme, a Hydrogen or other headless storefront, or any website with its own checkout.

**Before you start**

- Pick your path below: a Shopify theme, Hydrogen (or any headless Shopify build), or any other website.
- Kwik set up for the store, and one working share code to test with (we use `ABC123`).
- Hydrogen: your cart query fragment includes `attributes { key value }`.
- Shopify themes: the Kwik 2.0 app installed, with its **Referral Attribution** app embed turned on.
- Other websites: you control what is saved on each order. See [what to send on every order](/docs/storefront/order-data/).

#### How attribution travels

A shopper opens a rep's link: `/products/hoodie?waveLink=ABC123`. The code has to survive every page they visit after that, then land on the order.

1. **Read** the `waveLink` parameter. The name is case-sensitive, and so is the code. Keep `ABC123` exactly as it came in.
2. **Store** it in a first-party cookie, `_kwik_waveLink`, for 30 days. Links on later pages won't carry the parameter.
3. **Write** it to the Shopify cart as the `waveLink` attribute, keeping any attributes already on the cart.
4. **Check** the finished order for `waveLink = ABC123`, then confirm Kwik credited the right rep.

A newer link replaces an older one: the cookie and the cart attribute always hold the last code the shopper followed.

| Your site | How the code reaches the order | Jump to |
| --- | --- | --- |
| Shopify theme (Liquid) | The Referral Attribution app embed does it. No code. | [Liquid themes](#liquid) |
| Hydrogen or headless Shopify | Your code: cookie, cart attribute, every checkout path | [Hydrogen 1 to 3](#read) |
| Any other website | A copy-paste snippet, then save the code on your order | [Any other website](#any-site) |

> **Needs confirmation from Kwik engineering:** Which field a store's Kwik integration reads can differ by setup: the cart attribute `waveLink`, a hidden line attribute `_kwik_waveLink` (Kwik 2.0 app stores), or the order tag `waveLink=ABC123`. The samples below set the cart and line attributes together, which is safe. Ask your Kwik contact which one your store uses before launch.

#### Hydrogen 1: Read the code and set the cookie

Read the code on the server, in the root loader, so it works on the very first request, even before JavaScript runs. Only accept 1 to 64 letters and digits.

*TypeScript · app/lib/kwik-attribution.server.ts*

```
// app/lib/kwik-attribution.server.ts
// Reads a Kwik share code from the URL or the attribution cookie.
const PARAM = 'waveLink';                 // exact case: ?waveLink=ABC123
const COOKIE = '_kwik_waveLink';
const MAX_AGE = 60 * 60 * 24 * 30;        // 30 days
const VALID = /^[A-Za-z0-9]{1,64}$/;      // keep the code's case as-is

export function readWaveLink(request: Request) {
  const fromUrl = new URL(request.url).searchParams.get(PARAM);
  if (fromUrl && VALID.test(fromUrl)) return {code: fromUrl, fromUrl: true};

  const cookies = request.headers.get('Cookie') ?? '';
  const match = cookies.match(/(?:^|;\s*)_kwik_waveLink=([A-Za-z0-9]{1,64})(?:;|$)/);
  return {code: match ? match[1] : null, fromUrl: false};
}

export function waveLinkCookie(code: string) {
  return `${COOKIE}=${code}; Max-Age=${MAX_AGE}; Path=/; SameSite=Lax; Secure`;
}

```

*TypeScript · app/root.tsx*

```
// app/root.tsx (loader only). Uses React Router 7 / current Hydrogen imports.
import {data, type LoaderFunctionArgs} from 'react-router';
import {readWaveLink, waveLinkCookie} from '~/lib/kwik-attribution.server';
import {syncCartWaveLink} from '~/lib/kwik-cart.server';

export async function loader({request, context}: LoaderFunctionArgs) {
  const {code, fromUrl} = readWaveLink(request);
  const headers = new Headers();

  if (code && fromUrl) {
    headers.append('Set-Cookie', waveLinkCookie(code));   // 30-day first-party cookie
    await syncCartWaveLink(context.cart, code);           // updates a cart that already exists
  }

  // ...your existing root data
  return data({waveLink: code}, {headers});
}

```

#### Hydrogen 2: Write it to the cart

Shopify's `cartAttributesUpdate` replaces the whole attribute list. Read the cart first and merge, or you will wipe attributes other apps set, like gift notes or delivery dates.

*TypeScript · app/lib/kwik-cart.server.ts*

```
// app/lib/kwik-cart.server.ts
// Writes the code to the cart as the `waveLink` attribute and keeps every other attribute.
// cartAttributesUpdate replaces the whole list, so merge before you write.
// Your cart query fragment must include: attributes { key value }
import type {HydrogenCart} from '@shopify/hydrogen';

export async function syncCartWaveLink(cart: HydrogenCart, code: string | null) {
  if (!code) return null;
  const current = await cart.get();
  if (!current) return null;                       // no cart yet: the cart action adds it on the first add
  const attrs = current.attributes ?? [];
  if (attrs.some((a) => a.key === 'waveLink' && a.value === code)) return null;  // already set

  const kept = attrs
    .filter((a) => a.key !== 'waveLink')
    .map(({key, value}) => ({key, value: value ?? ''}));
  return cart.updateAttributes([...kept, {key: 'waveLink', value: code}]);
}

```

#### Hydrogen 3: Cover every path to checkout

Every add to cart must end with the attribute set. Route them all through one cart action and set it there.

| Path | What to do |
| --- | --- |
| Product page add to cart | Goes through the cart action. Covered. |
| Quick-add on product cards | Use the same `CartForm` and cart action, not a separate client-side Storefront API call. |
| Cart drawer and upsells | Same cart action. The attribute is checked again after every change. |
| First add (no cart yet) | The first add creates the cart, so the action sets the attribute after the add, not before. |
| "Buy now" or direct checkout | Skips the cart. Create the cart with the attribute already on it, then send the shopper to `checkoutUrl`. |

*TypeScript · app/routes/cart.tsx*

```
// app/routes/cart.tsx (action). Every add to cart goes through here:
// the product page, quick-add on cards, the cart drawer and upsells.
import {CartForm} from '@shopify/hydrogen';
import {data, type ActionFunctionArgs} from 'react-router';
import {readWaveLink} from '~/lib/kwik-attribution.server';
import {syncCartWaveLink} from '~/lib/kwik-cart.server';

export async function action({request, context}: ActionFunctionArgs) {
  const {cart} = context;
  const formData = await request.formData();
  const {action, inputs} = CartForm.getFormInput(formData);
  const {code} = readWaveLink(request);            // from the 30-day cookie

  let result;
  switch (action) {
    case CartForm.ACTIONS.LinesAdd: {
      // Kwik 2.0 app stores: also tag each new line (hidden from shoppers because of the "_").
      const lines = code
        ? inputs.lines.map((l) => ({...l, attributes: [...(l.attributes ?? []), {key: '_kwik_waveLink', value: code}]}))
        : inputs.lines;
      result = await cart.addLines(lines);
      break;
    }
    // ...your other cart actions (LinesUpdate, LinesRemove, DiscountCodesUpdate)
    default:
      result = await cart.get();
  }

  // The first add creates the cart, so set the cart attribute after every action.
  const synced = await syncCartWaveLink(cart, code);
  const finalCart = synced?.cart ?? result?.cart;
  const headers = finalCart?.id ? cart.setCartId(finalCart.id) : new Headers();
  return data({cart: finalCart, errors: result?.errors}, {headers});
}

```

*TypeScript · app/routes/buy-now.tsx*

```
// app/routes/buy-now.tsx (action). A "Buy now" button that skips the cart
// still needs the code, so create the cart with the attribute already on it.
import {redirect, type ActionFunctionArgs} from 'react-router';
import {readWaveLink} from '~/lib/kwik-attribution.server';

export async function action({request, context}: ActionFunctionArgs) {
  const form = await request.formData();
  const merchandiseId = String(form.get('merchandiseId'));
  const {code} = readWaveLink(request);

  const {cart} = await context.cart.create({
    lines: [{
      merchandiseId,
      quantity: 1,
      attributes: code ? [{key: '_kwik_waveLink', value: code}] : [],
    }],
    attributes: code ? [{key: 'waveLink', value: code}] : [],
  });
  return redirect(cart.checkoutUrl);
}

```

#### Find it on the Shopify order

In Shopify admin, open the order. Cart attributes show in the **Additional details** card: you should see `waveLink` with the value `ABC123`. In the Admin API it is in `customAttributes` (GraphQL) or `note_attributes` (REST webhooks).

Line attributes that start with an underscore, like `_kwik_waveLink`, are hidden from shoppers at checkout.

#### When you also need the order tag

Some setups also want the literal tag `waveLink=ABC123` on the order. Add it when:

- Your Kwik contact says your store's integration reads order tags.
- The merchant wants to filter or export referred orders in Shopify admin. Tags are searchable there. Attributes are not.

Add the tag on the server after the order exists, never from the browser. Two ways: a **Shopify Flow** workflow (Order created → check the `waveLink` attribute → Add order tags), or an `orders/create` webhook in your own app:

*TypeScript · orders/create webhook*

```
// Server only: a webhook handler in your own Shopify app (needs the write_orders scope).
// Topic: orders/create. Verify the X-Shopify-Hmac-Sha256 header before trusting the body.
export async function handleOrderCreated(order: any, adminGraphql: (q: string, v: object) => Promise<any>) {
  const attr = (order.note_attributes ?? []).find((a: any) => a.name === 'waveLink');
  const code = attr?.value;
  if (!code || !/^[A-Za-z0-9]{1,64}$/.test(code)) return;

  await adminGraphql(
    `mutation AddTag($id: ID!, $tags: [String!]!) {
      tagsAdd(id: $id, tags: $tags) { userErrors { field message } }
    }`,
    {id: order.admin_graphql_api_id, tags: [`waveLink=${code}`]},
  );
}

```

#### Shopify themes: what changes

- Turn on the Kwik 2.0 **Referral Attribution** app embed (Online Store → Themes → Customize → App embeds). It reads `waveLink`, `wavelink` or `kwiklink` from the URL and sets the 30-day `_kwik_waveLink` cookie for you.
- App embeds don't run on Hydrogen. That is why the code above exists.
- If your theme needs the `waveLink` cart attribute too, `/cart/update.js` only changes the attributes you send, so other attributes stay put.
- Test custom quick-add buttons and drawer carts the same way. A theme that builds its own checkout links can skip the cart.

*Liquid theme · snippet*

```
<!-- Liquid theme: only for custom cart code. With the Kwik 2.0 "Referral Attribution"
     app embed turned on, the cookie is already handled for you. -->
<script>
  (function () {
    var VALID = /^[A-Za-z0-9]{1,64}$/;
    var code = new URLSearchParams(location.search).get('waveLink');
    if (!code || !VALID.test(code)) {
      var m = document.cookie.match(/(?:^|;\s*)_kwik_waveLink=([A-Za-z0-9]{1,64})/);
      code = m ? m[1] : null;
    } else {
      document.cookie = '_kwik_waveLink=' + code + '; Max-Age=2592000; Path=/; SameSite=Lax; Secure';
    }
    if (!code) return;
    // /cart/update.js changes only the attributes you send, so other attributes stay.
    fetch('/cart/update.js', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({attributes: {waveLink: code}})
    });
  })();
</script>

```

#### Any other website

Not on Shopify, or building your own checkout? The idea is the same on any site: remember the code for 30 days, save it on the order, and send it to Kwik with the order. Paste this snippet before `</body>` on every page:

*HTML · any website*

```
<!-- Kwik share-link snippet for any website. Paste before </body> on every page.
     It keeps the code for 30 days and puts it wherever your checkout can pick it up. -->
<script>
(function () {
  var VALID = /^[A-Za-z0-9]{1,64}$/;            // letters and digits, case kept as-is
  var COOKIE = '_kwik_waveLink';
  var DAYS = 30;

  function readCookie() {
    var m = document.cookie.match(/(?:^|;\s*)_kwik_waveLink=([A-Za-z0-9]{1,64})(?:;|$)/);
    return m ? m[1] : null;
  }

  // 1. Read ?waveLink=ABC123 (exact case) and remember it. A newer link replaces an older one.
  var fromUrl = new URLSearchParams(location.search).get('waveLink');
  if (fromUrl && VALID.test(fromUrl)) {
    document.cookie = COOKIE + '=' + fromUrl + '; Max-Age=' + (DAYS * 86400) + '; Path=/; SameSite=Lax; Secure';
    try {
      localStorage.setItem('kwik_landing', JSON.stringify({ url: location.href, at: new Date().toISOString() }));
    } catch (e) {}
  }

  // 2. Give your checkout code one function to call.
  window.KwikAttribution = {
    code: function () { return readCookie(); },
    landing: function () {
      try { return JSON.parse(localStorage.getItem('kwik_landing') || 'null'); } catch (e) { return null; }
    },
    // The "attribution" object for the order body
    forOrder: function () {
      var l = this.landing();
      return this.code() ? { wave_link: this.code(), landing_url: l && l.url, first_seen_at: l && l.at } : null;
    }
  };

  // 3. Server-rendered checkout forms: add a hidden field to any form marked data-kwik-checkout.
  function fillForms() {
    var code = readCookie();
    if (!code) return;
    document.querySelectorAll('form[data-kwik-checkout]').forEach(function (form) {
      var input = form.querySelector('input[name="wave_link"]');
      if (!input) {
        input = document.createElement('input');
        input.type = 'hidden';
        input.name = 'wave_link';
        form.appendChild(input);
      }
      input.value = code;
    });
  }
  document.addEventListener('DOMContentLoaded', fillForms);
  document.addEventListener('submit', fillForms, true);
})();
</script>

```

Then get the code onto the order, whichever way your checkout works:

- **Server-rendered checkout form:** add `data-kwik-checkout` to the form. The snippet adds a hidden `wave_link` field, and your server saves it on the order.
- **JavaScript checkout:** call `KwikAttribution.forOrder()` and include it when you create the order.
- **A platform with order custom fields** (like WooCommerce, BigCommerce or Squarespace): copy the `_kwik_waveLink` cookie into an order field at checkout.

*JavaScript · custom checkout*

```
// A JavaScript checkout: include the attribution when you create the order.
const res = await fetch('/api/checkout', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({
    cart,                                              // your own cart
    attribution: window.KwikAttribution?.forOrder(),   // {wave_link, landing_url, first_seen_at} or null
  }),
});
// Save attribution.wave_link on your order record. It goes to Kwik with the order.

```

*PHP · example: WooCommerce*

```
<?php
// Example for a WooCommerce store (functions.php or a small plugin).
// Copies the share code from the 30-day cookie onto the order when it is created.
add_action('woocommerce_checkout_create_order', function ($order) {
    $code = $_COOKIE['_kwik_waveLink'] ?? '';
    if (preg_match('/^[A-Za-z0-9]{1,64}$/', $code)) {
        $order->update_meta_data('waveLink', $code);
    }
});
// The code is then on the order as the "waveLink" custom field.
// Send it as attribution.wave_link with the rest of the order body.

```

However it is saved, the code goes to Kwik as `attribution.wave_link` in the order body. See [what to send on every order](/docs/storefront/order-data/) for every field.

> **Note:** Kwik's built-in store connection is for Shopify. On other platforms, the snippet and order body on these pages are how you connect today, with the details set up with your Kwik contact.

#### End-to-end test

1. Open a private window and go to `/products/hoodie?waveLink=ABC123`.
2. Check the browser cookies: `_kwik_waveLink` = `ABC123`, about 30 days to expire.
3. Click to another page, like a collection. The URL no longer has the code.
4. Quick-add a different product (a cap) from a product card. Open the cart drawer.
5. Check the cart: attributes include `waveLink` = `ABC123`, and the cap line has `_kwik_waveLink`.
6. Check out with a test payment.
7. In Shopify admin, the order shows `waveLink` = `ABC123` under Additional details (and the tag `waveLink=ABC123`, if you add tags).
8. In Kwik, confirm the order is credited to the rep behind `ABC123`.
9. Repeat with "Buy now", and once with a second link (`?waveLink=XYZ789`) to confirm the newer code wins.

### Show The Referring Rep's Name And Photo

Greet shoppers who came in on a Kwik link with "You're shopping with Ava", using the rep's name and photo.

**Before you start**

- Share-link tracking from the previous guide, so the root loader returns `waveLink`.
- The share-link lookup address for your store, from your Kwik contact. Save it as `KWIK_SHARELINK_LOOKUP_URL`.
- One valid share code and one made-up code to test with.

#### Two separate clocks

| What | Where it lives | How long | What it controls |
| --- | --- | --- | --- |
| The rep's profile | `localStorage` key `waveData` | 24 hours | Only the banner on the storefront |
| The share code | Cookie `_kwik_waveLink` and the cart attribute | 30 days | Who gets credit for the order |

An old or missing profile only changes what the banner shows. It never changes attribution. If the lookup is down, the store and checkout keep working.

#### The share-link lookup

The lookup takes a share code and returns the rep's public profile. The Hydrogen setup expects three fields:

*Response · GET {KWIK_SHARELINK_LOOKUP_URL}/ABC123*

```
{
  "key": "ABC123",
  "name": "Ava Martinez",
  "photo_url": "https://cdn.example.com/reps/ava.jpg"
}

```

| Field | What it is |
| --- | --- |
| `key` | The share code this profile belongs to. Only use the profile if it matches the code you asked for, exactly. |
| `name` | The name to show. |
| `photo_url` | The rep's photo. It can be missing or empty. |

> **Needs confirmation from Kwik engineering:** The lookup address is not published here. Get it from your Kwik contact, and confirm the field names above with a real code from your brand before you ship. What an unknown code returns (an error status or an empty profile) also needs to be confirmed, so the sample treats both as "no rep".

#### 1. Proxy the lookup through your store

Call the lookup from a small server route. The address stays in your environment, the browser only talks to your own domain, and you can cache good answers for a few minutes.

*TypeScript · app/routes/api.kwik-rep.$code.tsx*

```
// app/routes/api.kwik-rep.$code.tsx: a small server route, so the lookup address
// stays in your environment and the browser only ever talks to your own domain.
import {data, type LoaderFunctionArgs} from 'react-router';

const VALID = /^[A-Za-z0-9]{1,64}$/;

export async function loader({params, context}: LoaderFunctionArgs) {
  const code = params.code ?? '';
  if (!VALID.test(code)) return data({rep: null}, {status: 400});

  // KWIK_SHARELINK_LOOKUP_URL comes from Kwik. Example shape: https://<host>/<path>/shareLink
  const base = context.env.KWIK_SHARELINK_LOOKUP_URL;
  try {
    const res = await fetch(`${base}/${encodeURIComponent(code)}`, {signal: AbortSignal.timeout(4000)});
    if (!res.ok) return data({rep: null}, {status: 404});
    const body = await res.json();
    // Only accept a profile for the exact code we asked for (case-sensitive).
    if (body?.key !== code || !body?.name) return data({rep: null}, {status: 404});
    return data(
      {rep: {key: body.key, name: String(body.name), photo_url: body.photo_url || null}},
      {headers: {'Cache-Control': 'public, max-age=300'}},
    );
  } catch {
    return data({rep: null}, {status: 502});
  }
}

```

#### 2. The banner component

- **Matches the code:** a cached or returned profile is used only when its `key` equals the current `waveLink`.
- **Caches for 24 hours** in `localStorage` as `waveData`, then looks the rep up again.
- **Replaces the rep** when the shopper follows another rep's link, because the code no longer matches.
- **Missing photo:** shows the rep's initials instead, and falls back to initials if the image fails to load.
- **Invalid link:** clears `waveData` and shows nothing, so a shopper never sees the wrong rep.

*TSX · app/components/ShoppingWith.tsx*

```
// app/components/ShoppingWith.tsx
// Shows "You're shopping with Ava" for shoppers who arrived on a Kwik link.
// The 24-hour cache only controls this banner. Attribution lives in the 30-day cookie and the cart.
import {useEffect, useState} from 'react';

type Rep = {key: string; name: string; photo_url: string | null};
const KEY = 'waveData';
const DAY_MS = 24 * 60 * 60 * 1000;

function readCache(code: string): Rep | null {
  try {
    const saved = JSON.parse(localStorage.getItem(KEY) ?? 'null');
    if (!saved || saved.key !== code) return null;                 // another rep's link: replace it
    if (Date.now() - saved.savedAt > DAY_MS) return null;          // older than 24 hours: refresh it
    return saved.rep;
  } catch {
    return null;
  }
}

export function ShoppingWith({waveLink}: {waveLink: string | null}) {
  const [rep, setRep] = useState<Rep | null>(null);
  const [photoFailed, setPhotoFailed] = useState(false);

  useEffect(() => {
    if (!waveLink) return setRep(null);
    const cached = readCache(waveLink);
    if (cached) return setRep(cached);

    fetch(`/api/kwik-rep/${encodeURIComponent(waveLink)}`)
      .then((r) => (r.ok ? r.json() : {rep: null}))
      .then(({rep}) => {
        if (rep && rep.key === waveLink) {
          localStorage.setItem(KEY, JSON.stringify({key: waveLink, rep, savedAt: Date.now()}));
          setRep(rep);
        } else {
          localStorage.removeItem(KEY);     // invalid link: never keep showing the last rep
          setRep(null);
        }
      })
      .catch(() => setRep(null));           // lookup down: hide the banner, never block the store
  }, [waveLink]);

  if (!rep) return null;
  const initials = rep.name.split(/\s+/).map((w) => w[0]).join('').slice(0, 2).toUpperCase();

  return (
    <aside className="shopping-with" aria-label="Your rep">
      {rep.photo_url && !photoFailed ? (
        <img src={rep.photo_url} alt="" width={40} height={40} onError={() => setPhotoFailed(true)} />
      ) : (
        <span className="shopping-with__initials" aria-hidden="true">{initials}</span>
      )}
      <p>You're shopping with <strong>{rep.name}</strong></p>
    </aside>
  );
}

```

Render it in your layout with the code from the root loader: `<ShoppingWith waveLink={rootData.waveLink} />`.

**Any other website or framework:** the logic is the same in plain JavaScript or any framework. Read the code with `KwikAttribution.code()` from the [share-link snippet](/docs/storefront/share-links/#any-site), call your own server route for the profile, and apply the same rules: match the code, cache for 24 hours, replace on a new link, and hide on any error.

#### Shopify themes: what changes

- The same component logic works as a plain script. Read the code from the `_kwik_waveLink` cookie that the Referral Attribution app embed sets.
- A theme has no server route of its own. Use a Shopify app proxy, or ask your Kwik contact whether the lookup can be called from the browser on your domain.

#### End-to-end test

1. Open `/?waveLink=ABC123` in a private window. The banner shows the rep's name and photo.
2. In dev tools, check `localStorage.waveData`: its `key` is `ABC123`.
3. Set `savedAt` in `waveData` to 25 hours ago and reload. The banner looks the rep up again.
4. Open `/?waveLink=XYZ789` (a second valid rep). The banner switches, and `waveData` is replaced.
5. Open `/?waveLink=NOTREAL1`. No banner, `waveData` is gone, and add to cart and checkout still work.
6. Block the photo URL in dev tools. The banner shows initials.
7. Finish a test order and check attribution on the order, not the banner. The banner proves the display. The order proves the credit.

### Connect A Countdown Timer To Kwik

Power your own announcement bar, product page timer or cart countdown with the giveaway schedule Kwik syncs to the store.

**Before you start**

- The Kwik 2.0 Shopify app installed. It writes the giveaway schedule to shop metafields (Kwik 1 stores don't have this data).
- A giveaway with its weeks (earning periods) set up in Kwik: dates, timer text, and banner images if you use them.
- Read [the giveaway data reference](/docs/storefront/giveaway-data/) for the full field list.

#### Try the native blocks first

On Liquid themes, the Kwik 2.0 app has two app blocks that already do this. Add them from the **App blocks** page in the Kwik 2.0 app, then style them in the theme editor. Both switch weeks on their own at the exact boundary.

| Block | What it does |
| --- | --- |
| Giveaway Countdown | Timer text plus days, hours, minutes and seconds to the end of the week, with an optional progress bar. Colors, sizes, labels and layout are adjustable. |
| Giveaway Banner | The running week's desktop and mobile image, with an optional link, alt text and a fallback image for days between weeks. |

Build your own only when the design needs it: a timer inside an existing announcement bar, in the cart, or combined with entry badges. The rest of this page shows how.

#### The data source

Kwik syncs the schedule to the shop metafield `giveaway_weeks`, in the namespace `app--330349150209`. When week settings are saved in Kwik, the store gets them in about a minute. It holds the running week and the upcoming weeks. Ended weeks drop off.

In the example, a shopper is browsing on Thursday afternoon. The 50× offer ends tonight at midnight, Mountain time. The giveaway keeps going at 25× through Sunday.

*JSON · giveaway_weeks*

```
{
  "version": 1,
  "weeks": [
    {
      "geId": 11,
      "geName": "Truck Giveaway",
      "weekId": 204,
      "startsAt": "2026-11-30T07:00:00Z",
      "endsAt": "2026-12-04T07:00:00Z",
      "startTs": 1796022000,
      "endTs": 1796367600,
      "timeZone": "America/Denver",
      "timerText": "50X Ends Tonight",
      "desktopImage": { "url": "https://cdn.example.com/50x-desktop.jpg", "width": 2400, "height": 800 },
      "mobileImage": { "url": "https://cdn.example.com/50x-mobile.jpg", "width": 1080, "height": 1350 }
    },
    {
      "geId": 11,
      "geName": "Truck Giveaway",
      "weekId": 205,
      "startsAt": "2026-12-04T07:00:00Z",
      "endsAt": "2026-12-07T07:00:00Z",
      "startTs": 1796367600,
      "endTs": 1796626800,
      "timeZone": "America/Denver",
      "timerText": "25X Through Sunday",
      "desktopImage": null,
      "mobileImage": null
    }
  ]
}

```

#### Two questions, two timers

| Shopper asks | Pick | Count down to | In the example |
| --- | --- | --- | --- |
| "When does the current 50× offer end?" | The running week: `startTs <= now < endTs`, for your giveaway's `geId` | That week's `endTs` | Tonight, 12:00 AM Friday |
| "When does the giveaway end?" | Every week for your `geId` | The latest `endTs` among them | End of Sunday |

Label the offer timer with the week's `timerText`. Pick the giveaway with its `geId` when more than one runs at once. If you don't pick one, use the first running giveaway.

> **Needs confirmation from Kwik engineering:** A rate change that ends partway through a week only gets its own timer when it is set up as its own week in Kwik, as in the example. The storefront data has no separate end time for a single multiplier yet, and the API preview's dated multipliers are not live. Until Kwik confirms one, count down to the week's `endTs`. The giveaway's end is only as complete as the weeks Kwik has scheduled so far.

#### Time zones

- **Count down with `startTs` and `endTs`.** They are Unix seconds, the same moment everywhere, so a countdown needs no time zone math. `startsAt` and `endsAt` are the same moments as ISO dates in UTC.
- **Show dates in the week's `timeZone`** (for example `America/Denver`) with `Intl.DateTimeFormat`, not the shopper's time zone. Liquid's `date` filter uses the store's time zone, which may be different.
- **Weeks end at midnight.** A week that ends Monday 12:00 AM should read "through Sunday", so format `endTs - 1` when you show the last day.

#### 1. Get the data onto the page

On a Liquid theme, print the metafields as JSON from a small section, and paint the bar in Liquid so it never flashes empty. Custom code must use the full namespace. `$app` only works inside Kwik's own app blocks.

*Liquid · sections/kwik-data.liquid*

```
{%- comment -%} sections/kwik-data.liquid: prints Kwik's giveaway data as JSON for your scripts.
Render it once in layout/theme.liquid with {% section 'kwik-data' %}. The same file also answers
/?sections=kwik-data, which is how the page gets fresh data after a timer hits zero. {%- endcomment -%}
{%- assign kwik = shop.metafields['app--330349150209'] -%}
<script type="application/json" id="kwik-data">
  {
    "weeks": {{ kwik.giveaway_weeks.value | json }},
    "entries": {{ kwik.giveaway_entries.value | json }},
    "wavelinkRequired": {{ kwik.wavelink_required.value | json }},
    "serverTs": {{ 'now' | date: '%s' }}
  }
</script>

```

*Liquid · announcement bar*

```
{%- comment -%} Announcement bar first paint, so there is no empty flash before JavaScript runs.
The page may be cached, so the script below re-checks the running week on load. {%- endcomment -%}
{%- assign weeks = shop.metafields['app--330349150209'].giveaway_weeks.value.weeks -%}
{%- assign now_ts = 'now' | date: '%s' | plus: 0 -%}
{%- assign running = nil -%}
{%- for week in weeks -%}
  {%- if week.startTs <= now_ts and week.endTs > now_ts -%}{%- assign running = week -%}{%- break -%}{%- endif -%}
{%- endfor -%}
<div class="kwik-bar" data-kwik-bar {% unless running %}hidden{% endunless %}>
  <strong data-kwik-label>{{ running.timerText }}</strong>
  <span data-kwik-offer-timer></span>
  <span data-kwik-giveaway-end></span>
</div>

```

On Hydrogen, app blocks and app embeds don't run, so read the same metafields through the Storefront API in your own route:

*TypeScript · app/routes/api.kwik-promo.tsx*

```
// app/routes/api.kwik-promo.tsx: Kwik's giveaway data for a Hydrogen storefront.
// Needs confirmation: these metafields come back as null unless Kwik's metafield
// definitions allow Storefront API access on your store. Check with Kwik first.
import {data, type LoaderFunctionArgs} from 'react-router';

const QUERY = `#graphql
  query KwikPromo {
    shop {
      weeks: metafield(namespace: "app--330349150209", key: "giveaway_weeks") { value }
      entries: metafield(namespace: "app--330349150209", key: "giveaway_entries") { value }
      wavelinkRequired: metafield(namespace: "app--330349150209", key: "wavelink_required") { value }
    }
  }`;

export async function loader({context}: LoaderFunctionArgs) {
  const {shop} = await context.storefront.query(QUERY, {cache: context.storefront.CacheShort()});
  const parse = (m: {value: string} | null, fallback: unknown) => (m?.value ? JSON.parse(m.value) : fallback);
  return data({
    weeks: parse(shop.weeks, {weeks: []}),
    entries: parse(shop.entries, []),
    wavelinkRequired: parse(shop.wavelinkRequired, false),
  });
}

// In the browser:
// const promo = createPromo({ read: () => window.__KWIK__, reload: () => fetch('/api/kwik-promo').then((r) => r.json()) });

```

**Not on Shopify?** The schedule isn't synced to your site for you. Load the same fields from your own server (from the API preview's `GET /giveaways/{giveaway_id}/weeks` once it is live, or from data your Kwik contact sets up) and pass them to the shared clock below. The clock only needs `read` and `reload` functions, so the rest of this page works on any site.

#### 2. One shared clock

Use one clock for the whole page. The announcement bar, product badges and cart estimate all read the same state, so they always agree. Each second it re-checks the running week. When a week starts or ends, it reloads the data and tells every display.

*JavaScript · kwik-promo.js*

```
// kwik-promo.js: one shared clock for the announcement bar, product badges and cart estimate.
// Works on Liquid themes and Hydrogen. You pass in how to read and re-load the data.
export function createPromo({read, reload, geId = null}) {
  let data = read();                     // {weeks: {...} | [...], entries: [...], wavelinkRequired}
  let state = compute();
  let updating = false;
  const listeners = new Set();

  function now() { return Math.floor(Date.now() / 1000); }
  function weeksOf(d) {
    const list = Array.isArray(d?.weeks) ? d.weeks : d?.weeks?.weeks ?? [];
    return list.filter((w) => geId == null || String(w.geId) === String(geId));
  }

  function compute() {
    const t = now();
    const weeks = weeksOf(data);
    const week = weeks.filter((w) => w.startTs <= t && t < w.endTs).sort((a, b) => a.endTs - b.endTs)[0] ?? null;
    const next = weeks.filter((w) => w.startTs > t).sort((a, b) => a.startTs - b.startTs)[0] ?? null;
    const giveawayEndTs = weeks.length ? Math.max(...weeks.map((w) => w.endTs)) : null;
    const id = week?.geId ?? geId;
    // No running week means no earning rate. Kwik awards nothing between weeks, so neither do we.
    const rate = week ? (data?.entries ?? []).find((e) => id == null || String(e.geId) === String(id)) ?? null : null;
    return {week, next, giveawayEndTs, rate, updating};
  }

  function emit() { state = compute(); listeners.forEach((fn) => fn(state)); }

  async function refresh() {
    updating = true; emit();                       // badges and cart hide numbers while this is true
    try { data = await reload(); } catch {}
    updating = false; emit();
  }

  setInterval(() => {
    const before = state.week?.weekId ?? null;
    const after = compute().week?.weekId ?? null;
    if (before !== after) {
      refresh();                                    // a week ended or started: get the new rate
      setTimeout(refresh, 60_000);                  // and once more, in case the store data lagged
    } else {
      emit();                                       // just tick the countdowns
    }
  }, 1000);

  return {
    get state() { return state; },
    subscribe(fn) { listeners.add(fn); fn(state); return () => listeners.delete(fn); },
    refresh,
  };
}

// Helpers for labels
export function countdown(endTs) {
  const s = Math.max(0, endTs - Math.floor(Date.now() / 1000));
  return {d: Math.floor(s / 86400), h: Math.floor((s % 86400) / 3600), m: Math.floor((s % 3600) / 60), s: s % 60};
}
export function dayName(ts, timeZone) {
  // Show dates in the giveaway's own time zone, not the shopper's.
  return new Intl.DateTimeFormat('en-US', {weekday: 'long', timeZone}).format(new Date(ts * 1000));
}
export function lastDay(endTs, timeZone) {
  // Weeks end at midnight. Subtract a second so "ends Monday 12:00 AM" reads "through Sunday".
  return dayName(endTs - 1, timeZone);
}

```

*Liquid theme · wire up the bar*

```
<script type="module">
  import {createPromo, countdown, dayName, lastDay} from '{{ "kwik-promo.js" | asset_url }}';

  const parse = (html) => {
    const el = new DOMParser().parseFromString(html, 'text/html').getElementById('kwik-data');
    return JSON.parse(el.textContent);
  };
  const promo = createPromo({
    read: () => JSON.parse(document.getElementById('kwik-data').textContent),
    // Section Rendering API: fresh metafields without reloading the page.
    reload: () => fetch(`/?sections=kwik-data&t=${Date.now()}`).then((r) => r.json()).then((j) => parse(j['kwik-data'])),
  });
  window.kwikPromo = promo;            // product badges and the cart estimate subscribe to the same clock

  const bar = document.querySelector('[data-kwik-bar]');
  promo.subscribe(({week, next, giveawayEndTs}) => {
    if (!week) {                        // a gap between offers
      bar.hidden = !next;
      if (next) bar.querySelector('[data-kwik-label]').textContent = `${next.timerText} starts ${dayName(next.startTs, next.timeZone)}`;
      bar.querySelector('[data-kwik-offer-timer]').textContent = '';
      return;
    }
    const t = countdown(week.endTs);
    bar.hidden = false;
    bar.querySelector('[data-kwik-label]').textContent = week.timerText;
    bar.querySelector('[data-kwik-offer-timer]').textContent = `Offer ends in ${t.d ? t.d + 'd ' : ''}${t.h}h ${t.m}m ${t.s}s`;
    bar.querySelector('[data-kwik-giveaway-end]').textContent =
      giveawayEndTs > week.endTs ? `Giveaway runs through ${lastDay(giveawayEndTs, week.timeZone)}` : '';
  });
</script>

```

#### When the timer hits zero

1. **Re-pick the running week.** In the example, the 50× week ends and the 25× week starts at the same moment. The label changes to "25X Through Sunday" and the timer counts to the new `endTs`. Never sit at 00:00:00.
2. **Reload the rate.** The rate and multipliers in `giveaway_entries` belong to the week that was running when the page loaded. Fetch fresh data (the Section Rendering API on Liquid, your own route on Hydrogen) and hide entry numbers until it arrives.
3. **Check again a minute later,** in case the store data lagged behind the switch.

**A gap between promotions:** if no week is running, Kwik awards no entries. Hide entry badges and estimates. Show "25X starts Friday" from the next week's `startTs` instead, or hide the bar.

**A page left open across the switch:** the shared clock handles it. The page doesn't need a reload, and every display updates in the same second.

> **Needs confirmation from Kwik engineering:** How soon `giveaway_entries` shows the new week's rate after a week boundary. The sample reloads at the switch and again 60 seconds later. If your store lags longer, ask Kwik.

#### End-to-end test

1. On a test store, set up two back-to-back weeks in Kwik. The first ends in 3 minutes, with different timer text and rates.
2. Wait a minute, then load the page. The bar shows the first week's text, the offer timer counts to its end, and the giveaway line shows the second week's last day.
3. Leave the page open. At zero, the label and timer switch to the second week without a reload, and entry numbers hide briefly, then return at the new rate.
4. Set up a gap (the second week starts an hour later). At zero, badges hide and the bar shows when the next offer starts.
5. Compare a displayed date with the Kwik admin, in the giveaway's time zone.

### Show Multipliers And Estimate Entries

Show the right multiplier on product cards and product pages, then estimate a cart's entries the way Kwik counts them.

**Before you start**

- The shared clock from the timer guide, so badges, timers and cart estimates use the same promotion.
- Each product's numeric id, tags and collection titles available to your script.
- The share-link cookie from the first guide, for referral multipliers.

#### The data

The shop metafield `giveaway_entries` has one object per running giveaway: this week's base rate and its `multipliers`. The example uses one entry per dollar.

*JSON · giveaway_entries (example)*

```
[
  {
    "geId": 11,
    "geName": "Truck Giveaway",
    "forEachAmt": null,
    "forEachPct": 100,
    "pointValue": 1,
    "multipliers": [
      { "multiplierType": "purchase_multiplier", "forEachAmt": 5, "shopifyProductIds": [8100000000001],
        "stkAny": false, "stkRefMulti": false, "stkMulRef": false },
      { "multiplierType": "site_wide_multiplier", "forEachAmt": 2 },
      { "multiplierType": "order_multiplier", "forEachAmt": 2, "shopifyProductIds": [8100000000001, 8100000000002],
        "stkAny": false, "stkRefMulti": false, "stkMulRef": false },
      { "multiplierType": "referral_multiplier", "forEachAmt": 3 }
    ]
  }
]

```

| Field | What it means |
| --- | --- |
| `forEachPct` and `pointValue` | The base rate. Entries per $1 = `forEachPct / 100 × pointValue`. 100 and 1 means 1 entry per dollar. |
| `forEachAmt` (on the giveaway) | A flat number of entries per item instead of per dollar. When it is set, don't show an "NX" label. |
| `forEachAmt` (on a multiplier) | The multiplier itself: 5 means 5×. It is not a base rate. |
| `multiplierType` | `purchase_multiplier` (product), `site_wide_multiplier`, `order_multiplier` or `referral_multiplier`. |
| `shopifyProductIds` | The products it applies to. An empty list matches nothing. On very large catalogs it can be left out, and `values` holds tag names (`multiOn` 1) or collection titles (`multiOn` 3). |
| `stkAny`, `stkRefMulti`, `stkMulRef` | Who gets it, not how it stacks. None set: the buyer. `stkRefMulti`: the buyer on a referred order. `stkMulRef`: the referrer only, never show it to the buyer. `stkAny`: both. |

#### The calculation, in Kwik's order

1. **Base:** each eligible line's amount paid × the base rate.
2. **Product or sitewide:** apply the product's multiplier when one matches. Otherwise use the active sitewide multiplier. They never stack. If two multipliers of the same type match, the higher one counts.
3. **Order and referral:** add up the lines, then apply the order multiplier and the referral multiplier. The referral multiplier only counts when the shopper came in on a share link.
4. **Fixed bonus entries last.** They are never multiplied.

##### Worked example

| Step | Hoodie, $40 | Cap, $20 | Cart |
| --- | --- | --- | --- |
| 1. Base at 1 entry per $1 | 40 | 20 |  |
| 2. Product 5×, or sitewide 2× | 40 × 5 = **200** | 20 × 2 = **40** | 240 |
| 3a. Order multiplier 2× |  |  | 240 × 2 = 480 |
| 3b. Referral multiplier 3× |  |  | 480 × 3 = **1,440** |
| 4. Fixed bonus |  |  | 1,440 + 100 = **1,540** |

Kwik rounds once, at the end, and applies an order multiplier only to the products it lists. When it lists every product in the cart, as here, that is the same as multiplying the cart total.

*JavaScript · kwik-entries.js*

```
// kwik-entries.js: multiplier badges and cart estimates from giveaway_entries.
// "product" is {id, tags, collections}: numeric Shopify product id, tag names, collection titles.

const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
const isFlat = (rate) => num(rate?.forEachAmt) > 0;

// Entries per $1 at the base rate. forEachPct 100 with pointValue 1 = 1 entry per dollar.
export function perDollar(rate) {
  return (num(rate.forEachPct) / 100) * (rate.pointValue == null ? 1 : num(rate.pointValue));
}

// The flags say WHO gets a multiplier. Never show a referrer-only multiplier to the buyer.
function buyerGets(m, hasWaveLink) {
  if (m.multiplierType === 'referral_multiplier') return hasWaveLink;
  if (m.multiplierType === 'site_wide_multiplier') return true;
  if (m.stkAny) return true;
  if (m.stkRefMulti) return hasWaveLink;
  if (m.stkMulRef) return false;
  return true;
}

function matches(m, product) {
  if (String(m.multiOn) === '5') return false;            // promo-code multipliers: not shown on the storefront
  if (Array.isArray(m.shopifyProductIds)) return m.shopifyProductIds.some((id) => String(id) === String(product.id));
  const values = (m.values ?? []).map((v) => String(v).toLowerCase());
  const pool = String(m.multiOn) === '1' ? product.tags ?? [] : String(m.multiOn) === '3' ? product.collections ?? [] : [];
  return pool.some((v) => values.includes(String(v).toLowerCase()));
}

function best(rate, type, hasWaveLink, product) {
  const factors = (rate.multipliers ?? [])
    .filter((m) => m.multiplierType === type && num(m.forEachAmt) > 0 && buyerGets(m, hasWaveLink))
    .filter((m) => !product || matches(m, product))
    .map((m) => num(m.forEachAmt));
  return factors.length ? Math.max(...factors) : 0;        // same type twice: the highest wins
}

// Step 2: a product multiplier replaces the sitewide one. They never stack.
export function productOrSitewide(rate, product, hasWaveLink = false) {
  return best(rate, 'purchase_multiplier', hasWaveLink, product) || best(rate, 'site_wide_multiplier', hasWaveLink) || 1;
}

export function estimateCart(lines, rate, {hasWaveLink = false, fixedBonus = 0} = {}) {
  if (!rate) return null;                                   // between offers: no rate, no estimate
  const rows = lines.map((line) => {
    // Step 1: amount paid x base rate (or a flat amount per item)
    const base = isFlat(rate) ? num(rate.forEachAmt) * line.quantity : line.amountPaid * perDollar(rate);
    // Step 2: product multiplier, or the sitewide multiplier
    const factor = productOrSitewide(rate, line.product, hasWaveLink);
    const order = best(rate, 'order_multiplier', hasWaveLink, line.product) || 1;
    return {title: line.title, base, factor, order, entries: base * factor};
  });
  // Step 3: sum the lines, then the order multiplier and the referral multiplier
  const lineTotal = rows.reduce((t, r) => t + r.entries, 0);
  const afterOrder = rows.reduce((t, r) => t + r.entries * r.order, 0);
  const referral = best(rate, 'referral_multiplier', hasWaveLink) || 1;
  const multiplied = Math.round(afterOrder * referral);    // round once
  // Step 4: fixed bonus entries last. They are never multiplied.
  return {rows, lineTotal, afterOrder, referral, multiplied, fixedBonus, total: multiplied + fixedBonus};
}

```

*JavaScript · the worked example as a test*

```
// The worked example as a test (Vitest or Jest).
import {estimateCart} from './kwik-entries.js';
import rateList from './fixtures/giveaway_entries.json';   // the JSON above

const hoodie = {id: 8100000000001, tags: [], collections: []};
const cap = {id: 8100000000002, tags: [], collections: []};

test('worked example: 1,540 entries', () => {
  const est = estimateCart(
    [
      {title: 'Hoodie', amountPaid: 40, quantity: 1, product: hoodie},
      {title: 'Cap', amountPaid: 20, quantity: 1, product: cap},
    ],
    rateList[0],
    {hasWaveLink: true, fixedBonus: 100},
  );
  expect(est.rows.map((r) => r.entries)).toEqual([200, 40]);   // 40 x 1 x 5, 20 x 1 x 2
  expect(est.lineTotal).toBe(240);
  expect(est.afterOrder).toBe(480);                              // x2 order multiplier
  expect(est.multiplied).toBe(1440);                             // x3 referral multiplier
  expect(est.total).toBe(1540);                                  // + 100 fixed bonus
});

test('no referral link: no referral multiplier', () => {
  const est = estimateCart([{title: 'Hoodie', amountPaid: 40, quantity: 1, product: hoodie}], rateList[0]);
  expect(est.total).toBe(400);                                   // 40 x 5 x 2
});

```

**Any website:** `kwik-entries.js` is plain JavaScript with no Shopify code in it. Give it the giveaway's rate and multipliers in the shape above, from Shopify metafields or your own server, and your cart lines as `{title, amountPaid, quantity, product: {id, tags, collections}}`.

> **Needs confirmation from Kwik engineering:** Fixed bonus entries, like sign-up, free or promo-code entries, are not in the storefront data. Pass a known amount as `fixedBonus` or leave it at 0. Promo-code multipliers (`multiOn` 5) can't be shown before checkout.

#### Badges on product cards and pages

A badge shows the product's multiplier and what it earns at full price: "5× · Earn 200 entries". Use the product multiplier when one matches, otherwise the sitewide one. Hide the badge between offers, while the clock is reloading, and, when `wavelink_required` is true, for shoppers who didn't come in on a share link.

*Liquid theme · product card badge*

```
<!-- In your product card snippet. Liquid prices are in cents. -->
<span class="kwik-badge" hidden
  data-kwik-badge
  data-product-id="{{ card_product.id }}"
  data-price="{{ card_product.price }}"
  data-tags="{{ card_product.tags | join: '|' | escape }}"
  data-collections="{{ card_product.collections | map: 'title' | join: '|' | escape }}"></span>

<!-- Once per page, after kwik-promo.js -->
<script type="module">
  import {perDollar, productOrSitewide} from '{{ "kwik-entries.js" | asset_url }}';
  const hasWaveLink = /(?:^|;\s*)_kwik_waveLink=[A-Za-z0-9]{1,64}/.test(document.cookie);

  window.kwikPromo.subscribe(({rate, updating}) => {
    document.querySelectorAll('[data-kwik-badge]').forEach((el) => {
      if (!rate || updating) return (el.hidden = true);          // between offers or refreshing: hide
      const product = {
        id: el.dataset.productId,
        tags: el.dataset.tags.split('|').filter(Boolean),
        collections: el.dataset.collections.split('|').filter(Boolean),
      };
      const factor = productOrSitewide(rate, product, hasWaveLink);
      const base = Number(rate.forEachAmt) > 0 ? Number(rate.forEachAmt) : (Number(el.dataset.price) / 100) * perDollar(rate);
      const entries = Math.round(base * factor);
      el.textContent = `${factor > 1 ? factor + '× · ' : ''}Earn ${entries.toLocaleString('en-US')} entries`;
      el.hidden = false;
    });
  });
</script>

```

Always pass the product, never just a price. Tag and collection multipliers can only match when the script knows the product's tags and collections. Shopify's `/cart.js` doesn't include them, so print them in Liquid for cart lines too.

#### 25 entries per dollar is not the same as 25×

| Label | What it means | $40 hoodie |
| --- | --- | --- |
| "25 entries per $1" | The base rate: `forEachPct` 2500, `pointValue` 1 | 1,000 entries |
| "25×" at a base of 1 per $1 | A multiplier on the base rate | 1,000 entries |
| "25×" at a base of 2 per $1 | Same multiplier, different base | 2,000 entries |

The two only match when the base is 1 entry per dollar. Kwik's own timer text often says "30X" for a 30-per-dollar week. In your own copy, say "per $1" for a rate and "×" for a multiplier, and show the entries it earns.

#### Theme tags like kwik10

Older themes set multipliers with product tags. Kwik data now comes first. Keep tags only as a fallback for stores that aren't on Kwik 2.0 yet, then remove them.

| Tag | Old meaning |
| --- | --- |
| `kwik10` | A tag containing "kwik" plus a number sets that product's multiplier: 10×. The last matching tag wins. |
| `bonus:100` | Adds 100 flat bonus entries to that product. |

- The old theme math was `ceil(price) × N`: price rounded up to the dollar, then multiplied. Kwik's math rounds once, at the end, so the two can differ by a few entries.
- Don't fall back to tags between weeks. Kwik awards nothing then, so tag numbers would over-promise.
- Never show both a tag badge and a Kwik badge on the same card.

#### Keep the bar, badges and cart in sync

Subscribe every display to the same shared clock. When the 50× week ends, one event updates all three together:

| Display | Before midnight | After midnight |
| --- | --- | --- |
| Announcement bar | "50X Ends Tonight", counting down | "25X Through Sunday", counting to Monday 12:00 AM |
| Product badge on a $40 hoodie | "Earn 2,000 entries" (50 per $1) | Hidden for a moment, then "Earn 1,000 entries" (25 per $1) |
| Cart estimate | At the 50× rate | Recalculated at the 25× rate |

Never compute a display from its own copy of the data or its own timer. That is how a bar ends up saying 25× while a badge still says 50×.

#### Compare the estimate with what Kwik records

- After a test order, check the entries on the Kwik thank-you page block or the **Point Tracker** block (with **Show** set to include giveaway entries), or the customer's entries in the Kwik admin.
- Expect small differences from rounding, promo-code multipliers, products the giveaway excludes, and refunds.
- A big difference usually means the product's tags or collections weren't passed, so a product multiplier didn't match.
- The API preview has `GET /giveaways/{giveaway_id}/customers/{customer_id}` for this. It is a preview, not live yet.

Customer entry balances ("you have 4,200 entries") are not in the storefront data. Use the native Point Tracker, Points Overview or Loyalty popup blocks for those.

#### End-to-end test

1. On a test store, set the example up in Kwik: 1 entry per $1, the hoodie at 5×, sitewide 2×, order 2× on both products, referral 3×.
2. Open `/products/hoodie?waveLink=ABC123`. The hoodie badge shows "5×" and the cap badge "2×".
3. Add both to the cart. The estimate reads 1,540 when you pass a 100-entry bonus, or 1,440 without it.
4. Repeat in a new private window without the share link. The estimate drops to 480, because the referral multiplier no longer applies.
5. Place the referred order with a test payment and compare the entries Kwik records with the estimate.

### What Kwik Needs On Every Order

Every reward and every referral credit starts from an order. This is the data Kwik reads from each one, the fields that carry attribution, and the signals to send when an order changes. It applies to any platform.

**Before you start**

- Shopify stores: Kwik reads orders from Shopify for you. You only need the share code to reach the order ([track share links](/docs/storefront/share-links/)).
- Other platforms: a server that can send each paid order, refund and cancellation to Kwik.

#### The signals Kwik needs

| Signal | When to send it | What Kwik does with it |
| --- | --- | --- |
| **Order paid** | Once the payment goes through. Send it again if the order changes. | Finds who to credit, then calculates entries, points, cashback, commissions and Waves |
| **Refund** | For each full or partial refund | Takes back the rewards for what was refunded |
| **Cancellation** | When an order is cancelled | Takes back everything the order earned |
| **Share-link visit** (optional) | The Kwik Pixel records visits where it is installed | Reporting. Credit always comes from the order, not the visit. |

Rewards start as pending and clear after the return window, so a refund or cancellation that arrives later still counts.

#### The order body

This is the full shape, using the same hoodie and cap order as the other guides. Amounts are decimals in the order's currency. Times are ISO 8601 in UTC.

*JSON · order body*

```
{
  "order_id": "1042",
  "order_number": "#1042",
  "created_at": "2026-12-03T22:14:05Z",
  "paid_at": "2026-12-03T22:14:09Z",
  "status": "paid",
  "currency": "USD",
  "customer": {
    "id": "8812",
    "email": "jane@example.com",
    "first_name": "Jane",
    "last_name": "Lee",
    "phone": "+15555550123",
    "accepts_marketing": true
  },
  "line_items": [
    {
      "line_id": "1",
      "product_id": "8100000000001",
      "variant_id": "4400000000011",
      "sku": "HOOD-BLK-M",
      "title": "Hoodie",
      "quantity": 1,
      "unit_price": 40.00,
      "amount_paid": 40.00,
      "tags": ["outerwear"],
      "collections": ["Winter"]
    },
    {
      "line_id": "2",
      "product_id": "8100000000002",
      "variant_id": "4400000000022",
      "sku": "CAP-BLK",
      "title": "Cap",
      "quantity": 1,
      "unit_price": 20.00,
      "amount_paid": 20.00,
      "tags": [],
      "collections": ["Accessories"]
    }
  ],
  "discount_codes": [{ "code": "WELCOME100", "amount": 0.00 }],
  "subtotal": 60.00,
  "discount_total": 0.00,
  "shipping_total": 5.00,
  "tax_total": 4.80,
  "total": 69.80,
  "attribution": {
    "wave_link": "ABC123",
    "landing_url": "https://yourstore.com/products/hoodie?waveLink=ABC123",
    "first_seen_at": "2026-12-01T17:02:44Z"
  }
}

```

| Field | Needed | What Kwik uses it for |
| --- | --- | --- |
| `order_id` | Required | One order, counted once. Sending the same id again updates it and never awards rewards twice. |
| `created_at`, `paid_at` | Required | Which giveaway week and promotion the order falls in, and when holds start. |
| `status` | Required | `paid`, `partially_refunded`, `refunded` or `cancelled`. Only paid orders earn. |
| `currency` | Required | Reads every amount in the right currency. |
| `customer.email` | Required | Who earns the rewards. It links the order to the shopper's Kwik account. |
| `customer.id`, names, `phone` | Recommended | Matching repeat customers and personalizing emails. `accepts_marketing` keeps messages within consent. |
| `line_items[].product_id` | Required | Product multipliers, product bonuses and excluded products. Use the same product ids Kwik has for the store (Shopify product ids on Shopify). |
| `line_items[].amount_paid` | Required | What each line earns on: after discounts, before tax and shipping. |
| `line_items[].quantity`, `unit_price` | Required | Flat per-item rewards and partial refunds. |
| `line_items[].tags`, `collections` | Recommended | Tag and collection multipliers on large catalogs. |
| `line_items[].line_id`, `variant_id`, `sku` | Recommended | Matching refunds to lines, and variant-level rules. |
| `discount_codes` | Required if used | Promo-code bonuses, and credit for an ambassador's personal code, even without a share link. |
| `subtotal`, `discount_total`, `shipping_total`, `tax_total`, `total` | Recommended | Reporting and checks. |
| `attribution.wave_link` | Required if present | Who referred the order, the people before them (Waves), and the referral multiplier. |
| `attribution.landing_url`, `first_seen_at` | Optional | Reporting on which links and pages bring orders. |

Never send card numbers or other payment details. Kwik doesn't need them.

> **Needs confirmation from Kwik engineering:** Which order time places an order in a giveaway week (created or paid) and the exact field names for non-Shopify orders. Confirm both with your Kwik contact before you build. On Shopify, Kwik reads these from the Shopify order itself.

#### Where the share code goes

| Platform | Put the code here | Example |
| --- | --- | --- |
| Any platform, order body | `attribution.wave_link` | `"wave_link": "ABC123"` |
| Shopify, cart attribute | Cart attribute `waveLink` (shows on the order as an attribute) | `waveLink` = `ABC123` |
| Shopify, line attribute | Hidden line attribute `_kwik_waveLink` on each line (Kwik 2.0 app stores) | `_kwik_waveLink` = `ABC123` |
| Shopify, order tag | Order tag, when the store's setup reads tags | `waveLink=ABC123` |

- **Send the code exactly as it arrived.** It is case-sensitive, and only 1 to 64 letters and digits.
- **The last link wins.** If a shopper followed two reps' links, send the newer code.
- **No code? Send nothing.** Leave `attribution` out or set it to null. Never guess or fill in a default rep.
- **Discount codes count too.** An order that used an ambassador's personal code is credited to them even without a share link, so always send `discount_codes`.

#### Shopify: where each field comes from

On Shopify stores you send nothing. Kwik reads the Shopify order as it is paid, with a regular full sync as a backup. This is how the fields line up, for checking an order by hand:

| Kwik field | Shopify order |
| --- | --- |
| `order_id`, `order_number` | `id`, `name` |
| `created_at`, `paid_at`, `status` | `created_at`, `processed_at`, `financial_status` and `cancelled_at` |
| `customer` | `customer` and `email` |
| `line_items[].amount_paid` | Line price × quantity, minus its `discount_allocations` |
| `discount_codes` | `discount_codes` |
| `attribution.wave_link` | The `waveLink` attribute (`note_attributes`), the `_kwik_waveLink` line property, or a `waveLink=` tag |
| Refunds | `refunds` |

#### Refunds and cancellations

Send one refund for each refund in your system, with the lines and amounts refunded. Kwik takes back the rewards for those lines only. For a cancellation, send the order again with `status` set to `cancelled`.

*JSON · refund*

```
{
  "order_id": "1042",
  "refund_id": "r-7781",
  "refunded_at": "2026-12-09T15:30:00Z",
  "line_items": [
    { "line_id": "2", "quantity": 1, "amount": 20.00 }
  ],
  "shipping_refunded": 0.00
}

```

#### Sending orders from another platform

Send orders from your server, never from the browser, because the request carries your secret key. Retry on errors: the same `order_id` is never counted twice.

*TypeScript · server*

```
// Server only. Run when an order is paid, and again for each refund or cancellation.
// Preview: the path and auth below are a sample. Get the current way to send orders from Kwik.
export async function sendOrderToKwik(order: KwikOrder) {
  const res = await fetch('https://api.kwik.com/v1/orders', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.KWIK_API_KEY}`,   // never in the browser
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(order),                               // the order body on this page
  });
  if (res.status === 429 || res.status >= 500) throw new Error('retry later');  // safe to retry: same order_id never counts twice
  return res.json();
}

```

> **Needs confirmation from Kwik engineering:** The self-serve orders endpoint is part of the API preview and not live yet. Today, non-Shopify order connections are set up with your Kwik contact. Build your order data in the shape on this page, and they will tell you where to send it.

#### End-to-end test

1. Follow a share link (`?waveLink=ABC123`) and place a test order with two products and a promo code.
2. Check your order record: the code is saved exactly as `ABC123`, and the lines show amounts after discounts.
3. Send the order (or let Shopify sync it). In Kwik, the order shows the right customer, the rep behind `ABC123`, and rewards matching your estimate.
4. Send the same order again. Nothing is awarded twice.
5. Refund one line. Only that line's rewards are taken back.
6. Place an order with no share link. It has no referrer, and the buyer still earns their own rewards.

### Giveaway Data In Shopify

The Kwik 2.0 Shopify app keeps the giveaway schedule, rates, multipliers and banners in shop metafields. Read them to build timers, badges, banners and trackers.

**Before you start**

- The Kwik 2.0 Shopify app installed (Kwik 1 stores don't have this data).
- A giveaway set up in Kwik with weeks, timer text and, optionally, banner images.

#### How the data gets to the store

1. The brand sets up the giveaway in Kwik: weeks, rates, multipliers, timer text and banners.
2. When those settings are saved, the Kwik 2.0 app syncs them to shop metafields, usually within a minute.
3. Your theme reads them in Liquid, or your Hydrogen app reads them through the Storefront API.

The storefront never calls Kwik directly. Everything it needs is already in the store.

#### The namespace

Every key lives in the Kwik 2.0 app's namespace, `app--330349150209`. It is the same on every store. Kwik's own app blocks can use the `$app` shortcut, but your custom sections, snippets and Custom Liquid blocks must use the full name:

*Liquid*

```
{{ shop.metafields['app--330349150209'].giveaway_entries.value | json }}
```

#### The keys

| Key | Type | What it holds |
| --- | --- | --- |
| `giveaway_weeks` | JSON object | `{version, weeks: [...]}`: the running and upcoming weeks of every giveaway, with dates, timer text and banner images. |
| `giveaway_entries` | JSON array | One object per running giveaway: this week's base rate and its multipliers. |
| `cashback_config` | JSON object | The cashback rate and rules. |
| `loyalty_points` | JSON array | The loyalty point earning rules. |
| `wavelink_required` | Boolean | `true` when rewards should only show to shoppers who came in on a share link. |

#### giveaway_weeks

| Field | What it is |
| --- | --- |
| `geId`, `geName` | The giveaway's id and name. Several giveaways can run at once. |
| `weekId` | The week (earning period) id. |
| `startTs`, `endTs` | Start and end in Unix seconds. A week is running when `startTs <= now < endTs`. |
| `startsAt`, `endsAt` | The same moments as ISO dates in UTC. |
| `timeZone` | The giveaway's time zone, for showing dates, like `America/Denver`. |
| `timerText` | Short text for the timer or bar, like "50X Ends Tonight". |
| `desktopImage`, `mobileImage` | `{url, width, height}`, or null. Always check before using. |

*JSON · example*

```
{
  "version": 1,
  "weeks": [
    {
      "geId": 11,
      "geName": "Truck Giveaway",
      "weekId": 204,
      "startsAt": "2026-11-30T07:00:00Z",
      "endsAt": "2026-12-04T07:00:00Z",
      "startTs": 1796022000,
      "endTs": 1796367600,
      "timeZone": "America/Denver",
      "timerText": "50X Ends Tonight",
      "desktopImage": { "url": "https://cdn.example.com/50x-desktop.jpg", "width": 2400, "height": 800 },
      "mobileImage": { "url": "https://cdn.example.com/50x-mobile.jpg", "width": 1080, "height": 1350 }
    },
    {
      "geId": 11,
      "geName": "Truck Giveaway",
      "weekId": 205,
      "startsAt": "2026-12-04T07:00:00Z",
      "endsAt": "2026-12-07T07:00:00Z",
      "startTs": 1796367600,
      "endTs": 1796626800,
      "timeZone": "America/Denver",
      "timerText": "25X Through Sunday",
      "desktopImage": null,
      "mobileImage": null
    }
  ]
}

```

*Liquid · the running week*

```
{%- assign weeks = shop.metafields['app--330349150209'].giveaway_weeks.value.weeks -%}
{%- assign now_ts = 'now' | date: '%s' | plus: 0 -%}
{%- for week in weeks -%}
  {%- if week.startTs <= now_ts and week.endTs > now_ts -%}
    {{ week.timerText }}: through {{ week.endTs | minus: 1 | date: '%A, %b %-d' }}
  {%- endif -%}
{%- endfor -%}
```

Pages can be cached, so a running week picked in Liquid can be out of date. Pick it again in JavaScript on load.

#### giveaway_entries

One object per running giveaway, for the week running now. Between weeks there is no rate, and Kwik awards no entries. Hide entry displays then.

*JSON · example*

```
[
  {
    "geId": 11,
    "geName": "Truck Giveaway",
    "forEachAmt": null,
    "forEachPct": 100,
    "pointValue": 1,
    "multipliers": [
      { "multiplierType": "purchase_multiplier", "forEachAmt": 5, "shopifyProductIds": [8100000000001],
        "stkAny": false, "stkRefMulti": false, "stkMulRef": false },
      { "multiplierType": "site_wide_multiplier", "forEachAmt": 2 },
      { "multiplierType": "order_multiplier", "forEachAmt": 2, "shopifyProductIds": [8100000000001, 8100000000002],
        "stkAny": false, "stkRefMulti": false, "stkMulRef": false },
      { "multiplierType": "referral_multiplier", "forEachAmt": 3 }
    ]
  }
]

```

Per product, Kwik counts: `entries = round(base × referral × (product or sitewide) × order)`. Base is the flat `forEachAmt`, or price × `forEachPct` / 100 × `pointValue`. Different types multiply. The same type: the highest wins. Sitewide only counts when no product multiplier matches. See [the entries guide](/docs/storefront/entries/) for the full walk-through.

| Multiplier flags | Who gets it |
| --- | --- |
| none set | The buyer |
| `stkRefMulti` | The buyer, on a referred order only |
| `stkMulRef` | The referrer only. Never show it to the buyer. |
| `stkAny` | Both |

Sitewide and referral multipliers ignore the flags. A referral multiplier needs a share link. Promo-code multipliers (`multiOn` 5) can't be shown on the storefront.

#### cashback_config and loyalty_points

*JSON · cashback_config*

```
{ "amount": 5, "calculationMethod": "variable", "firstOrderOnly": false, "referralMultiplier": 1, "referralFirstOrderOnly": false }
```

- `amount` is a percentage when `calculationMethod` is `variable` ("5% back"), and a fixed amount when it is `fixed`. Check before you print a % sign.
- `loyalty_points` rows use `lpName`, `forEachAmt`, `forEachPct`, `pointValue`, `multp` and `currencyCode`. Print the raw JSON on a test page to see a store's real rules before building on them.

#### wavelink_required

When `true`, show rewards only to shoppers who came in on a share link. Check the URL first (`waveLink`, `wavelink` or `kwiklink`), then the `_kwik_waveLink` cookie. Only codes of 1 to 64 letters and digits count. Liquid can't see the cookie on first paint, so render reward displays hidden and let JavaScript decide.

#### Native app blocks

For Liquid themes, check these before building anything. Add them from the **App blocks** page in the Kwik 2.0 app. They don't run on Hydrogen.

| Need | Block | Key setting |
| --- | --- | --- |
| Weekly hero banner | Giveaway Banner | Optional link, alt text, fallback image for days between weeks |
| Countdown and timer text | Giveaway Countdown | Days, hours, minutes, seconds, optional progress bar |
| Entries on the product page and thank-you page | Giveaway entries block | Uses the running week's rate. Shows nothing between weeks. |
| A customer's own entries and history | Point Tracker, Points Overview, Loyalty popup | **Show**: loyalty points, giveaway entries, or both |
| Referral link and code | ShareLink | "Require promo code" is optional. Untick it on older installs. |
| Share-link tracking | Referral Attribution (app embed) | Turn it on under App embeds |

> **Note:** A shared entries calculation that themes can call anywhere (product cards, featured products, mini cart and product pages) is in development. When it ships, prefer it to custom entry math.

#### Banner images

- Desktop about 2400px wide, mobile about 1080px wide, JPG or WebP at full quality.
- Public HTTPS links with no login or expiry. Upload a new file each time an image changes. Replacing a file at the same address can keep showing the old one.
- The images are outside links, not Shopify files, so use `<picture>` with the `width` and `height` from the metafield, with the mobile source at `max-width: 749px`.
- Keep `timerText` short. It shows in large letters.

#### When the data is empty

1. Check that today is inside a week. Between weeks, no rate is correct.
2. Print the raw metafields on a test page to rule out a bug in your code.
3. In the Kwik 2.0 app, open the **Sync** page and click **Resync now**, then check again.
4. Still empty while the giveaway is clearly live? Contact Kwik with the giveaway name and dates.
5. Meanwhile, show your manual fallback (a fixed title, end date and image) so the page is never blank.

Every custom display should have a manual fallback and a debug switch that prints the raw data. Turn the debug switch off before publishing.
