# WooCommerce Integration

Tracknow integrates with WooCommerce stores to automatically transmit data for completed purchases into your Tracknow dashboard. This enables accurate tracking and attribution of purchases made by customers referred by your affiliates.

***

### Methods of Integration

There are two supported methods for integrating Tracknow with a WooCommerce store:

{% columns %}
{% column %}
**Tracknow Plugin**

Tracknow provides a plugin that can be installed on a WooCommerce store to enable purchase tracking
{% endcolumn %}

{% column %}
**Postback**

Implement the required scripts and configure postbacks to enable purchase tracking
{% endcolumn %}
{% endcolumns %}

<table><thead><tr><th width="369">Plugin</th><th>Postback</th></tr></thead><tbody><tr><td>Simple installation process</td><td>More manual and technical implementation</td></tr><tr><td>A pre-configured set of purchase details are sent</td><td>Full control over which details are sent</td></tr></tbody></table>

***

### Prerequisites

Both integration methods require you to enable passing our unique affiliate identifier `click_id` to your landing page.\
\
For instructions, click [here](https://docs.tracknow.io/integrations/passing-click_id-to-a-landing-page).

***

### Plugin Integration

Login to the WordPress admin dashboard → **Plugins** → **Add Plugin** →  Search for the [Tracknow for WooCommerce](http://kb.local/wp-admin/plugin-install.php?tab=plugin-information\&plugin=tracknow-for-woocommerce\&TB_iframe=true\&width=600\&height=550) plugin → Install the plugin and activate it

<figure><img src="https://1097958070-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHX682uo79XLNkfkN58br%2Fuploads%2FUbieIajvEKdl9dCFbOR7%2Fimage.png?alt=media&#x26;token=7c07c7cd-dfe4-43e1-af5a-82f4143f24e4" alt=""><figcaption></figcaption></figure>

Navigate to **WooCommerce** → **Settings** → **Tracknow** tab → Fill out the plugin configuration → **Save Changes**

<figure><img src="https://1097958070-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHX682uo79XLNkfkN58br%2Fuploads%2Fxc76EkGrF6TTXoyfDiqV%2Fchrome_6bCOmkp4ZC.gif?alt=media&#x26;token=a699cdf2-8dc6-4363-a952-bbdf4ce47629" alt=""><figcaption></figcaption></figure>

<table><thead><tr><th width="216">Field</th><th>Description</th></tr></thead><tbody><tr><td><strong>Namespace</strong> (Mandatory)</td><td>Enter the Tracknow namespace to which data should be sent. This value is available in the Tracknow dashboard main menu</td></tr><tr><td><strong>Default Campaign</strong> (Mandatory)</td><td>Enter the Tracknow Camapign ID to which data should be sent</td></tr><tr><td><strong>Enable Tracking</strong> (Mandatory)</td><td>Check this checkbox to enable sending data (activates plugin data transfer)</td></tr><tr><td><strong>Include Client Personal Info</strong> (Optional)</td><td>Check this checkbox in order to see client details for each conversion on Tracknow (First name, Last name, Email, Address)</td></tr><tr><td><strong>Enable Lifetime Tracking</strong> (Mandatory if using lifetime)</td><td>Check this checkbox if your affiliate program associates a client with his referring affiliate for lifetime</td></tr><tr><td><strong>Custom Coupon Meta Key</strong> (Mandatory if custom coupon field is used)</td><td>Specify the custom meta key you use to store coupon codes if it differs from the default WooCommerce order coupon field</td></tr><tr><td><strong>Coupon Contains Filter</strong> (Optional)</td><td>Provide a string value to restrict data transmission to purchases that either include our unique affiliate identifier or use a coupon code containing that specified string</td></tr><tr><td><strong>Thank You Page Pixel</strong> (Optional)</td><td>A fallback option that fires postbacks when client reaches the thank you page. Leave off by default</td></tr><tr><td><strong>API Key</strong> (Optional)</td><td>Enter the Tracknow API key you generated to enable automatic syncing of conversion statuses from WooCommerce to Tracknow</td></tr><tr><td><strong>Auto Approve on Completed</strong> (Optional)</td><td>Enable this checkbox to automatically approve conversions in Tracknow when the corresponding WooCommerce order reaches the “Completed” status</td></tr><tr><td><strong>Auto Decline on Cancelled</strong> (Optional)</td><td>Enable this checkbox to automatically reject conversions in Tracknow when the corresponding WooCommerce order reaches the “Cancelled” status</td></tr><tr><td><strong>Enable Debug Logs</strong> (Optional)</td><td>For Tracknow team troubleshooting only. Leave this option disabled unless instructed by our support team</td></tr></tbody></table>

***

### Postback Integration

Login to the WordPress admin dashboard → **Appearance** → **Theme File Editor** → Locate your current theme's **functions.php** file

<figure><img src="https://1097958070-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHX682uo79XLNkfkN58br%2Fuploads%2FtMegXQAnOjRoqu6IbFnQ%2Fchrome_iosZcPLD0K.gif?alt=media&#x26;token=2dfc6150-3b8c-451a-b27e-dd9c15b5cd85" alt=""><figcaption></figcaption></figure>

Add the following code inside the functions.php file:

```php
function add_custom_script_to_head() {
    ?>
    <script>
        // Get a query parameter by name from the URL
        function getQueryParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }

        // Set a cookie for the root domain, available across subdomains
        function setCookie(name, value, days) {
            const maxAge = days * 24 * 60 * 60; // Convert days to seconds
            const domain = "." + window.location.hostname
                .split('.')
                .slice(-2)
                .join('.'); // example.com

            document.cookie = `${name}=${encodeURIComponent(value)}; path=/; domain=${domain}; max-age=${maxAge}; secure;`;
        }

        // Main: look for click_id and store it
        (function () {
            const clickId = getQueryParam("click_id");

            if (clickId) {
                setCookie("click_id", clickId, 365); // Store for 1 year
            }
        })();
    </script>
    <?php
}

add_action('wp_head', 'add_custom_script_to_head');
```

This script captures our unique identifier (`click_id`) from the URL query parameters and stores it in a browser cookie for later use.

It is added to your website’s header to ensure it loads and runs across all pages.

{% hint style="info" %}
If your website includes pages that are not powered by WordPress, you will need to manually add this script to those pages as well to ensure consistent tracking.
{% endhint %}

Next, add the following code to your theme’s **functions.php** file:

```php
function tracknow_tracking( $order_id ) {
    // Ensure the order exists
    $order = wc_get_order( $order_id );
    if ( ! $order ) {
        return;
    }

    // Retrieve the `click_id` from cookies if it exists
    $click_id = isset($_COOKIE['click_id']) ? $_COOKIE['click_id'] : null;

    // Get order details
    $order_total    = $order->get_total();
    $order_shipping = $order->get_shipping_total();
    $coupons        = $order->get_used_coupons();
    $coupon_code    = ! empty( $coupons ) ? $coupons[0] : '';

    // Common query parameters
    $query_args = [
        'order_id' => $order_id,
        'amount'   => $order_total - $order_shipping,
        'coupon'   => $coupon_code,
    ];

    // Add tracking ID
    if ( $click_id ) {
        $query_args['click_id'] = $click_id;
    } else {
        $query_args['campaign_id'] = {CAMPAIGN ID}; // Replace with actual campaign ID if needed
    }

    // Determine if we're on the thank you page
    if ( is_wc_endpoint_url( 'order-received' ) ) {
        // Use success.jpg (pixel tracking)
        $tracking_url = add_query_arg( $query_args, 'https://{NAMESPACE}-tracking.tracknow.info/success.jpg' );
        echo '<img src="' . esc_url( $tracking_url ) . '" width="1" height="1" style="display:none;" alt="" />';
    } else {
        // Use postback endpoint (server-side GET)
        $postback_url = add_query_arg( $query_args, 'https://{NAMESPACE}-tracking.tracknow.info/postback' );
        wp_remote_get( $postback_url );
    }
}

// Hook into WooCommerce order completion to trigger the tracking
add_action( 'woocommerce_thankyou', 'tracknow_tracking', 40 );
add_action( 'woocommerce_order_status_processing', 'tracknow_tracking', 45 );
add_action( 'woocommerce_pre_payment_complete', 'tracknow_tracking', 50 );
add_action( 'woocommerce_payment_complete', 'tracknow_tracking', 55 );
```

This code is responsible for gathering the order data, generating the postback URL and firing it to your Tracknow dashboard when the order is complete.

{% hint style="info" %}
Replace the **{NAMESPACE}** placeholder with your actual Tracknow namespace before pasting this code Replace the **{CAMPAIGN ID}** placeholder with your actual Tracknow campaign ID before pasting this code
{% endhint %}
