Skip to content

Shop integration

Lukas Bestle edited this page Apr 10, 2023 · 2 revisions

This tutorial explains how you can add the parts of a product or plan configuration to the user's shopping cart when the "add to cart" button is clicked.

You can implement this feature with any shop software or Kirby shop plugin. To keep it simple, this tutorial only shows the general setup for a shop that can receive products from Kirby backend code.

1. Create a custom route

A custom Kirby route will receive the request from the frontend with the configuration data. In this example we implement the route with a Kirby option in site/config/config.php:

<?php

return [
  'routes' => [
    [
      'pattern' => 'configuration-to-cart',
      'method'  => 'POST',
      'action'  => function () {
        if ($plan = roomlePlan()) {
          foreach ($plan->items() as $item) {
            foreach ($item->parts() as $part) {
              yourShop()->addToCart([
                'articleNr'  => $part->articleNr(),
                'parameters' => $part->parameters()->rawData()
              ]);
            }
          }
        }

        return go('cart');
      }
    ],
  ]
];

This example only passes the article numbers and the parameter data (custom options like size, color and features depending on the part) to the shop. This works if the shop knows all the part details such as name and price. It is recommended to use this approach if possible. This ensures that users cannot manipulate the data and e.g. change the price of the parts.

If you really need to use data from the client and have other protections against manipulations, you can also access other fields from the configuration objects. To see what is possible, please take a look at the plugin classes, particularly Configuration, Parameter, Part and Plan.

2. Point the plugin to the custom route

Now you need to tell the Roomle plugin that it should submit the configuration data to this custom route whenever the "add to cart" button is clicked. You can do this by setting the target option in site/config/config.php:

<?php

return [
  'lukasbestle.roomle' => [
    'target' => 'configuration-to-cart'
  ]
];

Please note that it is not possible to set this value via the block settings in the Panel as the block settings only allow Kirby pages as the target. You can only do this via the global default option as shown above. If you need to customize the shop target for each block separately, you can e.g. move the handling code from the custom route to the controller of your cart page and then set the cart page as the target.

Clone this wiki locally