# OpenCart Extension

The BasketBooster Recommender extension for OpenCart syncs your catalog,
tracks shopper events, and shows recommendation widgets on your store. It is
a normal OpenCart module: you place it on layouts like any other module, and
the extension does that for you for the common pages.

There are two builds with the same features: one for OpenCart 4 and one for
OpenCart 3.0.x. This page describes the OpenCart 4 build first; the
[OpenCart 3.0.x section](#opencart-30x) at the end lists what is different
there.

## Requirements

- OpenCart 4.0.2 or newer (tested on 4.1.0.4), or OpenCart 3.0.2 or newer
  with the separate 3.0.x build (tested on 3.0.5.1, see below).
- PHP 8.1 or newer with the cURL extension (OpenCart needs it anyway).
- A BasketBooster account (<https://dashboard.basketbooster.eu/register>,
  30-day free trial, no card).
- An active trial or plan (catalog sync requires one).

## Install

1. Download the extension:
   <https://api.basketbooster.eu/plugin/basketbooster.ocmod.zip>
   (also linked from your dashboard's setup page).
2. In the OpenCart admin open **Extensions > Installer**, upload the zip and
   click the green install button next to it.
3. Open **Extensions > Extensions**, choose the **Modules** type, find
   **BasketBooster Recommender** and click the green install button.
4. Click the edit (pencil) button to open the settings page.

Uploading a new version of the zip over an installed one works the same way:
uninstall the old one in the Installer first, then upload the new zip.

## Connect

From your BasketBooster dashboard copy two keys into the settings page:

- **Publishable key** (`pk_...`), from the *Recommender > Widget snippet*
  page. The widgets use it in the shopper's browser.
- **Secret API key**, from the *API Keys* page (create one; it is shown only
  once). OpenCart uses it server-side for catalog sync.

Leave the **API base URL** at `https://api.basketbooster.eu`, switch the
**Status** on, save, then click **Test connection**. A successful test also
registers the extension with your account (platform, store URL, extension
version), which checks off the setup steps on your dashboard's Home page.

## Sync your catalog

Click **Sync now** on the settings page. The extension pushes every enabled
product of your default store (name, image, price as shoppers see it, with
tax, categories, manufacturer, attributes and options, stock, SKU or model,
URL) to BasketBooster. The search index and recommendation engines are
provisioned and filled automatically.

After the first sync, saving a product in the admin syncs it right away.
Disabling or deleting a product removes it from the catalog. When an order is
paid, the stock levels of the ordered products are refreshed too.

The settings page shows engine status (catalog items, last engine sync, last
trained) plus **Sync catalog to engines** and **Train now** buttons, useful
after a big import.

Variants (products with a master product) are synced as their own items,
which matches how OpenCart shows them. Only the default store is synced.

## Widgets

The extension is one module that shows different things depending on the
page it is placed on. The **Automatic placements** checkboxes put it on the
matching layouts under **Design > Layouts** for you:

- **Product pages**: "You may also like" for the viewed product. The built-in
  "Related Products" section is hidden so there are not two similar grids
  (you can keep it with the checkbox under the placement).
- **Cart page**: "Frequently bought together", seeded by the last item added.
- **Home page**: trending products.
- **Category pages** (off by default): trending products of the viewed
  category, with the title "Trending in {category}".
- **Order success page**: trending products, as a post-purchase placement.

You choose the position (content top or bottom, left or right column). You
can also add "BasketBooster Recommender" to any other layout by hand in
**Design > Layouts**; there it shows trending products.

For custom theme placements, the widget is a plain element you can put in a
Twig template:

```html
<product-recs data-key="pk_..." data-api="https://api.basketbooster.eu"
  data-item-id="{{ product_id }}" data-source="mix" data-num="8"></product-recs>
```

See [widget-embed](widget-embed.md) for every attribute.

## Appearance

Two places, one source of truth (stored in your BasketBooster account,
fetched live by the widgets):

- **Dashboard designer**: colors, fonts, headings, custom CSS.
- **Extension settings**: layout (grid, or carousel with arrows), the number
  of products per widget (a default plus an optional value per placement:
  product page, cart, home, category) and the widget titles.

## Purchase tracking

The extension tracks product views, add-to-cart actions and purchases.
Purchases are sent from PHP when an order reaches one of your processing or
complete statuses (System > Settings > Option), so they survive ad blockers
and off-site payment gateways. Every order line carries the `order_id`, which
feeds the Frequently-Bought-Together model. To seed it with pre-existing
sales, upload your order history CSV on the dashboard (see
[v1-api-reference](v1-api-reference.md), `POST /orders/upload`).

Events are pseudonymous: a random session id stored in the shopper's browser
and, for logged-in customers, the numeric customer id. Mention this in your
privacy policy.

## Customer events (win-back, replenishment)

On a Customer Intelligence plan the extension can act on BasketBooster's
customer change feed from inside the store, where the customer's email and
newsletter consent live. Everything is off by default; switch it on under
**Customer events** on the settings page.

- **Receive customer events**: an hourly poll of the change feed through
  OpenCart's cron job (Extensions > Cron Jobs). Your server has to call
  OpenCart's cron for this to run; in OpenCart 4.1.0.4 the command line
  `cron.php` fails with a missing Twig class, so call
  `https://your-store/index.php?route=cron/cron` from your system cron
  instead. **Check for events now** runs the poll on demand.
- **Register webhook**: for stores with a public `https://` URL the extension
  registers `index.php?route=extension/basketbooster/webhook/basketbooster`
  via `POST /account/webhooks`, stores the returned secret and verifies
  `X-BasketBooster-Signature` on every delivery (5-minute tolerance,
  duplicate deliveries ignored). The hourly poll keeps running as a safety
  net.
- **Who may be emailed**: by default only customers subscribed to your
  newsletter; or all active customers.
- **Win-back coupon email** (`became_at_risk`): a single-use percentage coupon
  (OpenCart coupons cannot be bound to one customer, so it requires a login
  and allows one use in total) emailed with the customer's personal picks; at
  most once per 30 days per customer. Subject, heading and body are editable
  with `{name}`, `{coupon}`, `{discount}`, `{expires}`, `{store}`.
- **Replenishment reminder** (`replenishment_due`): the due products as
  cards; at most once per 14 days per customer. Placeholders `{name}`,
  `{products}`, `{store}`.

Emails go through OpenCart's mail settings (System > Settings > Mail).

## Email Flows contact sync

From version 0.2.0 the extension can keep BasketBooster's contact list in step
with your store, which [Email Flows](email-flows.md) needs before it can send
anything. It is off by default.

Switch on **Sync contacts** under **Email Flows** on the settings page and
save. The extension then:

- imports your existing customers once, 200 at a time, through the hourly
  cron job (or click **Sync contacts now** to run the import right away);
- sends each later change as it happens: a new registration, an edited email
  or name, a newsletter subscription switched on or off, in the storefront or
  in the admin;
- erases the contact when you delete the customer;
- on every cron run, sends a batch of up to 500 customers again, working
  through the whole list in turn. That picks up changes made where no
  OpenCart event fires, such as a direct database import;
- on every cron run, checks who unsubscribed through an email, bounced or
  complained, and switches off their newsletter subscription in OpenCart.

For each customer it sends the customer id, email, first and last name,
language, registration date and marketing consent. It does not send guest
checkouts.

**Consent** follows the *Who may be emailed* setting:

| setting | sent as subscribed |
|---|---|
| Only customers subscribed to the newsletter (default) | active customers with the newsletter switched on |
| All active customers | every active customer |

The extension sends everyone else with consent `unknown`, and Email Flows
never emails them. An address that unsubscribed, bounced or complained stays suppressed in
BasketBooster even if the store later sends it as subscribed.

The settings page shows how far the import is and the last sync problem, if
there was one. Sync needs the secret API key, a plan with Email Flows and a
working cron (see [Customer events](#customer-events-win-back-replenishment)
for how to call it).

If you update from an earlier version, upload the new zip and save the
settings page once. Saving registers the store events that contact sync and
unique discount codes listen to, so you do not have to reinstall.

If a flow is live for *became at risk* or *replenishment due*, the extension
skips its own email for that event, so the customer is not mailed twice.

You remain the controller of your customers' data, so mention contact sync in
your privacy policy.

### Unique discount codes

From version 0.3.0 an email can give each customer a discount code of their
own (see [Discount codes](email-flows.md#discount-codes)). You do not create
these in OpenCart. The first time a shopper enters one in the cart, the
extension checks it with BasketBooster and creates a normal coupon with the
same rules: percent or fixed amount, how many orders it works for and the
expiry date. After that it is an ordinary coupon under **Marketing >
Coupons**, named `BasketBooster: CODE`, which you can edit or delete. When an
order that used it is confirmed, the extension reports the order back, so the
BasketBooster dashboard can count it.

OpenCart cannot tie a coupon to one customer, so the extension does that
part. A personal code works only while its owner is logged in. Anyone else
who enters it gets OpenCart's usual "invalid coupon" message. The extension
also stops a code at its exact expiry time, because OpenCart only compares
dates.

A few limits come from OpenCart itself:

- A coupon code holds at most 20 characters. Codes are 8 characters long, so
  keep a code prefix to 11 characters or fewer. The extension ignores longer
  codes.
- A fixed-amount code is in your store's default currency. The extension
  does not create a code issued in another currency.
- The **Coupon** order total has to be enabled under **Extensions > Order
  Totals**, as for any coupon.

This runs only while **Sync contacts** is on. The extension checks a code
that is not from BasketBooster once and then leaves it alone for five
minutes. If BasketBooster cannot be reached, the cart answers as it would
without the extension. Saving the settings page with **Sync contacts** on
tells BasketBooster that your store accepts unique codes, and the cron
repeats that every day. You need this before you can publish a flow that
uses them.

## Troubleshooting

- **Mixed content**: an HTTPS store must use the HTTPS API base, because
  browsers block `http://` calls from `https://` pages. The settings page
  warns about this.
- **CORS**: publishable keys with an empty origin allowlist accept any origin.
  If you configured an allowlist in the dashboard, add your store's domain.
- **Sync errors**: shown verbatim on the settings page. The most common cause
  is an expired trial with no plan selected (`402 billing_inactive`). Pick a
  plan on the dashboard's Billing page.
- **Widgets not visible**: confirm the Status switch is on, the publishable
  key is saved, the module is placed on the layout (Design > Layouts) and
  check the browser console on a product page.
- **Product edits not syncing**: the extension's events must be enabled under
  Extensions > Events (they are created on install). Errors are written to
  the OpenCart error log (System > Maintenance > Error Logs).

## OpenCart 3.0.x

OpenCart 3 stores are still common, so the extension also ships as a 3.0.x
build with the same settings page, sync, widgets, events and customer-events
support. Download it from
<https://api.basketbooster.eu/plugin/basketbooster-oc3.ocmod.zip> (also linked
from your dashboard's setup page). It needs OpenCart 3.0.2 or newer and PHP
8.1 or newer, which OpenCart 3.0.4 and later require anyway.

What is different from the OpenCart 4 build:

- **Install**: upload the zip under **Extensions > Installer** (it uses the
  standard `upload/` layout, so the files are copied into your store), then
  open **Extensions > Extensions**, choose **Modules** and click the install
  button next to **BasketBooster Recommender**. The pencil button opens the
  settings page. To update, upload the new zip in the Installer and install the
  module again; your settings are kept.
- **Settings page**: the **Status** switch is an enabled/disabled list and the
  page reloads after you save (it stays on the settings page, so you can click
  **Test connection** right away). Every other control is the same.
- **Customer events** (win-back, replenishment): OpenCart 3 has no built-in
  cron jobs, so the settings page shows a cron URL with a token that only your
  store knows. Add it to your server's cron so it runs every hour, for
  example:

  ```
  0 * * * * curl -fsS "https://your-store/index.php?route=extension/module/basketbooster/cron&token=..." >/dev/null
  ```

  **Check for events now** runs the same poll on demand. The webhook address
  is `index.php?route=extension/module/basketbooster/webhook`.
- **Email Flows contact sync**: the same cron URL runs the customer import,
  the repeat batch and the unsubscribe check, so add it to your server's cron
  even if you do not use customer events. Storefront and admin customer
  changes are sent right away, like on OpenCart 4. Unique discount codes
  work the same way too.
- **Product sync events**: saving or deleting a product in the admin syncs it
  right away, like on OpenCart 4. Copying a product does not trigger a sync
  (copies are created disabled); the copy is synced when you edit and enable
  it.
- **Variants** do not exist in OpenCart 3, so every product is one catalog
  item. The SKU field is used as the item SKU, falling back to the model.
- **Themes**: the widget template lives in the default theme folder and
  OpenCart falls back to it for other themes. To change the markup for your
  theme, copy
  `catalog/view/theme/default/template/extension/module/basketbooster.twig`
  into your theme's folder.

Everything else on this page (keys, sync, widget placements, appearance,
purchase tracking, troubleshooting) applies to both builds. The extension's
events are listed under **Extensions > Events** in OpenCart 3.
