lmsqueezy/lemonsqueezy.js

Updated way to add Affiliate Tracking Links to Checkout URL

Closed this issue · 5 comments

Hi -

Is there an updated doc on how to add the affiliate tracking link to a checkout URL? I'm creating the checkout url in the backend (next.js serverless function) so assume I have to add this myself.

Since the SDK has changed now I could not find an updated method like GetId, Build or Affiliate that I could use to retrieve this. I suppose I can parse it out in the url using searchParams but I just want to know the best practice for doing this.

I'm using this doc as reference: https://docs.lemonsqueezy.com/help/affiliates-for-merchants/getting-referrals

Thanks,

Hey @btahir,

The SDK is designed for backend use and does not offer methods for frontend interaction. For working with the frontend, consider using Lemon.js: https://docs.lemonsqueezy.com/guides/developer-guide/lemonjs.

If you have access to the affiliate ID on the backend, you can create a checkout using the SDK and then append the affiliate ID in the following format: ?aff=affiliateId.

Here's an example:

import { createCheckout, lemonSqueezySetup } from "../src/index.js";

const apiKey = import.meta.env.LEMON_SQUEEZY_API_KEY;

// Setup
lemonSqueezySetup({ apiKey });

// dummy data, replace with your own
const storeId = 123;
const variantId = 123;
const affiliateId = "123";

// Get the checkout URL
const checkoutResponse = await createCheckout(storeId, variantId);
const checkoutUrl = checkoutResponse?.data?.data.attributes.url;

if (checkoutUrl) {
  // Create a URL object from the checkout URL
  const url = new URL(checkoutUrl);

  // Append the affiliate parameter
  url.searchParams.append("aff", affiliateId);

  const affiliateUrl = url.toString();

  console.log(affiliateUrl);
} else {
  console.error("Checkout URL not found in the response.");
}

@brankoconjic Thanks for the reply.

This makes sense but I'm still trying to think of the best way to be able to do this without adding unnecessary code.

Just to clarify - say I use my backend to generate this url e.g. https://my-store.lemonsqueezy.com/checkout/buy/0a841cf5-4cc2-4bbb-ae5d-9529d97deec6 and return it to the client.

If I have the affiliate lemonjs script in my html

<script>
  window.lemonSqueezyAffiliateConfig = { store: '[store slug]' }
</script>
<script src="https://lmsqueezy.com/affiliate.js" defer></script>

And I then navigate on the client to this url e.g. router.push(checkout_url)

Would the script automatically add the affiliate tracking cookie to the checkout session?

Yes, the script will automatically create a cookie and include it with the request.

Great!

Yes, the script will automatically create a cookie and include it with the request.

so this code will automatically capture the ?aff=xxx suffix and create a cookie based on it?