Skip to main content
コミュニティの新しい会話を Slack に移動するため、オンライン Trailblazer Community は 2026 年 10 月 30 日に参照のみになります。FAQ を参照

Code a B2C Commerce Web Service Integration

Learning Objectives

After completing this unit, you'll be able to:

  • Describe what a web service script does.
  • List the steps to implement SOAP or WS-Security.
  • Explain how to create a controller for a web service.
  • List the steps an admin takes before a web service goes live.
  • Describe what the webreferences2 call does.

What a Web Service Script Does

After you’ve created your Business Manager configurations, you can start writing the code that powers the integration: a web service script, a controller, and any extra steps required for SOAP and WS-Security. In this unit, you learn the coding side of web service development and walk through what happens before a service goes live.

A web service script is the code that connects your storefront logic to an external service. It has four responsibilities.

  1. Obtain a Service object. The script calls LocalServiceRegistry.createService() with two arguments: the name of a service configuration defined in Business Manager, and a callback object. The callback object provides the handlers—createRequest, parseResponse, and mockCall—that the service framework invokes at the appropriate points during the call.
  2. Configure and invoke the service. The script calls Service.call() to invoke the web service. Before calling the services, the framework checks the rate limiter and circuit breaker. If either trips, the framework skips the call. If not, the framework runs your callbacks in sequence.
  3. Handle errors. After Service.call() returns, the script inspects the Result object. Use result.ok to check for success, result.error for service-specific error codes such as an HTTP 404, and result.errorMessage for exception details such as a SocketTimeoutException. To throw a JavaScript error on failure instead of inspecting the result manually, call service.setThrowOnError().call().
  4. Pass output to the pipeline dictionary or controller. For pipeline-based storefronts, the script writes output variables to the pipeline dictionary for use by the rendering template. For SFRA controllers, embed the web service script directly in the controller rather than writing it as a separate file.

Example: Minimal HTTP Service Script

This script puts the four responsibilities into a single HTTP service. It registers a service named mycartridge.http.payment.authorize (that name must match a service configuration in Business Manager) and implements the three callbacks an HTTP service typically uses: createRequest, parseResponse, and mockCall.

  • createRequest configures the request from the arguments you pass to Service.call(). It sets the HTTP method and headers, then returns the request body. The HTTP service uses that return value as the body, call JSON.stringify() explicitly when you send JSON.
  • parseResponse receives the HTTPClient and converts client.text into the object that Service.call() returns.
  • mockCall supplies a simulated response when the service mode in Business Manager is Mocked, so you can test without calling the live endpoint.
  • After Service.call(), check result.ok. On success, pass result.object to the controller or pipeline dictionary. On failure, inspect result.status and result.errorMessage.
var LocalServiceRegistry = require('dw/svc/LocalServiceRegistry');
var paymentService = LocalServiceRegistry.createService('mycartridge.http.payment.authorize', {
    createRequest: function (svc, args) {
        svc.setRequestMethod('POST');
        svc.addHeader('Content-Type', 'application/json');
        return JSON.stringify(args);
    },
    parseResponse: function (svc, client) {
        return JSON.parse(client.text);
    },
    mockCall: function (svc, client) {
        return { statusCode: 200, statusMessage: 'Success', text: '{"authorized": true}' };
    }
});
var result = paymentService.call(requestData);
if (result.ok) {
    // pass result.object to the controller or pipeline dictionary
} else {
    // inspect result.status and result.errorMessage
}

Implement SOAP and WS-Security

SOAP services require more setup beyond a standard HTTP integration. Follow these steps for implementation.

  1. Create the required files. At a minimum, include a .wsdl file for the web service. If you're using WS-Security, also include a Java keystore file (.jks or .pkcs12) with the same base filename as the WSDL. If your WSDL has namespace collisions or underscore characters in element names, also include a .wsdl.properties file—again with the same base filename.
  2. Place the files in the webreferences2 folder. All three files belong in the webreferences2 directory of your cartridge. B2C Commerce uses matching filenames to associate the keystore and properties file with the correct WSDL.
  3. Add a SOAP service definition to your service registry. A SOAP service definition requires four callbacks:
    • initServiceClient: Obtains a webreferences2 object and service port, and sets svc.serviceClient. Required only for SOAP.
    • createRequest: Creates the request object and, for WS-Security, builds the security HashMaps.
    • execute: Makes the actual service call using svc.serviceClient.
    • parseResponse: Converts the response into the object returned by Service.call().
  4. For WS-Security, build request and response security HashMaps in createRequest. Create a secretsMap with your client key password, service key password, and username. Create a requestCfg HashMap that sets WSUtil.WS_ACTION to the interceptor actions (timestamp, signature, encryption), and sets the corresponding keystore type, password, and alias. Create a matching responseCfg HashMap for the response. Pass both into WSUtil.setWSSecurityConfig(port, requestCfg, responseCfg).
  5. Run the pipeline to generate WSDL classes. B2C Commerce uses Apache CXF to generate script classes from the WSDL when you first run a pipeline containing the webreferences2 reference. Run this pipeline at least once even if your integration ultimately uses an OCAPI hook rather than a pipeline to generate the classes. Download the generated API in Studio by selecting your server connection and selecting Download Web Service API.
Note

If the WSDL changes, run the pipeline again to regenerate the classes.

Creating a Controller for a Web Service

When you create an SFRA controller that calls a web service, handle two things.

Error handling: The controller checks the result of the service call and responds appropriately when the call fails. Inspect result.ok, result.status, and result.errorMessage. Common failure states are a tripped circuit breaker (Failure Count Exceeded), a rate limit violation (Rate Limit Exceeded), and a timeout (SocketTimeoutException: Read timed out). Use this information to return a meaningful error response or fallback behavior to the shopper.

Rendering results: If the service call succeeds, the controller renders the results, typically by passing result.object to an ISML template or returning it as a JSON response. Because SFRA controllers don't use a pipeline dictionary, you pass data directly to the template or response writer.

Unlike pipeline-based integrations—where the web service script lives in a separate script node with an explicit error transition—an SFRA controller can embed the service definition and invocation in the controller itself, reducing the number of files to maintain.

Admin Steps Before a Web Service Goes Live

Deploying a web service integration to production requires four steps performed by a B2C administrator.

  1. Configure credentials, private keys, and certificates on each instance. Credentials and certificates don’t replicate. Create them manually on the Development and Production instances. In Business Manager, go to Administration | Operations | Private Keys to import TLS certificates or private key files (.p12 or .pfx). For WS-Security, keystores go in the cartridge itself; import other certificates through Business Manager.
  2. Push code to each instance using code replication. Upload the updated cartridge (including the webreferences2 folder) to your Development and Production instances. This upload makes your scripts, WSDL files, and keystores available on each server.
  3. Export and import service configurations. In Business Manager, go to Administration | Operations | Import & Export | Service. Export your service configurations, profiles, and credentials from the source instance and import them into each target instance. This import confirms that the framework configurations match your code on every instance.
  4. Activate the service. B2C Commerce disables new service configurations by default. In Business Manager, go to Administration | Operations | Services, open the service configuration, and select Enabled. Also confirm that Service Mode is set to Live—not Mocked—so that calls go to the real endpoint.

What the webreferences2 Call Does

webreferences2 is the B2C Commerce mechanism for invoking SOAP web services defined by a WSDL file.

When you reference a webreferences2 object in a script and run the associated pipeline, B2C Commerce uses Apache CXF to read the WSDL and automatically generate script classes that represent the service's operations and data types. B2C Commerce places these classes in the webreferences2 namespace, scoped to the WSDL filename. For example, for HelloWorld.wsdl, the generated namespace is webreferences2.HelloWorld.

You use these generated classes in your initServiceClient callback to get a WebReference2 object and call getDefaultService() to obtain a port—the typed proxy that exposes the WSDL's operations as callable methods. Store the port as svc.serviceClient. The execute callback uses it to make the actual call.

initServiceClient: function () {
    this.webReference = webreferences2.HelloWorld;
    return this.webReference.getDefaultService();
},
execute: function (svc, requestObject) {
    return svc.serviceClient.hello(requestObject);
}

If the WSDL contains elements whose names conflict across namespaces, set namespace=true in the .wsdl.properties file to generate namespace-qualified class names, and then reference objects using their fully qualified names in your script. If element names contain underscores, set underscoreBinding=asCharInWord in the same file to prevent code-generation errors.

Next Up

In this unit, you learned the code required for an B2C Commerce web service integration, including how to structure the web service script and implement SOAP services. Next, build on this knowledge by covering the critical security aspects of these integrations, from the OSI model and secure protocols, to configuring transport and application layer security.

Resources

Salesforce ヘルプで Trailhead のフィードバックを共有してください。

Trailhead についての感想をお聞かせください。[Salesforce ヘルプ] サイトから新しいフィードバックフォームにいつでもアクセスできるようになりました。

詳細はこちら フィードバックの共有に進む