# Shipping addons

URL: https://shoptet.dev/addons/documentation/shipping-addons

This article describes all the steps needed to implement an addon that provides a new shipping method. Such a shipping method can be very flexible in offering delivery options and calculating the price.

## Shipping registry

A new shipping addon must be agreed with the [API team](mailto:api@shoptet.cz) . A code (identifier) is registered for the addon – usually two, one for development and one for production. You have to provide:

- The addon, already created, with its ID or URL from the Shoptet administration
- The addon name in every language the shipping should be offered in

## Shipping addon options

In the **API Partner** section, the addon detail has a tab dedicated to shipping settings (visible after the API team's approval):

- URL of a JavaScript file implementing the frontend functionality (see below)
- Price calculation – either Shoptet calculates the price (prices are defined in the Shoptet administration, on the **Shipping methods** screen), or the addon does, because the price depends on options not available in Shoptet. In the latter case, the price is calculated on the fly during the ordering process.
- Delivery address handling – there are three options:
- not needed at all (digital delivery, pickup points)
- the standard Shoptet form is used (when the price and delivery options do not depend on the delivery address, because the address is entered one step later in the ordering process)
- the addon provides its own delivery address fields, so it can offer shipping options and a price based on the address (the address is later provided via the API and stored in the order, and Shoptet hides the standard address fields in the next step of the ordering process)
- Tracking URL (the placeholder `#PACKAGE_NUMBER#` is expanded for each order later on)
- Label of the link that opens the popup for selecting the shipping details for the first time (such as "Pickup point selection")
- Label of the link that opens the popup again to change the selection (such as "Change timeframe for delivery")

## Shipping method in e-shop administration

To make the shipping available in an e-shop, two steps are needed:

- The addon must be installed.
- A new shipping method has to be defined in the Shoptet administration. The e-shop owner can do it manually, or the addon can prepare it using the [Add shipping](https://api.docs.shoptet.com/shoptet-api/openapi/shipping-methods/createshippingmethod) endpoint.

## Ordering process

The JavaScript file specified in the addon settings is linked in the HTML page.

### Shipping details popup

During the ordering process, the buyer selects the addon's shipping and clicks the link that opens the popup with detailed options. The content of the popup is defined in the main function of the addon's JavaScript file, with several required objects. A self-describing sample is the [externalShippingOne.js](https://github.com/shoptet/templates-assets/blob/master/00/js/libs/externalShippingOne.js) file – let's take a closer look at it.

In this part, you set up the content of the modal window that is displayed when the buyer chooses your shipping. You are free to create any HTML structure you need. In the `link.addEventListener` part of the sample, random data are set up – this is where you should communicate with your API and retrieve the information about the shipping. The `label` and the price with/without VAT (if the price is calculated by the addon) are required. Call `shoptet.modal.close();` after all the necessary operations to close the open modal window.

### Attach custom object to the external shipping

To make it all work, create an object named after the code your shipping is saved under in the Shoptet database (you will be told this name) – called the *custom object* below. The custom object name is in camelCase, `externalShippingOne` in the sample above. **Never overwrite**`shoptet.externalShipping` , only add your own object to it.

### Required keys of custom object

The required keys of the custom object are:

- `modalContent` – the previously set up content of the modal window
- `onComplete` – gives you access to the element that triggered opening the modal. Call `shoptet.modal.resize();` after all other operations.
- `onClosed` – called when the popup closes; set all the details of the selected shipping, then create and dispatch an event on the passed element in exactly the same form as shown in the sample. The event name ( `ShoptetExternalShippingChanged` ) is required, and its `detail` is your entry in `shoptet.checkoutShared.externalShippingDetails` with:
- `price` – `withVat` and `withoutVat` (and `vat` )
- `label.selected` – the label of the selected shipping
- `verificationCode` – the code returned by the [PUT shipping request](https://api.docs.shoptet.com/shoptet-api/openapi/shipping-requests/updateshippingdata) endpoint; Shoptet puts it into the order form (see Submitting shipping offer )
- `invalidate` – `true` resets the selection, `false` keeps it
- `expires` (optional) – a `Date` when the offer expires; the checkout then watches the expiration
The custom object may also set `modalWidth` and `modalClass` to adjust the popup.

The popup is provided with the following information:

- `language` : current frontend language ( `new DataLayerHelper(dataLayer).get('shoptet').language` )
- `shippingRequestCode` : unique code identifying this potential shipping request (32 random alphanumeric characters), stable for the lifetime of the cart ( `shoptet.checkoutShared.shippingRequestCode` )
- `eshopId` : e-shop ID, e.g. 222651 ( `new DataLayerHelper(dataLayer).get('shoptet').projectId` )
- delivery country ( `shoptet.checkoutShared.deliveryCountryId` )
- delivery countries ( `shoptet.checkoutShared.deliveryCountries` ) – array of objects with data about the available countries
- delivery regions ( `shoptet.checkoutShared.deliveryRegions` ) – array of objects with data about the available regions in the selected country
- currency ( `shoptet.checkoutShared.currencyCode` )
- payment method ( `shoptet.checkoutShared.activeBilling` )
- own `guid` – GUID of the shipping method ( `shoptet.checkoutShared.activeShipping.querySelector('input[data-guid]').getAttribute('data-guid')` ); the API calls below need it
The `ShoptetBaseShippingInfoObtained` event is fired only once, after the page loads. After it, you can access `shoptet.checkoutShared.deliveryCountryId` , `shoptet.checkoutShared.regionCountryId` and `shoptet.checkoutShared.currencyCode` .

The addon must call the [GET /api/shipping-request/{shippingRequestCode}/{shippingGuid}](https://api.docs.shoptet.com/shoptet-api/openapi/shipping-requests/getshippingrequestforcartdetails) endpoint with a valid access token of the given e-shop on the backend (an AJAX call to the addon backend). The shipping GUID must belong to your addon, otherwise the API refuses the request. The response contains the key information about the e-shop (ID, URL, VAT payer), the current cart (price, currency, free shipping) and its items. The cart data are available for one hour after the buyer opens the first step of the checkout; after that the endpoint returns an error and the buyer has to reload the checkout.

The popup content is fully up to the addon. It should, however, respect the design and language of the e-shop as much as possible.

### Delivery address

To confirm the shipping and/or calculate the price, the addon may need to know the delivery address. This is not known yet, because in the Shoptet ordering process the address fields are on the next screen. If that is too late for the addon, it has to provide its own address fields in the popup. The address is passed to Shoptet via an API call, and Shoptet hides the standard address fields.

Note: The addon may need to know which fields are mandatory in the e-shop – see the [Eshop mandatory fields](https://api.docs.shoptet.com/shoptet-api/openapi/eshop/geteshopmandatoryfields) endpoint.

### E-shop stock location and ready-to-ship time

The addon may need to know where the products are prepared for delivery and how long it takes to prepare the package. Shoptet does not store this information, so the addon has to provide its own settings or imports for it if needed.

### Submitting shipping offer

Once the buyer selects all the options and the popup closes, the addon has to provide a shipping offer.

On the frontend, it provides the price, label and verification code in the `ShoptetExternalShippingChanged` event (see Required keys of custom object ).

The following information also has to be sent to the backend via the API:

- `description` – text of the shipping item in the order, and optionally `additionalText`
- `price` ( `priceWithVat` or `priceWithoutVat` , plus `vatRate` ) and `currency` – **required** if the addon calculates the price, and **rejected** if Shoptet does (Shoptet then calculates it from the delivery country, currency and weight). The currency must be the currency of the cart.
- `deliveryAddress` – **required** if the addon fills in the delivery address, and **rejected** otherwise
- `branchId` and `branchName` – the pickup point, if applicable
- `trackingNumber` – always required; send an empty string if the package number is not known yet
- `expires` – always required; the offer expiration, or `null` if the offer does not expire
To do so, use the [PUT shipping request](https://api.docs.shoptet.com/shoptet-api/openapi/shipping-requests/updateshippingdata) endpoint ( `PUT /api/shipping-request/{shippingRequestCode}/{shippingGuid}` ). Make sure the request succeeds before closing the popup window, so that the backend has the price offer stored and it is consistent with the frontend. At this moment, it is just a shipping offer, because the buyer can still select another shipping method. The data are stored for the winning shipping method when the order is finally submitted. The shipping, price and address data from this endpoint are stored in the order.

The [PUT shipping request](https://api.docs.shoptet.com/shoptet-api/openapi/shipping-requests/updateshippingdata) endpoint returns a verification code ( `{"verificationCode": "..."}` , 10 characters). Pass it to the frontend in the `verificationCode` key of the `ShoptetExternalShippingChanged` event detail; Shoptet submits it with the order form. Shoptet checks that the verification code on the backend matches the one delivered from the frontend, to ensure the offer presented on the frontend is the same as the one stored on the backend. If they differ, the buyer is told the shipping request was reloaded and returns to the first step of the checkout.

The addon may also be unable to fulfil the shipping and refuse to provide an offer – for example, because of insufficient delivery capacity. The order must then be completed with another shipping method. Handle this case in your JavaScript file.

Keep in mind that the buyer can open the popup multiple times, modify the parameters, and change the shipping method multiple times.

### Changes after shipping details selection

After the popup is displayed, the shipping details are selected and the price is calculated, the buyer can still change some fields on the page – currency, delivery country or payment method. A change of currency or delivery country reloads the page. A change of payment method triggers a JavaScript notification.

In general, there are three possible consequences:

- the addon does not care – the shipping details and price are still valid (e.g. digital delivery)
- the addon can recalculate the price (e.g. add 20 CZK as a cash-on-delivery fee) – the new price has to be updated on the frontend and sent to the backend via the API ( [shipping request](https://api.docs.shoptet.com/shoptet-api/openapi/shipping-requests) endpoint)
- the shipping details have to change and the previous offer is no longer valid (e.g. a new pickup point has to be selected after the delivery country changed) – the addon has to open the popup window again

### Events you should listen to

`ShoptetShippingMethodUpdated` and `ShoptetBillingMethodUpdated` are fired every time the shipping or billing method is changed or confirmed, even if the change is caused by your shipping method.

After the event is fired, you can access `shoptet.checkoutShared.activeShipping` (or `activeBilling` ). It is currently an HTML `div` element containing all the information about the shipping or billing, which you can read with a query selector.

## Submitting the order

Once the order is finalized and submitted, we send a webhook confirming that the shipping offer was accepted and used in the order. The webhook looks like this:

```json
{
    "eshopId": 222651,
    "event": "shippingRequest:confirmed",
    "eventCreated": "2019-01-08T15:13:39+0100",
    "eventInstance": "os8ftuoz7ppo46z87euea0ban9rclb2d/ecb3e399-2f57-11eb-8853-0800275177b9"
}
```

There are two webhook events:

- `shippingRequest:confirmed` – the order was submitted with your shipping, your offer was accepted
- `shippingRequest:cancelled` – the order was submitted with another shipping method, your offer will not be needed
The `eventInstance` item contains the `shippingRequestCode` and the shipping GUID, separated by a slash ( `{shippingRequestCode}/{shippingGuid}` ). Use them to ask for the shipping request status with the [Shipping request status](https://api.docs.shoptet.com/shoptet-api/openapi/shipping-requests/getshippingrequestforgettingorderstatus) endpoint ( `GET /api/shipping-request/{shippingRequestCode}/{shippingGuid}/status` ), which also returns the assigned order code:

```json
{
    "status": "completed",
    "orderCode": "20200001"
}
```

Possible statuses are:

- `open` – the ordering process is pending ( `orderCode` is `null` , because the order is not submitted yet)
- `completed` – the order was submitted and your addon won the delivery
- `cancelled` – the order was submitted with another shipping method
The `cancelled` status and webhook are only sent when the order is submitted with another shipping method. If the buyer abandons the cart, nothing is sent, and a later cancellation of the order does not change the status either (watch the order itself, see After an order is submitted ). The addon can use the expiration (see below), and it can call the [Shipping request status](https://api.docs.shoptet.com/shoptet-api/openapi/shipping-requests/getshippingrequestforgettingorderstatus) endpoint at any time. Even the webhook can be missed, so it is good practice to keep a list of open orders and check their status periodically.

## Shipping request expiration

Some shipping methods do not care whether the shipping offer is finally selected (such as package delivery), but for others it is crucial. For example, short-time deliveries may reserve a car or a timeframe and need to release it if the shipping is not used. This timeout is individual for each shipping addon.

To manage this, the [Shipping request update](https://api.docs.shoptet.com/shoptet-api/openapi/shipping-requests/updateshippingdata) endpoint has an `expires` item. When the addon submits a shipping offer, it can set a deadline by which the offer has to be confirmed (the order submitted), otherwise it expires. The Shoptet ordering process checks the expiration and does not allow an order to be submitted with an expired shipping request.

## After an order is submitted

After the order is submitted, there are further steps and events for the addon:

- the order is ready for shipping
- the order was cancelled
- the shipping was changed manually (the e-shop admin can do so)
- the order changed (e.g. items were added or removed)
Events important for the shipping can be monitored using webhooks (the `order:update` event) and the [Last order changes](https://api.docs.shoptet.com/shoptet-api/openapi/orders/getlastorderchanges) endpoint. The addon has to filter the orders of interest – either by keeping a list of orders or by verifying the shipping GUID (the shipping GUID is different for each e-shop!).

Most probably, the addon will need settings for each e-shop that define which order status signals readiness for shipping and which one means cancellation.

## Order maintenance in e-shop administration

Once the order is submitted and the shipping request confirmed, the shipping options can no longer be changed in the Shoptet administration. The order and its shipping item, additional text or price can still be modified, but these changes are not synchronized to the shipping provider's system automatically. Such situations have to be clarified with the shipping company or settled manually in the shipping provider's administration.

## Shipping variants

Multiple shipping options (e.g. the company offers both package delivery and a pickup service) can be implemented in two ways:

- as two independent shipping addons
- as one addon that offers the choice in its popup during the ordering process (such as "express" delivery)

## Security and consistency

Part of the shipping options and price calculation runs in JavaScript during the ordering process. This part can easily be read and modified by a buyer who tries to cheat. It is therefore necessary to replicate all the important information to the backend through AJAX and API calls. For Shoptet, the information provided via the API on the backend is the source of truth.

It is not secure, and therefore must not be done, to pass the API access token to the frontend and call the API from the frontend JavaScript.

## Related endpoints

- [List of shipping methods](https://api.docs.shoptet.com/shoptet-api/openapi/shipping-methods/getlistofshippingmethods) – detects the methods already defined in the e-shop
- [Add shipping method](https://api.docs.shoptet.com/shoptet-api/openapi/shipping-methods/createshippingmethod) – prepares the shipping method for the e-shop owner when the addon is installed
