Skip to content

API Integration (HTML Response)

clock Avg. 4 min read

API Integration (HTML Response)

If you are starting your Pages setup, read this guide first. This guide covers backend integration in depth.


Requirements & Prerequisites

This approach is useful when you want to use Hello Retail’s default designs but render them server-side.

  • Ensure the Hello Retail script is loaded on the frontend. The returned JavaScript depends on this script and its events to initialize.
  • Read more about the Pages API in our developer documentation.

Process

With this method, the initial content for the category page is fetched by your webshop’s backend via the Pages API. The response contains HTML, CSS, and JavaScript, which you render server-side so the page has content on first load. Subsequent interactions such as pagination and filtering are handled by AJAX from the frontend.

The process consists of 3 steps.

  1. Send an API request to Hello Retail to fetch the page content. The response contains HTML, CSS, and JavaScript.
  2. Inject the returned HTML and CSS into the page. Place the HTML inside a dedicated container element (for example, a div) and keep a reference to it for the next step.
  3. Inject the returned JavaScript into the page. Delay execution until the Hello Retail script is ready. Wait for the Hello Retail script to emit the context_ready event before running the returned JavaScript.

The category page generated by Hello Retail typically includes filters. When a filter is applied, it is added to the URL. To preserve filters on reload, read the filter values on the backend and include them in the API request.


Example

The following shows how to implement the backend integration in WooCommerce. The default category page is implemented in the /wp-content/plugins/woocommerce/templates/archive-product.php file.

You will see similarities with the frontend integration code that creates the container div.

The example requires the Hello Retail page template to store filters in the hr-page query string parameter.

<?php
    $key = '621ca9f152b27467bdb8d06a';
    $breadcrumbs = (new WC_Breadcrumb())->generate();
    $baseFilter = ['hierarchies' => []];
    foreach($breadcrumbs as $b) {
        $baseFilter['hierarchies'][] = $b[0];
    }
    $baseFilter = json_encode($baseFilter);
    $trackingUserId = $_COOKIE['hello_retail_id'];
    $filters = [];
    $sorting = [];
    $start = 0;
    $count = 24;
    if (isset($_GET['hr-page'])) {
        $decoded = json_decode($_GET['hr-page'], true);
        if (isset($decoded['filters'])) {
            $filters = $decoded['filters'];
        }
        if (isset($decoded['sorting'])) {
            $sorting = $decoded['sorting'];
        }
        if (isset($decoded["page"])) {
            if (isset($decoded["pagesize"])) {
                $count = $decoded["pagesize"];
            } else {
                $count = 24;
            }
            $start = ($decoded["page"] - 1) * $count;
        }
    }
    $req = [
        "url" => $_SERVER["REQUEST_URI"],
        "layout" => true,
        "products" => [
            "start" => $start,
            "count" => $count,
            "filters" => $filters,
            "sorting" => $sorting
        ],
        "params" => [
            "filters" => $baseFilter
        ],
        "firstLoad" => true,
        "trackingUserId" => $trackingUserId
    ];
    $opts = [
        "http" => [
            'method' => 'POST',
            'header' => 'Content-type: application/json',
            'content' => json_encode($req)
        ]
    ];
    $context = stream_context_create($opts);
    $content = file_get_contents('https://core.helloretail.com/serve/pages/' . $key, false, $context); 

    if ($content) {
        $content = json_decode($content, true);
        $req["products"]["count"] = $content["products"]["count"];
        $req["products"]["total"] = $content["products"]["total"];
        ?>
            <div id='hr-category-page'>
                <?=$content['products']['html']?>
            </div>
            <style><?=$content['products']['style']?></style>
            <script>
                hrq = window.hrq || [];
                hrq.push(function(){
                    (function(_, container, data, page){
                        <?=$content['products']['javascript']?>
                    })(
                        ADDWISH_PARTNER_NS,
                        document.getElementById('hr-category-page'),
                        <?=json_encode($req)?>,  {  key:'<?=$key?>'  }
                    )
                });
            </script>
        <?php
    } else {
        // output the default platform category page
    }

The various parts of this are often split between a controller (request and data preparation) and a view (markup injection and initialization).

Note

Because the backend calls the Hello Retail API, you can fall back to the platform’s default category page immediately if the API request fails.