Server-side tracking overview

Refersion's server-side tracking works by matching affiliate referral activity on the front end of your website to the transactional data you'll send later to Refersion's system from your backend web server. Below is an image that explains how Refersion's tracking works for link-based affiliate referrals.

Server Side Tracking Flow Chart


Step 1 (Client-side): Tracking Visits

The code below will be responsible for capturing clicks when an affiliate refers a customer to your website using their referral link. Please copy/paste the following code into the <head> section of every page on your website where you expect your affiliates to drive traffic.

Make sure to replace YOUR-PUBLIC-KEY below with the Public API key from your Refersion account.

<!-- REFERSION TRACKING: BEGIN -->
<script>
! function(e, n, t, i, o, c, s, a) {
    e.TrackingSystemObject = "r", (s = n.createElement(t)).async = 1, s.src = "https://cdn.refersion.com/refersion.js", s.onload = function() {

        // Replace with your Refersion Public API Key
        r.pubKey = "YOUR-PUBLIC-KEY";

        // Uncomment next line if you need to debug during testing
        // r.settings.dbg_mode = true;

        r.settings.fp_off = true;

        r.initializeXDLS().then(() => {
            r.launchDefault().then(() => {

                // Send a custom  event that can be listened to later
                const rfsnTrackingEvent = new Event("refersion-loaded");
                document.dispatchEvent(rfsnTrackingEvent);

            })
        })
    }, (a = n.getElementsByTagName(t)[0]).parentNode.insertBefore(s, a)
}(window, document, "script");
</script>
<!-- REFERSION TRACKING: END -->

Step 2 (Client-side): Identifying Visits

Once affiliate clicks are tracked on your website, we'll need a way to associate the click that happened on your website to the order data you plan to send to Refersion's system later via webhooks.

Since Webhooks are reported from the server side and not the client side, we can not access the relevant customer's browser session information. For this reason, we ask that you send us a cart_id as a way to connect the clicks that happen on your website to the order data you plan to send later via a JSON webhook.

The cart_id may be any string value up to 255 characters.

For security, make sure that cart_id is not sequential or may be easily guessed such as a session ID or an encrypted version of several strings.

Some platforms already provide their own identifiers you may be able to leverage in your code. We've included some examples you can use below. If you're using something else, you may need to research the proper identifier or create your own.

PlatformSample IdentifierAvailabilityReference
ShopifyCart TokenAll storefront pagesGet Cart (Ajax API)
ShopifyCheckout TokenAfter creating a checkoutCheckout Storefront API
BigCommerceCart ID / Checkout IDAll pages (after a cart is created)Get cart
WooCommerceOrder KeyOrder Confirmation PageOrder Information breakdown
StripeCustomer IDAfter creating a customerCreate a customer (REST API)
StripeSubscription IDAfter creating a subscriptionCreate a subscription (REST API)
ChargebeeSubscription IDAfter creating a subscriptionSubscription attributes (REST API)

Code snippet for identifying visits

You can use the code snippet below to report your cart_id to Refersion's system during your customer's browsing session. It's best to add this code snippet towards the very bottom of your website's "Thank you" or "Order confirmation page"; usually before the closing </body> tags.

If your site doesn't use a thank you/confirmation page, you can call the sendRefersionCheckoutEvent() function directly within your code after a customer's order is completed.

Please note: You must replace YOUR-CART-ID with the actual cart_id value from your site.

<!-- REFERSION TRACKING: BEGIN -->
<script>
function sendRefersionCheckoutEvent(cartID) {
    const rfsn = {
        cart: cartID,
        id: localStorage.getItem("rfsn_v4_id"),
        url: window.location.href,
        aid: localStorage.getItem("rfsn_v4_aid"),
        cs: localStorage.getItem("rfsn_v4_cs")
    };
    r.sendCheckoutEvent(rfsn.cart, rfsn.id, rfsn.url, rfsn.aid, rfsn.cs);
}

// Listen for the custom event added previously
document.addEventListener("refersion-loaded", function() {

    // Obtain your card ID from your commerce platform or create one and replace YOUR-CART-ID
    let uniqueCartID = "YOUR-CART-ID";

    // Send your cart ID value to the checkout function
    sendRefersionCheckoutEvent(uniqueCartID)
})
</script>
<!-- REFERSION TRACKING: END -->

❗️

Important note

The code snippet above MUST be run on the same domain and security level (http or https) where the customer started their shopping session.

  • If the customer starts their journey on https://example.com, the code snippet MUST also be run on a page from the https://example.com domain such as https://example.com/orders/thank-you.
  • If customers finish their checkout somewhere else such as https://shop.example.com or https://checkout.example.com you'll need to implement cross-domain tracking.
  • As an alternative, you may also choose to run the function above BEFORE the customer switches domains.

Step 3 (Sever-side): Posting the Webhook

Data must be reported as JSON string which contains the order data as well as the cart_id you reported earlier. Your Refersion API keys (public and secret) should be sent in the header of the request. Below is an example of the JSON that we are expecting.

{
	"cart_id": "DDXqfBngTWuX8N8Asqr2mY3RkmHCXdM7Vz6mdHkjwrEnN5zyRY",
	"order_id": "20150401102883",
	"shipping": 9.99,
	"tax": 0.57,
	"discount": 2.25,
	"discount_code": "HOLIDAY1",
	"currency_code": "USD",
	"customer":{
		"first_name": "John",
		"last_name": "Doe",
		"email": "[email protected]",
		"ip_address": "234.192.4.75"
	},
	"items": [
		{
			"price": 5.50,
			"quantity": 2,
			"sku": "PROD_A",
			"name": "Product A"
		},
		{
			"price": 10.00,
			"quantity": 1,
			"sku": "PROD_B",
			"name": "Product B"
		},
		{
			"price": 15.00,
			"quantity": 3,
			"sku": "PROD_C",
			"name": "Product C"
		}
	]
}

To deliver this data to us you must send it via an HTTP POST. Below is an example PHP code snippet using cURL.

<?php

// The complete data that you are sending
$order_data = array(...); // Omitting data for demonstration

// Convert array into JSON
$json_data = json_encode($order_data);

// The URL that you are posting to
$url = 'https://inbound-webhooks.refersion.com/tracker/orders/paid';

// Start cURL
$curl = curl_init($url);

// Verify that our SSL is active (for added security)
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE);

// Send as a POST
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');

// The JSON data that you have already compiled
curl_setopt($curl, CURLOPT_POSTFIELDS, $json_data);

// Return the response
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);

// Set headers to be JSON-friendly
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($json_data),
    'Refersion-Public-Key: YOUR-PUBLIC-KEY',
    'Refersion-Secret-Key: YOUR-SECRET-KEY')
);

// Seconds (30) before giving up
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);

// Execute post, capture response (if any) and status code
$result = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// Close connection
curl_close($curl);

Variable Descriptions

Transaction Data

A transaction represents the entire order that occurred, and contains the following values:

ValueTypeRequiredDescription
cart_idStringYes - Webhook onlyCart ID that matches what you're reported as rfsn.cart in the r.sendCheckoutEvent() function, as per above.
order_idStringYesUnique shopping cart order ID or transaction number used to reference the purchase that you're reporting.
subscription_idStringYes - Subscriptions onlyFor subscription purchases only: A unique identifier that represents the whole subscription, which can be a reference to all of the individual order_ids within this subscription.

Only available in webhook reporting.
is_subscriptionBooleanYes - Subscriptions onlyIf you are reporting an event which belongs to a subscription, set this to TRUE, otherwise leave blank.

Only available in webhook reporting.
auto_credit_affiliate_idNumberNo(optional) The ID of the affiliate you'd like to credit the order to.
shippingNumberNoTotal shipping and handling the customer was charged for the order.
taxNumberNoTotal tax the customer was charged for the order.
discountNumberNoTotal in discounts that were applied to the order.
discount_codeStringNoThe discount or coupon code that was used on the order.
currency_codeStringYesThe three letter currency code of the order totals that you are reporting. Example: USD, CAD, GBP.

Customer Data

A customer represents the individual customer who purchased, and contains the following values:

ValueTypeRequiredDescription
first_nameStringNoCustomer’s first name.
last_nameStringNoCustomer’s last name.
emailStringNoCustomer’s email address.
ip_addressStringNoThe IP address of the customer.

Item Data

An item represents an individual product that the customer had ordered, and contains the following values:

ValueTypeRequiredDescription
skuStringYesA unique Product SKU or identifier ID. Can be blank, but we highly recommend that you populate the field.
nameStringNoThe name of the item.
quantityNumberYesTotal quantity ordered of the product.
priceNumberYesPrice of each item. For example, if the customer ordered 10 items at $5 each, you should report $5, not $50. Do not include currency symbols.