Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 28 ยท Extending the Platform

Service Framework and Third-Party Integrations

Call external systems safely from Salesforce B2C Commerce: LocalServiceRegistry, credentials, profiles, timeouts, circuit breakers, mocks and payment or tax integrations.

A storefront rarely lives alone. It asks a tax engine for rates, a payment provider to authorize a card, a shipping service for labels, an ERP for stock. Each of those calls can be slow, fail, or hang, and in Commerce Cloud a request that waits too long hurts the whole shop, because request threads are limited and the platform enforces its own timeouts.

The Service Framework is the platform's answer. You define a service in code (what the request looks like and how to read the response), and you configure the where and how patiently in Business Manager: URL, credentials, timeout, rate limit and circuit breaker. That split is the whole point: operations can change an endpoint or switch a service off without a deployment. This lesson shows the pieces and then lets you build a tiny working model.

Code on one side, configuration on the other

flowchart LR
    S["Your script<br/>svc.call(params)"] --> F["Service framework"]
    F --> CFG["Business Manager<br/>service, credential, profile"]
    F --> X["External system"]
    X --> F
    F --> R["Result object<br/>ok, status, object, error"]
    R --> S

Your code talks to the framework; configuration decides the URL, secrets and limits.

A service in Business Manager (Administration > Operations > Services) has three parts:

  • Service: a unique ID (for example payments.psp.authorize), a type (HTTP, HTTP Form, FTP, SFTP, SOAP or generic), and links to a profile and a credential.
  • Credential: URL, user and password. Different instances can hold different credentials, so a sandbox points at the provider's test system and production at the real one. Secrets stay out of your code and out of version control.
  • Profile: the behaviour limits. Typical fields are a timeout, a rate limit (calls allowed per time interval) and a circuit breaker (how many errors in an interval before calls are blocked for a while). Check the current names and defaults in your Business Manager.

Defining a service in code

You create the service with LocalServiceRegistry.createService and a callback object. Place this in a script such as int_psp/cartridge/scripts/services/pspService.js:

JavaScript
// read-only: needs the real platform
'use strict';

var LocalServiceRegistry = require('dw/svc/LocalServiceRegistry');

function createAuthorizeService() {
    return LocalServiceRegistry.createService('payments.psp.authorize', {
        createRequest: function (svc, params) {
            svc.setRequestMethod('POST');
            svc.addHeader('Content-Type', 'application/json');
            svc.addHeader('Idempotency-Key', params.idempotencyKey);
            return JSON.stringify({
                amount: params.amountMinor,
                currency: params.currency,
                token: params.token
            });
        },
        parseResponse: function (svc, client) {
            return JSON.parse(client.text);
        },
        mockCall: function (svc, request) {
            return {
                statusCode: 200,
                statusMessage: 'OK',
                text: JSON.stringify({ status: 'authorized', id: 'mock-123' })
            };
        },
        filterLogMessage: function (message) {
            // never write card tokens or secrets to the log files
            return message.replace(/"token":"[^"]*"/g, '"token":"***"');
        }
    });
}

module.exports = { createAuthorizeService: createAuthorizeService };

The four callbacks have clear jobs:

  • createRequest builds the outgoing request (method, headers, body) from the parameters you pass to call. The URL and credentials come from the configuration.
  • parseResponse turns the raw HTTP response into the object your code works with.
  • mockCall is returned instead of a real call when the service is switched to mock mode (a Business Manager option on the service). It lets development and automated tests run without the real provider.
  • filterLogMessage cleans the request and response text before the framework logs it. Always use it for anything sensitive.

You then call it:

JavaScript
var result = createAuthorizeService().call({
    idempotencyKey: order.orderNo,
    amountMinor: 4999,
    currency: 'EUR',
    token: paymentToken
});

if (!result.ok) {
    // result.status is 'ERROR' or 'SERVICE_UNAVAILABLE'; result.error is the HTTP code
    Logger.error('PSP failed: {0} {1}', result.error, result.errorMessage);
    return { error: true };
}
var payload = result.object; // whatever parseResponse returned

call never throws for a network problem or a bad HTTP status: it returns a Result whose ok is false, with status (OK, ERROR, SERVICE_UNAVAILABLE), the HTTP code in error, a message, and the parsed object in object on success. A status of SERVICE_UNAVAILABLE generally means the framework refused or stopped the call (timeout, rate limit or open circuit breaker) rather than the remote system answering with an error. Branching on ok is therefore the standard pattern.

Timeouts, rate limits and circuit breakers

Each protection solves a different failure:

Protection Problem it solves What it does
Timeout The remote system hangs Stops waiting after N milliseconds and returns an unavailable result
Rate limit You exceed the provider's quota Rejects calls beyond a number per interval
Circuit breaker The remote system is down, and every shopper waits for the timeout After enough errors in an interval, stops calling at all for a short period, then lets calls through again to probe

The circuit breaker is the most valuable of the three. Without it, an outage of your tax engine would make every cart page wait for the full timeout, filling request threads and turning one failing integration into a site-wide slowdown. With it, the first failures open the circuit and later requests fail fast, so the page can show a fallback (an estimated tax, "shipping calculated at checkout") immediately.

Pick timeouts from the user's point of view: a call on the critical path of a page should be short (a second or two), a call in a background job can be longer. Never let a service call sit in a hook that runs on every request, such as dw.system.request.onRequest.

Mocks and testing

Real providers are slow, rate limited and sometimes billable. Use mocks:

  • Set the service to mock mode on development and test instances, and implement mockCall with realistic success and failure responses (decide by a parameter).
  • Unit-test your createRequest and parseResponse in isolation, as shown in Testing, Debugging and Logging.
  • Keep the callbacks small and move business decisions ("what do I do on failure?") into a normal function that is easy to test.

Integration notes: payments, tax and others

The same pattern covers every integration:

  • Payments. Authorization normally happens through a payment hook (dw.order.payment.authorize and friends, see Hooks and Extension Mechanisms), which uses a service to call the provider. Send an idempotency key (the order number works well), because a timeout leaves you not knowing whether the charge happened; the theory is in Idempotency and Payments Overview. Never log card data; keep the card out of your system with provider-hosted fields, which also shrinks PCI scope.
  • Tax. A tax service is called from the basket calculation. Cache or batch when you can, and define a fallback rate for outages (see Taxes).
  • Webhooks coming in are not services: they arrive as controller routes or API calls, and need signature checks and de-duplication; see Webhooks and Signatures.
  • Files (FTP or SFTP) use the same registry with a different service type; large transfers belong in jobs, covered in Jobs, Feeds and Import/Export.

Stand-ins below are teaching models, not the real framework. In particular, the platform's exact circuit breaker and rate limit semantics (what counts as an error, how long the circuit stays open) are configured in Business Manager; read the current documentation for the precise rules.

Live stand-ins

The first stand-in is a service wrapper with a timeout. Calls here are simulated with fixed latencies, so the output is always the same.

JS A service with a timeout and a result object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in adds a circuit breaker with a fake clock. Watch how the third failure opens the circuit, how the next calls fail without touching the remote system, and how a probe after the cool-down closes it again.

JS A circuit breaker that fails fast

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should the URL and password of a payment provider live?

    Credentials are configuration, not code. They differ per instance and stay out of version control.
  2. 2. service.call() returns a result with ok set to false. What is the right reaction?

    The framework returns a Result rather than throwing for network or HTTP problems. Your code must check ok and decide what to do.
  3. 3. What is the main benefit of a circuit breaker?

    When the remote system is clearly down, further calls are blocked for a while, which protects the storefront from slow pages.
  4. 4. Why does a payment service call send an idempotency key such as the order number?

    After a timeout you do not know whether the provider processed the request. The key lets the provider recognise a repeat of the same operation.

Summary

  • Define a service in code with LocalServiceRegistry.createService (createRequest, parseResponse, mockCall, filterLogMessage); configure URL, credentials and limits in Business Manager.
  • call() returns a Result: check ok, then use object, or status, error and errorMessage.
  • Timeouts, rate limits and circuit breakers protect the storefront from slow or broken partners; design fallbacks.
  • Use mock mode and small callbacks for fast development and tests, and filter sensitive data from logs.
  • Payments need idempotency keys and minimal PCI scope; tax needs fallbacks; incoming webhooks are a different mechanism.

Next, the platform's own HTTP APIs: OCAPI and SCAPI.