Getting Started

Guides

REST API: Campaigns

Affiliates

Conversions

Affiliate Teams

SCALE

Coupons

Payouts

Other

Webhooks

MCP Server (AI)

← All guides

Track Shopify app billing conversions

Credit affiliates for installs of your Shopify app and for every charge after, renewals included. LinkJolt checks the install token for you.

Intermediate

30 min read

Ultimate plan

Who this guide is for

Developers shipping apps on the Shopify App Store that bill through Shopify: plans on Shopify App Pricing, or subscriptions created with the Billing API. If you sell physical products on a Shopify store, you want the Shopify store affiliate tracking guide instead.

What you'll get

  • One LinkJolt account covering every Shopify app you ship, one campaign each
  • Hosted affiliate links at linkjolt.io/s/<handle>/<code>
  • A referral that survives Shopify's install, checked by LinkJolt with one API call
  • Every charge reported, renewals chained to the first sale at your recurring rate
  • Test keys for wiring it up before going live

How it works

  1. An affiliate shares linkjolt.io/s/your-app-handle/AFF_CODE. LinkJolt records the click, signs a state token carrying the affiliate and the campaign, and redirects to your install endpoint with ?state=<token> appended. That is the only parameter it adds.
  2. Your install endpoint keeps the token in a first-party cookie and starts your usual Shopify install. Your OAuth state stays your own random nonce, as Shopify requires.
  3. Your OAuth callback sends the token to LinkJolt, POST /api/v1/shopify/install-state/verify, and saves the affiliate and campaign against the shop. The token is signed with a key only LinkJolt holds, so there is no secret to copy and nothing to check on your side.
  4. A scheduled job reads each charge from Shopify's Partner API and posts it to POST /api/v1/conversions: the shop's first charge as the original sale, every later charge as a renewal of it.

Why a scheduled job and not a webhook. Shopify sends no webhook when an app subscription renews, and since April 28, 2026 apps on Shopify App Pricing get no subscription webhooks at all. The Partner API lists every charge as an APP_SUBSCRIPTION_SALE transaction, renewals included, with its amount, currency, shop and an id that makes a safe orderId. Your app reads it with your own Partner API token; LinkJolt never needs access to your Partner account.

Language support. The code below is Node and Express. Any language works the same way: two HTTP calls to LinkJolt and one GraphQL query to Shopify.

Step 1 - Create a campaign per app

In LinkJolt, create one campaign per Shopify app you sell. For each, fill in:

  • Shopify app handle: the slug from your App Store listing URL. For apps.shopify.com/seo-toolkit, the handle is seo-toolkit. It names the hosted link.
  • Your install endpoint URL: the /install route from step 5, e.g. https://your-app.com/install. NOT the apps.shopify.com/your-app listing URL.
  • Recurring commissions on, if affiliates should earn on renewals. With them off, LinkJolt refuses each renewal with recurring_disabled, and the code records that and moves on.

Why not the App Store listing URL? Shopify strips all query parameters from apps.shopify.com/<handle> URLs before the install starts, so the ?state=<token> would silently die. This is a long-standing Shopify limitation with no workaround on the App Store side, confirmed in the Shopify Partner community. LinkJolt refuses those URLs when you save the campaign.

Step 2 - Get your two keys

  • LinkJolt: go to Settings → API keys and generate a test key (lj_pk_test_...) for development and a live key (lj_pk_live_...) for production. Recording conversions needs an Ultimate or Scale plan. Save it as LINKJOLT_KEY.
  • Shopify Partner API: in the Partner Dashboard, Settings → Partner API clients, create a client with the View financials permission (only an organization owner can). Save its token as SHOPIFY_PARTNER_TOKEN, your organization id (in the Partner Dashboard URL) as SHOPIFY_PARTNER_ORG_ID, and your app's Partner id (gid://partners/App/<number>) as SHOPIFY_PARTNER_APP_ID.

Step 3 - The shared setup

One helper for calls to LinkJolt, and the four database calls the rest of the code uses. Map them onto your own tables: an installs table keyed by shop, and a table of charges already reported.

// LinkJolt + Shopify App Billing. Node 18+ (global fetch), Express with cookie-parser.
// LINKJOLT_KEY            an Ultimate API key from https://www.linkjolt.io/merchant/api-keys
// SHOPIFY_PARTNER_ORG_ID  your Partner organization id (it is in the Partner Dashboard URL)
// SHOPIFY_PARTNER_TOKEN   a Partner API client with the "View financials" permission
// SHOPIFY_PARTNER_APP_ID  your app's Partner id, e.g. gid://partners/App/1234
// db is your own database:
//   db.installs.get(shop), db.installs.save(shop, fields) (merges, returns the row)
//   db.reportedCharges.has(id), .add(id, fields), .newestCreatedAt()
// Built with a test key (lj_pk_test_)? Clear firstConversionId and reportedCharges when
// you switch to the live key: a live key cannot chain onto a test conversion.
const LINKJOLT_API = 'https://www.linkjolt.io/api/v1';
const DAY_MS = 24 * 60 * 60 * 1000;

function linkjolt(path, init = {}) {
  return fetch(`${LINKJOLT_API}${path}`, {
    ...init,
    headers: { Authorization: `Bearer ${process.env.LINKJOLT_KEY}`, 'Content-Type': 'application/json' },
  });
}

Step 4 - Ask LinkJolt who referred an install

Send the state token back to LinkJolt with your API key. You get the affiliate and the campaign for a token LinkJolt signed, for a campaign of your brand, from a click in the last 30 days. Anything else is an install with no referral. Any key works for this call, live or test.

// 1. Ask LinkJolt who referred an install. LinkJolt signs the state token with a
// key only it holds, so your app sends the token back instead of checking it.
// Returns { affiliateId, campaignId, clickId, issuedAt }, or null for no referral
// (no token, a changed one, one older than 30 days, or another brand's campaign).
// Throws when LinkJolt did not answer, so you can keep the token and ask again.
async function readLinkjoltReferral(state) {
  if (!state) return null;
  const res = await linkjolt('/shopify/install-state/verify', {
    method: 'POST',
    body: JSON.stringify({ state }),
  });
  if (res.ok) return (await res.json()).data;
  if (res.status === 400 || res.status === 404) return null;
  throw new Error(`LinkJolt answered ${res.status}`);
}

The answers: 200 with { affiliateId, campaignId, clickId, issuedAt } (clickId can be null); 400 validation_error, invalid_state or state_expired, and 404 not_found for a campaign outside your key's brand, all meaning no referral. On 401, 429 or a 5xx the function throws, so you can keep the token and ask again. The full reference is on the API reference.

Step 5 - Your install endpoint and OAuth callback

LinkJolt sends a referred visitor to your install endpoint with the token. Keep it in its own cookie, start your usual install, and read it back in your OAuth callback, which Shopify opens in the merchant's browser after the install is approved.

// 2. Your install endpoint: the URL saved on the campaign in LinkJolt. A referred
// visitor arrives as /install?state=<token>. Keep the token in its own cookie and
// start your usual install. Your OAuth state stays your own random nonce.
app.get('/install', (req, res) => {
  const state = typeof req.query.state === 'string' ? req.query.state : '';
  if (state) {
    res.cookie('linkjolt_state', state, { maxAge: 30 * DAY_MS, httpOnly: true, secure: true, sameSite: 'lax' });
  }
  return startShopifyInstall(req, res); // yours: ask for the store, redirect to https://{shop}/admin/oauth/authorize
});
// 3. Your OAuth callback, after your own nonce and HMAC checks and the token exchange.
app.get('/shopify/auth/callback', async (req, res) => {
  const shop = await completeShopifyOAuth(req); // yours: returns the verified *.myshopify.com domain
  const state = req.cookies.linkjolt_state;
  res.clearCookie('linkjolt_state');
  const install = await db.installs.get(shop);
  if (state && !install?.affiliateId) { // the first affiliate to bring a shop keeps it
    try {
      const referral = await readLinkjoltReferral(state);
      if (referral) await db.installs.save(shop, { affiliateId: referral.affiliateId, campaignId: referral.campaignId });
    } catch {
      await db.installs.save(shop, { pendingState: state }); // LinkJolt did not answer: step 4 asks again
    }
  }
  res.redirect(`https://${shop}/admin/apps/${process.env.SHOPIFY_APP_HANDLE}`);
});

The first affiliate to bring a shop keeps it: a later click on another affiliate's link does not move an install that already has one. If LinkJolt cannot be reached during the callback, the token is kept on the shop and step 6 asks again before it reports that shop's first charge.

Embedded apps on Shopify managed installation. An app that installs only through Shopify managed installation never opens an OAuth callback on your server, and the Shopify admin frame cannot read your install cookie in every browser. For those installs, have /install ask for the store's .myshopify.com address, call readLinkjoltReferral(state) there, and keep the referral against that shop for a day; attach it when that shop's first session reaches your app. The address is typed by the visitor rather than proven by Shopify, so keep that window short.

Step 6 - Report every charge

Run this every hour from your scheduler. It reads the Partner API from a week before the newest charge it has already seen, skips what it reported before, and posts each new charge of a referred shop:

  • orderId is the Partner API transaction id, so a charge sent twice answers 409 instead of paying twice.
  • The shop's first charge goes without a parent: it is the original sale. Every later charge carries parentConversionId set to it, and LinkJolt pays it at the campaign's recurring rate, within its recurring limit.
  • A refusal such as recurring_disabled or recurring_cap_reached is final and recorded. A bad key, the rate limit or an outage stops the run, and the next run tries the same charge again.
// 4. Report every charge. Shopify sends no webhook when a subscription renews (and
// none at all for apps on Shopify App Pricing since April 2026), but its Partner
// API lists each charge as an APP_SUBSCRIPTION_SALE transaction. Run this every
// hour from your scheduler; each charge is reported once.
const SALES_QUERY = `query Sales($appId: ID!, $since: DateTime!, $after: String) {
  transactions(appId: $appId, types: [APP_SUBSCRIPTION_SALE], createdAtMin: $since, first: 100, after: $after) {
    edges { cursor node { id createdAt ... on AppSubscriptionSale { grossAmount { amount currencyCode } shop { myshopifyDomain } } } }
    pageInfo { hasNextPage }
  }
}`;

async function fetchShopifySales(since) {
  const sales = [];
  let after = null;
  do {
    const res = await fetch(`https://partners.shopify.com/${process.env.SHOPIFY_PARTNER_ORG_ID}/api/2026-10/graphql.json`, {
      method: 'POST',
      headers: { 'X-Shopify-Access-Token': process.env.SHOPIFY_PARTNER_TOKEN, 'Content-Type': 'application/json' },
      body: JSON.stringify({ query: SALES_QUERY, variables: { appId: process.env.SHOPIFY_PARTNER_APP_ID, since, after } }),
    });
    const json = res.ok ? await res.json() : null;
    if (!json?.data || json.errors?.length) throw new Error(`Partner API answered ${res.status}: ${JSON.stringify(json?.errors ?? [])}`);
    const { edges, pageInfo } = json.data.transactions;
    sales.push(...edges.map((edge) => edge.node));
    after = pageInfo.hasNextPage ? edges[edges.length - 1].cursor : null;
  } while (after);
  // Oldest first: a shop's first charge is its original sale.
  return sales.sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
}

async function findConversionByOrderId(install, orderId) {
  const query = new URLSearchParams({ campaignId: install.campaignId, affiliateId: install.affiliateId, sort: 'createdAt:asc', limit: '100' });
  const res = await linkjolt(`/conversions?${query}`);
  if (!res.ok) throw new Error(`LinkJolt answered ${res.status}`);
  return (await res.json()).data.find((conversion) => conversion.orderId === orderId)?.id ?? null;
}

async function syncShopifyChargesToLinkjolt() {
  // A week before the newest charge already seen: late transactions and a stopped scheduler are both caught.
  const newest = await db.reportedCharges.newestCreatedAt();
  const since = new Date((newest ? Date.parse(newest) : Date.now()) - 7 * DAY_MS).toISOString();
  for (const sale of await fetchShopifySales(since)) {
    if (await db.reportedCharges.has(sale.id)) continue;
    const shop = sale.shop?.myshopifyDomain;
    let install = shop ? await db.installs.get(shop) : null;
    if (install?.pendingState) { // step 3 could not reach LinkJolt; a throw here stops the run until it can
      const referral = await readLinkjoltReferral(install.pendingState);
      install = await db.installs.save(shop, { pendingState: null, affiliateId: referral?.affiliateId ?? null, campaignId: referral?.campaignId ?? null });
    }
    const amount = Number(sale.grossAmount?.amount);
    if (!install?.affiliateId || !(amount > 0)) { // an install no affiliate referred, or nothing charged
      await db.reportedCharges.add(sale.id, { createdAt: sale.createdAt, outcome: 'no_referral' });
      continue;
    }
    const res = await linkjolt('/conversions', {
      method: 'POST',
      body: JSON.stringify({
        campaignId: install.campaignId,
        affiliateId: install.affiliateId,
        amount,
        currency: sale.grossAmount.currencyCode,
        orderId: sale.id, // one conversion per Shopify charge: sending it again answers 409
        conversionType: 'recurring', // a subscription payment
        // The shop's first charge is the original sale and every later one renews it,
        // paid at the campaign's recurring rate and within its recurring limit.
        ...(install.firstConversionId ? { parentConversionId: install.firstConversionId } : {}),
      }),
    });
    const body = await res.json().catch(() => ({}));
    let conversionId = null;
    if (res.status === 201) conversionId = body.data.id;
    else if (res.status === 409) conversionId = await findConversionByOrderId(install, sale.id); // sent by a run that stopped before saving
    else if (res.status !== 400 && res.status !== 404 && body.error?.code !== 'earnings_limit_reached') {
      throw new Error(`LinkJolt answered ${res.status}`); // a bad key, the rate limit, an outage: the next run retries this charge
    }
    if (conversionId && !install.firstConversionId) await db.installs.save(shop, { firstConversionId: conversionId });
    // A refusal (recurring commissions off, the limit reached, a rejected first sale) is final, so it is recorded too.
    await db.reportedCharges.add(sale.id, { createdAt: sale.createdAt, outcome: conversionId ? 'recorded' : body.error?.code, conversionId });
  }
}

Step 7 - Refunds and cancellations

  • A refund appears in the Partner API as an APP_SALE_ADJUSTMENT transaction. To take the commission back, reject the matching conversion in Commissions, or send PATCH /api/v1/conversions/:id with { "status": "rejected" } while it is unpaid.
  • A cancelled or frozen subscription simply stops producing charges, so nothing more is reported. If a frozen one recovers, its next charge is reported as usual.

Step 8 - Test end-to-end

  1. Visit https://www.linkjolt.io/s/<your-app-handle>/<test-affiliate-code> in incognito. Confirm it redirects to your install endpoint with ?state=... appended.
  2. Install the app on a development store. Confirm your OAuth callback saved the affiliate and campaign against the shop.
  3. With a test key, run the charge sync. Each charge of that shop the Partner API lists becomes a test conversion (isTest: true) on the campaign, the first without a parent and the rest chained to it. Shopify does not document whether a development store's test charge is listed as a transaction; if none appears, send one conversion yourself with the body step 6 builds.
  4. Before switching LINKJOLT_KEY to the live key, clear the firstConversionId and reported charges written in testing: a live key cannot chain a renewal onto a test conversion.

Attribution boundaries

Attribution is deterministic when the affiliate link is used. An install where the visitor never touched your linkjolt.io/s/... link arrives with no token, is saved with no affiliate, and earns no commission. A token is accepted for 30 days from the click, the same window as every other LinkJolt link.