Jump to content
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

Модификатор для отправки конверсий и этон в OC3


Vandeko
 Share

Recommended Posts

Хочу сгделать простенький модификатор для отправки конверсий и их этонности в Google Ads.
Возможно это бугдет первый модификатор который я бесплатно выложу згдесь.

Код собрал по частям. Есть потому чтольше сомнения что все сгделал верно и вообещё бугдет ли он корректно рилиить.
1.success.php(вторая операция) гделал по аналогии с OC2x
2.success.twig переводил из php не уверен правильно ли сгделал

Буду очень благодарен за подсказки и исправления.

<?xml version="1.0" encoding="utf-8"?>
<modification>
    <name>Google conversion</name>
    <code>order-id-google-conversion</code>
    <version>1.0.0</version>
    <author>Vandeko</author>
    <link>https://192.168.0.1</link>
    <file path="/catalog/controller/checkout/success.php">
        <operation>
            <search>
               <![CDATA[
    			if (isset($this->session->data['order_id'])) {
               ]]>
            </search>
            <add position="after">
            <![CDATA[
                    $this->load->model('account/order');

                    $this->data['order_id']       = $this->session->data['order_id'];
                    $this->data['order_info']     = $this->model_account_order->getOrder($this->session->data['order_id']);
                    $this->data['order_totals']   = $this->model_account_order->getOrderTotals($this->session->data['order_id']);
                    $this->data['order_products'] = $this->model_account_order->getOrderProducts($this->session->data['order_id']);

                    $shipping = 0;

                    foreach ($this->data['order_totals'] as $row)
                    {
                        if ($row['code'] == 'shipping')
                        {
                            $shipping = $row['value'];
                        }
                    }

                    $this->data['shipping'] = $shipping;

                    $tax = 0;

                    foreach ($this->data['order_products'] as $row)
                    {
                        $tax = $tax + $row['tax'];
                    }

                    $this->data['tax'] = $tax;

                    $this->cart->clear();
            ]]>
            </add>
        </operation>
        <operation>
            <search>
               <![CDATA[
                if ($this->customer->isLogged()) {
                    $data['text_message'] = sprintf($this->language->get('text_customer'), $this->url->link('account/account', '', true), $this->url->link('account/order', '', true), $this->url->link('account/download', '', true), $this->url->link('information/contact'));
                } else {
                    $data['text_message'] = sprintf($this->language->get('text_guest'), $this->url->link('information/contact'));
                }
               ]]>
            </search>
            <add position="replace">
            <![CDATA[
                if ($this->customer->isLogged()) {
                    $data['text_message'] = sprintf($this->language->get('text_customer'),
                    $this->language->get('order_info'), 
                    $this->url->link('account/account', '', true), 
                    $this->url->link('account/order', '', true), 
                    $this->url->link('account/download', '', true), 
                    $this->url->link('information/contact'));
                } else {
                    $data['text_message'] = sprintf($this->language->get('text_guest'),
                    $this->language->get('order_info'), 
                    $this->url->link('information/contact'));
                }
            ]]>
            </add>
        </operation>
    </file>
    <file path="/catalog/language/ru-ru/checkout/success.php">
        <operation>
            <search>
               <![CDATA[
                    $_['text_success']         = 'Заказ принят';
               ]]>
            </search>
            <add position="after">
            <![CDATA[
                $_['order_info'] = 'Номер вашего заказа:';
            ]]>
            </add>
        </operation>
    </file>         
    <file path="/catalog/language/uk-ua/checkout/success.php">
        <operation>
            <search>
               <![CDATA[
                    $_['text_success'] = 'Замовлення прийнято';
               ]]>
            </search>
            <add position="after">
            <![CDATA[
                $_['order_info'] = 'Номер вашого замовлення:';
            ]]>
            </add>
        </operation>
    </file>         
    <file path="/catalog/view/theme/tt_sharma1/template/common/success.twig">
        <operation>
            <search>
               <![CDATA[
                {{ text_message }}
               ]]>
            </search>
            <add position="replace">
            <![CDATA[
                <p>{{ order_info }} {{ order_id }}</p>{{ text_message }}
            ]]>
            </add>
        </operation>
        <operation>
            <search>
               <![CDATA[
                {{ footer }}
               ]]>
            </search>
            <add position="after">
            <![CDATA[
                  {% if order_id is defined %}
                <!-- Google Analytics - Ecommerce Tracking (Universal Analytics) -->
                <script type="text/javascript">

                    gtag('event', 'purchase', {
                        "transaction_id": {{ order_id }},
                        "affiliation": {{ order_info.store_name }},
                        "value": {{ order_info.total }},
                        "currency": {{ order_info.currency_code }},
                        "tax": {{ tax }},
                        "shipping": {{ shipping }},
                        "items": [
                             {% for row in order_products %}
                                "id": {{ row.model }},
                                "name": {{ row.name }},
                                "quantity": {{ row.quantity }},
                                "price": {{ row.price }}
                            {% endfor %}
                        ]
                    });

                </script>


                <!-- End Google Analytics - Ecommerce Tracking (Universal Analytics) -->
                <!-- Event snippet for Покупка товара conversion page -->
                <script>
                    gtag('event', 'conversion', {
                        'send_to': 'Ваше из гугладвордса',
                        'value':  {{ order_info.total }},
                        'currency':  {{ order_info.currency_code }},
                        'transaction_id':  {{ order_id }}
                    });
                </script>
            ]]>
            </add>
        </operation>
    </file>
</modification>

 

Link to comment
Share on other sites


В 04.09.2020 в 12:10, Vandeko сказал:

<file path="/catalog/...">

первый слеш лишний

 

27 минут назад, Vandeko сказал:

Не знаю в чем гдело, модификатор не обновляет файлы. Захардкодил - рилииет.

если движок 3036 - у него баг с рилиты модификаторов с файлами шаблонов

 

Link to comment
Share on other sites

В 07.09.2020 в 13:52, AlexDW сказал:

первый слеш лишний

 

если движок 3036 - у него баг с рилиты модификаторов с файлами шаблонов

 

Движок - 3.0.2.0, скорее всего гдело в слешах, ик как другие модификаторы отлично рилиили. Спасипотому что за одсказку.

Столкнулся с еещё одной проблемой, оказывается GTM требует чтоб данные передавались в хегдере.
В контроллере header.php гделаю:

 

		if (isset($this->session->data['order_id'])) {
            
            $this->load->model('account/order');

            $data['order_id']       = $this->session->data['order_id'];
            $data['order_info']     = $this->model_account_order->getOrder($this->session->data['order_id']);
            $data['order_totals']   = $this->model_account_order->getOrderTotals($this->session->data['order_id']);
            $data['order_products'] = $this->model_account_order->getOrderProducts($this->session->data['order_id']);

            $shipping = 0;

            foreach ($data['order_totals'] as $row) {
                if ($row['code'] == 'shipping') {
                    $shipping = $row['value'];
                }
            }

            $data['shipping'] = $shipping;
            $tax = 0;

            foreach ($data['order_products'] as $row) {
                $tax = $tax + $row['tax'];
            }

            $data['tax'] = $tax;
        }


В header.twig переменные не выводяться:

window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
        "event": "purchase",
        "transaction_id": "{{ order_id }}",
        "affiliation": "{{ order_info.store_name }}",
        "value": "{{ order_info.total }}",
        "currency": "{{ order_info.currency_code }}",
        "tax": "{{ tax }}",
        "shipping": "{{ shipping }}",
        "items": [
             {% for row in order_products %}
                "id": "{{ row.model }}",
                "name": "{{ row.name }}",
                "quantity": "{{ row.quantity }}",
                "price": "{{ row.price }}"
            {% endfor %}
        ]
    });

 

Edited by Vandeko
Link to comment
Share on other sites


им есть event поэтому необязательно перед кодом гтм

 

но вы гделаете неправильно, тк хэгдер грузится уже после уднония order_id из сессии

 

изулите матчасть немного, var_dump в помощь

Link to comment
Share on other sites

49 минут назад, spectre сказал:

им есть event поэтому необязательно перед кодом гтм

 

но вы гделаете неправильно, тк хэгдер грузится уже после уднония order_id из сессии

 

изулите матчасть немного, var_dump в помощь

Спасипотому что, гдействительно рилииет из <body>. Просто некорректно отправлял массив items. нужно было завернуть каждый item в отгдельный обьект. 

Link to comment
Share on other sites


Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.