# Shopify

## Шаг 1: Создать предложение

Для отслеживания без cookie обязательно включить параметр click ID и токен в URL предложения, а также на всех посадочных страницах при создании предложения в панели Offer18.

{% code title="Пример" overflow="wrap" %}

```
https://shopurl.com/?<YOUR-CLICK-ID-PARAMETER>={tid}
```

{% endcode %}

***

## Шаг 2: Размещение кода

1. В админ-панели Shopify перейдите в "**Настройки**"

2. Перейдите в "**События клиентов**" **»** "**Добавить пользовательский пиксель**"

3. Введите "**Имя пикселя**" и затем нажмите "**Добавить пиксель**"<br>

   <figure><img src="/files/ed45eadb55789bf779d00e964d13fae0620702b6" alt=""><figcaption></figcaption></figure>

4. Удалите существующее содержимое из раздела "**Код**"

5. Теперь вставьте приведённый ниже скрипт в "**редакторе пикселя**"

```javascript
analytics.subscribe("page_viewed", (event) => {
  const sdkScript = document.createElement('script');
  sdkScript.setAttribute('src', 'https://web-resources.offer18.net/sdk/web/WebSDK.js');
  sdkScript.setAttribute('async', '');
  document.head.appendChild(sdkScript);
  sdkScript.onload = function () {
    // window.Offer18WebSDK.activateDebugMode(); 
    window.Offer18WebSDK.initializeConversion('<YOUR-CLICK-ID-PARAMETER>');
  };
  sdkScript.onerror = function () {
    console.error('Failed to load the Offer18 Web SDK.');
  };
});

analytics.subscribe('checkout_completed', (event) => {
  var discountString;
  var totalAmount = event.data.checkout.totalPrice.amount;
  var orderID = event.data.checkout.order.id;
  var currency = event.data.checkout.currencyCode;
  var allDiscountCodes = event.data.checkout.discountApplications.map((discount) => { if (discount.type === 'DISCOUNT_CODE') { return discount; } });
  if (allDiscountCodes.length > 10) { discountString = ''; } else { discountString = allDiscountCodes.map((item) => item.title).join(','); }
  const sdkScript = document.createElement('script');
  sdkScript.setAttribute('src', 'https://web-resources.offer18.net/sdk/web/WebSDK.js');
  sdkScript.setAttribute('async', '');
  document.head.appendChild(sdkScript);
  sdkScript.onload = function () {
    // window.Offer18WebSDK.activateDebugMode();
    window.Offer18WebSDK.trackConversion({
      domain: '<YOUR-POSTBACK-DOMAIN>',
      accountId: '<YOUR-ACCOUNT-ID>',
      offerId: '<CAMPAIGN-ID>',
      postbackType: 'ajax',
      coupon: `${discountString}`,
      conversionData: {
        sale: `${totalAmount}`,
        currency: `${currency}`,
        adv_sub5: `${orderID}`,
      }
    });
  };
  sdkScript.onerror = function () {
    console.error('Failed to load the Offer18 Web SDK.');
  };
});
```

**Убедитесь, что заполнители в скрипте заменены на фактические данные для кампании. Пояснения к заполнителям приведены в таблице ниже.**

<table data-header-hidden><thead><tr><th width="362"></th><th></th></tr></thead><tbody><tr><td><strong>Placeholder</strong></td><td><strong>Explanation</strong></td></tr><tr><td><code>&#x3C;YOUR-CLICK-ID-PARAMETER></code></td><td>This is the <code>clickid</code> parameter used while creating the offer.</td></tr><tr><td><code>&#x3C;YOUR-POSTBACK-DOMAIN></code></td><td>Postback domain of the user. (<strong>domain</strong>)</td></tr><tr><td><code>&#x3C;YOUR-ACCOUNT-ID></code></td><td>Offer18 account id of the user. (<strong>accountId</strong>)</td></tr><tr><td><code>&#x3C;CAMPAIGN-ID></code></td><td>Id of the offer. (<strong>offerId</strong>)</td></tr></tbody></table>

{% hint style="warning" %}
In case of shopify '**postbackType'** must be **'ajax'**
{% endhint %}

6. Перейдите к сохранению

<figure><img src="/files/41cfcfa388afa9dde7ce9f707b65a2034adb89dc" alt=""><figcaption></figcaption></figure>

***

## Пользовательские параметры оформления заказа

Если вы используете какие-либо из перечисленных ниже пользовательских оформлений заказа, необходимо использовать соответствующий скрипт конверсии, предназначенный именно для этого стороннего оформления заказа.

### Shiprocket

```javascript
analytics.subscribe("page_viewed", (event) => {
  const sdkScript = document.createElement('script');
  sdkScript.setAttribute('src', 'https://web-resources.offer18.net/sdk/web/WebSDK.js');
  sdkScript.setAttribute('async', '');
  document.head.appendChild(sdkScript);
  sdkScript.onload = function () {
    // window.Offer18WebSDK.activateDebugMode(); 
    window.Offer18WebSDK.initializeConversion('<YOUR-CLICK-ID-PARAMETER>');
  };
  sdkScript.onerror = function () {
    console.error('Failed to load the Offer18 Web SDK.');
  };
});

analytics.subscribe('PurchaseSR', (event) => {
  var totalAmount = event.customData.value;
  var orderID = event.customData.transaction_id;
  const sdkScript = document.createElement('script');
  sdkScript.setAttribute('src', 'https://web-resources.offer18.net/sdk/web/WebSDK.js');
  sdkScript.setAttribute('async', '');
  document.head.appendChild(sdkScript);
  sdkScript.onload = function () {
    // window.Offer18WebSDK.activateDebugMode();
    window.Offer18WebSDK.trackConversion({
      domain: '<YOUR-POSTBACK-DOMAIN>',
      accountId: '<YOUR-ACCOUNT-ID>',
      offerId: '<CAMPAIGN-ID>',
      postbackType: 'ajax',
      conversionData: {
        sale: `${totalAmount}`,
        adv_sub5: `${orderID}`,
      }
    });
  };
  sdkScript.onerror = function () {
    console.error('Failed to load the Offer18 Web SDK.');
  };
});
```

### GoKwik

```javascript
analytics.subscribe("page_viewed", (event) => {
  const sdkScript = document.createElement('script');
  sdkScript.setAttribute('src', 'https://web-resources.offer18.net/sdk/web/WebSDK.js');
  sdkScript.setAttribute('async', '');
  document.head.appendChild(sdkScript);
  sdkScript.onload = function () {
    // window.Offer18WebSDK.activateDebugMode(); 
    window.Offer18WebSDK.initializeConversion('<YOUR-CLICK-ID-PARAMETER>');
  };
  sdkScript.onerror = function () {
    console.error('Failed to load the Offer18 Web SDK.');
  };
});

analytics.subscribe('gokwik_purchase_event', (eventData) => {
  var totalAmount = eventData.customData.total_price;
  var orderID = eventData.customData.order_name;
  const sdkScript = document.createElement('script');
  sdkScript.setAttribute('src', 'https://web-resources.offer18.net/sdk/web/WebSDK.js');
  sdkScript.setAttribute('async', '');
  document.head.appendChild(sdkScript);
  sdkScript.onload = function () {
    // window.Offer18WebSDK.activateDebugMode();
    window.Offer18WebSDK.trackConversion({
      domain: '<YOUR-POSTBACK-DOMAIN>',
      accountId: '<YOUR-ACCOUNT-ID>',
      offerId: '<CAMPAIGN-ID>',
      postbackType: 'ajax',
      conversionData: {
        sale: `${totalAmount}`,
        adv_sub5: `${orderID}`,
      }
    });
  };
  sdkScript.onerror = function () {
    console.error('Failed to load the Offer18 Web SDK.');
  };
});
```

### Razorpay Magic Checkout

Внедрите приведённый ниже скрипт в файл "theme.liquid" в вашем аккаунте Shopify.

1. В админ-панели Shopify перейдите в **Онлайн-магазин » Темы**.
2. Нажмите “…” (три точки) **»** Отредактируйте код в вашей активной теме.
3. Откройте файл: **Макет » `theme.liquid`**
4. Теперь вставьте приведённый ниже скрипт непосредственно перед закрывающим `</body>` тегом **»** Сохранить

```javascript
<script src="https://web-resources.offer18.net/sdk/web/WebSDK.js"></script>
<script>
    window.Offer18WebSDK.shopifyRazorpayMagicListenEvents({});
    window.Offer18WebSDK.initializeConversion("<YOUR-CLICK-ID-PARAMETER>");
</script>
```

Поместите приведённый ниже код в [**События клиентов**](#step-2-code-placement) в аккаунте Shopify.

```javascript
const sdkScript = document.createElement("script");
sdkScript.src = "https://web-resources.offer18.net/sdk/web/WebSDK.js";
sdkScript.async = true;
document.head.appendChild(sdkScript);
sdkScript.onload = function () {
  //console.log("SDK loaded.");
  //window.Offer18WebSDK.activateDebugMode();
  var order_id = "";
  var coupon_code = "";
  var coupon_discount = "";
  var currency = "";
  var total_amount = "";
  
  analytics.subscribe("razorpay_magic_event", (event) => {
    const eventName = event.customData?.topic;
    const data = event.customData?.data;
    if (data.order_id) {
      order_id = data.order_id;
    }
    if (data.appliedCouponCode) {
      coupon_code = data.appliedCouponCode;
    }
    if (data.couponDiscountValue) {
      coupon_discount = data.couponDiscountValue / 100;
    }
    if (data.currency) {
      currency = data.currency;
    }
    if (data.totalAmount) {
      total_amount = data.totalAmount / 100;
    }
    if (data.appliedCouponCode && data.couponDiscountValue == 0) {
      coupon_code = "";
      coupon_discount = "";
    }

    //console.log("Magic Pixel -> event:", eventName, data);
    if (eventName === "payment.success") {
      //console.log("SDK page initiate");
      window.Offer18WebSDK.trackConversion({
        domain: "<YOUR-POSTBACK-DOMAIN>",
        accountId: "<YOUR-ACCOUNT-ID>",
        offerId: "<CAMPAIGN-ID>",
        postbackType: "ajax",
        clickIdData: data?.offer18_click_ids || null,
        conversionData: {
          sale: `${total_amount}`,
          adv_sub1: `${order_id}`,
          adv_sub2: `${coupon_code}`,
          adv_sub3: `${coupon_discount}`,
          currency: `${currency}`,
        },
      });
    }
  });
};
sdkScript.onerror = function () {
  console.error("Failed to load the Offer18 Web SDK.");
};
```

***

## Collect Data

You can collect conversion data using various Offer18 Postback Parameters

<table data-header-hidden><thead><tr><th width="259"></th><th width="252"></th><th></th></tr></thead><tbody><tr><td><strong>Conversion Data</strong> </td><td><strong>Offer18 Postback Parameter</strong></td><td><strong>Variable to use</strong></td></tr><tr><td>Currency</td><td>currency</td><td><pre><code>`${currency}`
</code></pre></td></tr><tr><td>Total Amount of the Order</td><td>sale</td><td><pre><code>`${totalAmount}`
</code></pre></td></tr><tr><td>Order ID of the Order</td><td>adv_sub5</td><td><pre><code>`${orderID}`
</code></pre></td></tr><tr><td>Discount Coupons</td><td>coupon</td><td><pre><code>`${discountString}`
</code></pre></td></tr></tbody></table>

***

## Режим отладки

Пользователь может включить режим отладки, раскомментировав '**window\.Offer18WebSDK.activateDebugMode()**;'

<figure><img src="/files/bceedd54351ed4f647e1954c2c1ae7c5e2225f4a" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://knowledgebase.offer18.com/ru/set/integraciya-elektronnoi-kommercii/shopify-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
