Skip to main content

Apply B2C Commerce SDK

Learning Objectives

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

  • List four parameters you can use to instantiate a ClientConfig object.
  • Describe how to retrieve a guest token to access the B2C Commerce APIs.
  • List the Commerce SDK functions you can use to search, get search suggestions, and create a wishlist.
  • Explain how to code user registration with Commerce SDK to add products to a registered user’s wishlist.

Get Started with Commerce SDK

Vijay Lahiri, Cloud Kicks developer, is excited to begin using Salesforce B2C Commerce SDK in his back-end code to improve its maintainability. Before he integrates the SDK into his code he wants to try out a few features.

He wants to add code that:

  1. Searches for products
  2. Adds search suggestions
  3. Creates a wishlist
Note

You must have a B2C Commerce storefront to run the code snippets in this unit.

He starts by instantiating a ClientConfig object and retrieving a guest token to access the B2C Commerce APIs. He turns to the Commerce Cloud Developer Center and the Commerce SDK documentation for help.

Make the Connection

Vijay instantiates a ClientConfig object and configures its parameters. 

import { ClientConfig } from 'commerce-sdk';
// To import everything, use:
// import * CommerceSdk from "commerce-sdk";
// const { ClientConfig } = CommerceSdk;
// In CommonJS:
// const { ClientConfig } = require("commerce-sdk");
const clientConfig: ClientConfig = {
parameters: {
clientId: 'a1234567-b12345-c12345-d12345',
organizationId: 'f_ecom_abc_015',
shortCode: 'd12345',
siteId: 'cloudKicks'
}
}

Here are the ConfigObject parameters.

Variable

Description

COMMERCE_CLIENT_CLIENT_ID

Unique ID used only for API access. See Add an API Client.

COMMERCE_CLIENT_ORG_ID

Combination of realm and instance ID that’s prefixed with f_ecom_

  • A realm ID is a unique four-character ID, for example, ck01
  • An instance ID is a unique instance ID within a realm, for example, 015 for an on-demand sandbox

COMMERCE_CLIENT_SHORT_CODE

Unique region-specific merchant identifier, for example, staging-001

COMMERCE_CLIENT_API_SITE_ID

Unique site ID, for example, cloudKicks

Retrieve a Guest Token

Vijay needs a guest JWT token to make a search query. He uses the getShopperToken method of the Commerce SDK helpers class to easily retrieve it. He adds the token to the headers parameter of his clientConfig object, so that he doesn’t have to specify it every time he makes a query.

import { helpers } from 'commerce-sdk';
const token = await helpers.getShopperToken(config, { type: 'guest' });
clientConfig.headers = { authorization: token.getBearerHeader() };

Search for Products

To perform the search, Vijay creates a client of the API class he intends to communicate with, which in this case is ShopperSearch

import { Search } from 'commerce-sdk';
const searchClient = new Search.ShopperSearch(clientConfig);

He creates a parameters object with the details of his search query. He wants to search for dresses, with the maximum of 5 results returned.

const parameters = {
q: 'dress',
limit: 5
}

He uses the productSearch method to make the call.

const searchResults = await searchClient.productSearch({parameters});

With these few lines of code, Vijay created a simple script that can do product searches. What’s amazing is that if he wants to enhance this script by adding more functionality, he can reuse most of the code.

Search Suggestions

Vijay wants to add search suggestions to his search. He reviews the commerce-sdk documentation and finds the getSearchSuggestions method in the searchShopperSearch class. It’s just what he needs.

The getSearchSuggestions method documentation page

He uses the searchClient method he already configured to call the getSearchSuggestions()method to get the suggestions.

const searchSuggestions = await searchClient.getSearchSuggestions({parameters});

Create a Wishlist

Now Vijay wants to try something a little more advanced, such as creating a wishlist. That means user registration. Authentication requires an authorization token retrieved with registered user’s credentials.

Register a User

He searches the Commerce SDK documentation to determine which client and method to use for user registration. As he suspected, the client he can use is ShopperCustomers and the method to register a customer, registerCustomer.

The registerCustomer method documentation page

He creates a client and makes a call to the method.

import { Customer } from 'commerce-sdk';
const shopperCustomersClient = new Customer.ShopperCustomers(clientConfig);
await shopperCustomersClient.registerCustomer({
headers: { authorization: token.getBearerHeader() },
body: {
password: "password",
customer: {
login: "username",
email: "something@example.com",
last_name: "lastName"
}
}
});
Note

Commerce SDK does not store credentials or authorization tokens. See Security Considerations for Headless Commerce for details.

Retrieve an Authorization Token

Vijay uses his own user credentials to retrieve an authorization token with the same getShopperToken helper he used earlier to get a guest token. This time he has to encode his user credentials in base64 format and set the encoded credentials in the authorization header. When making the getShopperToken call, he must set the type field in the body to credentials.

const credentials = `${username}:${password}`;
const buff = Buffer.from(credentials);
const base64data = buff.toString("base64");
clientConfig.headers = { Authorization: `Basic ${base64data}` };
const token = await helpers.getShopperToken(clientConfig, { type: 'credentials' });

Create the Wishlist

Vijay has successfully fetched a token and already created a ShopperCustomers client. He’s all set to make a call to the createCustomerProductList method to create a wishlist.

const productList = await shopperCustomersClient.createCustomerProductList({
parameters: {
customerId: customerId,
},
headers: {
authorization: token.getBearerHeader()
},
body: {
type: "wish_list"
}
});

Vijay can now add products to and remove products from his wishlist using the createCustomerProductListItem and deleteCustomerProductListItem methods.

Troubleshoot

While working with the SDK, Vijay saw a behavior that didn’t make sense. He wants to better understand what’s going on behind the scenes, and decides that reviewing the raw requests and responses might help. He changes the logging level from WARN, the default, to DEBUG.

import { sdkLogger } from 'commerce-sdk';
sdkLogger.setLevel(sdkLogger.levels.DEBUG);
Note

The log level is global. Subsequent uses of the SDK, unless changed, print the logs at the current level of verbosity.

He sees a lot of useful information on the console, and notices the curl command for the request. While using the headers he must have changed the authorization header to an incorrect value. It was easy enough to change it back.

Next Steps

In this unit, you saw Vijay instantiate a client and retrieve a guest token to access the B2C Commerce APIs. And how he used the Commerce SDK to search for products, add search suggestions, create a wishlist, and do a little troubleshooting. Next, Vijay explores caching with Commerce SDK.

Resources

在 Salesforce 帮助中分享 Trailhead 反馈

我们很想听听您使用 Trailhead 的经验——您现在可以随时从 Salesforce 帮助网站访问新的反馈表单。

了解更多 继续分享反馈