Introducing our brand new Rules Engine —
Read the docs
LogoLogo
Core APIOther APIsChangelog
Getting started
Getting started
  • Welcome to Commerce Layer
    • Guided setup
    • Manual configuration
  • API specification
  • API credentials
  • Authentication
    • Client credentials
    • Password
    • Authorization code
    • Refresh token
    • JWT bearer
    • Revoking a token
  • Roles and permissions
  • Fetching resources
  • Fetching relationships
  • Including associations
  • Sparse fieldsets
  • Sorting results
  • Pagination
  • Filtering data
  • Creating resources
  • Updating resources
  • Tagging resources
  • Deleting resources
  • Importing resources
  • Exporting resources
  • Cleaning up resources
  • External resources
    • External order validation
    • External prices
    • External shipping costs
    • External payment gateways
    • External promotions
    • External tax calculators
  • Rate limits
  • Handling errors
  • Real-time webhooks
  • Callbacks security
On this page
  • Circuit breaker
  • Payload format
  • Response format
  • Notifications
  • Request headers

External resources

How to manage resources via external serverless functions

PreviousCleaning up resourcesNextExternal order validation

Last updated 8 days ago

Commerce Layer lets you manage some resources (i.e. prices, promotions, payment gateways, tax calculators, and more to come) from the outside of the platform itself, using an external service of your choice or a serverless function.

In order to get the data from the external source, when needed, we trigger a POST request to the endpoint that you specified. The request contains a JSON payload that will be detailed case by case, along with the successful response (or error) format we expect to receive back.

When you create a new external resource, a shared secret is generated. It will be used each time we send data to the specified endpoint to sign the payload. The signature will be stored in the X-CommerceLayer-Signature so that you can verify the callback authenticity and consider it reliable.

Circuit breaker

All the external resources are subject to a circuit breaker check: if the call to your external endpoint fails consecutively more than 30 times, the circuit breaker opens and any further request to the resource will be skipped.

An open circuit for an external resource might result in a 422 error in some specific cases (e.g. ), but it is usually ignored with a 200 OK response status to avoid accidental side effects on the order lifecycle.

Resetting the circuit

The circuit is automatically reset anytime a call to your external endpoint succeeds before reaching the counter's threshold.

You can also reset the circuit manually by passing the _reset_circuit trigger attribute (you must use API credentials). This is also your only option in case the circuit is stuck in the open state:

curl -g -X PATCH \
  'https://yourdomain.commercelayer.io/api/external_gateways/bGHfCxZJKl' \
  -H 'Accept: application/vnd.api+json' \
  -H 'Authorization: Bearer your-access-token' \
  -H 'Content-Type: application/vnd.api+json' \
  -d '{
    "data": {
      "type": "external_gateways",
      "id": "bGHfCxZJKl",
      "attributes": {
        "_reset_circuit": true
      }
    }
  }'

You'll be notified via email every time the circuit breaker counter reaches 10 consecutive failures, as an early warning. Another notification is sent when the circuit breaker opens.

Payload format

The request payload sent to an external endpoint has the same format that you get when fetching a resource through the REST API, with some relevant resources included.

  "data": {
    "id": "resource-id",
    "type": "resource-type",
    "links": { ... },
    "attributes": {...},
    "relationships": { ... },
    "meta": { ... }
  },
  "included": [
    {
      "id": "included-resource-id",
      "type": "included-resource-type",
      "links": { ... },
      "attributes": { ... },
      "relationships": { ... },
      "meta": { ... }
    },
    { ... }
  ]
}

Response format

The response we require from the external endpoint is a JSON featuring the outcome of the operation, along with some data and error information (if any), based on what type of external resource is involved.

In case of success, you can add additional info by populating the response metadata object and messages array (that information will be stored respectively in the resource's metadata attribute and associated notifications relationship):

{
  "success": true,
    "data": {
      ...
      "messages": [ ... ],
      "metadata": {
        "foo": "bar"
     }
  }
}

In case of error, you must respond with an HTTP code >= 400. You can populate the error object with any other relevant code and message and add an additional messages array that will be stored in the resource's associated notifications relationship:

{
  "success": false,
  ...
  "error": {
    "code": "YOUR-ERROR-CODE",
    "message": "Your error message"
  },
  "data": {
    "messages": [ ... ]
  }
}

Any external endpoint has 3 seconds to respond before being timed out.

Notifications

Key
Type
Required
Description

name

String

The internal name of the notification.

body

Object

All the information to be notified.

flash

Boolean

Set it to true to mark the notification as temporary (default is false).

{
  "success": true,
  "data": {
    ...
    "messages": [
      { 
        "name": "free_item",
        "body": { "sku_code": "AAA" },
        "flash": true 
      },
      { 
        "name": "fidelity_score",
        "body": { "score": 10000 }
      }
    ],
    "metadata": { ... }
  }
}
{
  "success": false,
  ...
  "error": {
    "code": "YOUR-ERROR-CODE",
    "message": "Your error message"
  },
  "data": {
    "messages": [
      { 
        "name": "warning",
        "body": { "message": "Your error message" }
      }
    ]
  }
}

You can add notifications on your response payload whether if it's succeeded or not, just remember to specify the messages array within the data key.

Request headers

Any request sent to an external endpoint is enriched with the following headers:

Header
Description

User-Agent

The type of external request, in the format CommerceLayer {{ClassName}} (e.g. CommerceLayer ExternalGateway).

X-CommerceLayer-Signature

X-CommerceLayer-TraceId

The ID of the API request that triggered the call to external service (i.e. the trace_id exposed in the meta object of the response to that API request — useful for debugging purposes, and more).

X-CommerceLayer-Topic

Header
Description

traceparent

Uniquely identifies the request in a tracing system.

tracestate

Extends traceparent with platform-specific span or trace IDs, providing additional vendor-specific trace identification information across different distributed tracing systems.

All the external resources, with the exception of external order validation, can automatically add to the resource they are called for (for example external promotions can add notifications directly to the order on which they are performing the computation, external prices on the patched line item, etc.), as listed in the table below:

External resource
Notified resource
External order validation
External prices
External shipping costs
External payment gateways
External promotions
External tax calculators

The notifications data must be specified inside the messages node of the data key of the , and passed as an array of objects each one containing at least least the name and the body attributes (pass the flash flag if you want mark the notification as temporary):

The encrypted signature you need to .

The topic of the event that triggered the call to the callback URL (e.g. orders.place — present only in that specific case).

Additionally (e.g. if you need to trace the calls to your external endpoints on your APM) you can pass the following optional headers:

Trace Context
response
verify the callback authenticity
webhook
Line items
Shipping methods
Orders
Orders
Orders
Callbacks security
external prices
header
notifications
integration