0% found this document useful (0 votes)
75 views283 pages

CME Digital Commerce PDF-en

Uploaded by

maja_stojanova
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views283 pages

CME Digital Commerce PDF-en

Uploaded by

maja_stojanova
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 283

Digital Commerce

Copyright 2021 Vlocity LLC, a Salesforce company. All rights reserved. Information in this document is subject to change without
notice. This documentation and the software, tools, templates and other material described in this document (“Vlocity Materials”) are
furnished exclusively under a subscription services agreement or nondisclosure agreement. The Vlocity Materials may be used or
copied only in accordance with the terms of those agreements. No part of the Vlocity Materials may be reproduced, stored in a
retrieval system, or transmitted in any form or any means electronic or mechanical, including photocopying or recording for any
purpose other than the licensee’s personal use as set forth in the applicable agreement without the prior written permission of Vlocity
LLC. Vlocity is a trademark of Vlocity LLC, a Salesforce company, as are other names and marks. Other marks appearing herein may
be trademarks of their respective owners.
Digital Commerce

Table of Contents
Digital Commerce ....................................................................................................................... 1
Digital Commerce APIs ....................................................................................................... 1
Digital Commerce SDK ....................................................................................................... 1
Web Components ............................................................................................................... 2
Digital Commerce Lightning Web Components ............................................................. 2
Digital Commerce Web Components ............................................................................ 2
Vlocity Digital Cache Management ....................................................................................... 2

Guest User Security Restrictions ................................................................................................. 3


Cart-Based APIs ................................................................................................................. 3
/carts ......................................................................................................................... 3
/cpq/carts/* ................................................................................................................. 3
/cpq/carts/*/attributes .................................................................................................. 3
/cpq/carts/*/cancel ...................................................................................................... 3
/cpq/carts/*/items ........................................................................................................ 4
/cpq/carts/*/items/checkout .......................................................................................... 4
/cpq/carts/*/items/*/itemattributes ................................................................................. 4
/cpq/carts/*/items/*/pricing ........................................................................................... 4
/cpq/carts/*/price ......................................................................................................... 4
/cpq/carts/*/pricelists ................................................................................................... 5
/cpq/carts/*/products ................................................................................................... 5
/cpq/carts/*/promotions ............................................................................................... 5
/cpq/catalogs/* ............................................................................................................ 5
Digital Commerce APIs ....................................................................................................... 5
/carts ......................................................................................................................... 5
/catalogs/*/basket/* ..................................................................................................... 6
/catalogs/*/offers/* ....................................................................................................... 6
See Also ............................................................................................................................ 6

Digital Commerce Cache Management ........................................................................................ 7


See Also ............................................................................................................................ 7
Digital Commerce API Caching ............................................................................................ 8
On-Platform Solution ................................................................................................... 9
Off-Platform Solution ................................................................................................... 9
Preparing to Use Vlocity CPQ API Caching ......................................................................... 10
Initializing the API Cache .................................................................................................... 12
Updating the API Cache ..................................................................................................... 14
Running Maintenance and Digital Commerce Cache Jobs Remotely ..................................... 15
Product Hierarchy Maintenance .................................................................................. 16
Clear Managed Platform Cache .................................................................................. 16

© 2021 Vlocity LLC, a Salesforce


company
Digital Commerce

Refresh Platform Cache ............................................................................................. 16


ClearCacheBatch ...................................................................................................... 16
Clear Cache .............................................................................................................. 17
Check Job Status ...................................................................................................... 17
ContextEligibilityGenerator Job ................................................................................... 17
Generate Full Cache .................................................................................................. 17
GetOffersHierarchyHelper Job .................................................................................... 18
GetOffers Job ............................................................................................................ 18
GetContainsOffers Job ............................................................................................... 18
GetPrices Job ............................................................................................................ 18
GetOfferDetails Job ................................................................................................... 19
Generating the Cache for Specific Catalogs ................................................................ 19
Regenerate Cached API Records ............................................................................... 19
See Also ................................................................................................................... 19
Running Digital Commerce Cache Jobs Remotely with API .................................................. 20
See Also ................................................................................................................... 22
Updating the AWS Cache ................................................................................................... 22
Prerequisites ............................................................................................................. 22
Update the AWS Cache Using a Batch Job ................................................................. 22
Update the AWS Cache Using a REST API ................................................................. 22
Invoke Cache Migration when OAuth2 is Deployed ...................................................... 23
Configure Remote Site Setting .................................................................................... 24
Troubleshooting ......................................................................................................... 24

Digital Commerce (Cacheable) APIs ........................................................................................... 26


Digital Commerce API Usage Considerations ...................................................................... 26
Get Offers By Catalog ................................................................................................ 27
Get Offer Details ........................................................................................................ 28
Get Contains Products ............................................................................................... 28
Post Offer Details with Configuration ........................................................................... 29
Basket API ................................................................................................................ 29
Create Basket with Basket Action ............................................................................... 29
Price ......................................................................................................................... 30
Context Eligibility (Products and Promotions) Rules Limitations .................................... 30
Pricing Context Rules (Tightest Match) ........................................................................ 31
Create Cart ............................................................................................................... 32
Cache Management ................................................................................................... 32
Performance Considerations ...................................................................................... 32
Detailed API Parameters and Calling Information ......................................................... 33
Digital Commerce API Response Optimization ............................................................ 33
Context Eligibility Rules .............................................................................................. 40
Multi-Transaction Service ........................................................................................... 41
Sample Implementation to Override the 255-Character Limitation ................................. 48
Troubleshooting Digital Commerce API Calls ............................................................... 50

© 2021 Vlocity LLC, a Salesforce


company
Digital Commerce

Attribute Basket Cache Exclusion ............................................................................... 53


Digital Commerce API Quick-Start Guide ............................................................................ 57
Before You Begin ....................................................................................................... 57
API Task Reference ................................................................................................... 58
Getting Things Ready ................................................................................................ 58
Retrieve OAuth Authorization ..................................................................................... 61
Run the API Examples ............................................................................................... 62
See Also ................................................................................................................... 72
Digital Commerce API Swagger Reference ......................................................................... 72
Browse Operations ............................................................................................................ 72
Get Offers by Catalog API .......................................................................................... 73
Get Featured Offers API ............................................................................................. 78
Get Contains Products API ......................................................................................... 80
Get Offer Details API .................................................................................................. 81
Post Offer Details with Configuration API ..................................................................... 83
Basket Operations ............................................................................................................. 86
Get Basket Details API ............................................................................................... 86
Create Basket with BasketAction ................................................................................ 87
Update Basket Contents API ...................................................................................... 91
Add Multiple Products to a Basket ............................................................................. 102
Basket Validation ..................................................................................................... 109
Use Trim Mode to Decrease Overhead ..................................................................... 119
Check Out Operations ...................................................................................................... 135
Create Cart from Basket ........................................................................................... 135
Digital Commerce Remote Calls ....................................................................................... 145
Sample Remote Calls .............................................................................................. 145
POST API Sample Calls ........................................................................................... 148

Digital Commerce SDK ............................................................................................................ 154


SDK Proxy Support .......................................................................................................... 156
SDK Core Class Structure and Methods ............................................................................ 156
.............................................................................................................................. 157
SDK Usage Examples (Fall '20 version) ............................................................................ 158
Example Code ......................................................................................................... 158
SDK Example: Get Cart Details (Fall '20 version) ....................................................... 159
SDK Example: getCatalogOffers with the contains parameter (Fall '20 version) .......... 160
SDK Example: Get filtered list of products and promotions (Fall '20) ............................ 160
SDK Example: Get List of Promotions or Promotions associated with a Product (Fall
'20) ......................................................................................................................... 161
SDK Example: getOfferDetails via API (Fall '20) ......................................................... 162
SDK Example: ValidateOffer (Fall '20) ....................................................................... 162
SDK Example: Add to Cart with Configuration Changes (Fall '20) ............................... 163
SDK Example: Add to Cart with No Configuration Changes (Fall '20) .......................... 164
SDK Example: Delete From Basket (Fall '20) ............................................................. 164

© 2021 Vlocity LLC, a Salesforce


company
Digital Commerce

SDK Example: Add a Child Product to the Basket (Fall '20) ........................................ 166
SDK Example: Delete a Child Product from the Basket (Fall '20) ................................. 167
SDK Example: Update Items in Basket (Fall '20) ........................................................ 168
SDK Example: Checkout Cart (Fall '20) ..................................................................... 169
SDK Example: Create a Basket from an Asset (Fall '20) ............................................. 170
SDK Example: Sign Out User (Fall '20) ..................................................................... 170
SDK Usage Examples (Winter '20 version) ........................................................................ 171
Example Code ......................................................................................................... 171
SDK Example: getCatalogOffers without the contains parameter (Winter '20) ............. 172
SDK Example: getCatalogOffers with the contains parameter (Winter '20) .................. 173
SDK Example: Create and Submit the Order (Winter '20) ........................................... 173
SDK Example: Get List of Promotions or Promotions associated with a Product
(Winter '20) ............................................................................................................. 174
SDK Example: getOfferDetails via API (Winter '20) .................................................... 175
SDK Example: ValidateOffer (Winter '20) ................................................................... 176
SDK Example: Add to Cart with Configuration Changes (Winter '20) ........................... 176
SDK Example: Add to Cart with No Configuration Changes (Winter '20) ...................... 177
SDK Example: Delete From Basket (Winter '20) ........................................................ 178
SDK Example: Add a Child Product to the Basket (Winter '20) .................................... 179
SDK Example: Delete a Child Product from the Basket (Winter '20) ............................ 180
SDK Example: Update Items in Basket (Winter '20) ................................................... 181
SDK Example: Get Cart Details (Winter '20) .............................................................. 182
SDK Example: Checkout Cart (Winter '20) ................................................................. 183
SDK Example: Create a Basket from an Asset (Winter '20) ......................................... 183
SDK Example: Authenticate a User (Winter '20) ......................................................... 184
SDK Example: Update Billing and Shipping Details (Winter '20) .................................. 185
SDK Example: Save the Cart (Winter '20) .................................................................. 186
SDK Example: Get Filtered List of Products and Promotions (Winter '20) .................... 187
Setting Up the Pubsub SDK (Winter '20) ................................................................... 188
SDK Usage Examples (Fall '19 version) ............................................................................ 188
Example Code ......................................................................................................... 188
SDK Example: getCatalogOffers without the contains parameter (Fall '19) ................. 189
SDK Example: getCatalogOffers with the contains parameter (Fall '19) ...................... 190
SDK Example: getOfferDetails via API (Fall '19) ......................................................... 191
SDK Example: ValidateOffer (Fall '19) ....................................................................... 191
SDK Example: Add a Configured Offer to the Cart (Fall '19) ....................................... 192
SDK Example: Add to Cart with No Configuration Changes (Fall '19) .......................... 192
SDK Example: Add to Cart with Configuration Changes (Fall '19) ............................... 193
SDK Example: Delete From Basket (Fall '19) ............................................................. 194
SDK Example: Delete a Child Product from the Basket (Fall '19) ................................. 195
SDK Example: Add a Child Product to the Basket (Fall '19) ........................................ 196
SDK Example: Update Items in Basket (Fall '19) ........................................................ 197
SDK Example: Get Cart Details (Fall '19) .................................................................. 198
SDK Example: Checkout Cart (Fall '19) ..................................................................... 199
Setting Up the Pubsub SDK (Winter '20) ................................................................... 200
Digital Commerce SDK Troubleshooting ............................................................................ 200

© 2021 Vlocity LLC, a Salesforce


company
Digital Commerce

Example 1: SDK returns 0 or null, or does not return correct data ............................... 200
ServerSDK Overview ....................................................................................................... 203
ServerSDK Architecture ........................................................................................... 204
Pros and Cons of running Digital Commerce SDK on a server .................................... 206
Pros and Cons of Running the Server on the Client .................................................... 206
APIs supported by ServerSDK .................................................................................. 206
SDK implementation ................................................................................................ 207
Server SDK Installation .................................................................................................... 207
Running ServerSDK on a local computer (optional) .................................................... 210
Running SDK Server in a Heroku Environment .......................................................... 211
ServerSDK Client Setup and Usage .................................................................................. 217
Client-Side SDK ...................................................................................................... 217
Proxy SDK .............................................................................................................. 217
Digital Commerce Web Component Setup ................................................................. 218
Redirect Authentication Reference Application ................................................................... 220
Authentication Logic Layer ....................................................................................... 221
UI Layer (Views) ...................................................................................................... 221
Authorization Flow ................................................................................................... 221

Digital Commerce Lightning Web Components .......................................................................... 223


Working With Digital Commerce Lightning Web Components in a Managed Package .......... 224
Changing the Theme or the CSS .............................................................................. 224
Replacing or Overriding the LWC HTML Template ..................................................... 225
Modifying a Small Portion of the LWC HTML Template ............................................... 226
Replacing or Overriding LWC css if not using an NDS library ...................................... 227
Overriding a Specific LWC JavaScript Method ........................................................... 228
Configuring the SDK That is Used by All Digital Commerce LWCs .............................. 229
Reading the LWC HTML Source Code ...................................................................... 229
Reading the LWC CSS ............................................................................................. 230
Reading the LWC JavaScript .................................................................................... 231

Digital Commerce Web Components ......................................................................................... 233

Digital Commerce API Context Rules for Logged In Users .......................................................... 236
Context Dimensions ......................................................................................................... 236
Digital Commerce API Caching Mechanism ....................................................................... 239
Context Shapes ....................................................................................................... 240
Best Practices ......................................................................................................... 244

Digital Commerce Artifacts ....................................................................................................... 246


Digital Commerce Lightning Web Component Artifacts ....................................................... 249
Digital Commerce Lightning Web Components only ................................................... 250

© 2021 Vlocity LLC, a Salesforce


company
Digital Commerce

Digital Commerce Lightning Web Components With OmniScript support ..................... 250
Digital Commerce Web Components and SDK for Off-Platform Use ............................ 250

Digital Commerce Gateway (DCG) Overview ............................................................................. 251


DCG Setup ...................................................................................................................... 251
Additional Resources ............................................................................................... 252
DCG Connected App Setup ...................................................................................... 252
DCG OAuth2 Setup and Usage ................................................................................ 261
DCG Troubleshooting ...................................................................................................... 272
Health check endpoints used for validation and troubleshooting .................................. 272
Troubleshooting Steps ............................................................................................. 272
HTTP Status Codes and Meanings ........................................................................... 273

© 2021 Vlocity LLC, a Salesforce


company
Digital Commerce

Digital Commerce

Vlocity Digital Commerce is a cloud-based solution that enables high-volume browsing and configuration of
product offers on digital self-service channels. Vlocity Digital Commerce is industry-specific and works with
Vlocity Communications, Media, and Energy verticals to provide a catalog-driven, unified commerce
solution.

The Vlocity Digital Commerce solution provides for both anonymous and known user scenarios and is
applicable (but not limited to) self-service channel scenarios. Digital Commerce is fully integrated with
ancillary Vlocity products such as CLM, Order Management, and CPQ for call-center agents.

Digital Commerce implements both a Digital Commerce tier and on-platform caching, which provide
advanced order-capture and guided-selling capabilities. These capabilities offer best-fit products and
services to customers with the ability to scale with demand together with speed and reliability.

Digital Commerce offers the following:

• A reduced time-to-market through catalog-driven Digital Commerce


• A compelling UI engagement
• Improved response times using intelligent caching
• The ability to manage peak traffic using elastic scaling
• A reduced load on the Salesforce platform by offloading static calls

Digital Commerce APIs


The Vlocity Digital Commerce APIs extend catalog-driven product selection and configuration. These APIs
reduce time-to-market, improve response times, and support anonymous browsing and configuration.

Using the Digital Commerce APIs, you can retrieve a list of Products and Promotions along with their
details and configuration without the need for a Salesforce Opportunity, Quote, or Order record.

Digital Commerce API Caching allows you to offload static calls from constrained services, accelerate
website responsiveness during peak events, and extend the dynamic range of the omnichannel solution.

Digital Commerce APIs also include a Cache Generator that generates the cache to accommodate
anticipated high-volume API call activity. The API Response Cache allows you to cache high volume API
calls on the Salesforce Platform for on-platform solutions. For additional scalability, Vlocity recommends
taking advantage of an off-platform configuration, which allows you to cache high volume API calls on the
elastic Amazon Web Services (AWS) platform.

See Digital Commerce APIs.

Digital Commerce SDK


The SDK provides a layer of abstraction between the user interface and the Digital Commerce APIs and
was developed using Pure JS UI libraries framework and a platform-agnostic approach. The SDK is
extensible and versioned with Node JS Module Delivery.

© 2021 Vlocity LLC, a Salesforce


company 1
Digital Commerce

You use the Vlocity Digital Commerce Software Development Toolkit (SDK) to improve usability and reduce
the effort to deliver a compelling UI. The SDK consolidates common application and business front-end
logic to reduce errors by validated API parameters.

Vlocity recommends using the SDK to communicate with the Digital Commerce APIs.

See Digital Commerce SDK.

Web Components
Vlocity provides two sets of web components; one set, the Digital Commerce Lightning Web Components,
are for use on the Salesforce platform, while the other, the Digital Commerce Web Components, can be
leveraged for off-platform use.

Digital Commerce Lightning Web Components


Vlocity Lightning Web Components are fast, lightweight, and reusable. They support every major browser
and use the same standards as Salesforce Lightning Web Components. The Digital Commerce Lightning
Web Components are for use on the Salesforce platform.

Vlocity Digital Commerce Lightning Web Components use JavaScript to extend the HTML element using
templates and custom logic. They provide the ability to segment CSS and JavaScript from the main
document. Vlocity provides reusable HTML templates and support for Lightning Web Components. See
Digital Commerce Lightning Web Components.

Digital Commerce Web Components


The Vlocity Digital Commerce Web Components are fast and lightweight, reusable, and support every
major browser. Vlocity Digital Commerce Web Components can be used either on.the Salesforce platform
or off-platform.

Web Components are JavaScript methods that extend HTML elements using templates and custom logic.
Web Components provide the ability to segment CSS and JS from the main document. Vlocity provides
reusable HTML templates and support for Digital Commerce Web Components. See Digital Commerce
Web Components.

Vlocity Digital Cache Management


The Cache Management system reduces the time it takes to generate the cache in the event of Vlocity
Product Model changes. The Cache Management system supports updates to the on-platform cache and
the Digital Commerce Tier cache.

The Cache Manager offers the ability to generate the cache for one or more specific catalogs. Cache
Management also provides support for REST API and JavaScript Remote actions for Cache Regeneration.

See Digital Commerce API Caching, Initializing the API Cache, and Preparing to Use Vlocity CPQ API
Caching.

© 2021 Vlocity LLC, a Salesforce


company 2
Digital Commerce

Guest User Security Restrictions

Beginning with the Winter '21 Salesforce release, Guest Users, also called anonymous users, cannot
access any records by default. This affects all Salesforce orgs.

For more about Vlocity's guest user implementation, see Guest User Enhancements Overview.

Beginning with CME Spring '20 Minor Release, Vlocity does not allow guest users to create and update
records by default with the exception of Cart-Based and Digital Commerce APIs listed in this topic.

Cart-Based APIs
The following URIs and their corresponding Cart-Based REST APIs, remote actions, and CpqAppHandler
calls allow guest users to create and update records.

/carts
Create Cart

POST /carts

/cpq/carts/*

• Get Cart Summary


GET /cpq/carts/{encrypted_cart_ID}
• Update Cart Summary
PUT /cpq/carts/{encrypted_cart_ID}

/cpq/carts/*/attributes
Get Filterable Attributes

GET /cpq/carts/{encrypted_cart_ID}/attributes

/cpq/carts/*/cancel

• Cancel Order
POST /cpq/carts/{encrypted_cart_ID}/cancel
• Create Supplemental Order
POST /cpq/carts/{encrypted_order_ID}/cancel
• Send Updates on Cancellations
PUT /cpq/carts/{encrypted_cart_ID}/cancel
• Submit a Cancel Order Request
POST /v2/cpq/carts/{encrypted_order_ID}/cancel

© 2021 Vlocity LLC, a Salesforce


company 3
Digital Commerce

/cpq/carts/*/items
• Add Items to Cart
POST /cpq/carts/{encrypted_cart_ID}/items
• Add to Cart
POST /cpq/carts/{encrypted_cart_ID}/items
• Get Cart Items
GET /cpq/carts/{encrypted_cart_ID}/items
• Get Line Items by ID
GET /cpq/carts/{encrypted_cart_ID}/items
• Remove Items from Cart
DELETE /cpq/carts/{encrypted_cart_ID}/items
• Update Items in Cart
PUT /cpq/carts/{encrypted_cart_ID}/items

/cpq/carts/*/items/checkout
• Checkout Items in Cart
POST /cpq/carts/{encrypted_cart_ID}/items/checkout
• Check Status of the Cart
GET /cpq/carts/{encrypted_cart_ID}/items/checkout

/cpq/carts/*/items/*/itemattributes
Update Item Attributes

PUT /cpq/carts/{encrypted_cart_ID}/items/{itemId}/itemattributes)

/cpq/carts/*/items/*/pricing
• Apply Adjustment
POST /cpq/carts/{encrypted_cart_ID}/items/{itemId}/pricing
• Applies an Adjustment (Discount, Markup, or Override to a Price)
PUT /cpq/carts/{encrypted_cart_ID}/items/{itemId}/pricing
• Delete Adjustment
DELETE /cpq/carts/{encrypted_cart_ID}/items/{itemId}/pricing
• Get Price Waterfall for Price
GET /cpq/carts/{encrypted_cart_ID}/items/{itemId}/pricing

/cpq/carts/*/price
• Price Items in Cart (Query)
GET /cpq/carts/{encrypted_cart_ID}/price
• Run Pricing for Items to Cart
POST /cpq/carts/{encrypted_cart_ID}/price

© 2021 Vlocity LLC, a Salesforce


company 4
Digital Commerce

/cpq/carts/*/pricelists
Get Price Lists for Cart

GET /cpq/carts/{encrypted_cart_ID}/pricelists

/cpq/carts/*/products
• Get Details of Product
GET /cpq/carts/{encrypted_cart_ID}/products/{pricebookEntryId}
• Get List of Products
GET /cpq/carts/{encrypted_cart_ID}/products
• Get Products by ID
GET /v2/cpq/carts/{encrypted_cart_ID}/products?{id}&includeAttachment=[true|
false]

/cpq/carts/*/promotions
• Add Promotion to Cart
POST /cpq/carts/{encrypted_cart_ID}/promotions
• Delete Applied Promo Items
DELETE /cpq/carts/{encrypted_cart_ID}/promotions
• Get Applied or Available Promotions for Cart
GET /cpq/carts/{encrypted_cart_ID}/promotions
• Get Cart Promotions
GET /cpq/carts/{encrypted_cart_ID}/promotions
• Post Cart Promotion Items
POST /cpq/carts/{encrypted_cart_ID}/promotions

/cpq/catalogs/*
Get Catalog Information

GET /cpq/catalogs

Digital Commerce APIs


The following URIs and their corresponding Digital Commerce APIs allow guest users to use the basket
and offer operations. The Create Basket with BasketAction API creates and updates records for guest
users.

Digital Commerce APIs that use a context key must encrypt them.

/carts
Create Cart from Basket

POST /carts

© 2021 Vlocity LLC, a Salesforce


company 5
Digital Commerce

/catalogs/*/basket/*
• Create Basket with BasketAction
POST /catalogs/{catalogcode}/basket
• Get Basket Details API
GET /catalogs/{catalogcode}/basket/{basketkey}
• Update Basket Contents API
POST /catalogs/{catalogcode}/basket/{basketkey}

/catalogs/*/offers/*
• Get Offers by Catalog API
GET /catalogs/{catalogcode}/offers
• Get Offer Details API
GET /catalogs/{catalogcode}/offers/{offercode}
• Post Offer Details with Configuration API
POST /catalogs/{catalogcode}/offers/{offercode}

See Also
• Salesforce's Guest User Record Access Development Best Practices
• Salesforce's Guest User Security Policies and Timelines
• Give Secure Access to Unauthenticated Users with the Guest User Profile
• Salesforce Guest User - How to Test and Update Sharing Settings

© 2021 Vlocity LLC, a Salesforce


company 6
Digital Commerce

Digital Commerce Cache Management

When Digital Commerce API calls are made, the API response cache is checked before processing the
request. If a response to a request is in the cache, the response is returned to the client without further
processing. If the specific request is not in the cache (a cache miss), the API will run Vlocity CPQ services
to calculate the response, return the response to the user, and store the response in the cache for future
use.

Any time you make changes to your products, promotions, rules or pricing in your catalogs, you must
refresh the Digital Commerce API cache before those changes will appear to your users.

The Digital Commerce API cache stores catalog data for quicker retrieval of information from API calls.
Digital Commerce cache management provides the ability to update or recreate the cache, for either on-
platform or off-platform solution architectures.

Starting with the CME Winter '20 release, you can update or create the cache on either the Salesforce
platform or Amazon Web Services (AWS). You can create new cache data or update existing cache data by
running either Apex jobs or REST API calls. You can also update the cache for all catalogs or for one or
more specific catalogs.

For a description of the purpose of each of the Digital Commerce batch jobs, see Preparing to Use Vlocity
CPQ API Caching. For an overview of Digital Commerce caching, see Digital Commerce API Caching.

Run one or more of the following batch jobs to prepare, manage, and refresh the cache:

• Load API Metadata: Populate the Vlocity API Metadata table. This job should only be only run one time.
See Preparing to Use Vlocity CPQ API Caching.
• Populate API Cache: Process existing data and to populate the API cache. See Initializing the API Cache
for information about the options available when running the batch job. See Preparing to Use Vlocity
CPQ API Caching for prerequisite information.
• Delete Expired Cache: Prior to the CME Winter '20 release, this batch job was used to delete expired
cache entries when changes to the product model were made. Starting with the CME Winter '20 release,
cache management is automatic and this batch job is not required.
• Delete Pseudo Records: Delete pseudo account records that were created by Digital Commerce API
calls prior to the CME Winter '20 release. These pseudo account records are no longer created as of the
CME Winter '20 release and there is no longer a need to run this job unless your org contains pseudo
records that were created before the CME Winter '20 release. See Delete Pseudo Records.
• Regenerate Cached API Records: Run when your product model or sales catalog has been modified.
Running this job re-generates the cached API response objects. See Updating the API Cache.
• Migrate Cache Records: (Beta) Synchronizes cache records with off-platform caching systems, such as
AWS. This job should be run only when you are using an off-platform solution. See Updating the AWS
Cache.

See Also
Preparing to Use Vlocity CPQ API Caching

© 2021 Vlocity LLC, a Salesforce


company 7
Digital Commerce

Digital Commerce API Caching

Vlocity Digital Commerce APIs are RESTful Web APIs that are designed to enable client applications such
as consumer-facing web and mobile apps to shop for products and services. Digital Commerce API caching
is optimized for consumer shopping use cases where the user is often anonymous until well into the check-
out process.

The APIs are also optimized to enable caching of API responses to provide additional performance and
scalability. In addition, the APIs are optimized for lower bandwidth connections between the client
application and the server by minimizing the metadata returned in the response.

When Digital Commerce API calls are made, the API response cache is checked before processing the
request. If a response to a request is in the cache, the response is returned to the client without further
processing. If the specific request is not in the cache (a cache miss), the API will run Vlocity CPQ services
to calculate the response, return the response to the user, and store the response in the cache for future
use.

Vlocity Digital Commerce API Caching provides cache administration controls to populate and delete the
cache using Vlocity CMT Administration pages. See Digital Commerce Cache Management.

A Vlocity catalog (or multiple catalogs) is required for shopping and browsing.

Vlocity Digital Commerce API caching uses the Vlocity context rules framework. The product administrator
defines context dimensions and rules which determine all permutations of a customer shape. Context rules
are evaluated for each product and cached against these permutations in an object inside Salesforce.

The Vlocity Omnichannel REST APIs simplify client application development by hiding the details of internal
CPQ processing. Client-side developers do not need to understand details of the underlying CPQ logic;
there is no need to know the proper order to apply eligibility and availability rules, and no need to learn the
methods of the underlying CPQ rules engines and other CPQ services.

The Vlocity Communications API Caching suite of Configure Price Quote (CPQ) Services is based on
modern, enterprise-scale Omnichannel Web application programming interfaces (APIs). The web APIs are
designed for use by web and mobile developers to extend Vlocity Industry Cloud Application functionality to
other applications, devices, and channels.

Vlocity Omnichannel Web APIs include a comprehensive set of CPQ-specific Web APIs that you use to
develop a variety of powerful CPQ services for your applications. The APIs provide a layer of abstraction
between client application developers and developers who configure and customize the underlying CPQ
logic.

You can call a CPQ API as a REST API resource using a Uniform Resource Identifier (URI).

In OmniScript, you can call the CPQAppHandler and methods directly. OmniOut calls the CPQAppHandler
through a “GenericInvoke” class.

You can also use the Workbench tool to try out the APIs:

© 2021 Vlocity LLC, a Salesforce


company 8
Digital Commerce

https://workbench.developerforce.com

Another option is to use a utility such as Postman to try out the APIs.

You can use Vlocity Digital Commerce API Caching to develop the following types of services:

• Product Selection (see Get Offers by Catalog API and Get Offer Details API)
• Product Configuration (see Update Basket Contents API, Create Cart from Basket)
• Attribute Based Pricing (see Attribute-Based Pricing )

To begin using the Digital Commerce APIs, start by configuring API custom settings detailed in: CPQ
Configuration Settings Reference.

On-Platform Solution
Product and pricing metadata stored in the Product Catalog provide the seed data to the engine, which
creates priced offers that are cached inside Salesforce. The cached API responses are then available when
new calls are made.

Vlocity works closely with Salesforce to consistently provide best-in-class performance and scalability on
the Salesforce platform. Very large communications, media, and energy companies might require additional
scalability for peak traffic events, such as iPhone roll-out or pay-per-view specials.

Off-Platform Solution
The Vlocity Digital Commerce API Caching Tier is an elastically scalable commerce engine that will offload
CPQ processing from the Salesforce platform. In the initial release of the Vlocity Communications API

© 2021 Vlocity LLC, a Salesforce


company 9
Digital Commerce

Caching Tier, the functionality is limited to an API gateway and a cache store. The architecture of our API
caching solution is platform-agnostic. However, the Vlocity Digital Commerce API Caching Tier is initially
certified and operated on Amazon Web Services (AWS) and managed by Vlocity.

The Vlocity Digital Commerce API Caching Tier is an optional component of the architecture that enables
customers to store the cached API responses outside of Salesforce.

Using off-platform caching moves the cache from the Salesforce platform to a scalable off-platform cache.
Off-platform caching is useful if you experience high-volume traffic at certain peak times, or if your network
traffic is always high-volume.

Preparing to Use Vlocity CPQ API Caching


Follow the steps in this section to prepare to use Vlocity Communications API Caching.

NOTE
If you have an existing Salesforce Organization ID (Org), ensure that Fall '18 or a later
update is installed. Go to Setup, use Quick Find to go to Installed Packages, and make
sure the version is at least 900.202.

© 2021 Vlocity LLC, a Salesforce


company 10
Digital Commerce

Perform the following steps:

1. Navigate to the Vlocity Catalogs tab.


2. Verify that you have a default price list identified as part of your Vlocity Catalogs/Categories. If you do
not have a catalog configured, see Create Product Catalogs. The catalog allows you to identify a
subset of products from your shared catalog and make them accessible to the Digital Commerce APIs.
Ensure that the items in the catalog are active.
3. Navigate to the CMT Administration screen, then select Cacheable API Jobs.
4. Run the Load API Metadata job, which should only be run once after a new installation or a release
upgrade. The job uploads any new metadata that may have been added in the release. For more
information about running the cacheable API jobs, see Running Cacheable API Jobs.
5. Run the Populate API Cache job, which populates the data in the Vlocity API Metadata object, which is
a custom object that stores the metadata required by Vlocity Communications API Caching.

NOTE
The Digital Commerce APIs require that you successfully execute the Cacheable API
Jobs whether or not the APIs will be run in cached mode.

NOTE
You can also run the Digital Commerce API cache jobs remotely using APEX. See
Running Maintenance and Digital Commerce Cache Jobs Remotely.

A window displays several choices with additional jobs. To run one or more jobs, enter the date and
time indicating the effective date for the cache data. Then enter a date and time to indicate when the
cache data expires. After the dates are specified, select the checkbox next to each job you wish to run
and click OK. To select all of the jobs, click the checkbox at the top of the list next to Name.

The following list describes the purpose of each of the jobs:

• ContextEligibilityGenerator: Populates the cache with eligible offers for individual context
combinations. This data is used in the GetOffers and GetContainOffers jobs.
• EcomDataProfileGenerator: Populates the cache with Products, Promotions, and PCIMap data for
existing products related to each catalog. This data is used in the ContextEligibilityGenerator Job.
• RuleSetCombinationGenerator: Populates the cache with RuleSet context combinations. This data is
used in the ContextEligibilityGenerator Job.
• GetOffersHierarchyHelper: Populates the cache with the hierarchy of bundles. This data is used in the
GetOfferDetails Job.
• GetOffers: Populates the cache with the list of offers for individual context combinations.
• GetContainOffers: Populates the cache with the parent offers for individual offers.
• GetPrices: Populates the cache with the prices of products.
• GetOfferDetails: Populates the cache with the details of individual offers (both products and
promotions).

© 2021 Vlocity LLC, a Salesforce


company 11
Digital Commerce

These additional jobs have related interfaces and CPQ custom settings. The custom settings specify limits
on the amount of data cached. The following table shows these relationships.

Table 1. Interfaces and Settings for Caching Batch Jobs


Batch Job Interface and Implementation Custom Settings
ContextEligibilityGenerator ContextEligibilityBatchJobRecord CacheAPI.GetRelOffersCacheRecLimit

CacheAPI.MaxGetRelOffersCacheRecLimit
EcomDataProfileGenerator DataProfileBatchJobRecord CacheAPI.CombinationLimit

CacheAPI.MaxCombinationLimit
RuleSetCombinationGenerator RuleSetCombinationBatchJobRecord CacheAPI.GetOffersCacheRecLimit

CacheAPI.MaxGetOffersCacheRecLimit
GetContainOffers GetRelatedOffersBatchJobRecord None
GetOfferDetails GetOfferDetailsBatchJobRecord None
GetOffers GetOffersBatchJobRecord None
GetOffersHierarchyHelper GetOffersHierarchyBatchJobRecord None
GetPrices GetPricesBatchJobRecord None

After completing the steps in this section, see Digital Commerce API Usage Considerations and Detailed
API Parameters and Calling Information.

Initializing the API Cache


You can populate and initialize the cache by running batch jobs from the CMT Administration screen.

For a description of the purpose of each of the batch jobs, see Preparing to Use Vlocity CPQ API Caching.
For an overview of Digital Commerce caching, see Digital Commerce API Caching.

To run the Populate API Cache batch jobs:

1. Navigate to the Vlocity CMT Administration screen.


2. Click Start next to Populate API Cache.
The Populate API Cache screen displays.

The illustration below shows a sample of the Populate API Cache screen:

© 2021 Vlocity LLC, a Salesforce


company 12
Digital Commerce

• To specify a particular cache job to run, check the box next to the job name.
• To specify that all of the cache jobs should run, check the box next to Name.
• To specify that you want to populate the cache with information from one or more catalogs, select the
checkbox next to each catalog.
• To specify that you want to populate the cache with information from all active catalogs, select the All
checkbox under Catalogs.
• Use the Effective Start Date and Expiration Date fields to specify the length of time the cache is active.

When finished with the preceding selections, click OK. You will receive a confirmation about whether the
job or jobs have run successfully.

© 2021 Vlocity LLC, a Salesforce


company 13
Digital Commerce

NOTE
The Populate API Cache screen shows only those catalogs marked as Active.

Updating the API Cache


Run the Regenerate Cached API Records job to regenerate cached API records. If the catalog has been
modified, this job regenerates the cached API response objects based on the modified sales catalog and
product models. You can regenerate the cache by navigating to Vlocity CMT Administration →
Cacheable API Jobs and then selecting Start next to Regenerate Cached API Records.

When the job is run, the following window displays:

NOTE
You must set CacheAPI.RegenerateFutureDatedCache=true for the Regenerate
Cached API Records window to display. See CPQ Configuration Settings Reference.

Enter the date and time when you want the cached records to become effective. For example, suppose you
update your product catalog some time in March, but want the updates to become effective at midnight on

© 2021 Vlocity LLC, a Salesforce


company 14
Digital Commerce

April first. Setting the data and time to 12:00 a.m. on April 1 updates the cache data so that subsequent to
the effective date, API calls retrieve the updated cached data.

When the CacheAPI.CacheManagement configuration setting is enabled, the Regenerate Cached API
Records job will programmatically regenerate cached API responses if your product model or sales catalog
is modified.

To use the incremental cache regeneration feature and import datapacks:

1. From Setup, in the Quick Find box, enter Custom Settings.


2. Click Custom Settings.
3. Go to Trigger Setup.
4. Next to Trigger Setup, click Manage. The Trigger Setup page appears.
5. Click Edit beside CacheAPI.CacheManagement, and turn the trigger on.
If you do not see a trigger for CacheAPI.CacheManagement:
a. Click New.
b. Enter CacheAPI.CacheManagement in the Name field.
c. Click Trigger On.
d. Click Save.

This ensures you can see catalog changes reflected in the cache after running the Regenerate Cached API
Records job.

IMPORTANT
There is a known issue with this trigger turned on that prevents you from importing large
datapacks. To work around this issue, import datapacks with a batch size of one.
Otherwise, the datapack import (deployment) fails due to excessive SOQL errors violating
Salesforce governor limits. Vlocity recommends that you do not enable the Digital
Commerce cache management trigger unless you are using Vlocity CME patch release
Spring '20 107.1.1.

If you do not use the incremental cache regeneration feature with Digital Commerce APIs, or if you want to
import datapacks with a batch size larger than one, disable the cache management trigger.

Running Maintenance and Digital Commerce Cache Jobs


Remotely
You can run the Maintenance Jobs and the Digital Commerce API cache jobs programmatically by using
anonymous Apex code as shown in the following examples.

© 2021 Vlocity LLC, a Salesforce


company 15
Digital Commerce

Product Hierarchy Maintenance


Use this anonymous Apex job to build a streamlined version of the product hierarchies in the Data Store
subjects. This is the same result as using Vlocity CMT Administration > Maintenance Jobs > Product
Hierarchy Maintenance.

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'startProductHierarchyJob'};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

Clear Managed Platform Cache


Use this anonymous Apex job to clear the org cache in the CPQPartition platform cache. This is the same
result as using Vlocity CMT Administration > Maintenance Jobs > Clear Managed Platform Cache.

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'clearPlatformCache'};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

Refresh Platform Cache


Use this anonymous Apex job to copy product hierarchy data to the platform cache and to rebuild the
product attribute cache. This is the same result as using Vlocity CMT Administration > Maintenance
Jobs > Refresh Platform Cache.

Note that you must include the appropriate Pricebook2 ID in the script shown here:

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'refreshPriceBook', 'priceBookId' => 'price book ID'};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

ClearCacheBatch
Copy and paste the following Apex class into your org. This is a batch job that clears the cache. Use this if
you have a large catalog or many context dimensions that result in a cache of 50k+ records.

global class ClearCacheBatch implements Database.Batchable<sObject> {


public String query = 'SELECT Id FROM vlocity_cmt__CachedAPIResponse__c';

global Database.QueryLocator start(Database.BatchableContext BC){


return Database.getQueryLocator(query);

© 2021 Vlocity LLC, a Salesforce


company 16
Digital Commerce

global void execute(Database.BatchableContext BC, List<sObject> scope){


delete scope;
DataBase.emptyRecycleBin(scope);
}

global void finish(Database.BatchableContext BC){


}
}

Clear Cache
You can fully clear the Digital Commerce API cache with the following anonymous Apex. Use it to debug
and troubleshoot failures with the Digital Commerce APIs.

Id batchInstanceId = Database.executeBatch(new ClearCacheBatch());

Check Job Status


Use this anonymous Apex job to check a jobs' status. This is critical as the jobs can take a long time to run
if you have a large catalog. Here is the anonymous apex for it:

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'refreshBatchJobLists'};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

ContextEligibilityGenerator Job
This job populates the cache with the eligible offers for individual context combinations. The data is used by
the GetOffers and GetContainOffers jobs.

You can run the job using anonymous apex code as shown here:

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'populateCacheCAJob', 'selectedList' => new
List<Object>{'ContextEligibilityGenerator'}};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

Generate Full Cache


Use this job to generate, or populate, a full cache. This is the same result as using Vlocity CMT
Administration > Cacheable API Jobs > Populate API Cache and selecting all of the jobs and catalogs.

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'populateCacheCAJob','selectedList' => new

© 2021 Vlocity LLC, a Salesforce


company 17
Digital Commerce

List<Object>{'ContextEligibilityGenerator','GetOffersHierarchyHelper','GetOffer
s','GetContainOffers','GetPrices','GetOfferDetails'},'filters'=> new
Map<String,List<Object>>{}};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

GetOffersHierarchyHelper Job
This job populates the cache with the hierarchy of bundles. The data is used in the GetOfferDetails Job.

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'populateCacheCAJob', 'selectedList' => new
List<Object>{'GetOffersHierarchyHelper'}};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

GetOffers Job
This job populates the cache with the list of offers for individual context combinations.

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'populateCacheCAJob', 'selectedList' => new
List<Object>{'GetOffers'}};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

GetContainsOffers Job
This job populates the cache with the parent offers for individual offers.

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'populateCacheCAJob', 'selectedList' => new
List<Object>{'GetContainOffers'}};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

GetPrices Job
This job populates the cache with the prices of products. This is used in GetOffers, GetContainsOffers
and GetOfferDetails jobs.

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'populateCacheCAJob', 'selectedList' => new

© 2021 Vlocity LLC, a Salesforce


company 18
Digital Commerce

List<Object>{'GetPrices'}};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

GetOfferDetails Job
This job populates the cache with the details of individual offers (product or promotion).

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'populateCacheCAJob', 'selectedList' =>
new List<Object>{'GetOfferDetails'}};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

Generating the Cache for Specific Catalogs


You can run any of the batch jobs from anonymous Apex code by specifying the ID of the catalog. In the
following example, the ID of the catalog is a0G0b00000dT45JEAS:

Map<String, Object> input = new Map<String, Object>{new Map<String,


Object>{'methodName' => 'populateCacheCAJob',
'selectedList' => new List<Object>
{'GetOfferDetails'},
'filters'=> new Map<String,List<Object>>{'Catalogs'=> new
List<Object>{'a0G0b00000dT45JEAS'}}};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

Regenerate Cached API Records


Run this job to regenerate cached API records. If the catalog has been modified, this job regenerates the
cached API response objects based on the modified sales catalog and product models.

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'regenerateCacheAPIRecordsJobs'};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

See Also
• Running Digital Commerce Cache Jobs Remotely with API

© 2021 Vlocity LLC, a Salesforce


company 19
Digital Commerce

Running Digital Commerce Cache Jobs Remotely with API


You can run Digital Commerce cache jobs anonymously from an API with the Salesforce Workbench tool.
This tool is an external Heroku application that can make REST calls to your Salesforce org.

One reason to invoke with APIs is to import products from another system and have the Digital Commerce
Tier's cache to reflect those new products, prices, and other changes. For example, you could load partner
catalogs with an enterprise service bus (ESB) or an extract, transform, and load (ETL) tool into the Vlocity
EPC, and the cache needs to show the new and updated products.

NOTE
When you running jobs remotely with APIs with an external system instead of Workbench,
you'll need to handle the authentication to Salesforce.

If this external system is a secure server like a web application, you can use the OAuth 2.0
JWT Bearer Flow for server-to-server authentication. You must pass in the access token
from the authentication call into the API call to this Tooling API.

If you're using an ESB with a Salesforce connector like Mulesoft, it handles the
authentication, similar to Workbench.

Before you begin:

• Your Salesforce org must be set up for remote access. See the Workbench Help for details.
• Plan when to run the Digital Commerce cache jobs for the following reasons:
• Cache jobs can take some time to run.
• Avoid calling other Digital Commerce APIs when the generate cache job (Generate Full Cache) is
running. Otherwise, the APIs might not work as expected.
• When the regenerate cache job (Regenerate Cache) is running, avoid calling Digital Commerce APIs if
possible. If you do, you can get some unexpected behaviors. While a small number of changes
executes quickly, it is better to do these off-hours.

To run Digital Commerce jobs remotely:

1. Go to the Salesforce Workbench.


2. For testing, set Environment to Sandbox, leave API Version as the default, and select I agree to the
terms of service.
3. Click Login with Salesforce, and log in to your Salesforce sandbox.
4. In the Workbench UI, select Utilities > REST Explorer.

© 2021 Vlocity LLC, a Salesforce


company 20
Digital Commerce

5. Prepare the URI for the job to run.


a. Select a job listed in Running Maintenance and Digital Commerce Cache Jobs Remotely, such as
the Generate Full Cache job.
b. Copy the Apex code for the job.
c. Select a URL encoder (such as https://www.url-encode-decode.com) and encode the Apex code
using the following format where v47.0 is the API version selected when you logged in.
/services/data/v47.0/tooling/executeAnonymous/?anonymousBody=<encoded
Apex here>
If you're doing this from another system, you might have an encoding method or function.
Example:

/services/data/v47.0/tooling/executeAnonymous/?anonymousBody=Map
%3CString%2C+Object%3E+input+%3D+new+Map%3CString%2C+Object%3E%7B
%27methodName%27+%3D%3E+%27populateCacheCAJob%27%2C%27selectedList%27+
%3D%3E+new+List%3CObject%3E%7B%27ContextEligibilityGenerator%27%2C
%27GetOffersHierarchyHelper%27%2C%27GetOffers%27%2C%27GetContainOffers
%27%2C%27GetPrices%27%2C%27GetOfferDetails%27%7D%2C%27filters%27%3D%3E
+new+Map%3CString%2CList%3CObject%3E%3E%7B%7D%7D%3B%0D
%0Avlocity_cmt.TelcoAdminConsoleController+controllerClass+%3D+new
+vlocity_cmt.TelcoAdminConsoleController%28%29%3B%0D
%0AcontrollerClass.setParameters%28JSON.serialize%28input%29%29%3B%0D
%0AcontrollerClass.invokeMethod%28%29%3B
6. Verify GET is selected, enter the URI you built, and click Execute.

Results
To see the running jobs:

© 2021 Vlocity LLC, a Salesforce


company 21
Digital Commerce

1. In your sandbox org's UI, click Setup and search for Apex Jobs.
2. Click Apex Jobs.

Your remotely executed job is listed, as in the following example.

See Also
• ,Running Maintenance and Digital Commerce Cache Jobs Remotely

Updating the AWS Cache


When changes are made to the catalog or product model, you can update the cache if you are using an off-
platform solution. The Migrate Cache Records job enables you to migrate CachedAPIResponses from
Salesforce to AWS.

Prerequisites
The AWS Cache Migration Batch job is dependent on the following custom settings. The custom settings
store information about the AWS instance and must be configured before running the batch job:

• CacheAPI.ExternalSystemPartitionKey
• CacheAPI.ExternalSystemAuthHeader
• CacheAPI.ExternalSystemURL

For information about configuring CPQ custom settings, see CPQ Configuration Settings Reference.

Update the AWS Cache Using a Batch Job


You can update the cache by running a batch job. The batch job does a full migration the first time it is run.
On subsequent runs, the batch job performs an incremental migration based on the last synchronization
timestamp.

1. Navigate to Vlocity CMT Administration > Cacheable API Jobs.


2. Click Start next to Migrate Cache Records.

You will be notified if the batch job was successful.

Update the AWS Cache Using a REST API


You can also initialize the cache using a remote API call.

© 2021 Vlocity LLC, a Salesforce


company 22
Digital Commerce

Map<String, Object> input = new Map<String, Object>{'methodName' =>


'cacheMigrationJobs'};
vlocity_cmt.TelcoAdminConsoleController controllerClass = new
vlocity_cmt.TelcoAdminConsoleController();
controllerClass.setParameters(JSON.serialize(input));
controllerClass.invokeMethod();

The API migrates CachedAPIResponse__c records from the Salesforce platform and inserts them into the
Redis (Remote Dictionary Server) cache on AWS. The API maintains a lastsynctimestamp on the Redis
cache.

REST endpoint:
POST /v3/migrate

Parameters:
fullLoad (Optional) - Used to indicate whether to perform a full or
incremental migration of the cache. The default value is false, which means
the API will perform an incremental migration based on the last sync
timestamp. If set to true, the API will do a full migration.

Invoke Cache Migration when OAuth2 is Deployed


You can migrate CachedAPIResponse__c records from the Salesforce platform to AWS when OAuth2 is
deployed by using the:

• Command Line Interface: Obtain the OAuth2 JWT token and call GET /cm/migrate endpoint.
• GUI (this solution is valid for one hour, after which the CacheAPI.ExternalSystemAuthHeader needs to be
updated again).

1. Obtain the OA uth2 JWT token.


2. Replace the CacheAPI.ExternalSystemAuthHeader field with the Bearer token value
(oauth2_jwt_token_value).
3. Make the API GET call.

If you are using Vlocity Communications, Media, and Energy Fall '20 or later, then set the following
parameter values:

Parameter Value
CacheAPI.ExternalSystemAuthHeader JSON with { "oauth2_server":"" , "customer_app_key":"" ,"customer_app_secret":""}
oauth2_server OAuth2 URL
customer_app_key OAuth2 application key
customer_app_secret OAuth2 application secret

For example:

{ "oauth2_server": "vlocity-exaple.amazoncognito.com", "customer_app_key":


"testKey", "customer_app_secret": "testSecret" }

© 2021 Vlocity LLC, a Salesforce


company 23
Digital Commerce

Then, add the URL to the remote site URL.

Configure Remote Site Setting


To update the cache when you are using an off-platform solution, you need to configure a remote site
setting.

1. From Setup, in the Quick Find box, enter Remote Site.


2. Click Remote Site Settings.
3. Click New Remote Site.
4. Add the following remote site details:
• Name: AWSCacheMigration
• Remote Site URL: The URL for the external system.
• Active: True
5. Click Save.
For example:

Troubleshooting
• If no cache is generated on AWS or Salesforce, then run the Populate API Cache job first, then run the
Migrate Cache Records job.
• If the Salesforce cache-generated AWS is empty with no history of the last run, then run the Migrate
Cache Records job.

© 2021 Vlocity LLC, a Salesforce


company 24
Digital Commerce

• If the Salesforce cache-generated AWS is empty with the history of the last run, then run the Populate
API Cache job first, then run the Migrate Cache Records job.
• If AWS has been updated with the Salesforce records but AWS is not synchronized with Salesforce, then
run the Migrate Cache Records job. This will synchronize the recently updated records in the AWS cache
with Salesforce.

© 2021 Vlocity LLC, a Salesforce


company 25
Digital Commerce

Digital Commerce (Cacheable) APIs

You can use the Digital Commerce APIs to develop consumer-facing web and mobile applications to shop
for products and services.

Vlocity recommends:

• Using the Digital Commerce SDK to make Digital Commerce API calls
• An off-platform API cache

Digital Commerce API Usage Considerations


Consider the following when making design and deployment decisions.

• The Digital Commerce Gateway provides 150 Million API calls per quarter, 12.5 GB cache, and maximum
data egress of 15 TB per quarter. Any data overages may require an additional licensing cost. Please
contact your sales representative for more information.
• Ensure that you delete logger trace flags and disable all logging services, such as
CacheAPI.EcommLogger and the pricing log in CPQ Configuration settings.
• Cacheable APIs do not currently support penalties that are invoked when attempting to
remove promotions from an active asset. To learn more about penalties, see Create a Penalty Rule.
• Attribute binding is not supported by Digital Commerce APIs. See Create a Pricing Element Adjustment
• The deltaPrice, deltaValidate, and levelBasedApproach custom settings are not supported when using
the Digital Commerce APIs. If deltaPrice or deltaValidate are enabled, line items that are added to the
cart will not be priced or validated correctly. If levelBasedApproach is enabled, Digital Commerce API
calls return only a partial response. In addition, subsequent API calls will not be able to perform any
further operations on an existing basket.
• For releases prior to CME Winter '20: Vlocity Communications API Caching does not honor product
selling period or effectivity dates. The following dates in the product catalog are ignored by Vlocity
Communications API caching: Selling Start Date, Selling End Date, Fulfillment Start Date, End Of Life
Date, Effective Date and Effective End.
Starting with the CME Winter '20 release, these product selling period and effectivity dates are
supported; however, effectivity dates for rules are not supported.
• Cacheable context dimensions do not support comparisons operations; only absolute values. For
example, a context dimension that specifies "Postal Code Range must be greater than {numeric value}"
is not supported. Therefore, it is advisable to convert these dimensions to Boolean values. For additional
complex dimensions, contact our Product Management team.
• Cache management will require manual steps while the admin capabilities are expanded.
• The off-platform solution will be designed to be gateway agnostic, but the first iteration will be optimized
on AWS (and managed by Vlocity).
• When creating a promotion override, excluding a child product from the promotion is not supported.
• For releases prior to CME Summer '20: When creating catalog product relationships, do not enter both
products and promotions in the same product relationship record. For example, do not create a record for
a product and then add a promotion to the same record. You should instead create one record for the
product and one record for the promotion.

© 2021 Vlocity LLC, a Salesforce


company 26
Digital Commerce

• Ensure there are no blank spaces in code fields in objects that are used in the Cacheable API
configuration.
• Run all appropriate CMT Administration jobs (such as Field Maps Maintenance, Product Hierarchy
Maintenance, and so on) before running the cache API jobs.
• Starting with the Winter '20 release, the Digital Commerce APIs support JSONAttribute v2.
• Consider removing old pseudo records. See Delete Pseudo Records.
• For the Winter '20 release, the custom setting UseAssetReferenceIdForParentAndRoot=True is
not supported for the Digital Commerce APIs. Set
UseAssetReferenceIdForParentAndRoot=false instead.

Get Offers By Catalog

• The GetOffers API accepts only one context parameter value in the API call. For example,
context={"AccountSla"="Gold"} would be supported, but
context={"AccountSla"="Gold,Silver"} would not be supported.
• The Get Offers by Catalog API returns override values of attributes only for products that are part of a
promotion. Because the API returns only root-level products and does not return child products, it does
not return overrides except in the case of products within a promotion.
• Be aware that availability and eligibility interface implementations are ignored while generating the cache.
Cache generation defaults to executing eligibility context rules by leveraging context dimensions for
Digital Commerce APIs. However, CPQCart leverages Cart-Based APIs which also support eligibility
context rules that could be set without affecting cache generation. Therefore, Digital Commerce API
cache generation ignores the following:
• ProductAvailabilityInterface
• ProductAvailabilityOpenInterface
• ProductEligibilityInterface
• ProductEligibilityOpenInterface
• As of the Fall ’20 release, after invoking the Populate API batch job, the following are honored: Active
flag, Orderable flag, Effectivity dates, selling start and end dates on offers (Products or Promotions). If
an offer becomes ineligible later, due to a selling end date or effectivity date expiration, it will not be
automatically removed from the response.
• To remove an inactive offer from a getOffers API response, clear the cached API response records and
rerun the Populate API cache batch job. Then, manually edit the offer entry in the Vlocity Product
Console to trigger cache management and run the regenerate cache batch job.
• For CME Fall '18 release, ensure that you clear the cache before running the GetOffers batch job.
Custom Settings (Fall '18):
• CacheAPI.GetOffersCacheRecLimit:
• DefaultValue: 9000
• Suggested Value: 5000
• Applicable On: GetOffers and GetContainsOffers batch jobs
This custom setting represents the maximum number of results that can be cached for each catalog
during the Populate API cache batch jobs for GetOffers or GetContainsOffers. Clear the cache
before running the GetOffers batch job. (CME Fall '18).
• API calls are cached during run time as part of incremental cache population.

© 2021 Vlocity LLC, a Salesforce


company 27
Digital Commerce

Get Offer Details

• The following custom settings are not supported: DeltaPrice, DeltaValidate, and LevelBasedApproach.
• As of the Fall ’20 release, after invoking the Populate API batch job, the following are honored: Active
flag, Orderable flag, Effectivity dates, selling start and end dates on offers (Products or Promotions). If an
offer becomes ineligible due to a selling end date or effectivity date expiration, the offer will not be
automatically removed from the response.
• To remove expired offer details from the Digital Commerce cache, clear the cached API response records
and rerun the Populate API Cache batch job. Then, manually edit the offer entry in the Vlocity Product
Console to trigger the cache management and run the regenerate batch job.
• Note the following about pricing when running this API:
• When Get Offer Details is called initially, the pricing interface is not executed.
• When Get Offer Details is called with context parameters, the correct pricing is returned based on
context eligibility (tightest match) of the prices. The pricing interface is not executed.
• The GetOfferDetails API triggers the pricing interface implementation only when a change to the offer
occurs. For example, the pricing interface implementation is triggered when a user modifies the QTY
amount or modifies an attribute value. Therefore, when GetOfferDetails is initially called, the pricing
interface implementation is not executed. If specific context key elements are passed, correct pricing is
returned based on the response when running API caching rules, which recognize the pricing interface
implementation.

Get Contains Products

• As of the Fall ’20 release, after invoking the Populate API batch job, the following are honored: Active
flag, Orderable flag, Effectivity dates, selling start and end dates on offers (Products or Promotions). If an
offer becomes ineligible due to a selling end date or effectivity date expiration, the offer will not be
automatically removed from the response.
• To remove expired offer details from the Digital Commerce cache, clear the cached API response records
and rerun the Populate API Cache batch job. Then, manually edit the offer entry in the Vlocity Product
Console to trigger cache management and run the regenerate cache batch job.
• The GetContainsProducts API accepts only one context parameter value in the API call. For example,
context={"AccountSla"="Gold"} would be supported, but
context={"AccountSla"="Gold,Silver"} would not be supported.
• The sortBy parameter and sorting are not supported in the CME Fall '18 release of this API.
• Because products are not added to the cart, validation and pricing rules do not run; therefore, product
relationship type rules are not supported.
• The DeltaPrice, DeltaValidate, and LevelBasedApproach are not supported.
• In addition to the offers returned by the API, Get Contains Products also returns the offer itself.
• Custom Settings (as of CME Fall '18): CacheAPI.GetOffersCacheRecLimit
• DefaultValue: 9000
• Suggested Value: 5000
• Applicable to GetOffers and GetContainsOffers batch jobs
• This custom setting represents the maximum number of results that can be cached for each catalog
during CachePopulation batch job for GetOffers or GetContainsOffers.

© 2021 Vlocity LLC, a Salesforce


company 28
Digital Commerce

• Ensure that you clear the cache before running the GetOffers batch job (CME Fall '18).

Post Offer Details with Configuration


• The deltaPrice, deltaValidate, levelBasedApproach custom settings are not supported.
• One-time charges and monthly charges (NRC and MRC) must be defined for each product. If NRC or
MRC are not available, set them to $0.00.
• The Configure Offer API uses the Pricing Interface Implementation; therefore Attribute-Based Pricing via
Price Plans is supported.
• The Post Offer Details with Configuration API is specific to the orderable Bundled Products that are being
configured. Post Offer Details with Configuration APIs do not honor Advanced Rules that are defined to
evaluate across multiple bundles.

Basket API
• For releases prior to CME Summer '19: Deleting any offer of type promotion or an offer that has been
affected by any rules due to a promotion from the basket will render the basket invalid. The user must
start with a fresh basket after such an operation, which can be handled by custom code.
• For releases prior to CME Summer '19: Only add and delete were supported, not update. Deleting from
the basket, configuring a new offer, and adding to the basket would effectively update the basket.
• The Basket API supports Multi-Transaction Service.
• deltaPrice, deltaValidate, and levelBasedApproach are not supported
• For releases prior to CME Winter '20: Cloned child line items are not supported. Cloned child line items
are supported as of the Winter '20 release.
• For releases prior to CME Winter '20: Adding the same promotion multiple times to a single basket is
not supported. This functionality is supported as of the Winter '20 release.

Create Basket with Basket Action


The Asset To Basket API does not support nesting of multiple baskets from the same asset with different
request dates.

Example: Assume you create an asset to basket order with a request date of August 1st 2020 and make
modifications. Next, another asset to basket order is created with request date of September 1st 2020; the
latest request will not have the changes made to the basket that was created on August 1st.

Example: Suppose you create an asset to basket order with a request date of August 1st, make
modifications, and convert the basket to a cart using the createCart API. Next, you create another asset to
basket order with a request date of September 1st; the basket will have the changes that were created on
August 1st.

IMPORTANT
The createCart API does not currently accept the order start date as a parameter. The cart
is always created on the date of the createCart API call.

© 2021 Vlocity LLC, a Salesforce


company 29
Digital Commerce

Price

• Only pricing-element prices are supported. A one-time charge and a recurring charge must be defined for
each product as a base price. Zero-base prices are allowed.
• Only one-time charge/total and recurring charge/total are supported in the Fall 2018 release. Therefore,
loyalty and other pricing variables are not supported.
• Prices shown in the GetOffers, GetOfferDetails, GetContainsProducts are read directly from the defined
price list entries for each product and promotion in the catalog.
• For releases prior to CME Winter '20: Time plan and time policy are not honored in the price result.
Time plan and time policy are supported as the Winter '20 release.
• The GetOffers, GetOfferDetails, and GetContainsProducts APIs do not have a cart context; therefore,
promotion discounts that are defined on a promotion product that is not a top-level offer, but that
references a parent offer in its price list entry definition, will not be calculated. This type of promotion
discount can be calculated only when a cart exists with the parent offer already added to it.
An example of the above scenario would be to define a promotion, add a promotion Product A, then
under product adjustments, add a 10% monthly recurring charge (MRC) discount for Product A with a
Parent Offer Context pointing to an offer Product B. This promotion means Product A's MRC price is 10%
less if Product B exists and Product A is under Product B's hierarchy in the cart.

Context Eligibility (Products and Promotions) Rules Limitations

• To Cache Eligibility Combinations, ensure you enable cacheable mode, and have populated values for
caching and default values for context dimensions. Otherwise, API performance will be negatively
impacted and result in frequent cache misses and might lead to caching of unwanted combinations.
• The context scope associated with the cacheable dimension must be of type Entity (Virtual and Session
are not supported).
• Cacheable dimension does not support any dynamic fields. (Domain Type must be of type "Type In" =>
SObject and picklist is not supported because there will not be any cross-validation while generating
combinations against the picklist values).
• The context parameter in all of the above APIs is case sensitive. Otherwise, eligibility results might not be
accurate.
• All the rules defined for generation of eligibility combination must have Rule Type as Qualification and
Rule purpose as Eligibility.
• The rule condition supports only == and != operators in the case of Eligibility Context Rules. The !=
operator is supported only for known users, while the == operator is supported for anonymous users as
well as known users.
• Rules support only AND or OR Expression Modes in rule condition evaluation.
• Rule Set supports only AND or OR Expression Mode rules evaluation. Custom expression modes are not
supported.
• Fail Level and Fail Message are not honored.
• For any configuration changes related to context dimension, rules, rule conditions, rule sets, or rule set
assignments to products or promotions, first clear the platform cache, then run the
ContextEligibilityGenerator batch job and the rest of the batch jobs under Populate API Cache in the
Vlocity CMT Administration screen.

© 2021 Vlocity LLC, a Salesforce


company 30
Digital Commerce

• Prior to the Summer '19 release, header rules within context rules are ignored for Digital Commerce
anonymous APIs.
• Eligibility Rules are applicable in GetOffers API and GetContainsProducts API only.
• For the Fall 2018 release, the Context Dimension Name and Code must be identical.
• Custom Settings (CME Fall '18): The CacheAPI.CombinationLimit custom setting represents the
maximum number of results that can be cached for each catalog during ContextEligibilityGenerator
CachePopulation batch job.
• DefaultValue: 9000
• Suggested Value: 5000

Pricing Context Rules (Tightest Match)


• Even though scope and mappings are defined for context dimension, Pricing Rules will obtain values
from the context parameter of the URL to evaluate the rule conditions.
• Pricing context rules are supported in Basket API, Configure API, and Create CART API.
• The Cart-Based defined scope for a context Dimension, which acted as input for rules. For example,
consider the following scenario:
• Create a Dimension: AccountSla, Scope: Account, Mapping: {SourceExpression:
Account.Sla__c}
• Create a Rule named R1 which says: AccountSla == gold, and create a rule set called RS1.
• Assign this ruleset to PriceListEntry (PLE1 => One time charge: 50) of product P1 to RS1. Assume one
more PLE for P1 (PLE2, one-time charge: 40).
• Now assume you are trying to add P1 in a Cart-Based API CPQ cart while adding product P1. This API
attempts to fetch the best possible match of the prices assigned to product P1 based on the context
rules assigned.
• Because PLE1 is assigned to RS1, it fetches the AccountSla value from the scope object that was
assigned to it.
• Assume that AccountSla value is gold in the Account object that is related to the current cart, then the
existing context rule service will replace AccountSla in the ( AccountSla == gold) condition with
the AccountSla value (which is obtained from the related account object) and the final expression of
the rule condition will be simplified to (gold == gold). Because this qualifies PLE1, PLE1 takes priority
over PLE2 based on the weight defined in the dimension.
• Based on the above scenario, the input source for the rule condition was given from the Scope objects.
• In the Digital Commerce APIs, context scope, mappings, rules, rule conditions, and rulesets must be
defined as specified above. But instead of using the scope object for the input source to evaluate the rule
conditions, the API uses the context parameter provided in the URL to evaluate the rule conditions.
To illustrate the above scenario, consider the following URL:
/v3/catalogs/Mobiles/basket/5b7f58ae49f221537c97e7fd4f6d063c?
context={"AccountSla":"Silver"}
• Assume the URL above is used to add product P1 to the basket. The URL has a context with
AccountSla as key, which is the code of the dimension that was defined.
Because silver is not equal to gold, the rule fails and PLE2 takes precedence over PLE1.
Because silver is not equal to gold, the rule fails and PLE2 takes precedence over PLE1.
The evaluated rule condition expression is as follows: ("Silver" == "Gold")

© 2021 Vlocity LLC, a Salesforce


company 31
Digital Commerce

• This feature is supported only by Basket API, Configure API, and Create CART API

Create Cart
• The Create Cart API requires that catalogCode be sent as an input to the API call. The catalogCode is
required to determine the PriceList to use for the cart. If you have a single catalog, then specify the
catalogCode in the input of the Create Cart API. If you have multiple catalogs, use the same price list on
all of the catalogs. Using one price list allows you to specify any one of the catalog codes in the input of
createCart API.
• When creating a cart using the Digital Commerce APIs, the order start date will be the date on which the
Create Cart from Basket API was called.
• When using the Create Cart API, effectivity and eligibility checks are supported only when the
cartContextKey parameter is set. Effectivity and eligibility checks are not supported by setting the
JSONResult parameter.

Cache Management
• The Digital Commerce Cache Manager is unable to regenerate or recompute existing baskets if they
contain configured offers. If a basket contains configured offers and changes are made to the catalog, the
cache manager invalidates the baskets.
• The Cache Manager is unable to regenerate or recompute responses to the Post Offer Details with
Configuration API call. If a basket contains configured offers and changes are made to the catalog,
information returned by the Post Offer Details with Configuration API is invalid.
• The Cache Manager does not support scenarios in which a child product within the catalog hierarchy is
changed to inactive.
• The Cache Manager does not support scenarios in which a promotion is active but the promotional
product is inactive.

Performance Considerations
For best performance, whether the user is known or anonymous, call the API with both the context
parameter and the context key. This is a two-step process.

For example, first issue a request to the Get Offers by Catalog API. The contextKey is returned in the
output of the API call, as shown here:

API Call:

/services/apexrest/cacheableapis/v3/catalogs/Mobiles/offers?
context={"accountId":"001f200001ci94Q"}&loggedin=true

API Response:
{"contextKey":"9425c79cd5f3ec005ebcf4b72d57a378","offers":[{"
... (truncated for clarity)

Subsequent requests are then made using the contextKey and the context. For example:

API Call:

© 2021 Vlocity LLC, a Salesforce


company 32
Digital Commerce

/services/apexrest/cacheableapis/v3/catalogs/Mobiles/offers?
context={"accountId":"001f200001ci94Q"}&contextKey=9425c79cd5f3ec005ebcf4b72d57
a378&loggedin=true

If the context shape changes (changes are made to the account, an asset that belongs to the account, or to
a contract), the context key must be regenerated.

Detailed API Parameters and Calling Information


The sections that follow provide detailed information about the calling parameters and methods for each of
the Vlocity Communications APIs.

Table 2. Available Digital Commerce APIs


API Description
Get Offers by Catalog Provides the ability to retrieve a list of offers (products or promotions) that are modeled within the Vlocity
Shared Catalog. The specified catalog code identifies the catalog that contains the offers. Offer eligibility can
be determined by API parameters which support both anonymous and known user journeys.

Eligibility can be controlled using context rules. Offer eligibility is determined by the default values for the
context dimensions. See Context Eligibility Rules.
Get Featured Offers Provides the ability to retrieve a list of offers (products or promotions) that are modeled within the Vlocity
Shared Catalog, which is sorted by a specified Catalog Product Relationship field. The specified catalog
code identifies the catalog that contains the offers. Offer eligibility can be determined by API parameters
which support both anonymous and known user journeys.
Get Contains Provides the ability to retrieve a list of offers (products or promotions) that are modeled within the Vlocity
Products Shared Catalog which contain the specified product. The specified catalog code identifies the catalog that
contains the offers. Offer eligibility can be determined by API parameters which support both anonymous
and known user journeys.
Get Offer Details Provides the ability to retrieve offer (product or promotion) details that are modeled within the Vlocity Shared
Catalog. The specified catalog code identifies the catalog that contains the offers. Offer eligibility can be
determined by API parameters which support both anonymous and known user journeys.
Post Offer Details with Provides the ability to pass offer details that are modeled within the Vlocity Shared Catalog in order to
Configuration retrieve pricing updates. The specified catalog code identifies the catalog that contains the offers. Pricing
eligibility can be determined by API parameters which support only an anonymous journey.
Create Basket with Provides the ability to create a basket with or without offer (product or promotions) configurations that are
BasketAction API modeled within the Vlocity Shared Catalog. The specified catalog code identifies the catalog that contains
the offers.

• (BasketAction: AddWithNoConfig): Add items to the basket without configuration.


• (BasketAction: AddAfterConfig): Add items to the basket with configuration.
• (BasketAction: AssetToBasket): Create basket as part of an asset based order.
Modify Basket Provides the ability to add or delete offers to or from a virtual basket. You use the cartContextKey to keep
track of the basket. The cartContextKey is not required if the basket is empty. The CartContextKey is
returned as part of the response after a successful basket operation.
Get Basket Details Retrieves details about a basket.
Create Cart from Create Order Cart from Basket. Provides the ability to create a cart from a basket with offers (product or
Basket promotions) and its configurations that are modeled within the Vlocity Shared Catalog. The specified catalog
code identifies the catalog that contains the offers.

Digital Commerce API Response Optimization


You can request specific nodes in the response from the following Digital Commerce APIs by creating a
DataRaptor interface, a DataRaptor transformer, and a post hook for the API response handler.

© 2021 Vlocity LLC, a Salesforce


company 33
Digital Commerce

• AssetToBasket
• BasketOperations
• ConfigureOffer
• GetOffers
• GetOfferDetails

You will need to specify the nodes you want to include in the API response. Specifying specific nodes in the
API call reduces the verbosity of the API response, thereby decreasing overhead and bandwidth
requirements.

The following example instructions use the GetOffers API and specify the offers:offerType,
offers:priceResult:UnitPrice, and offers:ProductCode nodes in the response.

To reduce the size of Digital Commerce API responses:

1. Go to the Vlocity DataRaptor tab in your org and click New.


2. In the Create Vlocity DataRaptor Interface window, enter a unique name for the DataRaptor interface,
such as OffersTransformer.
3. From the Interface Type list, select Transform.
4. From the Input Type and Output Type lists, select JSON and click Save. The DataRaptor transformer
is displayed on the Vlocity DataRaptor Interface page.

© 2021 Vlocity LLC, a Salesforce


company 34
Digital Commerce

5. Click + to add input and output JSON paths (nodes).


6. In Input JSON Path and Output JSON Path, enter a valid JSON path from the API's response, such
as offers:offerType.
7. From the Output Data Type list, select the data type for the node, such as String.

© 2021 Vlocity LLC, a Salesforce


company 35
Digital Commerce

8. Click Save and then click + to add more nodes as needed.

9. Use sample input to test the DataRaptor transformer. The following sample input to GetOffers should
return a transformed response similar to the following example output.
Sample GetOffers input:

{
"contextKey": "b50d669c29ef610a5b9ba6b4cd734258",
"offers": [
{
"addtocart": {
"rest": {
"params": {
"basketAction": "AddWithNoConfig",
"offer": "accessories"
},
"link": "v3/catalogs/mobiles/basket",
"method": "POST"
}
},
"offerDetailsAction": {
"rest": {
"params": {},
"method": "GET",
"link": "/v3/catalogs/mobiles/offers/accessories"

© 2021 Vlocity LLC, a Salesforce


company 36
Digital Commerce

},
"remote": {
"params": {}
},
"client": {
"records": [],
"params": {}
}
},
"Name": "accessories",
"Description": "accessories",
"ProductCode": "accessories",
"Attachments": null,
"offerType": "Product"
},
{
"addtocart": {
"rest": {
"params": {
"basketAction": "AddWithNoConfig",
"offer": "FastCharger"
},
"link": "v3/catalogs/mobiles/basket",
"method": "POST"
}
},
"offerDetailsAction": {
"rest": {
"params": {},
"method": "GET",
"link": "/v3/catalogs/mobiles/offers/FastCharger"
},
"remote": {
"params": {}
},
"client": {
"records": [],
"params": {}
}
},
"priceResult": [
{
"adjustments": [],
"overrides": [],
"chargeamount": 10,
"baseamount": 10,

© 2021 Vlocity LLC, a Salesforce


company 37
Digital Commerce

"Amount__c": 10,
"IsVirtualPrice__c": false,
"IsBasePrice__c": true,
"effectiveuntildatespec": null,
"effectivefromdatespec": null,
"SubType__c": "Standard",
"Type__c": "Price",
"RecurringFrequency__c": null,
"ChargeType__c": "One-time",
"DisplayText__c": "fc",
"UnitPrice": 10
}
],
"Name": "FastCharger",
"Description": "FastCharger",
"ProductCode": "FastCharger",
"Attachments": null,
"offerType": "Product"
},
{
"addtocart": {
"rest": {
"params": {
"basketAction": "AddWithNoConfig",
"offer": "S10"
},
"link": "v3/catalogs/mobiles/basket",
"method": "POST"
}
},
"offerDetailsAction": {
"rest": {
"params": {},
"method": "GET",
"link": "/v3/catalogs/mobiles/offers/S10"
},
"remote": {
"params": {}
},
"client": {
"records": [],
"params": {}
}
},
"priceResult": [
{

© 2021 Vlocity LLC, a Salesforce


company 38
Digital Commerce

"adjustments": [],
"overrides": [],
"chargeamount": 500,
"baseamount": 500,
"Amount__c": 500,
"IsVirtualPrice__c": false,
"IsBasePrice__c": true,
"effectiveuntildatespec": null,
"effectivefromdatespec": null,
"SubType__c": "Standard",
"Type__c": "Price",
"RecurringFrequency__c": null,
"ChargeType__c": "One-time",
"DisplayText__c": "one time base",
"UnitPrice": 500
},
{
"adjustments": [],
"overrides": [],
"chargeamount": 50,
"baseamount": 50,
"Amount__c": 50,
"IsVirtualPrice__c": false,
"IsBasePrice__c": true,
"effectiveuntildatespec": null,
"effectivefromdatespec": null,
"SubType__c": "Standard",
"Type__c": "Price",
"RecurringFrequency__c": "Monthly",
"ChargeType__c": "Recurring",
"DisplayText__c": "s10 rec base"
}
],
"Name": "S10",
"Description": "S10",
"ProductCode": "S10",
"Attachments": null,
"offerType": "Product"
}
],
"errorCode": "INVOKE-200",
"error": "OK"
}

Expected reduced output:

© 2021 Vlocity LLC, a Salesforce


company 39
Digital Commerce

{
"offers": [
{
"offerType": "Product",
"ProductCode": "accessories"
},
{
"offerType": "Product",
"ProductCode": "FastCharger",
"UnitPrice": 10
},
{
"offerType": "Product",
"ProductCode": "S10",
"UnitPrice": 500
}
]
}
10. Create a post hook for the response handler to transform responses from getOffers.
Sample post hook:

Object offers = output.get('offers');


Map<String, Object> bodyData = new Map<String, Object> {
'bulkUpload' => false,
'bundleName' => 'OffersTransformer', //name of the transformer
'debug' => false,
'objectList' => new List<Object> { output }
};
Map<String, Object> re = (Map<String,
Object>)DRGlobal.processPost(bodyData);
Map<String, Object> resultsData = (Map<String,
Object>)re.get('returnResultsData');
output.put('offers', resultsData.get('offers'));

See also: DataRaptor Transform Overview.

Context Eligibility Rules


You can specify which products, promotions, and prices are affected by Vlocity Communications API
Caching by building a context rules framework.

Using Vlocity Communications API Caching features, you can define rule sets, rules, rule conditions,
dimensions, context mappings, and scope as before by specifying context rules. Vlocity Communications
API Caching features allow users to be anonymous while browsing and adding items to the cart; therefore,
for anonymous users, account and order information are unknown.

© 2021 Vlocity LLC, a Salesforce


company 40
Digital Commerce

Given that users might be anonymous and account and order information might be unknown, Vlocity
Communications API Caching allows you to specify the context of the user. The following is an example of
an API call that specifies user context parameters:

/services/apexrest/vlocity_cmt/v3/catalogs/Mobiles/offers?
contains=iPhone8&context={"AccountSla":"1234",
“Region”:”CA”}&offset=0&pageSize=20

In the example API call shown above, user context is mapped to a Salesforce object in the following
manner:

• The AccountSla parameter represents the field mapping of the scope of the object, which serves as a
context dimension.
• The Region parameter specifies the general location of the user (California in this case).

This context information is passed to the API as part of the URL to determine the eligibility of products and
promotions in the getOffers API. You can also use the context information to find the tightest match of price
list entries using the configure Basket APIs.

Context Scope, Context Dimension, Context Mappings, Rule Conditions, Rule, and Rule Sets are defined in
the same manner as CPQ Context rules; however, a few additional options must be configured to enhance
the response time of the context rule services and to overcome the limitation of eligibility of objects for
anonymous users.

Option Description
Cacheable Mode Use this check box to specify whether the dimension is expected as part of the context.
Default Value The value in this field represents the default value for the Context Dimension. The value is used in case of tightest
match for price list entries. When a Vlocity Communications API is called and this value is not specified, the
context service is populated with this value.

If the default value is empty, then the value for this particular dimension is passed as null during rules evaluation.
Values For This field is used to generate context combinations. The values provided in this field determine all of the possible
Caching combinations of the context parameter specified in URL of the API call.

For more information about context rules see Context Rules Framework.

To leverage Attribute Based Pricing in your API calls, see Attribute-Based Pricing.

Multi-Transaction Service
The Multi-Transaction Service (MTS) is integrated with the Digital Commerce Basket APIs to split Apex
transactions into multiple transactions to avoid exceeding Salesforce Governor limits. Use its configuration
settings to enable it:

• MaxCPUTimePerTransaction: Sets the maximum allowed CPU time per Apex transaction before the
transaction is split.
• MaxHeapSizePerTransaction: Sets the maximum allowed heap size per Apex transaction before the
transaction is split.
• MTSEnabled: Enables the Multi-Transaction Service.

© 2021 Vlocity LLC, a Salesforce


company 41
Digital Commerce

• NumberOfDMLPerTransaction: Sets the maximum allowed data manipulation language (DML)


statements per Apex transaction before the transaction is split.
• NumberOfQueriesPerTransaction: Sets the maximum allowed SOQL queries per Apex transaction before
the transaction is split.

The MTS supports long-running transactions and returns a multiTransactionKey in the


nexttransaction action. To proceed, call the API again with the multitransactionKey in the request
payload as shown in the following example Add to Basket requests and responses with MTSEnabled set to
true (the default).

Example Requests and Responses

Example 1. Example Add to Basket Request


POST
/services/apexrest/{namespace}/v3/catalogs/{catalog_code}/basket?
contextKey=017d3c3f990567a3ce2ca3e60262ec90&context={"accountId":"0019P000024jK
uZ"}&isloggedin=true

Body
{
"offer": "TelcoResidential",
"basketAction": "AddWithNoConfig"
}

Example 2. Example Intermediate Response


{
"nexttransaction": {
"rest": {
"params": {
"multiTransactionKey": "3d719d4a3b14cea4187ea9a5332cff0e",
"method": "addWithNoConfig"
}
}
}
}

Example 3. Example Request to Pass the multiTransactionKey


POST
/services/apexrest/{namespace}/v3/catalogs/{catalog_code}/basket?
contextKey=017d3c3f990567a3ce2ca3e60262ec90&context={"accountId":"0019P000024jK
uZ"}&isloggedin=true

Body

© 2021 Vlocity LLC, a Salesforce


company 42
Digital Commerce

{
"offer": "TelcoResidential",
"basketAction": "AddWithNoConfig",
"multiTransactionKey": "3d719d4a3b14cea4187ea9a5332cff0e"
}

Example 4. Example Response


{
"cartContextKey": "20933d86217050b8d3b15654aeceae30",
"result": {
"totals": {
"EffectiveOneTimeTotal__c": 400,
"EffectiveRecurringTotal__c": 200
},
"totalSize": 1,
"records": [
{
"actions": {
"deleteFromBasketAction": {
"rest": {
"params": {
"basketAction": "deleteFromBasket",
"lineItemKey": "533befb7d15a0a400f09c59ecaef21ee",
"bundleContextKey": "533befb7d15a0a400f09c59ecaef21ee"
},
"link": "/v3/catalogs/vlocity_cmt/basket/
20933d86217050b8d3b15654aeceae30?
contextKey=017d3c3f990567a3ce2ca3e60262ec90&isloggedin=true",
"method": "deleteFromBasketAction"
}
},
"updateBasketAction": {
"rest": {
"params": {
"basketAction": "updateBasket",
"lineItemKey": "533befb7d15a0a400f09c59ecaef21ee",
"bundleContextKey": "533befb7d15a0a400f09c59ecaef21ee"
},
"link": "/v3/catalogs/{catalog_code}/basket/
20933d86217050b8d3b15654aeceae30?
contextKey=017d3c3f990567a3ce2ca3e60262ec90&isloggedin=true",
"method": "updateBasketAction"
}
}
},

© 2021 Vlocity LLC, a Salesforce


company 43
Digital Commerce

"lineItemKey": "533befb7d15a0a400f09c59ecaef21ee",
"bundleContextKey": "533befb7d15a0a400f09c59ecaef21ee",
"displaySequence": -1,
"Id": {
"value": "8024P000001gdBNQAY",
"previousValue": null,
"originalValue": null,
"messages": [],
"label": "Order Product ID",
"hidden": false,
"fieldName": "Id",
"editable": false,
"dataType": "ID",
"alternateValues": null,
"actions": {}
},
"Pricebook2Id": "01s4P000002BoBuQAK",
"Product2Id": "01t4P000007VDOkQAO",
"ProductCode": "TelcoResidential",
"UnitPrice": {
"value": 0,
"previousValue": null,
"originalValue": null,
"messages": [],
"label": "Unit Price",
"hidden": true,
"fieldName": "UnitPrice",
"editable": false,
"dataType": "CURRENCY",
"alternateValues": null,
"actions": {}
},
"Name": "Telco Residential",
"IsActive": true,
"vlocity_cmt__RecurringPrice__c": 200,
"Product2": {
"attributes": {
"type": "Product2",
"url": "/services/data/v46.0/sobjects/Product2/01t4P000007VDOkQAO"
},
"Id": "01t4P000007VDOkQAO",
"Name": "Telco Residential",
"vlocity_cmt__IsConfigurable__c": false,
"vlocity_cmt__Type__c": "None",
"vlocity_cmt__SubType__c": "None",
"vlocity_cmt__SellingStartDate__c": "2019-05-01T18:00:00.000+0000",

© 2021 Vlocity LLC, a Salesforce


company 44
Digital Commerce

"vlocity_cmt__SellingEndDate__c": "2019-09-30T18:00:00.000+0000",
"vlocity_cmt__JSONAttribute__c": null
},
"CurrencyCode": "USD",
"productId": "01t4P000007VDOkQAO",
"defaultQuantity": 1,
"minQuantity": 0,
"maxQuantity": 99999,
"groupMinQuantity": 0,
"groupMaxQuantity": 99999,
"sequenceNumber": 1,
"productChildItemDefinition": {
"attributes": {
"type": "vlocity_cmt__ProductChildItem__c"
},
"Name": "Root PCI",
"vlocity_cmt__IsVirtualItem__c": false,
"vlocity_cmt__Quantity__c": 1,
"vlocity_cmt__MaxQuantity__c": 99999,
"vlocity_cmt__MinQuantity__c": 0,
"vlocity_cmt__MaximumChildItemQuantity__c": 99999,
"vlocity_cmt__MinimumChildItemQuantity__c": 0,
"vlocity_cmt__IsOverride__c": false,
"vlocity_cmt__ParentProductId__c": "01t4P000007VDOkQAO",
"vlocity_cmt__ChildLineNumber__c": "1",
"vlocity_cmt__SeqNumber__c": 1,
"vlocity_cmt__CollapseHierarchy__c": false,
"vlocity_cmt__IsRootProductChildItem__c": true,
"vlocity_cmt__ParentProductId__r": {
"attributes": {
"type": "Product2",
"url": "/services/data/v46.0/sobjects/
Product2/01t4P000007VDOkQAO"
},
"Id": "01t4P000007VDOkQAO",
"Name": "Telco Residential",
"vlocity_cmt__SellingStartDate__c": "2019-05-01T18:00:00.000+0000",
"vlocity_cmt__SellingEndDate__c": "2019-09-30T18:00:00.000+0000"
}
},
"productHierarchyPath": "01t4P000007VDOkQAO",
"name": "Telco Residential",
"isVirtualItem": false,
"lineNumber": "0001",
"action": "Add",
"hasChildren": true,

© 2021 Vlocity LLC, a Salesforce


company 45
Digital Commerce

"SellingPeriod": "Present",
"itemType": "lineItem",
"PricebookEntryId": {
"value": "01u4P00000s2eZjQAI",
"previousValue": null,
"originalValue": null,
"messages": [],
"label": "Price Book Entry ID",
"hidden": false,
"fieldName": "PricebookEntryId",
"editable": false,
"dataType": "REFERENCE",
"alternateValues": null,
"actions": {}
},
"Quantity": {
"value": 1,
"previousValue": null,
"originalValue": null,
"messages": [],
"label": "Quantity",
"hidden": false,
"fieldName": "Quantity",
"editable": true,
"dataType": "DOUBLE",
"alternateValues": null,
"actions": {}
},
"vlocity_cmt__OneTimeTotal__c": {
"value": 400,
"previousValue": null,
"originalValue": null,
"messages": [],
"label": "One Time Total",
"hidden": false,
"fieldName": "vlocity_cmt__OneTimeTotal__c",
"editable": false,
"dataType": "CURRENCY",
"alternateValues": null,
"actions": {
"adjustmentcodes": {
"rest": {
"params": {},
"method": "GET",
"link": "/services/apexrest/vlocity_cmt/v2/listsofvalues?
listkeys=AdjustmentCodes&cartId=8014P0000022G0jQAE&id=8024P000001gdBNQAY&fields

© 2021 Vlocity LLC, a Salesforce


company 46
Digital Commerce

=vlocity_cmt__OneTimeTotal__c&PricingVariableCode=OT_STD_PRC_TOTAL"
},
"remote": {
"params": {}
},
"client": {
"records": [],
"params": {}
}
},
"pricedetail": {
"rest": {
"params": {},
"method": "GET",
"link": "/services/apexrest/vlocity_cmt/v2/cpq/carts/
8014P0000022G0jQAE/items/8024P000001gdBNQAY/pricing?
cartId=8014P0000022G0jQAE&id=8024P000001gdBNQAY&fields=vlocity_cmt__OneTimeTota
l__c"
},
"remote": {
"params": {}
},
"client": {
"records": [],
"params": {}
}
}
}

...

}
}
]
},
"createCartAction": {
"rest": {
"params": {
"cartContextKey": "20933d86217050b8d3b15654aeceae30"
},
"link": "/v3/carts",
"method": "createCartAction"
}
},
"errorCode": "INVOKE-200",

© 2021 Vlocity LLC, a Salesforce


company 47
Digital Commerce

"error": "OK"
}

NOTE
This example has been truncated.

Sample Implementation to Override the 255-Character Limitation


The Digital Commerce APIs use the vlocity_cmt__APIParams__c field in the
vlocity_cmt__VlocityAPIMetaData__c sObject to configure request response fields, batch size, and other
options. This field is also used to identify certain settings of the API while processing batch jobs or while
processing API requests at run time. However, the vlocity_cmt_APIParams__c field is by default limited to
255 characters. In some scenarios, this can be insufficient. For example, consider the following JSON
request for a batch job:

{"batchSize":20,"scopeAll":true, "productFields" :
["vlocity_cmt__IsActive__c"]}

In this example, if you specify multiple fields in productFields, the vlocity_cmt_APIParams__c field might
exceed the 255 character limitation. In such cases, to increase the number of characters this field can
contain, you can override the default character limitation. To do this, you can create an Apex class along
with an interface implementation. For example, create an implementation similar to the following sample.

Sample Implementation Name

DCAPIParamsImplementation

Sample Implementation Method

fetchAPIParamsOverride

Input

Key Type Description


apiName String Defines the name of the API from vlocity_cmt__VlocityAPIMetaData__c.vlocity_cmt__APIName__c
params String Defines the parameters of the given API name. This represents
vlocity_cmt__VlocityAPIMetaData__c.vlocity_cmt__VlocityAPIMetaData__c

Output

Key Type Description


result String Updates the API parameters for the given API name.

Sample Implementation

© 2021 Vlocity LLC, a Salesforce


company 48
Digital Commerce

/*
* We can override this default implementation by defining the following
interface
* INTERFACE : DCAPIParamsInterface
*/
global class DCAPIParamsImplementation implements
vlocity_cmt.VlocityOpenInterface {
public static Map < String, String > overiddenParamMap = new Map < String,
String > {};
static {
//Field should have their own string here for getoffers api
overiddenParamMap.put('GetOffers', '{"batchSize":20,"productFields" :
["vlocity_cmt__IsActive__c"]}');
//Field should have their own string here for getofferdetails api
overiddenParamMap.put('GetOfferDetails', '{"batchSize":20}');
//Field should have their own string here for getrelatedofferdetails
api
overiddenParamMap.put('GetRelatedOffers', '{"batchSize":20,
"productFields" : ["vlocity_cmt__IsActive__c"]}');
}
global DCAPIParamsImplementation() {}

global static Boolean invokeMethod(String methodName, Map < String, Object


> inputs, Map < String, Object > outputs, Map < String, Object > options) {
if (methodName == 'fetchAPIParamsOverride') {
return fetchAPIParamsOverride(inputs, outputs, options);
}
return false;
}

/*
Inputs :
1) key : apiName, type : String
2) key : params, type : String
Outputs :
1) key : result, type : String
*/
public static Boolean fetchAPIParamsOverride(Map < String, Object >
inputs, Map < String, Object > outputs, Map < String, Object > options) {
String apiName = (String) inputs.get('apiName');
String overiddenParam = overiddenParamMap.get(apiName) == null ?
((String) inputs.get('params')) : overiddenParamMap.get(apiName);
outputs.put('result', overiddenParam);
return true;
}
}

© 2021 Vlocity LLC, a Salesforce


company 49
Digital Commerce

Create an Apex Class


1. In your org, in Settings, click Setup.
2. In Quick Find, enter Apex and click Apex Classes.
3. Click New.
4. Copy the sample implementation provided above and paste it in the Apex Class Edit field.
5. Click Save.

Create an Interface Implementation


1. In your org, go to the App Launcher and click Interface Implementations.
2. Click New.
3. In Interface Name, enter DCAPIParamsInterface.

NOTE
Ensure that you name this interface correctly. When this interface exists, the
parameters specified in this iinterface override the default parameters.

4. In Active Implementation Class, enter the name of the Apex class that you just created,
DCAPIParamsImplementation.
5. Click Save.
6. Click Related.
7. Go to Interface Implementation Detail and click New.
8. In Available Implementation, enter the name of the Apex class that you just created,
DCAPIParamsImplementation.
9. Click Active to activate this implementation.
10. Click Default to set this as the default implementation.
11. Click Save.

Troubleshooting Digital Commerce API Calls


Use this table to diagnose problems that occur when executing the Digital Commerce APIs.

Table 3. API Troubleshooting


Problem Area Possible solution
getOffers API returns null result. • Ensure that the ContextEligibilityGenerator and GetPrices jobs have been run.
getOffers API returns "attempt to • Ensure that all context rules are configured correctly.
dereference null object" error. • Ensure that the Context dimension name and code are the same. (Only applicable for CME
Fall '18 .)
getOfferDetails API returning • Ensure that all of the products in the hierarchy are active.
"attempt to dereference null" error. • Ensure that the Product Hierarchy maintenance job has been run.
• Ensure that the GetOffersHierarchyHelper and GetPrices jobs have been run.
getOfferDetails API not returning the • Ensure that the GetPrices job has been run.
PriceResult node. • Ensure that the offer has both one-time and recurring prices defined.

© 2021 Vlocity LLC, a Salesforce


company 50
Digital Commerce

Problem Area Possible solution


getOfferDetails API fails with no error Ensure that virtual products do not have any attributes assigned. Assigning attributes to
in response. virtual products results in unpredictable results when calling the Digital Commerce APIs.
getOfferDetails API not returning the This error is likely caused by your product not having a price list entry or your catalog does
result node. not have a Price List defined in the vlocity_cmt_DefaultPriceListId_c field.
GetOfferDetails API returns "Invalid This error is returned when the user passes an invalid context parameter in the URL, or when
context input for context key" the context key of cartContext, eligibilityContext, or groupContext has expired in the
cachedapiresponse__c table.
The getOfferDetails batch job returns Check the value of the batchSize parameter. Go to the Vlocity API Metadata tab, and select
the following error: Too many SOQL the record whose API name is GetOfferDetails. Ensure the value is set as follows:
queries.
{batchSize":1"}
ConfigureOffer API returning "attempt Ensure that the CacheAPIFields custom setting has been set to true. CacheAPIFields is not
to dereference null" error. required for CME 103.1.14 and later versions.
ConfigureOffer API returning "attempt Ensure that the CacheAPIPartialConfigure custom setting is set.
to dereference null" error for a
promotion.
The API cache batch jobs are not Ensure that the following jobs have been run:
creating any batch records.
Interface Implementation Maintenance (Restore)

Interface Implementation Maintenance (Merge)

The above jobs are run by navigating to Vlocity CMT Administration > Maintenance Jobs.
The GetPrices batch job is not Ensure that you have added a default price list to the catalog.
running any batch records.
The Add To Basket API returns the • Check the Implementation for "PricingInterface."
following error: error: VLC-PPLAN- • If the Active Implementation is "PricingPlanService," then verify that "Default Pricing Plan"
ERR-001 No custom setting value exists in EPC and that it is active. Check whether the CPQ Configuration custom setting
found for DefaultPricingPlan". Name = DefaultPricingPlan and Value = DEFAULT_PRICING_PLAN exist.
The Add To Basket API returns a Run the following query:
time out error.
SELECT count() FROM vlocity_cmt__OrderPriceAdjustment__c where
vlocity_cmt__OrderItemId__c = null and vlocity_cmt__Source__c =
'Agent';

The above query should not return any rows. If the query returns rows, it is invalid data.
Please investigate why these records are generated and remove them.
The Add To Basket API fails Check and delete all attributes (JSONAttribute) from ‘Virtual Item’ products used as part of
withError: ‘null input to JSON parser’, product hierarchies.

Or GetOfferDetails returns an empty JSONAttribute is not supported for Virtual Items and should not be used.
response for a specific product.

© 2021 Vlocity LLC, a Salesforce


company 51
Digital Commerce

Problem Area Possible solution


The API cache batch jobs are not Ensure that the CachedAPIResponse__c.Type__c pick list values are up to date. See the
populating the cache or the Digital lists below:
Commerce APIs are returning null
results. The following values are new for CME Fall '18 :

• item
• itemDetails
• priceResult
• catalogCtxEligibilityResult
• cartContext
• eligibilityContext
• hierarchyResult
• itemConfig
• orderConfiguration

The following values currently exist in CME Winter '19:

• item
• itemDetails
• priceResult
• catalogCtxEligibilityResult
• cartContext
• eligibilityContext
• hierarchyResult
• itemConfig
• orderConfiguration

The following values are new in CME Winter '19:

• dataProfileResultItem
• ruleSetCombinationResultItem
• catalogCtxQualificationMap

The following values currently exist in the CME Summer '19:

• item
• itemDetails
• priceResult
• catalogCtxEligibilityResult
• cartContext
• eligibilityContext
• hierarchyResult
• itemConfig
• orderConfiguration
• dataProfileResultItem
• ruleSetCombinationResultItem
• catalogCtxQualificationMap

The following values are new in CME Summer '19:

• groupContext
• basketWrapper
• assetReferenceKey

© 2021 Vlocity LLC, a Salesforce


company 52
Digital Commerce

Problem Area Possible solution

NOTE
Digital Commerce APIs use the CachedAPIResponse__c custom
object to cache responses. Like other custom objects,
CachedAPIResponse__c can store records until the org's data storage
limit is reached.

Error Code: INVOKE-200, Unable to Ensure that you followed the Post Install Steps for CME Summer '19. Specifically, the section
process basket operation about adding the picklist values for the CachedAPIResponse object. For details, see Post-
Upgrade Steps for Winter '19 to Summer '19 for Vlocity Communications, Media, and Energy.
When the Vlocity API Metadata Ensure that you check all the Vlocity API Metadata records, and delete the ones that have a
record or records return a null API null API Name or a null API Parameter name.
Name field value and/or a null API
Parameter field value, you will see a
500 response with an attempt to de-
reference a null object in the
response body.

Attribute Basket Cache Exclusion


To increase performance and reduce overhead, you can specify whether product attributes are excluded
from the API cache.

When defining product and pricing metadata, product administrators have a goal of maximizing the
effectiveness of the application caching infrastructure. To achieve this, a product administrator typically
identifies and excludes those attributes that do not affect pricing or configuration validity, because these
attributes do not define the minimum unique set of API cache entries. The Attribute Basket Cache exclusion
feature provides Product Administrators this ability by selectively excluding basket cache attributes from the
context that defines API call uniqueness.

The Attribute Basket Cache exclusion feature reduces the number of possible basket combinations to
achieve a minimum set of unique and useful entries. As a result, there is increased likelihood of cache hits
and the elimination of additional cache entries that are effectively redundant.

To determine whether a product attribute is excluded from the cache, observe whether Exclude From
Basket Cache is checked in the attribute's General Properties.

© 2021 Vlocity LLC, a Salesforce


company 53
Digital Commerce

NOTE
The Attribute Basket Cache exclusion feature may be used with caching either on the
Salesforce platform or on the Digital Commerce Gateway. The operation of the feature is
subtly different between configurations. Please review the information below within the
context of your deployment choice.

Prior to the Fall '20 release, executing the Basket API, all attribute values (whether
updated or not) were saved to a basket and returned in the response.

In contrast, beginning with the Fall '20 release, attributes that are defined as “Excluded”
will be ignored in the API request from the standpoint of pricing or configuration. The best
practice for application developers is to not populate the excluded attributes in the
request. This will reduce the potential for inappropriate re-use of data in the API response.

API Responses
The behavior of the API response is different depending upon the cache deployment
configuration selected.

On Platform Cache: In this configuration, when a cache hit occurs, the API response will
reflect the specific response that triggered the creation of the cache record. The response
might include excluded attribute data if it was provided in the initial request. In this
situation, all excluded attributes in any API response should be disregarded. Observing the
best practice of not providing any excluded attributes in any request alleviates this
potential issue.

Digital Commerce Gateway Cache: In this configuration, when a cache hit occurs, the API
response will include the “excluded attribute" data mirrored from the current
request. Again, the best practice is not to provide excluded data in the request.

In either configuration, any excluded attributes provided will not be saved to the basket.

Management of "Excluded Attribute" data for UI Application Use


If your implementation requires the UI to display previously entered updated values for
“excluded attributes” then note the following:

On Platform Cache: Store the requested updated values outside of the request and then
append the values as part of the response.

Digital Commerce Gateway Cache: The best practice is to store the requested updated
values outside of the request and then append the values as part of the response. While it
is possible to consume the provided excluded attributes from the API response, be aware
that this will increase message size and excluded attributes will not be saved in the basket
cache, nor will they trigger the pricing or validation calculations.

© 2021 Vlocity LLC, a Salesforce


company 54
Digital Commerce

Example
The following scenario illustrates an example of how attribute exclusion works and the subtle differences
between on- and off-platform usage. Consider a scenario in which an on-platform user initiates a
PostConfigure or Basket API call. Suppose a user wishes to purchase a mobile phone, which has three
attributes: color, capacity, and IMEI (international mobile equipment identity).

During the product definition phase, the mobile phone was configured using the Enterprise Product Console
(EPC) with the color and capacity attributes identified as cacheable, while IMEI was set to non-cacheable.
Generally, IMEA is not associated with the device until the mobile phone is provisioned, and is left blank
during order capture.

Now suppose a user adds the mobile phone to the basket and configures all three attributes. A cache miss
occurs because the attribute values are not contained in the cache.

Here is a step-by-step workflow through the example:

• User 1 initiates a PostConfigure or Basket API call wanting to purchase a mobile phone that has three
attributes:
• Product: Mobile Phone
• Attribute 1: Color (Identified as cacheable)
• Attribute 2: Capacity (Identified as cacheable)
• Attribute 3: IMEI (Identified as non-cacheable)

• An API call is made specifying updates to attributes 1, 2, and 3 as shown here:


• Update Attribute 1: "Black"
• Update Attribute 2: "64GB"
• Update Attribute 3: "111111111111111" 1
• The result is a cache miss because none of the attributes exist in the cache response object for the
request. After the update, the attribute values are as follows:
• Attribute 1: "Black"
• Attribute 2: "64GB"
• Attribute 3: "111111111111111"

Now consider a second nearly identical API call but this time two of the three attributes are now contained
in the cache because of the previous call. Note that in this case attribute 3 is not changed from
"111111111111111" to "123456789123456" because "111111111111111" was contained in the cache.

• User 2: Initiates PostConfigure or Basket API with the following:


• Product: Mobile Phone
• Attribute 1 (cacheable)
• Attribute 2 (cacheable)
• Attribute 3 (non-cacheable)
• Request
• Update attribute 1: "Black"
• Update attribute 2: "64GB"

© 2021 Vlocity LLC, a Salesforce


company 55
Digital Commerce

• Update attribute 3: "123456789123456"


• The result is a cache hit because attribute 1, "Black" and "64GB" exist in the cache. The value for
attribute 3 remains the same because the value was stored in the cache from the previous API call.
• Update attribute 1: "Black"
• Update attribute 2: "64GB"
• Update attribute 3: "111111111111111" - Note that the response does not change with the updated
value.

Now consider the same scenario as before but run on off-platform. The results are nearly but not quite
identical. As before, a user initiates a PostConfigure or Basket API call with one product that has three
attributes. Attribute 1 and 2 have been configured as cacheable while attribute 3 is not cacheable:

• User 1 initiates a PostConfigure or Basket API call with the following:


• Product: Mobile Phone
• Attribute 1 (cacheable)
• Attribute 2 (cacheable)
• Attribute 3 (non-cacheable)

• An API call is made specifying updates to all three attributes:


• Update attribute 1: "Black"
• Update attribute 2: "64GB"
• Update attribute 3: "111111111111111"
• The result is a cache miss because attribute 1, "Black" and attribute 2 "64GB" do not exist in the cache
response object for the first request.
• Update attribute 1: "Black"
• Update attribute 2: "64GB"
• Update attribute 3: "111111111111111" 1

As before, a second nearly identical API call is made but this time attributes 1 and 2 are now contained in
the cache because of the previous API call. In this case, however, attribute 3 is updated with the second
API call.

• User 1 initiates a PostConfigure or Basket API call with the following:


• Product: Mobile Phone
• Attribute 1 (cacheable)
• Attribute 2 (cacheable)
• Attribute 3 (non-cacheable)

• An API call is made specifying updates to attributes 1 and 2:


• Update attribute 1: "Black"
• Update attribute 2: "64GB"
• Update attribute 3: "123456789123456"

1In either configuration, excluded attributes are not saved to the basket. Therefore, best practice is to omit values for non-cacheable
attributes during a basket operation; instead, append them after the Salesforce order record is created.

© 2021 Vlocity LLC, a Salesforce


company 56
Digital Commerce

• The result is a cache miss because attribute 1, "Black" and attribute 2, "64GB" do not exist in the cache
response object for the first request. However, attribute 3 is updated.
• Update attribute 1: "Black"
• Update attribute 2: "64GB"
• Update attribute 2: "123456789123456" <-- The responses does change with the updated value.

Digital Commerce API Quick-Start Guide


Using Postman, you can quickly and easily test and run the Digital Commerce APIs, giving you the
opportunity to experiment with different parameters and parameter data and view the values that are
returned.

By using the Digital Commerce API Postman collection, API variables and parameters are preconfigured
allowing you to get started testing quickly.

Information is included about basic Digital Commerce setup and Postman environment installation and
configuration. Hints and tips for calling the Digital Commerce APIs using Postman are also provided.

Postman is a third-party application that can be installed on Windows (32 or 64-bit), Mac, and Linux (64-bit).

Before You Begin


Before starting to use Vlocity Digital Commerce features, ensure you meet the following prerequisites:

• You have installed the Winter '19 version of CME or later.


• You have the latest version of Postman installed on your computer. You can download the latest version
here: https://www.postman.com/downloads/.
• You have added new picklist values to the CachedAPIResponse object (see Picklist Value Activation for
more information).
• If you are using the Winter '20 version or later, create a new trigger named
CacheAPI.CacheManagement from the Trigger Setup page and set it to On.
• Check Vlocity CMT Administration > CPQ Configuration Setup for the following:
• Multi-Transaction Service should be set to true by default (MTSEnabled = true) and is used to avoid
exceeding Salesforce Governor limits. See Multi-Transaction Service.
• The CacheAPI.CreateCartFromContextKey value is false by default, but it is recommended that the
value be set to true. The difference in usage explained in Create Cart from Basket section below
• Execute Vlocity CMT Administration > Cacheable API Jobs > LOAD API METADATA. See Initializing
the API Cache for more information.

NOTE
Run the Load API Metadata job only once. Subsequent executions reset the APIs to
their default configuration and erase any changes to API metadata (such as extensions
to parameters).

© 2021 Vlocity LLC, a Salesforce


company 57
Digital Commerce

API Task Reference


The table below shows which Digital Commerce API to use given a specific task to perform. Also shown are
the API methods to use (GET, POST, or PUT).

Table 4. API task reference


Task API method API
Retrieve a list of offers from a catalog GET Get Offers by Catalog API
Retrieve a list of featured offers GET Get Offers by Catalog API
Retrieve offers that contain a specified product GET Get Offers by Catalog API
Retrieve offer details and child items GET Get Offer Details API
Configure an offer and view updated prices, quantities, and attributes POST Post Offer Details with Configuration API
Put item in basket POST Create Basket with BasketAction
Put selection into existing basket POST Update Basket Contents API
Retrieve cart items GET Get Basket Details API
Convert basket to Salesforce order POST Create Cart from Basket

Getting Things Ready


The basic elements shown below must be configured for the Digital Commerce APIs to function properly.

1. EPC Configuration and Catalog Configuration


You must set up a product catalog and ensure that it is set up correctly for the Digital Commerce APIs.
For example, products should have Product Code populated, and price list entries should exist for all
products that are attached to the catalog. See Digital Commerce API Usage Considerations for more
information.
2. Cache Configuration
The Digital Commerce API cache stores catalog data for quicker retrieval of information from API calls.
Digital Commerce cache management provides the ability to update or recreate the cache, for either
on-platform or off-platform solution architectures.
To configure the Digital Commerce API cache:
1. Run the Maintenance jobs as required:
• Clear Managed Platform Cache
• Product Hierarchy Maintenance
• Refresh Platform Cache
See Digital Commerce Cache Management for more information.
2. Go to Vlocity CMT Administration > Populate API Cache, click Start and run the Cacheable API
Jobs.

TIP
If your project does not use the Get Contains Offers API (which searches for all
parent products and offers having the requested product as a child), then running
related batch jobs may be skipped to save time and data storage.

© 2021 Vlocity LLC, a Salesforce


company 58
Digital Commerce

NOTE
A Cache Management feature was introduced in the Winter ’20 release; any prior
release requires manual deletion of cached records before job execution. To
manually delete cached records, open the Developer Console and select and
paste the following command:Debug > Open Execute Anonymous Window

delete [select Id from vlocity_cmt__CachedAPIResponse__c];

3. Configure the Connected App


To call the Digital Commerce APIs from Postman, you must first deploy a connected app in your org.
The connected app handles security (OAuth in this case) and permits access to org data from external
APIs. If your API calls return authorization errors, ensure the IP restrictions of the app are set correctly
(Full Access).
To configure the connected app:
1. In your org, go to App Setup > Create > Apps, then under Connected Apps, click New.
2. Fill in a Connected App Name, API Name, and Contact email, then click Save.
3. Under API (Enable OAuth Settings) select Enable OAuth Settings.
4. Under Selected OAuth scope, specify Full Access.
5. Under Callback URL, enter the following:

https://www.getpostman.com/oauth2/callback

Your screen should resemble the following illustration:

© 2021 Vlocity LLC, a Salesforce


company 59
Digital Commerce

6. Click Save.
The following message displays:

Allow from 2-10 minutes for your changes to take effect on the server
before using the connected app.
7. When the app has been deployed, copy the Consumer Key and Secret into the environment
configuration in Postman.
4. Download and Configure the Postman Environment
Update the environment configuration with your details. Follow the steps below to download a Postman
configuration file that contains the necessary variables for you to run the APIs:
1. Use the following link to download the environment file:
https://volt.my.salesforce.com/sfc/p/o0000000IKm8/a/3m0000005umu/
ylHiaMX54l5.SlvjJDhAN1qXnfKgjva5RXvIL2CJufY
2. Start Postman and select the Manage Environments icon in the upper-right corner of the Postman
screen.
3. Click Import and select the environment file you downloaded in step 1.
4. Configure your environment with the following values:

Table 5. Postman environment settings


Key Value
URL https://login.salesforce.com or https://test.salesforce.com depending on the type of the
org used.
baseUrl Your org name with at the end /services/apexrest/vlocity_cmt

For example:

https://demo.my.salesforce.com/services/apexrest/vlocity_cmt
username Your org username
password Your org password. Avoid using the "&" character in the password; Postman does not process it correctly.
clientId The Connected app client ID from ???.
clientSecret The Connected app Secret from ???
5. Download and Install the Postman Collection
The file is a Postman collection that contains variables and configuration settings to make calling the
Digital Commerce APIs quickly and easily.
1. Use the following link to download the Postman collection file: https://volt.my.salesforce.com/sfc/p/
o0000000IKm8/a/3m0000005umv/X8mm38e.7nCeHE52342fSYgZVFnI9ANWfr0Q2iJJjd8
2. Start Postman (if necessary) and click Import.
3. Drag and drop the Postman collection you downloaded in step 1.
6. Configure Amazon Web Services (AWS) (Optional)
Use the information in this section if you are using an AWS off-platform solution.
AWS configuration is simple; just populate the template with the baseUrl and InitAccessToken
(Vlocity Cloud Engineering will provide these items upon provisioning an instance for your customer).
Make sure that /dc is at the end of the URL.
All API requests are designed to work with both AWS and SFDC; simply change the environment in the
dropdown and issue the API call.

© 2021 Vlocity LLC, a Salesforce


company 60
Digital Commerce

Retrieve OAuth Authorization


When the preceding steps are complete, run the SFDC OAuth Username Password API from the API
collection. This step must be performed every time you start a new session or when the token expires.

The API executes a script that auto-populates a unique session token {{InitAccessToken}} in the
environment variable. After executing, each call uses the token. If the token expires, simply rerun the API
call.

Stem sentence

1. If necessary, start Postman on your computer.


2. If necessary, load the Digital Commerce APIs collection.
3. Select SFDC OAuth Username Password and click Send. Your screen should resemble the
illustration below:

© 2021 Vlocity LLC, a Salesforce


company 61
Digital Commerce

NOTE
If the API call does not authorize transactions, check that the IP restrictions of the APP are
set correctly.

Run the API Examples


The following Postman examples illustrate how to run each of the Digital Commerce APIs, along with hints
and usage tips.

Get Offers By Catalog


To run the Get Offers By Catalog API, select it in Postman first, then define a catalog code as a path
variable in the Params tab (see illustration below). Other Parameters are optional and disabled by default.

© 2021 Vlocity LLC, a Salesforce


company 62
Digital Commerce

After filling in the catalog name click Send. The results of the API call are displayed in a Postman window.

Get Featured Offers


This API is the same as Get Offers by Catalog. Simply specify a value for the sortby parameter variable
and click Send.

Get Contains Products


This API is the same as Get Offers by Catalog. Enable the contains parameters variable and click Send.

© 2021 Vlocity LLC, a Salesforce


company 63
Digital Commerce

Get Offer Details


This API call uses two Path variables: catalogcode and offercode. Fill in with appropriate values for your
catalog and click Send.

© 2021 Vlocity LLC, a Salesforce


company 64
Digital Commerce

Post Offer Details with Configuration


This API (also known as Validate API) requires the same input as Get Offer details - that is, catalogcode
and offercode, plus a request body. First run Get Offer Details, copy the full response, paste it as a body
for the Post Offer Details with Configuration, remove contextKey from the body, and click Send.

Change Attribute values by modifying the userValues keys. For example, "userValues": "500". This API
will retrieve ABP prices (if configured) without the need to put item into the basket.

Create Basket with BasketAction


Split into two API calls: Create Basket (AddWithNoConfig) and Create Basket (AddAfterConfig). The
difference is in the body submitted in the call.

© 2021 Vlocity LLC, a Salesforce


company 65
Digital Commerce

Create Basket - AddWithNoConfig


This API requires catalogcode, basketAction, and offercode.

If the response will consume more resources or will take a long time to execute, set a threshold. A
multiTransactionKey will then be generated. Simply add the key/value into the request body and submit the
request again:

© 2021 Vlocity LLC, a Salesforce


company 66
Digital Commerce

Create Basket - AddAfterConfig


This API is a bit more complex than previous one. It requires a full payload from Get Offer Details.

Note that the response structure is slightly different and must be trimmed manually. Сopy the full response
from GetOfferDetails:

Replace everything after "productConfig": {

© 2021 Vlocity LLC, a Salesforce


company 67
Digital Commerce

Now, remove first 3 rows:

{
"contextKey": "970906428f3953cde9b252d8286e6e77",
"result": {

Make sure structure is correct; check that all curly brackets “{“, “}” are in place. Postman will highlight any
inconsistencies, such as an extra or missing bracket.

Create Basket - AssetToBasket


This API requires that you pass the following parameters: catalogcode, basketAction, rootAssetIds,
requestDateTime.

© 2021 Vlocity LLC, a Salesforce


company 68
Digital Commerce

Modify Basket
You can modify the contents of the basket in several ways as shown in the sections here.

Add Additional Product to Basket


This API is described by Create Basket (AddWithNoConfig) and Create Basket (AddAfterConfig). The
difference is the cartContextKey of the previous basket.

Copy the cartContextKey from the response; it should resemble the following:

"cartContextKey": "c96443b4c5ad00c2f6820a9d8b37f5cb"

Insert the value into the cartContextKey Path variable:

NOTE
The cartContextKey is generated every time a change is made to the basket. Make sure to
take the latest from the response to make additional changes to the basket.

Delete or Update Basket Item


The Basket response contains all of the required parameters to perform these actions. Look for the actions
node.

© 2021 Vlocity LLC, a Salesforce


company 69
Digital Commerce

Use the values from the actions node to form the request body:

{
"bundleContextKey": "<string>",
"lineItemKey": "<string>",
"basketAction": "<string>"
}

Update Item Quantity or Attributes


To update items, add Quantity or attributeCategories to the request body, as shown here.

{
"bundleContextKey": "<string>",
"lineItemKey": "<string>",
"basketAction": "<string>",
"Quantity": "<string>",
"attributeCategories": "<string>"
}

© 2021 Vlocity LLC, a Salesforce


company 70
Digital Commerce

Add Child Item


This API call is similar to the previous call. To run, inspect the data that is in the basket and copy the values
to the related keys in the request.

Get Basket Details


This API requires cartContextKey and catalogcode

Create Cart From Basket


This API request depends on the CacheAPI.CreateCartFromContextKey setting (refer to CPQ
Configuration Settings Reference). If set to true, then use Create Cart from Basket Key (recommended);
otherwise use Create Cart from Basket; however, the API call requires the entire basket response as
JSONResult, which might be quite large and not secure for transactions.

© 2021 Vlocity LLC, a Salesforce


company 71
Digital Commerce

See Also

• https://docs.vlocity.com/en/API-Usage-Considerations.html.
• https://docs.vlocity.com/en/Troubleshooting-Digital-Commerce-API-Calls.html
• https://docs.vlocity.com/en/CPQ-Configuration-Settings-Reference.html

Digital Commerce API Swagger Reference

NOTE
If the Swagger does not render, refresh this page.

Digital Commerce APIs

Browse Operations
You use the browse APIs to retrieve information about products in your catalog. Browse operations consist
mostly of GET API calls that you use to find featured offers, offer details, list featured offers and so on.

© 2021 Vlocity LLC, a Salesforce


company 72
Digital Commerce

Get Offers by Catalog API


The Get Offers by Catalog API provides the ability to retrieve products and promotions that are modeled
within the Vlocity Shared Catalog.

The specified catalog code identifies the catalog that contains offers (products and promotions). You can
optionally specify a page size to limit the number of results returned. The sort order of the result is based on
the sequence field or another specified field. You can search either by name or description.

The API also supports Get Filtered Products, where offers that contain specified child offers are returned. A
response code of 200 indicates a successful call while 400 indicates a failed response.

This API supports both anonymous and logged-in users. You use the isloggedin flag to indicate whether
the user is logged in or not.

For known users - that is, when isloggedIn=true and a context is specified - the Get Offers by Catalog
API returns a qualification node for each offer. The qualification node indicates whether the qualification
rules passed or failed for a given offer. qualificationType: Pass indicates that the offer passed
qualification rules, whereas qualificationType: Fail indicates that the offer did not pass qualification
rules.

For anonymous users, the API returns only qualified offers and the qualificationType node is not returned.
Offers that are not qualified are not returned.

Rules Supported
• Qualification Rules for Products
• Qualification Rules for Promotions
• Response contains Base Prices only (see Product Pricing)
• Also see Using Context Rules with Digital Commerce APIs

Prerequisites
• The Catalog should have the CatalogCode__c field populated. No spaces are permitted in
CatalogCode__c.
• Products should have ProductCode populated. No spaces are permitted in ProductCode.
• Promotions should have Code__c populated and no space is allowed in Code__c.
• Catalog should be present with products and promotions attached to it as records under
CatalogProductRelationship__c object.
• Catalog should be attached to a default price list through DefaultPriceList__c field on Catalog__c object.
• Price list entries should exist for all the products attached to the catalog.
• All products present under associated promotions (for a catalog ), must also have a relationship with
catalog. Products should be added to Catalog, before adding them to any promotion associated with the
catalog.
• A record should be created under the Vlocity API Metadata object for getOffers API. This can be
populated by running a batch job named as LOAD API METADATA which is present under CMT
Administration > Cacheable API Jobs.

© 2021 Vlocity LLC, a Salesforce


company 73
Digital Commerce

• (Optional) To cache records that are associated with the getOffers API you can optionally run the
Populate API Cache batch job (located in CMT Administration > Cacheable API Jobs). After populating,
context eligibility and pricing records, you can also run the batch job using the following statement:
database.executeBatch(new BatchCacheProcessor('getOffers'));
• Availability and eligibility rules are not supported. Eligibility can be controlled using context rules.
PricingRule and Tightest match for prices are also not supported; however, base prices, adjustments,
and override prices are supported.

Parameters
For API parameter names and descriptions, see Digital Commerce API Swagger Reference.

For information about returning Product2 or Promotion fields that are not returned by default, see Retrieving
Additional Product2 or Promotion Fields.

GetOffersByCatalog for an anonymous user


GET /v3/catalogs/{catalog_code}/offers

Examples
In the examples that follow, braces around items ( { } ) indicate replaceable parameters that you specify.

Return a list of offers:

Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers

The GetOffersByCatalog API supports pagination. The response contains an action named
nextOffersAction which contains a REST URL you can use to fetch the products on the next logical page.

Return a list of offers and specify a page size of 20:

Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
offset=0&pageSize=20

Return a list of offers and specify a page size and offset:

Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
offset=20&pageSize=20

© 2021 Vlocity LLC, a Salesforce


company 74
Digital Commerce

Return a list of offers and specify a context:

Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
context={"Status":"Active"}

Context parameters that specify which offers qualify for the end user can be passed to the API.

Return a list of offers and specify multiple contexts:

Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
context={"SLA__c":"Silver","Status":"Inactive"}

Sorting is based on fields passed from the Catalog Product Relationship object. Because the offers list
contains both products and promotions, the parameter on which to sort the offer list is added to the records
of the Catalog Product Relationship object.

Return a list of offers sorted by sequence number:

Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
sortby=vlocity_cmt__SequenceNumber__c_ASC

Return a list of offers sorted by Active status:

Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
sortby=vlocity_cmt__SequenceNumber__c_ASC,Name_DESC&context={"Status":"Active"}

GetOffersByCatalog for a logged-in user

GET /v3/catalogs/{catalog_code}/offers?
context{"accountid":"account_ID"}&isloggedin=true

Retrieves offers from the specified Catalog (identified by the Catalog Code). Offers can be a product or a
promotion. The sortby parameter can sort featured offers first in the result set.

© 2021 Vlocity LLC, a Salesforce


company 75
Digital Commerce

Examples

Return a list of offers for a logged-in user:

Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
context={"accountId":"{account_number}"}&loggedIn=true

Return a list of offers for a known user and specify a page size of 20:

Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
offset=0&pageSize=20?context={"accountId":"{account_number}"}&loggedIn=true

The rest of the examples are all the same format as for anonymous users, except that a context is specified
and the isloggedIn parameter is set to true.

Retrieving Additional Product2 or Promotion Fields


To return additional Product2 or Promotion fields that are not returned by default, use the
GetOffersByCatalog and GetOfferDetails APIs.

For the response to contain additional fields from the Product2 or Promotion objects, you must first specify
the fields as part of the GetOffersByCatalog or GetOfferDetails API metadata. Once configured, rerun the
API Response Batch jobs to populate the cache response.

To return additional Product2 or Promotion fields:

1. Navigate to the All Tabs page by clicking the + icon.


2. From the list of tabs, select Vlocity API Metadata. The list of API objects is displayed.
If the Vlocity API Metadata tab is not shown in the All Tabs list, see the Creating a Custom Object Tab
topic in the Salesforce help.
3. To display the metadata fields, select All from the Select Views list.

© 2021 Vlocity LLC, a Salesforce


company 76
Digital Commerce

4. Click the GetOffers API Name then select the Edit icon next to API Params.
5. In the API Params field, enter the Product2 or Promotions fields that you want to retrieve using the API
call. For example, to return the fields IsActive and Family from the Product2 catalog enter the
following in the API Params field:

{"productFields":["IsActive","Family"]}

You can return Promotion fields in a similar manner:

{"promotionFields":["pricelist","Service_continuation"]}
6. From the Vlocity CMT Administration screen, click Maintenance Jobs and then click Start next to
Clear Managed Platform Cache.
7. From the Vlocity CMT Administration screen, click Cacheable API Jobs, then click Start next to Delete
Expired API Cache.
8. From the Vlocity CMT Administration screen, click Cacheable API Jobs, click Start next to Populate
API cache, and run all of the jobs.
9. Run the GetOffersByCatalog or GetOfferDetails API. The additional fields are displayed in the JSON
output.
Only fields that are populated in the catalog are displayed in the API results. The API does not return
empty or undefined fields.

NOTE
Do not run the Load API Metadata job. Doing so will overwrite the data you specified
in the API metadata field.

© 2021 Vlocity LLC, a Salesforce


company 77
Digital Commerce

NOTE
The APIParms metadata returned by the GetOffers API overwrites the metadata
returned by the Get Contains Products API. That is, if the APIParams field is
configured with a specific value, and the GetOffers API is run, the metadata from
GetOffers overwrites the metadata for the Get Contains Products API.

Get Featured Offers API


The Get Featured Offers API provides the ability to retrieve a list of offers (products or promotions) that are
modeled within the Vlocity shared catalog which are sorted by a specified Catalog Product Relationship
field. The specified catalog_code identifies the catalog that contains the offers. Offer eligibility can be
determined by API parameters which support both anonymous and known user journeys.

This API support a flag called isloggedin to indicate whether a user is logged in or anonymous. If the
isloggedin parameter is true, it indicates a logged-in user, and an accountId must be specified in the
context parameter of the API call. If the isloggedin flag is false, it indicates that the user is anonymous.

See Get Offer Details API for more information and examples. Also see Digital Commerce API Swagger
Reference.

In this topic
Get Featured Offers for an Anonymous User

Get Featured Offers for a Logged In User

Rules Supported

• Qualification Rules for Products


• Qualification Rules for Promotions
• Response contains Base Prices only (see Product Pricing)
• Also see Using Context Rules with Digital Commerce APIs

Prerequisites

• The Catalog should have the CatalogCode__c field populated. No spaces are permitted in
CatalogCode__c.
• Products should have ProductCode populated. No spaces are permitted in ProductCode.
• Promotions should have Code__c populated and no space is allowed in Code__c.
• Catalog should be present with products and promotions attached to it as records under
CatalogProductRelationship__c object.
• Catalog should be attached to a default price list through DefaultPriceList__c field on Catalog__c
object.Pricelist entries should exist for all the products attached to the catalog.

© 2021 Vlocity LLC, a Salesforce


company 78
Digital Commerce

• All products present under associated promotions ( for a catalog ), must also have a relationship with
catalog. Products should be added to Catalog, before adding them to any promotion associated with the
catalog.
• A record should be created under the Vlocity API Metadata object for getOffers API. This can be
populated by running a batch job named as LOAD API METADATA which is present under CMT
Administration > Cacheable API Jobs.
• Optional: To cache records that are associated with the getOffers API you can optionally run the Populate
API Cache batch job (located in CMT Administration > Cacheable API Jobs). After populating, context
eligibility and pricing records, you can also run the batch job using the following statement:
database.executeBatch(new BatchCacheProcessor('getOffers'));
• The Interface Implementation under ProductAvailability and ProductEligibiltiy is ignored. You must use
Context Eligibility Rules to determine eligibility of Products. PricingRule and Tightest match for prices are
not supported; however, base prices, adjustments, and override prices are supported.

Parameters
For detailed API response descriptions, see Digital Commerce API Swagger Reference.

Response
For detailed API response descriptions, see Digital Commerce API Swagger Reference.

Get Featured Offers for an Anonymous User


GET /v3/catalogs/{catalog_code}/offers

You can return featured offers using the getOffersByCatalog API with the sortby parameter. First, populate
the Sequence Number field for products and promotions in the catalog. Then make an API call similar to
the following:

Method:
GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
sortby={namespace}__SequenceNumber__c_ASC

Get Featured Offers for a Logged In User


GET /v3/catalogs/{catalog_code}/offers?context={"accountId":"{account
number}"}&loggedIn=true

You can return featured offers using the getOffersByCatalog API for a logged in user with the sortby
parameter. First, populate the Sequence Number field for products and promotions in the Catalog. Then
make an API call similar to the following:

Method:
GET

© 2021 Vlocity LLC, a Salesforce


company 79
Digital Commerce

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
sortby=vlocity_cmt__SequenceNumber__c_ASC&context={"accountId":"{0016A0000053kH
N"}&loggedIn=true

Get Contains Products API


Retrieve offers for the specified product code.

This API is a variation of the Get Offers by Catalog API. The response includes orderable offers
(promotions and products) that contain the specified product. A cart ID is not required.

A promotion includes all the products associated with the promotion, including the root-level product.

This API support a flag called isloggedin to indicate whether a user is logged in or anonymous. If the
isloggedin parameter is true, it indicates a logged-in user, and an accountId must be specified in the
context parameter of the API call. If the isloggedin flag is false, it indicates that the user is anonymous.

See Get Offer Details API for more information and examples. See Digital Commerce API Swagger
Reference.

Rules supported
• Qualification Rules for Products
• Qualification Rules for Promotions
• Response contains Base Prices only (see Product Pricing)
• Also see Using Context Rules with Digital Commerce APIs

Prerequisites
• Catalog should have CatalogCode__c populated and no space is allowed in CatalogCode__c.
• Products should have ProductCode populated and no space is allowed in ProductCode.
• Promotions should have Code__c populated and no space is allowed in Code__c.
• Catalog should be present with products and promotions attached to it as records under
CatalogProductRelationship__c object.
• The catalog should be attached to a default price list through DefaultPriceList__c field on Catalog__c
object.
• Price list entries should exist for all products attached to the catalog.
• The Product Hierarchy Maintenance job should be run before executing this API.

Parameters
For API parameter names and descriptions, see Digital Commerce API Swagger Reference.

Response
A response code of 201 indicates a successful call while 400 indicates a failed response.

For detailed API response descriptions, see Digital Commerce API Swagger Reference.

© 2021 Vlocity LLC, a Salesforce


company 80
Digital Commerce

Get Contains Products for an Anonymous User

Method: GET
/v3/catalogs/{catalog_code}/offers?contains={product_code}

Example

Retrieve an offer with a specific product code for an anonymous user:

GET /services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
contains={offer_code}

Get Contains Products for a logged-in User

Method: GET
/v3/catalogs/{catalog_code}/offers?
contains={product_code}&context={"accountId":"{account_ID}"}&loggedIn=true

Example

Retrieve an offer with a specific product code for a logged-in user:

GET /services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
contains={offer_code}?context={"accountId":"{account_ID}"}&loggedIn=true

Get Offer Details API


Retrieve detailed information about a specific offer (either product or promotion). The API returns the full
hierarchy of a product or promotion as defined in the product catalog.

The API response is created from the pre-cached results present in the sObject (current caching layer). The
API also handles cache misses. Along with returning the offer detail, the API caches the data for future
requests. Prices, adjustments, and overrides are returned along with offers. The API does not use the
Salesforce ID as part of the request and response parameters.

This API supports the isloggedin flag to indicate whether a user is logged in or anonymous. If the
isloggedin flag is true, it indicates a logged-in user, and an accountId must be specified in the context
parameter of the API call. If the isloggedin flag is false, it indicates that the user is anonymous.

See Get Offer Details API and Digital Commerce API Swagger Reference.

Rules Supported

• Qualification Rules for Products


• Qualification Rules for Promotions
• Qualification (Context) Rules for Price List Entries

© 2021 Vlocity LLC, a Salesforce


company 81
Digital Commerce

NOTE
Qualification/Context rules for price list entries are supported for known users and not for
anonymous users.

• Also see Using Context Rules with Digital Commerce APIs

Prerequisites

• Catalog should have CatalogCode__c populated and no space is allowed in CatalogCode__c.


• Products should have ProductCode populated and no space is allowed in ProductCode.
• Promotions should have Code__c populated and no space is allowed in Code__c.
• Catalog should be present with products and promotions attached to it as records under
CatalogProductRelationship__c object.
• Catalog should be attached to a default price list through DefaultPriceList__c field on Catalog__c object.
• Price list entries should exist for all the products attached to the catalog.
• A record should be created under Vlocity API Metadata object for getOfferDetails API; this can be
populated by running a batch job named as LOAD API METADATA, which is present under CMT
Administration → Cacheable API Jobs.
• To cache records related to the getOfferDetails API, run the batch job named Populate API Cache.
Another way is to run the job is through anonymous block using the following statement (After populating,
context eligibility and pricing records): database.executeBatch(new
BatchCacheProcessor('getOfferDetails'));
• Create a custom setting called CacheAPIFields with a value of true. CacheAPIFields is not required for
CME 103.1.14 and later versions.

Parameters
For API parameter names and descriptions, see Digital Commerce API Swagger Reference.

For information about returning Product2 or Promotion fields that are not returned by default, see Retrieving
Additional Product2 or Promotion Fields.

Response
For detailed API response descriptions, see Digital Commerce API Swagger Reference.

Get Offer Details for an Anonymous User


In the examples below, substitute your own values for the following parameters:

• myCatalog = Catalog Code


• myOfferCode = Offer Code
• myPromotion = Promotion Code
• account - account_ID

© 2021 Vlocity LLC, a Salesforce


company 82
Digital Commerce

GET /v3/catalogs/{catalog_code}/offers/{offer_code}

Examples

Retrieve a list of offers for a specified product:


Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers/{product_code}

Retrieve offer details about a specific promotion:


Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers/
{promotion_code}

Get Offer Details for a Logged-In User


GET /v3/catalogs/{catalog_code}/offers/{offer_code}?
context={"accountId":"0016A0000053kHN"}&isloggedIn=true

Examples

Retrieve a list of offers for a specified product:


Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers/
{product_code}?context={"accountId":"0016A0000053kHN"}&isloggedIn=true

Retrieve offer details about a specific promotion:


Method: GET

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers/
{product_code}?context={"accountId":"0016A0000053kHN"}&isloggedIn=true

Post Offer Details with Configuration API


This API provides the ability to configure an offer (either a product or promotion) and view updated prices,
quantities, and attributes. Returns the configured product details.

The configured product details are cached so that subsequent requests for the same configuration are
retrieved with the data in the current cache layer.

© 2021 Vlocity LLC, a Salesforce


company 83
Digital Commerce

Validations, prices, adjustments, overrides, rules, context and so on are resolved internally. The Salesforce
ID is not used as part of the request or response parameters.

If validation fails, the OfferDetails structure is returned with an appropriate error message.

Attribute Basket Cache Exclusion


The Fall '20 release includes an Attribute Basket Cache feature. See Attribute Basket Cache Exclusion.

Rules Supported
• Qualification Rules for Price Lists
• Pricing Interface (see Attribute-Based Pricing)
• Product Validation Interface (see Context Rules Framework and Advanced Rules Framework)
• Also see Using Context Rules with Digital Commerce APIs

Prerequisites
• The catalog should have CatalogCode__c populated. Spaces are not allowed in CatalogCode__c.
• Products should have ProductCode populated. Spaces are not allowed in ProductCode.
• Promotions should have Code__c populated. Spaces are not allowed in Code__c.
• The catalog should be present with products and promotions attached to it as records under the
CatalogProductRelationship__c object.
• The catalog should be attached to a default price list through DefaultPriceList__c field on Catalog__c
object.
• Price list entries should exist for all products attached to the catalog.
• Create a custom setting called CacheAPIFields with a value of true. CacheAPIFields is not required for
CME 103.1.14 and later versions.

Parameters
For API parameter names and descriptions, see Digital Commerce API Swagger Reference

Response
For detailed API response descriptions, see Digital Commerce API Swagger Reference.

Post Offer Details for an anonymous user


POST /v3/catalogs/{catalog_code}/offers/{offer_code}

Sample Session
This example demonstrates how to add promotions using a two-step process.

Ensure you have created a catalog that contains both products and promotions.

Ensure that you have set the CacheAPIPartialConfigure custom setting to true. Also ensure you have set
the CacheAPIFields custom setting to true. You set custom parameters in Vlocity CMT Administration >
CPQ Configuration Setup.

© 2021 Vlocity LLC, a Salesforce


company 84
Digital Commerce

Ensure you have run the appropriate Cacheable API batch jobs. From the Vlocity CMT Administration >
Cacheable API Jobs screen, run the Load API Metadata job. Running this job populates metadata to the
metadata classes and also some metadata settings.

Run the Populate API Cache job by clicking Start. From the Populate API Cache window, select
GetOfferDetails and GetPrices.

You can use the Configure Offer API with a two-step process to easily configure an offer.

1. Execute the API with a GET method to retrieve the offer details structure. For example:

GET
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers/
{offer_code}
2. After receiving a result from the API call, copy the result and use it as the body for the POST call.
Before executing the POST call, remove the contextKey from the body, then edit any of the body
parameters as appropriate to configure the offer. When finished, execute the call and verify that the
result is as expected.

POST
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers/
{offer_code}

Request body (truncated):


{"result":{"offerDetails":{"offer":{"offerType":"Promotion","childProducts":
[{"priceResult":[{"adjustments"...
3. The next step applies validation rules, pricing, and updates the response with the PromoDetails
structure. In the response from the previous step, under the validateAndPriceAction, you will see the
transactionKey REST parameter. Add the transactionKey in the request body to make the request. In
the following example, the request body has been truncated for clarity.

POST
/services/apexrest/vlocity_cmt/v3/catalogs/Mobiles/offers/iPhone8Offer?
forceinvalidatecache=true

Request body (truncated):


{"transactionKey": "on08j8/
KOpxKTOTzjndq8F3yoFA7FMYeLyhnYywJt2jok0JZr6Bq3StBYDnoTwYl","result":
{"offerDetails":{...

NOTE
The forceinvalidatecache parameter is used only for debugging purposes. When
enabled by a server setting, forceinvalidatecache=true forces a cache refresh.

© 2021 Vlocity LLC, a Salesforce


company 85
Digital Commerce

Basket Operations
You use basket operations to add, subtract, or modify the contents of a basket.

The POST REST endpoint provides the ability for a user to add offers to a virtual basket maintained by the
user interface. The basket is tracked using the cartContextKey in the URL; for an empty basket, there is
no need to pass the cartContextKey, which is returned as part of the response of a successful basket
operation

Offers may include both products and promotions. Offers can be added directly or after configuring them.

The API returns a list of bundle structures in the basket. The list structure is compliant with pricing,
overrides, rules, adjustments, attributes, and so on.

The API uses cartContext to track existing basket contents and appropriate context parameters to price
products and run rules.

If the API result is present in the cache, that result is returned. If the result is not in the cache, it is treated
as a cache-miss, and the result is stored in the cache for successive calls.

The API also allows users to delete from an existing basket with the deleteBundleNumber parameter.

Get Basket Details API


Retrieves details about a basket.

This API supports the isloggedin flag to indicate whether a user is logged in or anonymous. If the
isloggedin flag is true, it indicates a logged-in user, and an accountId must be specified in the context
parameter of the API call. If the isloggedin flag is false, it indicates that the user is anonymous.

If the isloggedin flag is not specified or if the isloggedin flag is set to false then Context dimension values
should be specified in the following format: dimension1:val1,dimension2:val2. The key-value pairs specify
Context Dimension values that describe the context to be used in rule processing. If a value for a context
dimension defined in the Vlocity Product Catalog is not provided, the default value specified on the Context
Dimension is used to determine eligibility and pricing. If isloggedin=true is specified, you must also specify
one of the following: accountId, contractId , or rootAssetIds.

Attribute Basket Cache Exclusion


The Fall '20 release includes an Attribute Basket Cache feature. See Attribute Basket Cache Exclusion.

Rules Supported
This API does not run any rules.

Prerequisites
• Products must have ProductCode populated (no spaces are allowed in ProductCode).
• Promotions must have Code__c populated (no spaces are allowed in Code__c).

© 2021 Vlocity LLC, a Salesforce


company 86
Digital Commerce

• A catalog must be present with products and promotions attached to it as records under the
CatalogProductRelationship__c object. The catalog should have CatalogCode__c populated (no spaces
are allowed in CatalogCode__c).
• The catalog must be attached to a default price list through the DefaultPriceList__c field on the
Catalog__c object.
• Price list entries must exist for all the products that are attached to the catalog.
• Optional: To populate the cache, the following batch jobs may be run:
• Context combinations
• Offer details
• Pricing results
• Create a custom setting called CacheAPIFields with a value of true. CacheAPIFields is not required for
CME 103.1.14 and later versions.

Parameters and Response Information


For API parameter names, descriptions, and response information, see Digital Commerce API Swagger
Reference.

Get Basket Details for an Anonymous User


GET /v3/catalogs/{catalog_code}/basket/{basket_key}

Retrieves details about a basket.

GET /services/apexrest/vlocity_cmt/v3/catalogs/Mobile/basket/
bdbe113c6fd2d90835372d104f7a4a8b

Get Basket Details for a Known User


GET /v3/catalogs/{catalog_code}/basket/{cart_context_key}?
context="accountId":"{account_id}"&isloggedin=true

After one or more items have been added to a basket, you can view the basket contents for a known user
using a format similar to the following:

GET /services/apexrest/vlocity_cmt/v3/catalogs/TEST/basket/
bdbe113c6fd2d90835372d104f7a4a8b?
context={"accountId":"xxxxxxxxxxxxxx"}&isloggedin=true

Create Basket with BasketAction


The Create Basket with BasketAction API provides the ability to create a basket from items that were added
by a user during the configure operation. Also see Post Offer Details with Configuration API.

Use this API to create a basket in the following ways depending on the format of the request body:
AddWithNoConfig, AddAfterConfig, and AssetToBasket.

• returnBasket - This flag indicates whether to return basket information in the AssetToBasket API
response. The default value is true, meaning that the AssetToBasket API returns basket information as it

© 2021 Vlocity LLC, a Salesforce


company 87
Digital Commerce

did in previous releases, ensuring backward compatibility. If set to false, the Assettobasket API returns
only the basket key, and not the complete basket. To use the returnBasket flag, the
CacheAPI.SkinnyBasket custom setting must be set to true.
• includeAttachments - Use this flag to determine whether the API returns attachments URI or not. The
default value is false. If includeAttachment is true, the basket API returns a URI to the attachments. If
includeAttachment is false or the isloggedin flag is false, the basket API does not return the
attachments.
• When basket items are created, added, modified, or deleted, the basket contents effectivity are validated.

AddWithNoConfig
To add the offer without any configured attribute values, pass the following in the request body of the API
call:

"basketAction":"AddWithNoConfig",
"offer":"offer_code"

AddAfterConfig
To add a configured offer, pass the following in the body of the API call:

"basketAction":"AddAfterConfig"
"productConfig":"result_from_Get_Offer_Details_API"

AssetToBasket
To change an asset to a basket, format the body of the API call similar to the following:

"basketAction":"AssetToBasket"
"rootAssetIds":"the root asset Ids"
"requestDateTime":"requested_date_time"

Use UTC date format for the date-time string: YYYY-MM-DDTHH:MM:SS.SSSZ. Ensure that you specify
the RequestDateTime parameter using UTC date and time.

Attribute Basket Cache Exclusion


The Fall '20 release includes an Attribute Basket Cache feature. See Attribute Basket Cache Exclusion.

Rules Supported
• Qualification Rules for Price Lists
• Pricing Interface (see Attribute-Based Pricing)
• Product Validation Interface (see Context Rules Framework and Advanced Rules Framework)
• Also see Using Context Rules with Digital Commerce APIs

Prerequisites
• Catalog should have CatalogCode__c populated; spaces are not allowed in CatalogCode__c.
• Products should have ProductCode populated; spaces are not allowed in ProductCode.

© 2021 Vlocity LLC, a Salesforce


company 88
Digital Commerce

• Promotions should have Code__c populated; spaces are not allowed in Code__c.
• Catalog should be present with products and promotions attached to it as records under the
CatalogProductRelationship__c object.
• The Catalog should be attached to a default price list through the DefaultPriceList__c field on Catalog__c
object.
• Price list entries should exist for all the products attached to the catalog.
• Create a custom setting called CacheAPIFields with a value of true. CacheAPIFields is not required for
CME 103.1.14 and later versions.
• Batch jobs for the following should have been run ahead of time, thereby populating the cache:
• Context combinations
• Offer details
• Pricing results

Parameters and Response


For API parameter names and descriptions, see Digital Commerce API Swagger Reference

Sample Usage Scenario


To add an offer without any configured attribute values to a basket:

1. Follow the prerequisites.


2. Ensure you have run the appropriate batch jobs and configured the appropriate custom settings. See
Preparing to Use Vlocity CPQ API Caching.
3. Execute a call to the Get Offer Details API.
4. After successfully running GetOfferDetails, copy and save the entire contents of the OfferDetails
node. For example:
{"result:{"offerDetails":{"offer"...}}}

NOTE
To configure the offer before adding it to the basket, modify the offerDetails JSON
result.

5. Paste the result node from the previous step into the body of the Basket API request.
6. Execute the Create Basket API call:

Method: POST

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket

Request Body
{"basketAction":"AddAfterConfig",
"productConfig":{"offerDetails":{"offer": {}}}}

© 2021 Vlocity LLC, a Salesforce


company 89
Digital Commerce

Create Basket API for an Anonymous User

POST /v3/catalogs/{catalog_code}/basket

Create a new basket and add an offer example

Method: POST

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket

Request Body:
{"offer":"iPhone8","basketAction":"AddWithNoConfig"}

Add an offer to a previously created basket example


In the example, the request body is truncated for clarity.

Method: POST

API:
/services/apexrest/vlocity_cmt/v3/catalogs/Mobiles/basket/
50ba987c870c64774e24c27787288650

Request Body:
{"basketAction":"AddAfterConfig","productConfig":"{\"offerDetails\":{\"Offer\":
{\"priceResult\":...}

Create Basket API for a Known User

/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket?
context={"accountId":"{account_ID}"}&inloggedin=true

Add a Product to an Empty Basket example

Method: POST

API:
/services/apexrest/vlocity_cmt/catalogs/{catalog_code}/basket?
context={"accountId":"{account_ID}"&isloggedin=true

Request Body:
{"offer":"offer_code","basketAction":"AddWithNoConfig"}

Add a Product to an Existing Basket example

Method: POST

© 2021 Vlocity LLC, a Salesforce


company 90
Digital Commerce

API:
/services/apexrest/vlocity_cmt/catalogs/{catalog_code}/basket/
{cart_context_key}?context={"accountId":"{account_ID}"&isloggedin=true

Request Body:
{"offer":"offer_code","basketAction":"AddWithNoConfig"}

Create Basket with AddAfterConfig


The payload for AddAfterConfig is a response of GetOfferDetails API inside 'productConfigNode'. If you
have the response of offer details, you can add it for AddAfterConfig as follows:

{
"basketAction":"AddAfterConfig",
"productConfig":
"offerDetails":<GetOfferDetails response here>
}

Convert Asset to Basket


The following example shows how to convert an asset to a basket. The example assumes you know the
asset ID you wish to convert to a basket, and also the account of the user.

1. Format the request as follows:

Method: POST

API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket?
context={accountId":"{account_ID}"&isloggedin=true

Request POST Body:


{"rootAssetIds":"xxxxxxxxxxxxxx",
"basketAction":"AssetToBasket",
"RequestDateTime":"2019-12-22T00:00:00.000Z"}

To convert more than one asset, you can specify more than one root asset ID in the body of the API
call. Separate asset IDs with a comma:

{"rootAssetIds":"asset_1","asset_2","asset_3"
"basketAction":"AssetToBasket",
"RequestDateTime":"2019-12-22T00:00:00.000Z"}
2. Be sure to note the cartContextKey, the lineItemKey, and the bundleContextKey if you intend to change
or configure the offer.

Update Basket Contents API


The Basket API provides the ability to add, delete, and modify the contents of a basket. You can add or
delete offers, and update the quantity or attributes of an offer that was previously added to a basket. The
API works for both known and anonymous users.

© 2021 Vlocity LLC, a Salesforce


company 91
Digital Commerce

You can update the quantity and attributes for root items, child items of parent items, and child items of
virtual groups. Some definitions that might be helpful:

• lineItemKey: A unique key generated for a line item


• Quantity: The number of items. Includes any root or child item.
• bundleContextKey: A unique key generated for a bundle
• cartContextKey: The key for the cart

You use the cartContextKey to keep track of the basket. The cartContextKey is not required if the basket is
empty. The cartContextKey is returned as part of the response after a successful basket operation.

Offers may include both products and promotions and use unique offer codes, thereby removing depending
on Salesforce IDs. Offers can be added directly or after configuration.

The API returns the entire bundle structure that is contained in the basket. The list structure complies with
pricing, overrides, rules, adjustments, attributes, and so on.

The API uses cartContext to track existing basket contents and appropriate context parameters to price/run
rules.

To improve performance, the API returns the contents of the cache if possible. If the data is not cached, the
API call is treated as a cache-miss and handled (also resulting in a corresponding cache entry).

The API also permits the user to delete items from an existing basket with the deleteBundleNumber
parameter.

The API can be used in any of three ways, depending on the value of the basketAction parameter. The
allowable options for basketAction are addWithNoConfig, addAfterConfig, and deleteFromBasket.

If you know the offer code, specify it using the offer parameter, as shown below:

{
"offer":"NS_DC_ROOT-1",
"basketAction":"AddWithNoConfig"
}

When deleting a bundle from a basket, specify the bundle number in the deleteBundleNumber
parameter.

Attribute Basket Cache Exclusion


The Fall '20 release includes an Attribute Basket Cache feature. See Attribute Basket Cache Exclusion.

Rules Supported
• Qualification Rules for Products
• Qualification Rules for Promotions
• Response contains base prices only (see Product Pricing)

© 2021 Vlocity LLC, a Salesforce


company 92
Digital Commerce

• Also see Using Context Rules with Digital Commerce APIs

Prerequisites
• Products must have ProductCode populated (no spaces are allowed in ProductCode).
• Promotions must have Code__c populated (no spaces are allowed in Code__c).
• A catalog must be present with products and promotions attached to it as records under the
CatalogProductRelationship__c object. The catalog should have CatalogCode__c populated (no spaces
are allowed in CatalogCode__c).
• The catalog must be attached to a default price list through the DefaultPriceList__c field on the
Catalog__c object.
• Price list entries must exist for all the products that are attached to the catalog.
• Optional: To populate the cache, the following batch jobs may be run:
• Context combinations
• Offer details
• Pricing results
• Create a custom setting called CacheAPIFields with a value of true. CacheAPIFields is not required for
CME 103.1.14 and later versions.

Parameters
For API parameter names and descriptions, see Digital Commerce API Swagger Reference.

Response
For detailed API response descriptions, see Digital Commerce API Swagger Reference

Modify Basket for an Anonymous User


POST /v3/catalogs/{catalog_code}/basket/{basket_key}

Examples
When the basket is empty, to add an item to the basket without configuring:

POST
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket

Request body:
{"offer":"{offer_code}","basketAction":"AddWithNoConfig"}

To add an item to the basket after configuring (by running the previous example and changing the quantity
to 2) with basket after previous API call. The productConfig parameter accepts stringified offer details in this
example.

POST
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket/
50ba987c870c64774e24c27787288650

© 2021 Vlocity LLC, a Salesforce


company 93
Digital Commerce

Request body:
{"offer":"{offer_code}","basketAction":"AddWithNoConfig"}

To add after configuring (in this case, changing the quantity to 2) with basket after previous API call. The
productConfig parameter accepts offer details directly (as a map) in this example.

POST
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket/
50ba987c870c64774e24c27787288650

NOTE
The list grows from the bottom; that is if you add products A, B, and C in that order, the
JSONResult.records list would be C,B,A with respective numbering as 0, 1, and 2.
Therefore, list item 0 will always be the most recent addition.

To delete bundle 1 from the basket (assuming the previous API calls were run):

POST
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket/
2c2be114be30ac296d219f95d3c984d5

Context Parameters
Context parameters can be passed to the API, as in the following examples:

POST
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket?
context={"Status":"Active"}

POST
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket?
context={"SLA__c":"Silver","Status":"Inactive"}

Adding a Promotion to a Basket


Adding a promotion to a basket is a two-step process. After the second step is run, the API returns the
updated cart context.

The basket configuration is cached so that a second request for the same cart configuration is sent, the
stored cached data is returned. In this case, a second API call is not required; the API returns the result of
the from the first API call.

Validations, prices, adjustments, overrides, rules, context, and so on are managed by the back end.

The API does not use the Salesforce ID as part of the request and response parameters.

© 2021 Vlocity LLC, a Salesforce


company 94
Digital Commerce

If the API call validation fails, the OfferDetails structure returns with an error message.

Example:

Step 1: Create the order Item and apply the promotion:

POST
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket

Request body:
{"basketAction":"AddWithNoConfig","offer":"iPhone8Offer"}

Step 2: The second step applies validation, rules, and pricing to the basket and returns an updated
cartContext and the promotion in the response.

In the response of Step1, under the validateAndPriceAction, a REST parameter, transactionKey is present.
Add that transactionKey in the request body to make the request for Step2.

Create the order Item and apply promotion:

POST
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket

Request body:
{"basketAction":"AddWithNoConfig","offer":"iPhone8Offer",
"transactionKey":"111123mx12223232000"}

Modify Basket for a Known User


POST /v3/catalogs/{catalog_code}/basket/
{basket_key}context={"accountId":"account_ID"}&isloggedin=true

You can add context information if the user is known to the system.

This API supports the isloggedin flag to indicate whether a user is logged in or anonymous. If the
isloggedin flag is true, it indicates a logged-in user, and an accountId must be specified in the context
parameter of the API call. If the isloggedin flag is false, it indicates that the user is anonymous.

In the returned JSON, the bundleContextKey uniquely identifies a bundle within the basket. Use this key
when you need to identify a particular bundle. The lineItemKey parameter uniquely identifies a line item.

Also in the returned JSON, the actions node displays API calls for updating and deleting items.

Examples (for logged-in users)

Add a Product to an Empty Basket


POST
/services/apexrest/{namespace}/catalogs/{catalog_code}/basket?

© 2021 Vlocity LLC, a Salesforce


company 95
Digital Commerce

context={"accountId":"account_ID"}&isloggedin=true

Request body:
{"offer":"offer_ID",
"basketAction":"AddWithNoConfig"}

Note that in the following example the basket key is specified in the API:

POST
/services/apexrest/{namespace}/catalogs/{catalog_code}/basket/{basket_key}?
context={"accountId":"account_ID"}&isloggedin=true

Request body:
{"offer":"offer_ID",
"basketAction":"AddWithNoConfig"}

Add a Child Product to a Basket


POST
/services/apexrest/{namespace}/catalogs/{catalog_code}/basket/{basket_key}?
context={"accountId":"account_ID"}&isloggedin=true

Request body:
{
"parentLineItemKey":"parent line item key",
"parentHierarchyPath":"parent hierarchy path,
"offer":"Family",
"basketAction":"addWithNoConfig",
"bundleContextKey":"bundle context key"
}

Remove a Product or Child Product from a Basket


POST
/services/apexrest/{namespace}/catalogs/{catalog_code}/basket/{basket_key}?
context={"accountId":"account_ID"}&isloggedin=true

Request body:
{
"basketAction":"deleteFromBasket",
"lineItemKey":"line_item_key",
"bundleContextKey":"bundle_context_key"
}

Remove a Child Product from a Basket


POST
/services/apexrest/{namespace}/catalogs/{catalog_code}/basket/{basket_key}?

© 2021 Vlocity LLC, a Salesforce


company 96
Digital Commerce

context={"accountId":"account_ID"}&isloggedin=true

Request body:
{
"basketAction":"deleteFromBasket",
"lineItemKey":"line_item_key",
"bundleContextKey":"bundle_context_key"
}

If the API call violates cardinality rules (such as attempting to add or remove more than the maximum or
minimum quantity) a message is returned in the messages node (although the API returns no error or error
code).

Remove a Promotion from a Basket


The DeleteServices configuration setting determines whether line items are deleted. Setting DeleteServices
to No prevents line items from being deleted while setting DeleteServices to Yes allows line items to be
deleted.

In addition, when deleting a promotion from a basket, the following parameters are available:

• basketAction = DeleteFromBasket
• offer = promotion code to be deleted
• appliedAction: The action of the applied promotion (Apply, Add, or Existing)
• bundleContextKey: The bundle context key from which a child product needs to be deleted. If a
basket includes multiple promotions of the same type applied to a similar product object, include the
bundleContextKey parameter in the delete promotion call. This parameter is supported by CME
Winter '20 and later releases.
• cancellationDate: The cancellation date for a promotion in the case of a MACD order.
• cancellationReason: The reason for the cancellation of the promotion in the case of MACD order.

Remove a Promotion from a Basket

POST
/services/apexrest/{namespace}/catalogs/{catalog_code}/basket/{basket_key}?
context={"accountId":"account_ID"}&isloggedin=true

Request body:
{
"basketAction":"deleteFromBasket",
"offer":"promotion_code",
"appliedAction":"Add"
"bundleContextKey":"bundle_context_key"
}

Adding or Deleting Basket Items or Attributes


Use this API to update the quantity or attributes of an offer that has already been added to a basket.

© 2021 Vlocity LLC, a Salesforce


company 97
Digital Commerce

Typical Usage Scenario


The following example shows a typical sequence of API calls to update an item in a basket for a known
user.

1. Use the GetOffersByCatalog API to retrieve a list of offers from the catalog (see Get Offers by Catalog
API).

Method: GET

API:
/services/apexrest/{namespace}/v3/catalogs/{catalog_code}/offers
2. Based on the list of offers returned by the GetOffersByCatalog API, run the GetOfferDetails API to
retrieve details about a particular offer (see Get Offer Details API).

Method: GET

API:
/services/apexrest/{namespace}/v3/catalogs/{catalog_code}/offers/
{offer_code}
3. Create a basket and add an item to it by running the Basket API. If the user is known, use the following
API call and body:

Method: POST

API:
/services/apexrest/{namespace}/v3/catalogs/{catalog_code}/offers/
basket&isloggedin=true

Request Body:
{"offer": "{offer_code}","basketAction": "AddWithNoConfig"}
4. Note the cartContextKey from the API call in Step 3.
Be sure to note the CartContextKey, the lineItemKey, and the bundleContextKey if you intend to
change or configure the offer.
5. Update the basket with an API call formatted similar to the following:

Method: PUT

API:
/services/apexrest/{namespace}/v3/catalogs/{catalog_code}/basket/
{cart_context_key}&isloggedin=true

Request Body:
{"lineItemKey":"xxxxxxxxxxxx","Quantity":"2"
"bundleContextKey":"xxxxxxxxxxxxx"}

Update Basket Items for an Anonymous User


To update the quantity of an item:

© 2021 Vlocity LLC, a Salesforce


company 98
Digital Commerce

Method: PUT

API:
/services/apexrest/{namespace}/v3/catalogs/{catalog}/basket/{cart_context_key}

Request Body:
{
"lineItemKey":"xxxxxxxxxxxx",
"Quantity":"2"
"bundleContextKey":"xxxxxxxxxxxxx"
}

Update Basket Items for a Known User


To update the quantity of an item:

Method: PUT

API:
/services/apexrest/{namespace}/v3/catalogs/{catalog_code}/basket/
{cart_context_key}?context={"accountId":"account_ID"&isloggedin=true

Request Body:
{
"bundleContextKey":"bundle_context_key",
"lineItemKey":"line_item_key",
"Quantity":"2",
"basketAction":"updatebasket"
}

To update item attributes:

Method: PUT

API:
/services/apexrest/{namespace}/v3/catalogs/{catalog_code}/basket/
{cart_context_key}?context={"accountId":"account_ID"&isloggedin=true

Request Body:
{
"lineItemKey": "043f392362aaa1164871f3d5fb78b651",
"bundleContextKey": "043f392362aaa1164871f3d5fb78b651",
"Quantity": "4",
"attributeCategories": {
"totalSize": 1,
"records": [
{
"displaySequence": -123,

© 2021 Vlocity LLC, a Salesforce


company 99
Digital Commerce

"Code__c": "NS-COLORS",
"Name": "NS-COLORS",
"id": "a080b00000kds8yAAA",
"productAttributes": {
"totalSize": 3,
"records": [
{
"code": "COLOR-1",
"dataType": "text",
"inputType": "checkbox",
"multiselect": false,
"required": false,
"readonly": false,
"disabled": false,
"filterable": true,
"attributeId": "a090b00000W1zWPAAZ",
"label": "Color1",
"displaySequence": 1,
"hasRules": false,
"hidden": false,
"cloneable": true,
"isNotTranslatable": false,
"values": [
{
"readonly": false,
"disabled": false,
"value": true,
"defaultValue": true,
"selected": true,
"defaultSelected": true
}
],
"userValues": false
},
{
"code": "COLOR-2",
"dataType": "text",
"inputType": "text",
"multiselect": false,
"required": false,
"readonly": false,
"disabled": false,
"filterable": true,
"attributeId": "a090b00000W1zWUAAZ",
"label": "Color2",
"displaySequence": 2,

© 2021 Vlocity LLC, a Salesforce


company 100
Digital Commerce

"hasRules": false,
"hidden": false,
"cloneable": true,
"isNotTranslatable": false,
"values": [
{
"readonly": false,
"disabled": false,
"value": "Color2",
"defaultValue": "Color2"
}
],
"userValues": "Color22"
},
{
"code": "COLOR-3",
"dataType": "number",
"inputType": "number",
"multiselect": false,
"required": true,
"readonly": false,
"disabled": false,
"filterable": true,
"attributeId": "a090b00000W1zWZAAZ",
"label": "Color3",
"displaySequence": 3,
"hasRules": false,
"hidden": false,
"cloneable": true,
"isNotTranslatable": false,
"values": [
{
"readonly": false,
"disabled": false,
"value": 12,
"defaultValue": 12
}
],
"userValues": 1221
}
]
}
}
]
}
}

© 2021 Vlocity LLC, a Salesforce


company 101
Digital Commerce

Add Multiple Products to a Basket


You can add multiple products to a basket at one time using the Basket API. For example, a user might
select multiple products and add them to the Basket using a single transaction.

Multi-add functionality works for both known and anonymous users. The basket is validated after the
products are added.

Prerequisites
• The Catalog should have CatalogCode__c populated; spaces are not allowed in CatalogCode__c.
• Products should have ProductCode populated; spaces are not allowed in ProductCode.
• Promotions should have Code__c populated; space are not allowed in Code__c.
• The product catalog should be present with products and promotions attached to it as records under the
CatalogProductRelationship__c object.
• The product catalog should be attached to a default pricelist through the DefaultPriceList__c field
on the Catalog__c object.
• Price list entries should exist for all products attached to the catalog.
• Create a custom setting called CacheAPIFields' with the value set to True in the CPQ Configuration
Setup.
• Ensure you have run the following batch jobs to populate the cache:
• Context combinations
• Offer Details
• Pricing results

NOTE
The API cache is generated incrementally with successive calls for this API, and is not pre-
generated as is the case with some of the other APIs.

URI
/services/apexrest/{namespace}/v3/catalogs/{catalogcode}/basket/{cartContextKey}

HTTP Method
POST

Parameters
Parameter Description
CatalogCode The code of the catalog whose product is being queried.
cartContextKey A persistent cartContext hash key to maintain existing basket. Leave blank to create a new basked. For
example: /v3/catalogs/{CATALOGCODE}/basket?urlParam=value

© 2021 Vlocity LLC, a Salesforce


company 102
Digital Commerce

Required POST Body Parameters


Parameter Description
basketAction The action type. Choose from the following:

• AddWithNoConfig - If adding directly from offerCode; supplied to the offer parameter.


• AddAfterConfig - If adding from configured offerDetails; supplied to the productConfig parameter

isDebug Set this parameter to true for debugging.

Optional POST Body Parameters


Parameter Description
context Provide context dimensions as part of context param; examples given at the end
productConfig Provide configured offer details taken from response of configure API to add configured offer to cart. It will contain
array in case of multi-add.
sessionKey Persisting session Key that contains the combination of Order and BasketKey for fresh basket, don't pass anything
offer Offer code of the product/promotion being added has to be passed. It will contain array in case of multi-add.

Runtime Behavior
This API provides the ability for a user to add offers to a virtual basket maintained by the user interface. The
basket is tracked using the cartContextKey in the URL. For an empty basket, there is no need to pass the
cartContextKey.

/v3/catalogs/{CATALOGCODE}/basket?urlParam=value

Depending upon the parameters passed along in the POST body the Orders are either picked from the
Session else the pseudo Accounts and Orders are created. This changes the time for processing.

For an existing basket with COMPLETECACHEMISS, if the sessionKey is passed in the POST body
params the existing Order is used to process else a new Account and Order are created.

• The cartContextKey is returned as part of the response of a successful basket operation.


• The sessionKey is returned as a part of a successful basket operation. The sessionKey is used to track
the Order used for the current basket.
• The API uses cartContext to track existing basket contents and appropriate context parameters to price
products and run context rules.
• The API uses the sessionKey to store the Order Id used to create the basket against the Basket ID. This
provides performance improvement by avoiding creation of new Account and Order for every API call for
a CACHE MISS scenario.
• If pre-cached result is present, that will be returned in case it isn't, this will be treated as a cache-miss
and handled (also resulting in a corresponding cache entry)

Example
When the basket is empty, add an item to a basket without configuring.

© 2021 Vlocity LLC, a Salesforce


company 103
Digital Commerce

Method:
POST

URL:
/services/apexrest/cacheableapis/v3/catalogs/Mobiles/basket

Post body:
{"offer":["iPhone11","iphone12"],"basketAction":"addWithNoConfig"}

Response body (truncated):

{
"cartContextKey": "d48b4abf50f9f98b132202df490f1e62",
"createCartAction": {
"rest": {
"params": {
"cartContextKey": "d48b4abf50f9f98b132202df490f1e62"
},
"link": "/v3/carts",
"method": "createCartAction"
}
},
"sessionKey": "749b6aba422601cf548cd36401059956",
"result": {
"totals": {
"EffectiveOneTimeTotal__c": 200,
"EffectiveRecurringTotal__c": 100
},
"records": [
{
"actions": {
"deleteFromBasketAction": {
"rest": {
"params": {
"basketAction": "deleteFromBasket",
"lineItemKey": "dc4aaedd6a85c60ce7e857925c6bfcf1",
"bundleContextKey": "dc4aaedd6a85c60ce7e857925c6bfcf1"
},
"link": "/v3/catalogs/Mobiles/basket/
d48b4abf50f9f98b132202df490f1e62?contextKey=99914b932bd37a50b983c5e7c90ae93b",
"method": "deleteFromBasketAction"
}
},
"updateBasketAction": {
"rest": {
"params": {

© 2021 Vlocity LLC, a Salesforce


company 104
Digital Commerce

"basketAction": "updateBasket",
"lineItemKey": "dc4aaedd6a85c60ce7e857925c6bfcf1",
"bundleContextKey": "dc4aaedd6a85c60ce7e857925c6bfcf1"
},
"link": "/v3/catalogs/Mobiles/basket/
d48b4abf50f9f98b132202df490f1e62?contextKey=99914b932bd37a50b983c5e7c90ae93b",
"method": "updateBasketAction"
}
}
},
"lineItemKey": "dc4aaedd6a85c60ce7e857925c6bfcf1",
"bundleContextKey": "dc4aaedd6a85c60ce7e857925c6bfcf1",
"productCategories": {
"messages": [],
"totalSize": 0
},
"pricingLogValue": {
"LastPricingTime": "2020-12-15T05:33:27.713Z",
"PriceAsOfDateTime": "2020-12-15T05:33:27.713Z",
"LogVersion": "3.0",
"PricingVariableCodeBaseValues": {
"REC_MNTH_STD_PRC": 50,
"OT_STD_PRC": 100

Example
When basket is empty, add an item to a basket after configuring.

Method:
POST

URL:
/services/apexrest/cacheableapis/v3/catalogs/Mobiles/basket

POST Body (truncated)


{
"productConfig": [
{
"offerDetails": {
"offer": {
"priceResult": [
{
"adjustments": [],
"overrides": [],
"chargeamount": 100,
"baseamount": 100,
"Amount__c": 100,

© 2021 Vlocity LLC, a Salesforce


company 105
Digital Commerce

"IsVirtualPrice__c": false,
"IsBasePrice__c": true,
"effectiveuntildatespec": null,
"effectivefromdatespec": null,
"SubType__c": "Standard",
"Type__c": "Price",
"RecurringFrequency__c": null,
"ChargeType__c": "One-time",
"DisplayText__c": "100$ one time",
"UnitPrice": 100
},
{
"adjustments": [],
"overrides": [],
"chargeamount": 50,
"baseamount": 50,
"Amount__c": 50,
"IsVirtualPrice__c": false,
"IsBasePrice__c": true,
"effectiveuntildatespec": null,
"effectivefromdatespec": null,
"SubType__c": "Standard",
"Type__c": "Price",
"RecurringFrequency__c": "Monthly",
"ChargeType__c": "Recurring",
"DisplayText__c": "50$ recurring"
}
],
"addtocart": {
"rest": {
"params": {
"context": "{}",
"basketAction": "AddWithNoConfig",
"offer": "iPhone11"
},
"link": "v3/catalogs/Mobiles/basket",
"method": "POST"
}
},

Example
When basket is empty, add one offer with configuration and another without configuration.

Method:
POST

© 2021 Vlocity LLC, a Salesforce


company 106
Digital Commerce

URL:
/services/apexrest/cacheableapis/v3/catalogs/Mobiles/basket

Post body (truncated):


{
"offer": "iPhone12",
"productConfig": [
{
"offerDetails": {
"offer": {
"priceResult": [
{
"adjustments": [],
"overrides": [],
"chargeamount": 100,
"baseamount": 100,
"Amount__c": 100,
"IsVirtualPrice__c": false,
"IsBasePrice__c": true,
"effectiveuntildatespec": null,
"effectivefromdatespec": null,
"SubType__c": "Standard",
"Type__c": "Price",
"RecurringFrequency__c": null,
"ChargeType__c": "One-time",
"DisplayText__c": "100$ one time",
"UnitPrice": 100
},
{
"adjustments": [],
"overrides": [],
"chargeamount": 50,
"baseamount": 50,
"Amount__c": 50,
"IsVirtualPrice__c": false,
"IsBasePrice__c": true,
"effectiveuntildatespec": null,
"effectivefromdatespec": null,
"SubType__c": "Standard",
"Type__c": "Price",
"RecurringFrequency__c": "Monthly",
"ChargeType__c": "Recurring",
"DisplayText__c": "50$ recurring"
}
],

© 2021 Vlocity LLC, a Salesforce


company 107
Digital Commerce

Response (truncated)
{
"offer": "iPhone12",
"productConfig": [
{
"offerDetails": {
"offer": {
"priceResult": [
{
"adjustments": [],
"overrides": [],
"chargeamount": 100,
"baseamount": 100,
"Amount__c": 100,
"IsVirtualPrice__c": false,
"IsBasePrice__c": true,
"effectiveuntildatespec": null,
"effectivefromdatespec": null,
"SubType__c": "Standard",
"Type__c": "Price",
"RecurringFrequency__c": null,
"ChargeType__c": "One-time",
"DisplayText__c": "100$ one time",
"UnitPrice": 100
},
{
"adjustments": [],
"overrides": [],
"chargeamount": 50,
"baseamount": 50,
"Amount__c": 50,
"IsVirtualPrice__c": false,
"IsBasePrice__c": true,
"effectiveuntildatespec": null,
"effectivefromdatespec": null,
"SubType__c": "Standard",
"Type__c": "Price",
"RecurringFrequency__c": "Monthly",
"ChargeType__c": "Recurring",
"DisplayText__c": "50$ recurring"
}
],
"addtocart": {
"rest": {
"params": {
"context": "{}",

© 2021 Vlocity LLC, a Salesforce


company 108
Digital Commerce

"basketAction": "AddWithNoConfig",
"offer": "iPhone11"
},

See Also
• Basket Operations

Basket Validation
Basket validation ensures that certain conditions are met before performing an operation on a basket.

The following basket items are checked:

• The user is eligible for the offers contained in the basket.


• The offers in the basket are effective.
• The price list entries that were used to create the basket are still effective.

Basket validation is enabled or disabled by passing the validatebasket query parameter. The default
value is true. To turn off the basket validation, pass false as the value for the query parameter.

The basket operations that supports basket validation are shown here:

Basket Operation Description


Add offer to a basket The effectivity and eligibility of the root offer is checked. If the offer is eligible and effective, the
add-to-basket will proceed.
Add new offer to an existing basket The existing basket is validated. Only when the basket is valid, any add or update operations
are allowed.
Update an existing basket The existing basket is validated. Only when the basket is valid, any add or update operations
are allowed.
Get basket details The basket details are validated. Depending on the the validation result, the response will be
modified.
Delete offer from an existing The delete operation is performed first, and the validation is preformed on the remaining offers
basket in the basket.
Create cart using a basket The basket is validated. Only if the validation is successful will cart creation be allowed.

The fields in the table below are checked when performing effectivity checking:

Table 6. Effectivity checking


For products • IsActive
• IsOrderable
• SellingStartDate
• SellingEndDate
• EndOfLifeDate
For promotions • IsActive
• IsOrderable
• EffectiveFrom
• EffectiveUntil

© 2021 Vlocity LLC, a Salesforce


company 109
Digital Commerce

For price list entries • IsActive


• EffectiveFrom
• EffectiveUntil
• The calculated effective date based on the TimePlan and TimePolicy applied

Example 1: Validation when adding a new offer to a basket


When adding an offer (either a product or promotion) to the basket (either an empty basket or an existing
valid basket), the eligibility and effectivity of the offer that is being added is checked. Only when the offer is
eligible and effective will the basket be created. For invalid offers, depending on the reason, the different
responses are shown below.

Example: An ineligible offer is added

For anonymous users

Request URL
/services/apexrest/dc_108/v3/catalogs/DTHCatalog/basket

Request Body
{"offer":"DTHOffer","basketAction":"AddWithNoConfig"}

Condition
The product, DTHOffer, has a rule applied. The rule is valid for Account
SLA=Silver. The default value for rule dimension is Bronze.

Response
{"success":false,"result":{"BasketValidationResult":{"IneligibleOffers":
["DTHOffer"]}},"errorCode":"422","error":"One or more offers are ineligible."}

Response

For logged-in users

Request URL
/services/apexrest/dc_108/v3/catalogs/DTHCatalog/basket?

© 2021 Vlocity LLC, a Salesforce


company 110
Digital Commerce

context={"accountId":"<<AccountId With SLA not as Silver>>"}&isloggedin=true

Request Body
{"offer":"DTHOffer","basketAction":"AddWithNoConfig"}

Condition
The product, DTHOffer, has a rule applied. The is valid for Account SLA =
Silver. The default value for rule dimension is Bronze

Response
{"success":false,"result":{"BasketValidationResult":{"IneligibleOffers":
{"DTHOffer":"The SLA of Account should be
SILVER"}}},"errorCode":"422","error":"One or more offers are ineligible."}

Response

Example: The offer being added is not effective

Request URL
/services/apexrest/dc_108/v3/catalogs/DTHCatalog/basket

Request Body
{"offer":"SportsPack","basketAction":"AddWithNoConfig"}

Condition
The SellingEndDate of the offer SportsPack has expired

Response
{"success":false,"result":{"BasketValidationResult":{"InvalidOffers":
{"SportsPack":["SellingEndDate"]}}},"errorCode":"422","error":"The offer being
added to the basket is ineffective"}

Response

© 2021 Vlocity LLC, a Salesforce


company 111
Digital Commerce

Example: The product being added to the basket does not have a valid price list entry

Request URL
/services/apexrest/dc_108/v3/catalogs/DTHCatalog/basket

Request Body
{"offer":"EntertainmentPack","basketAction":"AddWithNoConfig"}

Condition
There are no valid PLEs on the offer EntertainmentPack

Response
{"success":false,"errorCode":"INVOKE-500","error":"No valid price list entry
found for product EntertainmentPack"}

Response

Example 2: Validation while running a basket operation on an invalid basket


An existing basket might have one or more ineligible offers in it. This may be because the basket was
created in an older version of the product (pre-Fall '20) or the basket was created with validatebasket
query parameter set to false. For this example, assume that the basket was created with a bundle named
DTHOffer, and DTHOffer is eligible only if the account SLA is Silver. Also, the default value of the SLA is
Bronze. Below is the basket structure:

Example: Validation while performing basket operation on an invalid basket having


ineligible offer(s)

{
"totalSize": 1,

© 2021 Vlocity LLC, a Salesforce


company 112
Digital Commerce

"records": [
{
"displaySequence": -1,
"Id": {
"value": "8026g000003qmNjAAI",
"previousValue": null,
"originalValue": null,
"messages": [],
"label": "Order Product ID",
"hidden": false,
"fieldName": "Id",
"editable": false,
"dataType": "ID",
"alternateValues": null,
"actions": {}
},
"Pricebook2Id": "01s6g000008qDnSAAU",
"Product2Id": "01t6g000003yHyWAAU",
"ProductCode": "DTHOffer",
"UnitPrice": {
"value": 0,
"previousValue": null,
"originalValue": null,
"messages": [],
"label": "Unit Price",
"hidden": true,
"fieldName": "UnitPrice",
"editable": false,
"dataType": "CURRENCY",
"alternateValues": null,
"actions": {}
},
"Name": "DTHOffer",
"IsActive": true,
"dc_108__RecurringPrice__c": 25,
"Product2": {
"attributes": {
"type": "Product2",
"url": "/services/data/v49.0/sobjects/Product2/01t6g000003yHyWAAU"
},
"Id": "01t6g000003yHyWAAU",
"Name": "DTHOffer",
"dc_108__IsConfigurable__c": false,
"dc_108__GlobalGroupKey__c": "eeed75c1-d269-c274-796d-0babcbf4d6fb",
"dc_108__Type__c": "None",
"dc_108__SubType__c": "None",

© 2021 Vlocity LLC, a Salesforce


company 113
Digital Commerce

"RecordTypeId": "0126g000001MCLdAAO",
"dc_108__JSONAttribute__c": null
},
"CurrencyCode": "USD",
"productId": "01t6g000003yHyWAAU",
"defaultQuantity": 1,
"minQuantity": 0,
"maxQuantity": 99999,
"groupMinQuantity": 0,
"groupMaxQuantity": 99999,
"sequenceNumber": 1,
"productChildItemDefinition": {
"attributes": {
"type": "dc_108__ProductChildItem__c"
},
*** and so on ***

For the above basket, a subsequent basket operation will return one of the following responses:

Anonymous user
Operation
Add Promotion to existing Basket

Condition
The basket was created by an anonymous user and the next basket operation is
also being performed by an anonymous user.

Request URL/services/apexrest/dc_108/v3/catalogs/DTHCatalog/basket/
273ea5445b7b80ab40b566baab089e41

Request Body
{"basketAction":"AddWithNoConfig","offer":"10%OffDTH"}

Response
{
"success": false,
"cartContextKey": "273ea5445b7b80ab40b566baab089e41",
"result": {
"BasketValidationResult": {
"isBasketValid": false,
"basketValidationMessage": "One or more offers are ineligible.",
"IneligibleOffers": [
"DTHOffer"
]
},

© 2021 Vlocity LLC, a Salesforce


company 114
Digital Commerce

"totals": {
"EffectiveOneTimeTotal__c": 200,
"EffectiveRecurringTotal__c": 25
},
"records": [
{
"actions": {
"deleteFromBasketAction": {
"rest": {
"params": {
"basketAction": "deleteFromBasket",
"lineItemKey": "eb4ba8910c60a25ae4d4dda7a1b60c64",
"bundleContextKey": "eb4ba8910c60a25ae4d4dda7a1b60c64"
},
"link": "/v3/catalogs/DTHCatalog/basket/
273ea5445b7b80ab40b566baab089e41?contextKey=9d6af941cb9c06b0a31d0e6be2dddf17",
"method": "deleteFromBasketAction"
}
},
"updateBasketAction": {
"rest": {
"params": {
"basketAction": "updateBasket",
"lineItemKey": "eb4ba8910c60a25ae4d4dda7a1b60c64",
"bundleContextKey": "eb4ba8910c60a25ae4d4dda7a1b60c64"
},
"link": "/v3/catalogs/DTHCatalog/basket/
273ea5445b7b80ab40b566baab089e41?contextKey=9d6af941cb9c06b0a31d0e6be2dddf17",
"method": "updateBasketAction"
}
}
},
(truncated for brevity)

Result

© 2021 Vlocity LLC, a Salesforce


company 115
Digital Commerce

Logged-in user, case 1

Operation
Add Promotion to existing Basket

Condition
The basket was created by a logged in user with account id <<AccountId1>>
having SLA as Bronze and the next basket operation is also being performed by
the same user without any change to the account shape.

Request URL/services/apexrest/dc_108/v3/catalogs/DTHCatalog/basket/
f4f58e16f583e8843ab5cc7c101b864e?
context={"accountId":"AccountId1"}&isloggedin=true

Request Body
{"basketAction":"AddWithNoConfig","offer":"10%OffDTH"}

Response

© 2021 Vlocity LLC, a Salesforce


company 116
Digital Commerce

Logged-in user, case 2


Operation
Add Promotion to existing Basket

Conditions - the response will be similar for both the cases mentioned below

Condition 1 - The basket was created by logged in user with account id


<<AccountId1>> having SLA as Bronze and the next basket operation is being
performed by same user but the account SLA has changed to Silver
Condition 2 - The basket was created by logged in user with account id
<<AccountId1>> having SLA as Bronze and the next basket operation is being
performed by different user with account id <<AccountId2>> with account SLA
Silver

Request URL/services/apexrest/dc_108/v3/catalogs/DTHCatalog/basket/
f4f58e16f583e8843ab5cc7c101b864e?
context={"accountId":"AccountId2"}&isloggedin=true

Request Parameter
{"basketAction":"AddWithNoConfig","offer":"10%OffDTH"}

Response

© 2021 Vlocity LLC, a Salesforce


company 117
Digital Commerce

Validation while performing a basket operation on an invalid basket having


eligible but ineffective offer(s)
After some time interval, the offers in the basket are eligible but,For offer SportsPack,

• The SellingEndDate and EndOfLifeDate are ineffective.


• The Effective Until Date of the OT PLE,50$OTCharge, used, is now ineffective

Once the basket is ineffective, further basket operations (except getBasket) return a response similar to the
response shown below.

Response

© 2021 Vlocity LLC, a Salesforce


company 118
Digital Commerce

Understanding the response structure


When an invalid basket is found during basket validation, the response will contain an extra node named
BasketValidationResult. In the node, the details about why the basket is invalid are available. The
InvalidOffers node contains:

1. InvalidPLEs - This node contains the details of all the ineffective price list entries for all of the invalid
offers in the basket.
2. InvalidProducts - This node contains the details of the products that are invalid, with the name of the
fields indicating which product is invalid.
3. InvalidPromotions - This node contains the details of the promotion(s) that are invalid, with the name of
the fields indicating which the promotion is invalid.

If basket validation fails, the errorCode in the response will be 422 with an appropriate error message.

When a getBasket operation is performed, an extra nextAction node is available in the response. This
node contains details about how to correct the basket. See the examples for more information.

Basket validation limitations

• For add-to-basket operations, validation is performed only when basketAction is set to


AddWithNoConfig.
• Price list entry validation is only for price list entries that were used to create the basket. If an offer has
more than one price list entry but was not used, then the validation will not be performed for those price
list entries.
• Price list entry validation is performed only if the basket was created with active PricingInterface
implementation as PricingPlanService.
• Basket validation does not support the price list entry validation if the pricing is done using a custom
implementation for PricingInterface; for example, if the prices were picked from a Matrix.
• For price list entry validation, there must be an entry in the CachedAPIResponse__c SObject of
Type=pleOfferMap and cacheKey=<<CartContextKey>> must be available. If the basket was created
using a version earlier than Fall '20, the pleOfferMap will not be available for that basket; therefore the
PLE validation for that basket will be skipped.
• Basket validation does not apply to the effectivity of the CatalogProductRelationship.
• When adding a new offer to either an empty or existing basket, validation is performed only for the root
offer; that is, only for the offer passed in the post body of the API call. Validations are not done for child
products or auto-add relationship products.
• Effectivity checking for new offers is supported starting in Fall '20f. If offer details were generated in an
earlier version, the effectivity check for the offer being added to the basket will not occur.
• The eligibility check for the offers in the basket is done only for the offers present in the catalog passed in
the input. If there are offers from different catalogs, they will not be checked for eligibility.

Use Trim Mode to Decrease Overhead


You use trim mode to reduce the amount of data returned by the basket operations, resulting in reduced
network traffic and improved performance.

© 2021 Vlocity LLC, a Salesforce


company 119
Digital Commerce

To enable trim mode, set the trimmode configuration setting (see CPQ Configuration Settings Reference .
You can also pass trimmode as a parameter to the API call. Note that trimmode API parameter overrides
the value set for the CacheAPI.TrimMode custom setting.

To use the trim mode feature, you create a class using the sample code below as a guide, create the
interface, and create the interface implementation.

1. Create a CustomResultToXli class as shown in the example below:

// The following is sample code


global inherited sharing class CustomResultToXli implements
vlocity_cmt.VlocityOpenInterface
{
private static Set<String> fieldsToUpdate = new Set<String>{
'vlocity_cmt__LineNumber__c'
};
private vlocity_cmt.VOIInvoker invoker =
vlocity_cmt.VOIInvoker.getInstance();
private vlocity_cmt.VlocityOpenInterface defaultResultToXli =
(vlocity_cmt.VlocityOpenInterface)invoker.invoke('DefaultResultToXLIImpleme
ntation', 'debugCreate', null, null, null);
// private VOIInvoker invoker = VOIInvoker.getInstance();// private
VlocityOpenInterface defaultResultToXli =
(VlocityOpenInterface)invoker.invoke('DefaultResultToXLIImplementation',
'debugCreate', null, null, null);public static void
iterateJsonResult(Map<String, Object> jsonResult)
{
List<Object> jsonRecords = (List<Object>)jsonResult.get('records');
for(Object jsonRecordObject : jsonRecords)
{
Map<String, Object> jsonRecord = (Map<String,
Object>)jsonRecordObject;
iterateJsonRecord(jsonRecord);
}
}

public static void iterateJsonRecord(Map<String, Object> jsonRecord)


{
for(String key : fieldsToUpdate)
{
if(jsonRecord.get(key) == null || (jsonRecord.get(key)
instanceOf Map<String,Object>))
{
continue;
}

Map<String, Object> objMap = new Map<String,Object> {

© 2021 Vlocity LLC, a Salesforce


company 120
Digital Commerce

'value' => jsonRecord.get(key)


};
jsonRecord.put(key, objMap);
}

if(jsonRecord.get('vlocity_cmt__PricingLogData__c') != null &&


jsonRecord.get('pricingLogValue') == null)
{
String logData =
(String)jsonRecord.get('vlocity_cmt__PricingLogData__c');
Map<String, Object> logDataMap = (Map<String,
Object>)JSON.deserializeUntyped(logData);
jsonRecord.put('vlocity_cmt__PricingLogData__c', logDataMap);
}

Map<String, Object> productGroupsMap = (Map<String,


Object>)jsonRecord.get('productGroups');
if(productGroupsMap != null)
{
List<Object> productGroups =
(List<Object>)productGroupsMap.get('records');
for(Object productGroupObject : productGroups)
{
Map<String, Object> productGroup = (Map<String,
Object>)productGroupObject;
iterateJsonRecord(productGroup);
}
}

Map<String, Object> lineItemsMap = (Map<String,


Object>)jsonRecord.get('lineItems');
if(lineItemsMap != null)
{
List<Object> lineItems =
(List<Object>)lineItemsMap.get('records');
for(Object lineItemObject : lineItems)
{
Map<String, Object> lineItem = (Map<String,
Object>)lineItemObject;
iterateJsonRecord(lineItem);
}
}

global Boolean invokeMethod(String methodName, Map<String, Object>

© 2021 Vlocity LLC, a Salesforce


company 121
Digital Commerce

inputMap, Map<String, Object> outputMap,


Map<String, Object> options)
{
System.debug('****methodName**** ::: ' + methodName);

if (methodName.equalsIgnoreCase('generateXLIFromResult'))
{
Object result = inputMap.get('result');
System.debug('****before**** ::: ' + JSON.serialize(result));
Map<String, Object> resultMap;
if(result instanceof String)
{
resultMap = (Map<String,
Object>)JSON.deserializeUntyped((String)result);
inputMap.put('result', resultMap);
}
else
{
resultMap = (Map<String, Object>)result;
}
iterateJsonResult(resultMap);
System.debug('****after**** ::: ' + JSON.serialize(resultMap));
}

//invoke actual method


defaultResultToXli.invokeMethod(methodName, inputMap, outputMap,
options);
return true;
}
}
2. Create a ResultToXLI interface with active Implementation as CustomResultToXli.
a. From the Vlocity home screen, click the Interface Implementations tab and click New.
b. Enter the following name and implementation class:
• Interface Name: ResultToXli
• Active Implementation Class: CustomResultToXli
• Description: Enter a helpful description.
c. Click Save.
d. Click New Interface Implementation Detail.
e. Enter the required information:
• Available Implementation: CustomResultToXli
• Interface Name: ResultToXli
• Active: Checked

© 2021 Vlocity LLC, a Salesforce


company 122
Digital Commerce

After performing the preceding steps, run one of the Basket APIs, such as Add to Basket, Update Basket,
or Delete from Basket with CacheAPI.trimmode enabled in custom settings, or by passing trimmode as
a parameter to the API call.

NOTE
The CacheAPI.trimmode custom setting and the trimmode API parameter are available
only in Winter '21 release or later.

When you use the response from the Baskeet API call and pass it as a request body to the Create Cart
API, a valid order is created. An example is shown below.

Example 5.
Method:
POST

URL:
/services/apexrest/cacheableapis/v3/carts?
context={}&contextKey=key&isLoggedIn=true/false

Request body (example)

"catalogCode": "{{dataPrefix}}{{catalogCode}}",
"accountId": "0014x000009kMSb",
"JSONResult": {
"totals": {
"EffectiveOneTimeTotal__c": 2400,
"EffectiveRecurringTotal__c": 240
},
"records": [
{
"actions": {
"deleteFromBasketAction": {
"rest": {
"params": {
"basketAction": "deleteFromBasket",
"lineItemKey": "65cf0791db3860be03efcd9c7bfc439a",
"bundleContextKey": "65cf0791db3860be03efcd9c7bfc439a"
},
"link": "/v3/catalogs/flows_dct_cf/basket/
78ec66d85c6e7ae244d0464c66a67b5c?contextKey=99914b932bd37a50b983c5e7c90ae93b",
"method": "deleteFromBasketAction"

© 2021 Vlocity LLC, a Salesforce


company 123
Digital Commerce

}
},
"updateBasketAction": {
"rest": {
"params": {
"basketAction": "updateBasket",
"lineItemKey": "65cf0791db3860be03efcd9c7bfc439a",
"bundleContextKey": "65cf0791db3860be03efcd9c7bfc439a"
},
"link": "/v3/catalogs/flows_dct_cf/basket/
78ec66d85c6e7ae244d0464c66a67b5c?contextKey=99914b932bd37a50b983c5e7c90ae93b",
"method": "updateBasketAction"
}
}
},
"lineItemKey": "65cf0791db3860be03efcd9c7bfc439a",
"bundleContextKey": "65cf0791db3860be03efcd9c7bfc439a",
"attributeCategories": {
"records": [
{
"productAttributes": {
"records": [
{
"userValues": null,
"values": [
{
"disabled": false,
"readonly": false
}
],
"isNotTranslatable": false,
"cloneable": true,
"hidden": false,
"hasRules": false,
"displaySequence": 1,
"label": "DateForBuyBack2",
"attributeId": "a0X4x000000ND1sEAG",
"filterable": true,
"disabled": false,
"readonly": false,
"required": false,
"multiselect": false,
"cacheable": true,
"inputType": "date",
"dataType": "date",
"code": "DateForBuyBack2"

© 2021 Vlocity LLC, a Salesforce


company 124
Digital Commerce

},
{
"userValues": null,
"values": [
{
"disabled": false,
"readonly": false
}
],
"isNotTranslatable": false,
"cloneable": true,
"hidden": false,
"hasRules": false,
"displaySequence": 1,
"label": "DateTimeForDelivery2",
"attributeId": "a0X4x000000ND1tEAG",
"filterable": true,
"disabled": false,
"readonly": false,
"required": false,
"multiselect": false,
"cacheable": true,
"inputType": "datetime",
"dataType": "datetime",
"code": "DateTimeForDelivery2"
}
],
"totalSize": 2
},
"id": "a0W4x000000ZmeIEAS",
"Name": "BASIC",
"Code__c": "BASIC",
"displaySequence": 1
},
{
"productAttributes": {
"records": [
{
"userValues": true,
"values": [
{
"displaySequence": 2,
"defaultSelected": false,
"value": "false",
"disabled": false,
"readonly": false,

© 2021 Vlocity LLC, a Salesforce


company 125
Digital Commerce

"label": "false",
"name": "c77778d2-b0ac-dd67-57a4-261bb6bb0e73",
"id": "c77778d2-b0ac-dd67-57a4-261bb6bb0e73"
},
{
"displaySequence": 1,
"defaultSelected": false,
"value": "true",
"disabled": false,
"readonly": false,
"label": "true",
"name": "92273834-d4b0-c020-ddbb-0503f4586d9b",
"id": "92273834-d4b0-c020-ddbb-0503f4586d9b"
}
],
"isNotTranslatable": false,
"cloneable": true,
"hidden": false,
"hasRules": false,
"displaySequence": 1,
"label": "IsValueForMoney2",
"attributeId": "a0X4x000000ND1uEAG",
"filterable": true,
"disabled": false,
"readonly": false,
"required": false,
"multiselect": false,
"cacheable": true,
"inputType": "dropdown",
"dataType": "text",
"code": "IsValueForMoney2"
},
{
"userValues": null,
"values": [
{
"disabled": false,
"readonly": false
}
],
"isNotTranslatable": false,
"cloneable": true,
"hidden": false,
"hasRules": false,
"displaySequence": 1,
"label": "Networth2",

© 2021 Vlocity LLC, a Salesforce


company 126
Digital Commerce

"attributeId": "a0X4x000000ND1vEAG",
"filterable": true,
"disabled": false,
"readonly": false,
"required": false,
"multiselect": false,
"cacheable": true,
"inputType": "number",
"dataType": "currency",
"code": "Networth2"
},
{
"userValues": null,
"values": [
{
"disabled": false,
"readonly": false
}
],
"isNotTranslatable": false,
"cloneable": true,
"hidden": false,
"hasRules": false,
"displaySequence": 1,
"label": "LikelhoodOfRecommendation2",
"attributeId": "a0X4x000000ND1wEAG",
"filterable": true,
"disabled": false,
"readonly": false,
"required": false,
"multiselect": false,
"cacheable": true,
"inputType": "number",
"dataType": "percentage",
"code": "LikelhoodOfRecommendation2"
},
{
"userValues": null,
"values": [
{
"disabled": false,
"readonly": false
}
],
"isNotTranslatable": false,
"cloneable": true,

© 2021 Vlocity LLC, a Salesforce


company 127
Digital Commerce

"hidden": false,
"hasRules": false,
"displaySequence": 1,
"label": "Age2",
"attributeId": "a0X4x000000ND1xEAG",
"filterable": true,
"disabled": false,
"readonly": false,
"required": false,
"multiselect": false,
"cacheable": true,
"inputType": "number",
"dataType": "number",
"code": "Age2"
},
{
"userValues": false,
"values": [
{
"defaultValue": false,
"value": false,
"disabled": false,
"readonly": false
}
],
"isNotTranslatable": false,
"cloneable": true,
"hidden": false,
"hasRules": false,
"displaySequence": 1,
"label": "NeedInsurance2",
"attributeId": "a0X4x000000ND1yEAG",
"filterable": true,
"disabled": false,
"readonly": false,
"required": false,
"multiselect": false,
"cacheable": true,
"inputType": "checkbox",
"dataType": "text",
"code": "NeedInsurance2"
}
],
"totalSize": 5
},
"id": "a0W4x000000ZmeJEAS",

© 2021 Vlocity LLC, a Salesforce


company 128
Digital Commerce

"Name": "SURVEY",
"Code__c": "SURVEY",
"displaySequence": 2
}
],
"totalSize": 2
},
"productCategories": {
"totalSize": 0
},
"pricingLogValue": {
"LastPricingTime": "2021-01-28T23:56:46.227Z",
"PriceAsOfDateTime": "2021-01-28T23:56:46.227Z",
"LogVersion": "3.0",
"PricingVariableCodeBaseValues": {
"REC_MNTH_STD_PRC": 15,
"OT_STD_PRC": 150
},
"PricingVariableCodeValues": {
"DISP_OT_STD_PRC": 150,
"ROLLUP_OT_STD_PRC_TOTAL": 2250,
"ROLLUP_REC_MNTH_STD_PRC_TOTAL": 225,
"REC_MNTH_STD_PRC_DISC_PCT_MAN": 0,
"OT_STD_PRC_DISC_PCT_MAN": 0,
"EFFECTIVE_QUANTITY": 1,
"LINE_QUANTITY": 1,
"EFF_REC_MNTH_STD_PRC_TOTAL": 240,
"REC_MNTH_STD_PRC_TOTAL": 240,
"REC_MNTH_STD_PRC_CALC": 15,
"REC_MNTH_STD_PRC": 15,
"EFF_OT_STD_PRC_TOTAL": 2400,
"OT_STD_PRC_TOTAL": 2400,
"OT_STD_PRC_CALC": 150,
"OT_STD_PRC": 150
},
"PriceAdjustmentPromoKeys": [],
"PricingVariableCodeFieldBinding": {
"navs_230__RecurringManualDiscount__c":
"REC_MNTH_STD_PRC_DISC_PCT_MAN",
"navs_230__OneTimeManualDiscount__c": "OT_STD_PRC_DISC_PCT_MAN",
"navs_230__EffectiveQuantity__c": "EFFECTIVE_QUANTITY",
"Quantity": "LINE_QUANTITY",
"navs_230__EffectiveRecurringTotal__c":
"EFF_REC_MNTH_STD_PRC_TOTAL",
"navs_230__RecurringTotal__c": "REC_MNTH_STD_PRC_TOTAL",
"navs_230__RecurringCalculatedPrice__c": "REC_MNTH_STD_PRC_CALC",

© 2021 Vlocity LLC, a Salesforce


company 129
Digital Commerce

"navs_230__RecurringCharge__c": "REC_MNTH_STD_PRC",
"navs_230__EffectiveOneTimeTotal__c": "EFF_OT_STD_PRC_TOTAL",
"navs_230__OneTimeTotal__c": "OT_STD_PRC_TOTAL",
"navs_230__OneTimeCalculatedPrice__c": "OT_STD_PRC_CALC",
"navs_230__OneTimeCharge__c": "OT_STD_PRC"
},
"LogData": {
"REC_MNTH_STD_PRC_TOTAL": [
{
"ChargeTiming": null,
"LogSequence": 0,
"DisplayText": "[Recurring Calculated Price (15.00) + Rollup
Recurring Total (225.00)] x Quantity (1.00)"
}
],
"REC_MNTH_STD_PRC_CALC": [
{
"ChargeTiming": null,
"LogSequence": 0,
"DisplayText": "Recurring Charge (15.00000) - Recurring Manual
Discount (0.00%)"
}
],
"OT_STD_PRC_TOTAL": [
{
"ChargeTiming": "One-Time",
"LogSequence": 0,
"DisplayText": "[One Time Calculated Price (150.00) + Rollup
One Time Total (2250.00)] x Quantity (1.00)"
}
],
"OT_STD_PRC_CALC": [
{
"ChargeTiming": null,
"LogSequence": 0,
"DisplayText": "One Time Charge (150.00000) - One Time Manual
Discount (0.00%)"
}
],
"REC_MNTH_STD_PRC": [
{
"LogSequence": 0,
"IsEffective": true,
"EndDate": null,
"StartDate": null,
"AdjustmentType": "None",

© 2021 Vlocity LLC, a Salesforce


company 130
Digital Commerce

"LoyaltyCode": "PTS",
"CurrencyCode": "USD",
"CurrencyType": "Currency",
"Amount": 15,
"AdjustmentValue": 0,
"AdjustmentMethod": null,
"BaseValue": 15,
"BaseAdjustment": null,
"PriceListId": "a3D4x0000009Fq4EAE",
"OfferId": null,
"PromotionId": null,
"PricingElementId": "a3F4x000000YdN1EAK",
"PricingVariableCode": "REC_MNTH_STD_PRC",
"DisplayText": "15_RB_flows_p_1",
"EndValue": 15,
"ChargeTiming": "Recurring",
"Frequency": "Monthly",
"SubType": "Standard",
"StartValue": 15,
"PricingElementGlobalKey": "8647d492-8302-
a75d-3d3b-160dbd123199",
"LogType": "PRICE",
"PriceListEntryId": "a3C4x000000Z01jEAC"
}
],
"OT_STD_PRC": [
{
"LogSequence": 0,
"IsEffective": true,
"EndDate": null,
"StartDate": null,
"AdjustmentType": "None",
"LoyaltyCode": "PTS",
"CurrencyCode": "USD",
"CurrencyType": "Currency",
"Amount": 150,
"AdjustmentValue": 0,
"AdjustmentMethod": null,
"BaseValue": 150,
"BaseAdjustment": null,
"PriceListId": "a3D4x0000009Fq4EAE",
"OfferId": null,
"PromotionId": null,
"PricingElementId": "a3F4x000000YdN0EAK",
"PricingVariableCode": "OT_STD_PRC",
"DisplayText": "150_OTB_flows_p_1",

© 2021 Vlocity LLC, a Salesforce


company 131
Digital Commerce

"EndValue": 150,
"ChargeTiming": "One-time",
"Frequency": null,
"SubType": "Standard",
"StartValue": 150,
"PricingElementGlobalKey": "89603aff-f59c-210e-d76e-
e88b0abf4b66",
"LogType": "PRICE",
"PriceListEntryId": "a3C4x000000Z01iEAC"
}
]
}
},
"PricebookEntry": {
"Product2": {
"navs_230__JSONAttribute__c": null,
"navs_230__IsConfigurable__c": false,
"navs_230__GlobalGroupKey__c": "1303db74-24f1-2eb4-
f3f5-7f61f410c602",
"navs_230__Type__c": "None",
"ProductCode": "flows_p_1",
"Name": "flows_p_1",
"Id": "01t4x000000ZFqbAAG",
"attributes": {
"url": "/services/data/v50.0/sobjects/
Product2/01t4x000000ZFqbAAG",
"type": "Product2"
}
},
"Pricebook2Id": "01s4x000007JWrxAAG",
"Product2Id": "01t4x000000ZFqbAAG",
"Id": "01u4x000002SnHzAAK",
"attributes": {
"url": "/services/data/v50.0/sobjects/PricebookEntry/
01u4x000002SnHzAAK",
"type": "PricebookEntry"
}
},
"OrderId": "8014x000000gFK4AAM",
"navs_230__IsChangesAllowed__c": true,
"navs_230__AssetReferenceId__c":
"607a5789-6e0a-6c60-2738-614f3f5f0945",
"navs_230__EffectiveRecurringTotal__c": 240,
"navs_230__EffectiveOneTimeTotal__c": 2400,
"navs_230__CurrencyPaymentMode__c": "Currency",
"navs_230__RecurringManualDiscount__c": 0,

© 2021 Vlocity LLC, a Salesforce


company 132
Digital Commerce

"navs_230__RecurringCalculatedPrice__c": 15,
"navs_230__RecurringCharge__c": 15,
"navs_230__OneTimeManualDiscount__c": 0,
"navs_230__OneTimeCalculatedPrice__c": 150,
"navs_230__OneTimeCharge__c": 150,
"ListPrice": 0,
"navs_230__InCartQuantityMap__c": "{\"01t4x000000ZFruAAG\":1}",
"navs_230__Product2Id__c": "01t4x000000ZFqbAAG",
"navs_230__RootItemId__c": "8024x000000kx0kAAA",
"navs_230__LineNumber__c": "0001",
"navs_230__ProductHierarchyPath__c": "01t4x000000ZFqbAAG",
"navs_230__ProvisioningStatus__c": "New",
"navs_230__Action__c": "Add",
"navs_230__RecurringTotal__c": 240,
"navs_230__OneTimeTotal__c": 2400,
"Quantity": 1,
"PricebookEntryId": "01u4x000002SnHzAAK",
"itemType": "lineItem",
"SellingPeriod": "Present",
"hasChildren": true,
"action": "Add",
"lineNumber": "0001",
"isVirtualItem": false,
"name": "flows_p_1",
"productHierarchyPath": "01t4x000000ZFqbAAG",
"productChildItemDefinition": {
"navs_230__ParentProductId__r": {
"Id": "01t4x000000ZFqbAAG",
"Name": "flows_p_1",
"navs_230__GlobalGroupKey__c": "1303db74-24f1-2eb4-
f3f5-7f61f410c602",
"attributes": {
"url": "/services/data/v50.0/sobjects/
Product2/01t4x000000ZFqbAAG",
"type": "Product2"
}
},
"navs_230__ChildLineNumber__c": "1",
"navs_230__MinQuantity__c": 0,
"navs_230__IsVirtualItem__c": false,
"navs_230__MaximumChildItemQuantity__c": 99999,
"navs_230__MaxQuantity__c": 99999,
"navs_230__IsRootProductChildItem__c": true,
"navs_230__IsOverride__c": false,
"navs_230__Quantity__c": 1,
"navs_230__CollapseHierarchy__c": false,

© 2021 Vlocity LLC, a Salesforce


company 133
Digital Commerce

"Name": "Root PCI",


"navs_230__MinimumChildItemQuantity__c": 0,
"navs_230__ParentProductId__c": "01t4x000000ZFqbAAG",
"navs_230__SeqNumber__c": 1,
"attributes": {
"type": "navs_230__ProductChildItem__c"
}
},
"sequenceNumber": 1,
"groupMaxQuantity": 99999,
"groupMinQuantity": 0,
"maxQuantity": 99999,
"minQuantity": 0,
"defaultQuantity": 1,
"productId": "01t4x000000ZFqbAAG",
"CurrencyCode": "USD",
"Product2": {
"navs_230__JSONAttribute__c": null,
"navs_230__SubType__c": "None",
"navs_230__Type__c": "None",
"navs_230__GlobalGroupKey__c": "1303db74-24f1-2eb4-
f3f5-7f61f410c602",
"navs_230__IsConfigurable__c": false,
"Name": "flows_p_1",
"Id": "01t4x000000ZFqbAAG",
"attributes": {
"url": "/services/data/v50.0/sobjects/Product2/01t4x000000ZFqbAAG",
"type": "Product2"
}
},
"navs_230__RecurringPrice__c": 240,
"IsActive": true,
"Name": "flows_p_1",
"UnitPrice": 0,
"ProductCode": "flows_p_1",
"Product2Id": "01t4x000000ZFqbAAG",
"Pricebook2Id": "01s4x000007JWrxAAG",
"Id": "8024x000000kx0kAAA",
"displaySequence": -1
}
],
"totalSize": 1
},
"errorCode": "INVOKE-200",
"error": "OK"
}

© 2021 Vlocity LLC, a Salesforce


company 134
Digital Commerce

For information and examples about using the Basket APIs, see: Basket Operations.

Check Out Operations


You use the Check Out Operations to complete the purchase. The check out APIs consist of the following:

Create Cart from Basket


POST /v3/carts

The Create Cart API provides the ability to create a cart after items have been added to a basket. The API
provides the ability to convert the basket into a corresponding order and order line item.

First, offers are configured without a cart, then this API is called to add the basket contents to the cart
(order and order line items) before submitting. The API creates a new cart. The API will validate and price
the cart after adding the items and returns a link to the full cart contents.

Beginning with the Summer 2019 release, the CacheAPI.CreateCartFromContextKey configuration setting
can be used to determine the behavior of the Create Cart API. If set to true, the Create Cart API uses the
cartContextKey passed in the input to create the cart. If set to false or not specified, the JSON result from
the Basket API must be passed in the request body of the Create Cart API to create the cart. The API
requires the user account, catalog code, and cartItems in the body of the request.

You can create multiple carts with a single Create Cart API call. See Batch Processing Example 1 for an
example.

You can batch process multiple carts at one time. See Batch Processing Example 2 for an example.

You can submit an order when the cart is created. See Example to Create Cart and Submit Order for an
example.

You can pass additional order capture information when creating an order from a basket. See Example
Showing Passing Additional Parameters for an example.

Rules Supported
• Qualification Rules for Price Lists
• Pricing Interface (see pricing plans, such as ABP)
• Attribute-Based Pricing
• Also see Using Context Rules with Digital Commerce APIs

Prerequisites
• Run the Load API Metadata job (Vlocity CMT Administration > Cacheable API Jobs > Load API
Metadata).
• Run all of the jobs under the Populate API Cache window.

© 2021 Vlocity LLC, a Salesforce


company 135
Digital Commerce

• The CacheAPIFields custom setting must be set to true for versions prior to CME 103.1.14.
• See Custom settings and query parameter recommendations for additional recommendations.

API Parameters and Response Format


For API parameter names and descriptions, see Digital Commerce API Swagger Reference.

Example
First, create a basket. To create a basket, first run the Basket API. Then, use the output of the Basket API
as input for the Cart API. Be sure to add the catalogCode and accountId parameters.

The body should resemble the following (note that JSONResult has been truncated for clarity):

{"JSONResult" : "{\"totalSize..."productCategories\":{\"totalSize
\":0}}]}}]}","catalogCode" : "catalog_code","accountId" : "account_ID"}

Now call the API:

https://{salesforce_domain}/services/apexrest/vlocity_cmt/v3/carts

The response includes the order number and order ID.

Batch Processing Example 1


You can create multiple carts with a single API call by specifying the multipleCartContext parameter in
the header.

NOTE
By default, pricing and basket validation are turned off when using the Create Cart API for
bulk processing.

URL:
/services/apexrest/featurehvo/v3/carts?
validate=false&price=false&validatebasket=false

Header:
{"multipleCartContext":[
{"accountId": "0016g000005GhgS",
"catalogCode": "Phones",
"cartContextKey": "03e2574d420baabe40c2210970afc837",
"orderItemFields": [
{
"bundleContextKey": "12b2d2fbbd91fab9b62c3689caf7e5a3",
"lineItemKey": "12b2d2fbbd91fab9b62c3689caf7e5a3",

© 2021 Vlocity LLC, a Salesforce


company 136
Digital Commerce

"Description": "iphone 4"


}
],"orderFields": {
"Description": "iphone 4"}
},
{
"accountId": "0016g00000LxUPf",
"catalogCode": "Phones",
"cartContextKey": "248c981213da8d58650d9c50ca578aff",
"orderItemFields": [
{
"bundleContextKey": "fcec25cc2013eca9f73db00b35020c29",
"lineItemKey": "fcec25cc2013eca9f73db00b35020c29",
"Description": "iphone 5"}],
"orderFields": {"Description": "iphone 5"}
},
{"accountId": "0016g00000LxUPL",
"catalogCode": "Phones",
"cartContextKey": "4ca6c995e66d71c163f509302566f7d6",
"orderItemFields":
[
{"bundleContextKey": "d61e242102fb4329e8a6acf273316159",
"lineItemKey": "d61e242102fb4329e8a6acf273316159",
"Description": "iphone 5s"}],
"orderFields": {
"Description": "iphone 5s"
}
}
]
}

Output

Batch Processing Example 2


You can batch process multiple carts at one time.

© 2021 Vlocity LLC, a Salesforce


company 137
Digital Commerce

URL:
/services/apexrest/featurehvo/v3/carts?
validate=false&price=false&validatebasket=false

Header
{"multipleCartContext":[
{"accountId": "0016g000005GhgS",
"catalogCode": "Phones",
"cartContextKey": "03e2574d420baabe40c2210970afc837",
"orderItemFields": [
{"bundleContextKey": "12b2d2fbbd91fab9b62c3689caf7e5a3",
"lineItemKey": "12b2d2fbbd91fab9b62c3689caf7e5a3",
"Description": "iphone 4"
}
],
"orderFields": {
"Description": "iphone 4"
}
},
{"accountId": "0016g00000LxUPf",
"catalogCode": "Phones",
"cartContextKey": "248c981213da8d58650d9c50ca578aff",
"orderItemFields": [
{
"bundleContextKey": "fcec25cc2013eca9f73db00b35020c29",
"lineItemKey": "fcec25cc2013eca9f73db00b35020c29",
"Description": "iphone 5"
}
],
"orderFields": {
"Description": "iphone 5"
}
},
{
"accountId": "0016g00000LxUPL",
"catalogCode": "Phones",
"cartContextKey": "4ca6c995e66d71c163f509302566f7d6",
"orderItemFields": [
{
"bundleContextKey": "d61e242102fb4329e8a6acf273316159",
"lineItemKey": "d61e242102fb4329e8a6acf273316159",
"Description": "iphone 5s"
}
],
"orderFields": {
"Description": "iphone 5s"}

© 2021 Vlocity LLC, a Salesforce


company 138
Digital Commerce

},
{"accountId": "0016g00000LxUPa",
"catalogCode": "Phones",
"cartContextKey": "2a060ccffb639df16448388fb944937c",
"orderItemFields": [
{
"bundleContextKey": "3d2e9657bb10e96ef663669e5cd9f8e2",
"lineItemKey": "3d2e9657bb10e96ef663669e5cd9f8e2",
"Description": "iphone 6"}],
"orderFields": {
"Description": "iphone 6"
}
},
{
"accountId": "0016g00000LyRtK",
"catalogCode": "Phones",
"cartContextKey": "6eadc50ae768c46cb5a24847918cd84e",
"orderItemFields": [
{
"bundleContextKey": "90801bc3d3ca1f1211fd7eff9fc576d9",
"lineItemKey": "90801bc3d3ca1f1211fd7eff9fc576d9",
"Description": "iphone 7"
}
],"orderFields": {
"Description": "iphone 7"
}
}
]
}

Output

Example to Create Cart and Submit Order


You can submit an order when the cart is created.

© 2021 Vlocity LLC, a Salesforce


company 139
Digital Commerce

NOTE
Creating assets using the CreateCart API can only be used with a single Create Cart API
call.

URL:
/services/apexrest/featurehvo/v3/carts?createAsset=true

Header:
{
"accountId": "0014R00002k5vPG",
"catalogCode": "Phones",
"cartContextKey": "1b42e612a401a072324c7ca026bc4e2f"
}

Output

Example Showing Passing Additional Parameters


You can pass additional order capture information when creating an order from a basket. After a Basket has
been created, and the user is ready to check out, you can pass additional information in the order header
and order Line Items. For example, you might want to pass an updated billing address or an external Order
Management system ID.

© 2021 Vlocity LLC, a Salesforce


company 140
Digital Commerce

URL:
/services/apexrest/featurehvo/v3/carts

Header:
{
"accountId": "0016g000005GhgS",
"catalogCode": "Phones",
"cartContextKey": "03e2574d420baabe40c2210970afc837",
"orderItemFields": [
{
"bundleContextKey": "a561caa70bd9e2343a3066ed316bdec8",
"lineItemKey": "a561caa70bd9e2343a3066ed316bdec8",
"Description": "new iphone 4",
"featurehvo__ItemName__c": "iphone4"
}
],
"orderFields": {
"Description": "Apple Products",
"featurehvo__Email__c": "[email protected]"
}
}

© 2021 Vlocity LLC, a Salesforce


company 141
Digital Commerce

Output

To prevent inadvertently updating a field that may invalidate ancillary operations, by default, the Create Cart
API is restricted to updating only the following Order and OrderItem fields:

Order Item:

• Line Description - Description


• Item Name - vlocity_cmt__ItemName__c
• Billing Account - vlocity_cmt__BillingAccountId__c
• Service Account - vlocity_cmt__ServiceAccountId__c
• Service Point - vlocity_cmt__ServicePointId__c
• Any Customer Created Custom Fields allows by SF Field Data security

© 2021 Vlocity LLC, a Salesforce


company 142
Digital Commerce

Order:

• Description - Description
• Order Name - Name
• Order Reference Number - OrderReferenceNumber
• Order Type - Type
• Delivery Installation Status - vlocity_cmt__Delivery_Installation_Status__c
• Email - vlocity_cmt__Email__c
• Lead Source - vlocity_cmt__LeadSource__c
• Billing Account - vlocity_cmt__DefaultBillingAccountId__c
• Service Account - vlocity_cmt__DefaultServiceAccountId__c
• Service Point - vlocity_cmt__DefaultServicePointId__c
• Any Customer Created Custom Fields allows by SF Field Data security

To update any fields other than the fields in the preceding list, you can create a fieldset on Orders for
Order field updates and OrderProducts for OrderItem field updates. The fieldset name and label should
match CartAllowedFieldSet for both Orders and OrderProducts.

To create a new field set:

1. Navigate to Setup then select either Orders or OrderProducts, then select Field Sets.
2. Add a new fieldset with name and label. For this example, we will use: CartAllowedFieldSet
3. Add any custom field allowed by SF Field Data security to the fieldset. In this example, we are adding
Order Start Date.

After adding the custom field, you can verify that it is present with the following steps:

1. Use the Create Cart API to create a new basket and save the CartContextKey.
2. Call the Create Cart API again using the CartContextKey and the new fieldset as shown using REST
Explorer below:

© 2021 Vlocity LLC, a Salesforce


company 143
Digital Commerce

For information about Salesforce field sets, see: https://help.salesforce.com/articleView?


id=sf.fields_about_field_sets.htm&amp;type=5.

For information about reducing the amount of data returned by basket operations, see Use Trim Mode to
Decrease Overhead.

Custom settings and query parameter recommendations


The following settings are recommended to increase performance when using the Create Cart API. These
settings are appropriate when creating either single or multiple carts.

Table 7.
Setting Type Value
CachedQueryMode CPQ Configuration Setup True
CacheEnabled CPQ Configuration Setup True
checkContextAuthenticity query parameter false
contextKey query parameter contextKey from getOffers

© 2021 Vlocity LLC, a Salesforce


company 144
Digital Commerce

Setting Type Value


price query parameter false
returnOrderNumber query parameter false
UseAssetReferenceIdForParentAndRoot CPQ Configuration Setup True
validate query parameter false
validatebasket query parameter false

Digital Commerce Remote Calls


You can use the code samples in this topic to make remote method calls to the Digital Commerce APIs for
both anonymous and logged-in users.

Sample Remote Calls

Get Offers By Catalog for Anonymous Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parameters


methodName = 'getOffersByCatalogCode';
input.put('apiName','getOffers');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/offers');
input.put('pagesize','20');
input.put('offset','0');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

For more details about which parameters correspond to the POST body, refer to the API documentation.

Get Offers By Catalog for Logged In Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parameters

© 2021 Vlocity LLC, a Salesforce


company 145
Digital Commerce

methodName = 'getOffersByCatalogCode';
input.put('apiName','getOffers');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/offers');
input.put('pagesize','20');
input.put('offset','0');
input.put('context','{"accountId":"accountId1", "contractId":"contractId1"}');
input.put('isloggedin','true');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

Get Contains Products for Anonymous Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parameters


methodName = 'getOffersByCatalogCode';
input.put('apiName','GetContainOffers');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/offers?
contains=Child1&context={}&pagesize=20&offset=0');
input.put('productCode', 'Child1');input.put('pagesize','20');
input.put('offset','0');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

Get Contains Products for Logged In Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parameters


methodName = 'getOffersByCatalogCode';
input.put('apiName','GetContainOffers');
input.put('catalogCode', 'ECOMM-CAT1');

© 2021 Vlocity LLC, a Salesforce


company 146
Digital Commerce

input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/offers?
contains=Child1&pagesize=20&offset=0');
input.put('productCode', 'Child1');input.put('pagesize','20');
input.put('offset','0');
input.put('context','{"accountId":"accountId1", "contractId":"contractId1"}');
input.put('isloggedin','true');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

GetOfferDetailsByCatalog for Anonymous Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parametersmethodName = 'getOfferDetailsByCatalogCode';


input.put('apiName','getOfferDetails');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/offers/iPhone8Bundle');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

GetOfferDetails ByCatalog for Logged In Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parameters


methodName = 'getOfferDetailsByCatalogCode';
input.put('apiName','getOfferDetails');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/offers/iPhone8Bundle');
input.put('context','{"accountId":"accountId1", "contractId":"contractId1"}');
input.put('isloggedin','true');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

© 2021 Vlocity LLC, a Salesforce


company 147
Digital Commerce

Get Basket for Logged In Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parameters


methodName = 'getBasket';
input.put('apiName','basketOperations');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/basket');
input.put('context','{"accountId":"accountId1", "contractId":"contractId1"}');
input.put('isloggedin','true');
input.put('cartContextKey', 'cartContextKey');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

The contains parameter in the requestURL is passed as productCode in the input map.

POST API Sample Calls

Configure Offer for Anonymous or Logged In Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parameters


methodName = 'configureOfferDetail';
input.put('apiName','ConfigureOfferDetail');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('offerCode', 'iPhone8Bundle');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/offer/iPhone8Bundle');
input.put('result', '{{offerdetailsStructure}}');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

© 2021 Vlocity LLC, a Salesforce


company 148
Digital Commerce

Additional Parameters

// Transactional break for ValidateAndPriceAction


input.put('orderId', '{{transactionKey}}');

// validate and price


input.put('validate', false);
input.put('price', false);

Basket API for Anonymous or Logged In Users

String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parametersmethodName = 'addWithNoConfig';


input.put('apiName','basketOperations');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('offer', 'Product1');input.put('methodName', 'addWithNoConfig');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/basket');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

Additional parameters
Different method names (note that their first letter is not capitalized unlike in REST POST body params):

• addWithNoConfig
• addAfterConfig
• deleteFromBasket

Additional input map params (refer to Basket APIs doc for more details on what they correspond to in
POST body params):

• offerDetails - same as productConfig


• orderId - same as transactionKey
• cartContextKey
• deleteBundleNumber

// validate and price


input.put('validate', false);
input.put('price', false);

© 2021 Vlocity LLC, a Salesforce


company 149
Digital Commerce

Basket API: Asset to Basket for Logged In Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parameters


methodName = 'assetToBasket';
input.put('apiName','basketOperations');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/basket');
input.put('methodName', 'assetToBasket');
input.put('context','{"accountId":"accountId1", "contractId":"contractId1",
"rootAssetIds":["rootItemId1", "rootItemId2"]}');
input.put('isloggedin','true');
input.put('rootAssetIds', 'rootItemId1,rootItemId2');
input.put('requestDateTime', '2020-01-08T12:00:00.000z');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/basket');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

Additional Parameters

// validate and price


input.put('validate', false);
input.put('price', false);

Basket API: Delete From Basket for Anonymous or Logged in Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parameters


methodName = 'deleteFromBasket';
input.put('apiName','basketOperations');
input.put('methodName','deleteFromBasket');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/basket');
input.put('cartContextKey', 'cartContextKey');

© 2021 Vlocity LLC, a Salesforce


company 150
Digital Commerce

//Use the cart context


keyinput.put('bundleContextKey', 'bundleContextKey');

//Use the key of the bundle under which the line to be deleted
input.put('lineItemKey', 'lineItemKey');

//Use the key of the line to be deleted


input.put('context','{"accountId":"accountId1", "contractId":"contractId1"}');
input.put('isloggedin','true');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

Additional Parameters
// validate and price
input.put('validate', false);
input.put('price', false);

Basket API: Update Basket for Anonymous or Logged In Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parameters


methodName = 'updateBasket';input.put('apiName','basketOperations');
input.put('methodName','updateBasket');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/basket');
input.put('cartContextKey', 'cartContextKey');

//Use the cart context keyinput.put('bundleContextKey', 'bundleContextKey');

//Use the key of the bundle under which the line to be deleted
input.put('lineItemKey', 'lineItemKey');

//Use the key of the line to be updatedinput.put('Quantity', 5);

//Quantity to be updated
input.put('context','{"accountId":"accountId1", "contractId":"contractId1"}');
input.put('isloggedin','true');

© 2021 Vlocity LLC, a Salesforce


company 151
Digital Commerce

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

Additional Parameters
// validate and price
input.put('validate', false);
input.put('price', false);

// to update attribute
input.put('attributeCategories', 'attributecategorystring'); //attribute
category to be updated

Basket API : Add Multiple Items to a Basket


String methodName;
Map<String, Object> input = new Map<String, Object>();
Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

methodName = 'addWithNoConfig';
input.put('apiName','basketOperations');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('productConfig', [list of product configs]); //this is the list of
product configs or single product config to add
input.put('offer', [list of offers to add]); //list of offer codes to add or
single offer code to add
input.put('methodName', 'addAfterConfig');
input.put('requestURL', '/v3/catalogs/ECOMM-CAT1/basket');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

Create Cart for Logged In Users


String methodName;

Map<String, Object> input = new Map<String, Object>();


Map<String, Object> output = new Map<String, Object>();
Map<String, Object> options = new Map<String, Object>();

// Setting remote parameters


methodName = 'createEcomCart';
input.put('apiName','createEcomCart');

© 2021 Vlocity LLC, a Salesforce


company 152
Digital Commerce

input.put('methodName','createEcomCart');
input.put('catalogCode', 'ECOMM-CAT1');
input.put('requestURL', '/v3/carts');
input.put('cartContextKey', 'cartContextKey');//Use the cart context key
input.put('context','{"accountId":"accountId1", "contractId":"contractId1"}');
input.put('isloggedin','true');

//remote action invocation


vlocity_cmt.CpqAppHandler appHandler = new vlocity_cmt.CpqAppHandler();
appHandler.invokeMethod(methodName, input, output, options);

Additional Parameters

// validate and price


input.put('validate', false);
input.put('price', false);

//Old format:
input.put('catalogCode', 'Mobiles');
input.put('accountId', '001f200001eSlhe');
input.put('JSONResult', '{{AddTobasketResponse}}');

© 2021 Vlocity LLC, a Salesforce


company 153
Digital Commerce

Digital Commerce SDK

The Vlocity Digital Commerce Software Development Toolkit (SDK) is a JavaScript library that abstracts
and simplifies the use of Digital Commerce API calls. The SDK improves usability and reduces the effort to
develop compelling user interfaces by hiding complex API semantics inside the SDK interface.

The SDK can be used in either of two ways: as a client-side SDK, or as a proxy SDK, redirecting all calls to
the SDK running on a Node.js server. Refer to the following architecture diagrams.

© 2021 Vlocity LLC, a Salesforce


company 154
Digital Commerce

See ServerSDK Overview for more information.

In some cases, the SDK invokes more than one API call (as required by some APIs) to complete a request.
In the previous architecture diagram, various UI components are shown calling the SDK, which in turn, calls
the appropriate Digital Commerce API and returns a result.

Vlocity Digital Commerce UI Interaction

The SDK ensures that errors are detected before API calls are made so that Vlocity data structure rules are
honored and data is not written incorrectly to Vlocity Cart or to the product database.

The SDK consolidates common application and business front-end logic that is shared by different user
interfaces such as Vlocity Digital Commerce Lightning Web Components and Web Components, and
Custom Digital Commerce UI. Components (which can be based on any framework), CMT Mobile App
Shopping UI, OmniScripts that use Digital Commerce APIs, and so on.

TIP
Vlocity recommends that you do not call the API directly and instead use the SDK. Vlocity
Digital Commerce API documentation is available for your reference so that you can
understand the data that is included in various calls.

© 2021 Vlocity LLC, a Salesforce


company 155
Digital Commerce

The SDK supports Node.js module delivery. Each module has its own context, cannot interfere with other
modules, or interfere with global scope.

See: Vlocity Digital Commerce SDK developer reference.

SDK Proxy Support


The Digital Commerce Server SDKs support a proxy configuration by using an optional proxyUrl
parameter when creating the SDK instance. For example:

const digitalCommerceConfig1 =
window.VlocitySDK.digitalcommerce.createConfigForLoginUser(
"https://{instance}.my.salesforce.com", "00D3i000000Eeay!AQoAQH8O7aSMu.
Foz1fYdtz9kGiodgGRdOuox1wFlRG9a_JgnLi1n.
jcjvTDc0XVyvGyENudSuhucZEUj_fhUxh2DHRDxHcK",
"https://node-salesforce-proxy.herokuapp.com/proxy/" // use your proxy URL);

SDK Core Class Structure and Methods


The Software Development Kit (SDK) is used by developers to create applications that call the Digital
Commerce APIs.

Fall '20 Release


The main class is VlocityDigitalCommerce, which has the following methods:

• getOffers()
• Retrieve a list of offers
• Maps to GetOffersByCatalog API (/v3/catalogs/{catalog_code}/offers) or, if the contains parameter
is specified, maps to the GetContainsProducts API (/v3/catalogs/{ catalog_code}/offers?
contains={product_code})
• getFilteredOffersList
• Retrieves a filtered list of products and promotions.
• getOffer()
• Retrieves an offer with details
• Maps to GetOfferDetails API (/v3/catalogs/{ catalog_code}/offers/{offer_code})
• validateOffer()
• Validates an offer
• Maps to Configure Offer API (/v3/catalogs/{ catalog_code}/offers/{offer_code})
• If the offer is of offerType=Promotion, then the client must get the transactionKey from the first
response and then call the same API again with transactionKey in the request POST body. This
complexity is handled inside the SDK; therefore the client only needs to call the SDK
configureOfferDetails method once regardless of what the offerType is.
• addToBasket()
• maps to Basket API: (/v3/catalogs/{catalog_code}/basket)
• If the offer is of offerType=Promotion, then the client must get the transactionKey from the first
response and then call the same API again with transactionKey inside the request Post body. This

© 2021 Vlocity LLC, a Salesforce


company 156
Digital Commerce

complexity is handled inside the SDK; therefore client only needs to call SDK addToBasket method
once regardless of what the offerType is.
• The basket is tracked using the cartContextKey in the URL; for an empty basket, there is no need to
pass the cartContextKey. After the first call, cartContextKey is returned and the client must include this
in all subsequent calls with cartContextKey in request Body. This complexity is handled and automated
inside this SDK method.
• updateItemsInCart()
• maps to Basket API: (/v3/catalogs/{catalog_code}/basket/{cart_context_key})
• If the offer is of offerType=Promotion, then the client must get the transactionKey from the first
response and then call the same API again with transactionKey inside the request Post body. This
complexity is handled inside the SDK; therefore client only needs to call SDK addToBasket method
once regardless of what the offerType is.
• The basket is tracked using the cartContextKey in the URL; for an empty basket, there is no need to
pass the cartContextKey. After the first call, cartContextKey is returned and the client must include this
in all subsequent calls with cartContextKey in request Body. This complexity is handled and automated
inside this SDK method.
• checkoutCart()
• Maps to the Create Cart from Basket API (/v3/carts)

• getPromotions()
• Maps to GetOffersByCatalog API: /v3/catalogs/{catalog_code}/offers
• Returns promotions for all products or for an associated to product.
• assetToBasket()
• Maps to Basket API: /v3/catalogs/{catalog_code}/basket/{asset_ID}
• Create a basket from a given asset ID

• authenticateUser()
• Maps to SignIn API: {checkout_SDK_node_server_URL}/signIn
• Maps to SignUp API: {checkout_SDK_node_server_URL}/signUp
• Securely login to salesforce using checkout node server SDK

• updateBillingDetails()
• Maps to SignIn API: {checkout_SDK_node_server_URL}/updateDetails
• Securely update shipping and billing address to the Salesforce user account.
• saveCart()
• Maps to SignIn API: {checkout_SDK_node_server_URL}/createOrder
• Securely save the cart by creating an Order.
• submitOrder()
• Maps to SignIn API: {checkout_SDK_node_server_URL}/submitOrder
• Securely create and submit order for given accountId and cartContextKey

© 2021 Vlocity LLC, a Salesforce


company 157
Digital Commerce

• signOutUser
• Signs out the user from the ServerSDK.

See the Vlocity SDK Reference for more details.

For reference information about the Spring '20 SDK release see https://docs.vlocity.com/devdocs/
archive/sdk/107.0/.

SDK Usage Examples (Fall '20 version)


This topic and the topics that follow illustrate several examples for instantiating and using the Digital
Commerce SDK.

Example Code
// Instantiate DigitalCommerceConfig for anonymous user
const digitalCommerceConfig =
VlocitySDK.digitalcommerce.createConfigForAnonymousUser();

// Instantiate the SDK itself


const digitalCommerce =
VlocitySDK.digitalcommerce.getInstance(digitalCommerceConfig);

OR

// Instantiate DigitalCommerceConfig for login user


const digitalCommerceConfig =
VlocitySDK.digitalcommerce.createConfigForLoginUser(salesforceUrl,
sessionToken);

// Instantiate DigitalCommerceConfig for login user with proxy server URL


const digitalCommerceConfig =
VlocitySDK.digitalcommerce.createConfigForLoginUser(salesforceUrl,
sessionToken, proxyUrl);

// Instantiate the SDK itself


const digitalCommerce =
VlocitySDK.digitalcommerce.getInstance(digitalCommerceConfig);

// To override the default namespace with your custom namespace


this.digitalCommerce.namespace = "vlocity_cmt"; // use your custom namespace

// To override the default custom api URL with your custom api URL
this.digitalCommerce.apiURL = "YOUR_CUSTOM_API_URL"; // use your custom URL

// To override the default api URL authToken


this.digitalCommerce.authToken = "YOUR_CUSTOM_AUTH_TOKEN"; // use your custom

© 2021 Vlocity LLC, a Salesforce


company 158
Digital Commerce

authToken

Note:
digitalCommerce is a Singleton object. Calling
getInstance(digitalCommerceConfig) repeatedly will return the same instance
instantiated the first time when getInstance(digitalCommerceConfig) was called.

// To instantiate a new instance of digitalCommerce, set create to true in the


digitalCommerceConfig object:
digitalCommerceConfig.create = true;
digitalCommerce =
VlocitySDK.digitalcommerce.getInstance(digitalCommerceConfig);

Possible error conditions:

• "VlocityDigitalCommerce::getInstance: Config object must be given in argument to create an instance the


first time."
• "VlocityDigitalCommerce::constructor: VlocityDigitalCommerce cannot be instantiated properly. Both
datasource and user context objects have to be in Config object as argument."

SDK Example: Get Cart Details (Fall '20 version)


Use the following example SDK code to obtain details about a cart:

// Instantiate the input object for getItemsInCart to specify parameters


const input = digitalCommerce.createGetItemsInCartInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.cartContextKey = "01tf2000007Rb9JAAS"; // use your cart_context_key
input.cacheable = true; // Optional boolean flag to indicate if the sdk call
should be cached. Default is false.
input.reload = true; // Optional boolean flag to discard cache and call the
api again Default is false.
input.customFields = ["customAttribute__c"]; // optional field which returns
your custom attributes or any given keys

// Invoke get basket API via method getItemsInCart()


digitalCommerce
.getItemsInCart(input)
.then(response => {
Logger.info("vlocity get cart items anonymous user rest call" + response);
})
.catch(error => {
Logger.info("get cart items anonymous user rest call failed" + error);
});

Possible error conditions:

© 2021 Vlocity LLC, a Salesforce


company 159
Digital Commerce

"GetItemsInCartInput::getAPIPath() must have catalogCode."

"GetItemsInCartInput::getAPIPath() must have cartContextKey."

SDK Example: getCatalogOffers with the contains parameter (Fall '20 version)
// Instantiate the input object for getOffers to specify parameters
const input = digitalCommerce.createGetOffersInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offset = 0; // use for pagination - optional
input.pageSize = 5; // use for pagination - optional
input.contains = "iPhone8"; // find all offers that CONTAIN "iPhone8" -
optional
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys
input.secureApiCall = false; // set to true if needs secure api calls without
context parameters and session key.

// Invoke GetContainsProducts API via method getOffers()


digitalCommerce
.getOffers(input)
.then(result => {
Logger.info("vlocity get offers anonymous user rest call" + result);
})
.catch(error => {
Logger.info("get offers anonymous user rest call failed" + error);
});

Possible error conditions:

"GetOffersInput::getAPIPath() must have catalogCode."

"GetOffersContainsInput::getAPIPath() should not have both sortBy and contains."

"GetOffersInput::getAnonymousRestUrl() must have catalogCode."

"GetOffersContainsInput::getAnonymousRestUrl() should not have both sortBy and contains."

SDK Example: Get filtered list of products and promotions (Fall '20)
Use the following example SDK code to retrieve a list of products and promotions:

// Instantiate the input object for getOffers to specify parameters.


const input = digitalCommerce.createGetOffersInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.returnPromotion = true; // If undefined return both products and
promotions, If true return only promotions, If false return only products -
optional

© 2021 Vlocity LLC, a Salesforce


company 160
Digital Commerce

// Invoke GetOffersByCatalog API via method getFilteredOffersList()


digitalCommerce
.getFilteredOffersList(input)
.then(result => {
Logger.info(
"vlocity get catalog filtered offers list anonymous user rest call" +
result
);
})
.catch(error => {
Logger.info("get catalog offers anonymous user rest call failed" + error);
});

Possible error conditions:

"GetCatalogOffersInput::getAPIPath() must have catalogCode."

"GetCatalogOffersInput::getAnonymousRestUrl() must have anonymousSiteUrl."

"GetCatalogOffersContainsInput::getAPIPath() should not have both sortBy and contains."

"GetCatalogOffersContainsInput::getAnonymousRestUrl() should not have both sortBy and contains."

SDK Example: Get List of Promotions or Promotions associated with a Product


(Fall '20)
Use the following example SDK code to retrieve all promotions or promotions that are associated with a
product:

// Instantiate the input object for getOffers to specify parameters.


const input = digitalCommerce.createGetOffersInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offerCode = "iPhoneX"; // If offerCode value is passed return all
associated promotions for that product.If offerCode not passed return all
promotions associated to products. - optional

// Invoke GetOffersByCatalog API via method getPromotions()


digitalCommerce
.getPromotions(input)
.then(result => {
Logger.info("vlocity get promotions anonymous user rest call" + result);
})
.catch(error => {
Logger.info("get promotions anonymous user rest call failed" + error);
});

Possible error conditions:

© 2021 Vlocity LLC, a Salesforce


company 161
Digital Commerce

"GetCatalogOffersInput::getAPIPath() must have catalogCode."

"GetCatalogOffersInput::getAnonymousRestUrl() must have anonymousSiteUrl."

"GetCatalogOffersContainsInput::getAPIPath() should not have both sortBy and contains.

"GetCatalogOffersContainsInput::getAnonymousRestUrl() should not have both sortBy and contains."

SDK Example: getOfferDetails via API (Fall '20)


SDK Example Code
// Instantiate the input object for getOfferDetails to specify parameters
const input = digitalCommerce.createGetOfferInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offerCode = "iPhoneXS"; // use your Offer Code
input.cacheable = false; // Optional Flag to indicate if the sdk call should
be cached. Default is false.
input.reload = false; // Optional Boolean flag to discard cache and call the
api again. Default is false.
input.isLoggedIn = true; // use to fetch offers based on given accountId -
optional
input.context = '{"accountId":"ACCOUNT ID"}'; // use to fetch offers based on
given context params - optional
input.customFields = ["customAttribute__c"]; // optional field which returns
your custom attributes or any given keys

// Invoke GetOfferDetails API via method getOfferDetails()


digitalCommerce
.getOffer(input)
.then(response => {
Logger.info("vlocity get offer anonymous user rest call" + response);
})
.catch(error => {
Logger.info("get offer anonymous user rest call failed" + error);
});

Possible error conditions:

"GetOfferInput::getAPIPath() must have catalogCode."

"GetOfferInput::getAPIPath() must have offerCode."

SDK Example: ValidateOffer (Fall '20)


// Instantiate the input object for validateOffer to specify parameters
const input = digitalCommerce.createValidateOfferInput();

© 2021 Vlocity LLC, a Salesforce


company 162
Digital Commerce

input.catalogCode = "Phones"; // use your Catalog Code


input.offerCode = "iPhoneX"; // use your Offer Code
(Fall '20)
// input.offerConfiguration: use digitalCommerce.getSelectedOffer(offerCode)
input.offerConfiguration = digitalCommerce.getSelectedOffer(offerCode);
input.customFields = ["customAttribute__c"]; // optional field which returns
your custom attributes or any given keys
input.secureApiCall = false; // set to true if needs secure api calls without
context parameters and session key.
// Invoke ConfigureOfferDetails API via method validateOffer()
digitalCommerce
.validateOffer(input)
.then(response => {
Logger.info(
"vlocity validate offer for anonymous user" + JSON.stringify(response)
);
})
.catch(error => {
Logger.info("vlocity validateOffer for anonymous user failed" + error);
});

Possible error conditions:

"ValidateOfferInput::getAPIPath() must have catalogCode."

"ValidateOfferInput::getAPIPath() must have offerCode."

"ValidateOfferInput::getPostBody() must have productConfiguration."

SDK Example: Add to Cart with Configuration Changes (Fall '20)


Use the following example SDK code to add an already configured item to a cart:

//
```javascript
const addToCartInput = digitalCommerce.createAddToCartInput();
addToCartInput.catalogCode = "Phones";
addToCartInput.offerConfiguration =
digitalCommerce.getSelectedOffer(offerCode);
addToCartInput.customFields = ["customAttribute__c"]; // optional field
which returns custom fields for given keys
input.basketAction = "AddAfterConfig";
return digitalCommerce.addToCart(addToCartInput);
})
.then(addToCartResponse => {
Logger.info(addToCartResponse.orderId);
})
.catch(error => {

© 2021 Vlocity LLC, a Salesforce


company 163
Digital Commerce

Logger.info("addToCart login user dual fail: " + error);


});

SDK Example: Add to Cart with No Configuration Changes (Fall '20)


Use the following example SDK code to add an already configured item to a cart:

// Instantiate the input object for addToCart to specify parameters


const input = digitalCommerce.createAddToCartInput();
input.catalogCode = "Mobiles"; // use your Catalog Code
input.basketAction = "AddWithNoConfig"; // adding an offer that has not been
configured (no change in its json structure from getOfferDetails) to cart
input.offerCode = "iPhone8Offer"; // use your Offer Code to be added to cart
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke Cart API via method addToCart()


digitalCommerce
.addToCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToCart with basketAction=AddWithNoConfig
for anonymous user: " +
JSON.stringify(response)
);
return response;
})
.catch(error => {
Logger.error(
"addToCart() with basketAction=AddWithNoConfig failed" + error
);
});

Possible error conditions:

"AddTocartInput::getAPIPath() must have catalogCode."

"AddTocartInput::getAnonymousSiteRestUrl() must have catalogCode."

"AddTocartInput::getRequestPayload() must have basketAction."

"AddTocartInput::getRequestPayload() must have offerCode."

"AddTocartInput::getRequestPayload() must have offer when basketAction is 'AddWithNoConfig'."

SDK Example: Delete From Basket (Fall '20)


Use the example code below to addToBasket with basketAction=DeleteFromBasket. The call must have
deleteBundleNumber as an input parameter.

© 2021 Vlocity LLC, a Salesforce


company 164
Digital Commerce

// Instantiate the input object for the addToBasket method to specify


parameters.
const input = digitalCommerce.createAddToBasketInput();
// Use your AWS gateway.
input.anonymousSiteUrl = "https://mubnr8cjgl.execute-api.us-
west-2.amazonaws.com/prod/dc";
// Use your Catalog Code.
input.catalogCode = "Mobiles";
// Delete an offer that was added to basket.
input.basketAction = "DeleteFromBasket";
input.forceInvalidateCache = true;

// The basket item list grows from the bottom up. For example: if you add
products A, B, and C in that order,
// the JSONResult.records list would be C,B,A with respective numbering as
0,1,2.
// The 0 item will always be the most recent addition.
input.deleteBundleNumber = 0;

// Invoke the Basket API via the addToBasket() method.


digitalCommerce
.addToBasket(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToBasket with basketAction=DeleteFromBasket
for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info(
"addToBasket with basketAction=DeleteFromBasket for anonymous user rest
call failed" +
error
);
});

Possible error conditions:

"AddToBasketInput::getAPIPath() must have catalogCode."

"AddToBasketInput::getAnonymousRestUrl() must have anonymousSiteUrl."

"AddToBasketInput::getAnonymousSiteRestUrl() must have catalogCode."

"AddToBasketInput::getPostBody() must have basketAction."

© 2021 Vlocity LLC, a Salesforce


company 165
Digital Commerce

"AddToBasketInput::getPostBody() must have deleteBundleNumber when basketAction is


'DeleteFromBasket'."

SDK Example: Add a Child Product to the Basket (Fall '20)


Use the following example SDK code to add a child product to a basket:

// Instantiate the input object for AddToCartInput to specify parameters


const input = digitalCommerce.createAddToCartInput();
input.catalogCode = "Mobiles"; // use your Catalog Code
input.basketAction = "AddChildProduct"; // deleting an offer that was added to
cart
input.basketKey = "01tf2000007Rb9JAAS"; // use your basketKey
input.actionParams = {
rootProductCode: "iPhoneX", // use your rootProductCode
parentLineKey: "c3a4590a2d231e7022e04e5eba539ead", // use your parentLineKey
parentHierarchyPath: "01tf2000007Rb9JAAS", // use your parentHierarchyPath
offer: "DeclineEquipmentProtection", // use your offer_code
cartContextkey: "d80b2927f07938aefdc7e2e349e2ede7", // use your
cartContextKey
bundleContextKey: "c3a4590a2d231e7022e04e5eba539ead" // use your
bundleContextKey};
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke Basket API via method addToBasket()digitalCommerce


.addToCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToCart with basketAction=AddChildProduct
for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info(
"addToBasket with basketAction=AddChildProduct for anonymous user rest
call failed" +
error
);
});

Possible error conditions:

"AddToCartInput::getAPIPath() must have catalogCode."

"AddToCartInput::getAnonymousSiteRestUrl() must have catalogCode."

© 2021 Vlocity LLC, a Salesforce


company 166
Digital Commerce

"AddToCartInput::getRequestPayload() must have basketAction."

"AddToCartInput::getRequestPayload() must have rootProductCode when basketAction is


'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have parentLineKey when basketAction is 'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have parentHierarchyPath when basketAction is


'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have offer when basketAction is 'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have cartContextkey when basketAction is 'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have bundleContextKey when basketAction is


'AddChildProduct'."

SDK Example: Delete a Child Product from the Basket (Fall '20)
Use the following example SDK code to delete a child product from a basket:

// Instantiate the input object for AddToCartInput to specify parameters


const input = digitalCommerce.createAddToCartInput();
input.catalogCode = "Mobiles"; // use your Catalog Code
input.basketAction = "DeleteChildProduct"; // deleting an offer that was added
to cart
input.actionParams = {
lineItemKey: "d83f475a776049d21054c105e9d53ee9", // use your lineItemKey
cartContextkey: "d80b2927f07938aefdc7e2e349e2ede7", // use your
cartContextKey
bundleContextKey: "c3a4590a2d231e7022e04e5eba539ead" // use your
bundleContextKey};
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke Basket API via method addToBasket()


digitalCommerce
.addToCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToCart with basketAction=DeleteChildProduct
for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info(
"addToBasket with basketAction=DeleteChildProduct for anonymous user

© 2021 Vlocity LLC, a Salesforce


company 167
Digital Commerce

rest call failed" +


error
);
});

Possible error conditions:

"AddToCartInput::getAPIPath() must have catalogCode."

"AddToCartInput::getAnonymousSiteRestUrl() must have catalogCode."

"AddToCartInput::getRequestPayload() must have basketAction."

"AddToCartInput::getRequestPayload() must have lineItemKey when basketAction is 'DeleteChildProduct'."

"AddToCartInput::getRequestPayload() must have cartContextkey when basketAction is


'DeleteChildProduct'."

"AddToCartInput::getRequestPayload() must have bundleContextKey when basketAction is


'DeleteChildProduct'."

SDK Example: Update Items in Basket (Fall '20)


Use the following example SDK code to update items in a basket:

// Instantiate the input object for AddToCartInput to specify parameters


let input = Object.assign(
this.digitalCommerceSDK.createUpdateItemsInCartInput(),
{
catalogCode: "Phones",
basketkey: "01tf2000007Rb9JAAS",
basketAction: "updateBasket",
bundleContextKey: "",
lineItemKey: "",
quantity: 2,
customFields: ["customAttribute__c"]
}
);
this.digitalCommerceSDK
.updateItemsInCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce updateItemsInCart for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info("updateItemsInCart action failed: ", error);
});

© 2021 Vlocity LLC, a Salesforce


company 168
Digital Commerce

Possible error conditions:

"UpdateItemsInCart::getAPIPath() must have catalogCode."

"UpdateItemsInCart::getAnonymousSiteRestUrl() must have catalogCode."

"UpdateItemsInCart::getRequestPayload() must have basketAction."

"UpdateItemsInCart::getRequestPayload() must have lineItemKey when basketAction is 'updateBasket'."

"UpdateItemsInCart::getRequestPayload() must have basketkey when basketAction is 'updateBasket'."

"UpdateItemsInCart::getRequestPayload() must have bundleContextKey when basketAction is


'updateBasket'."

SDK Example: Checkout Cart (Fall '20)


Use the following example SDK code to check out a cart:

// Instantiate the input object for checkoutCart to specify parameters


const input = digitalCommerce.checkoutCartInput();
input.catalogCode = "Mobiles"; // use your Catalog Code
input.accountId = "001f200001eSlhe"; // use your account Id
input.cartContextKey = "d5ff11cccd19472ca7c21fa80bc93d2a";

// Used in Checkout process to persist shopping cart content into SF Database


digitalCommerce
.checkoutCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce checkout cart for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info("checkout cart for anonymous user rest call failed" + error);
});

Possible error conditions:

"checkoutCartInput::getAPIPath() must have catalogCode."

"checkoutCartInput::getAPIPath() must have accountId."

"checkoutCartInput::getAnonymousSiteRestUrl() must have catalogCode."

"checkoutCartInput::getAnonymousSiteRestUrl() must have accountId."

"checkoutCartInput::getRequestPayload() must have cartContextKey."

© 2021 Vlocity LLC, a Salesforce


company 169
Digital Commerce

SDK Example: Create a Basket from an Asset (Fall '20)


Use the following example SDK code to create a basket from an existing asset:

// Instantiate the input object for assetToBasket to specify parameters


const input = digitalCommerce.createAssetToBasketInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.basketAction = "assetToBasket";
input.isLoggedIn = true;
input.canCreateBasket = false; // optional - default is false
input.context = '{"accountId":"YOUR ACCOUNT ID", "contractId":"YOUR CONTRACT
ID"}';
input.validatePrice = true; // optional - default is true
input.validateAction = true; // optional - default is true
input.rootAssetIds = "02i4P000009ion5QAA,02i4P000009ion6QAA";
input.requestDateTime = "2019-08-10T00:00:000z"; // date or date time in UTC
format.

// Invoke assetToBasket API via method assetToBasket()


digitalCommerce
.assetToBasket(input)
.then(response => {
Logger.info(
"Vlocity digital commerce assetToBasket: " + JSON.stringify(response)
);
})
.catch(error => {
Logger.info("assetToBasket apexrest call failed" + error);
});

Possible error conditions:

"AssetToBasketInput::getAPIPath() must have catalogCode."

"AssetToBasketInput::getAPIPath() must have context."

"AssetToBasketInput::getAPIPath() must have set isLoggedIn=true."

"AssetToBasketInput::getRequestPayload() must have rootAssetIds."

"AssetToBasketInput::getRequestPayload() must have basketAction."

"AssetToBasketInput::getRequestPayload() must have valid requestDateTime input."

SDK Example: Sign Out User (Fall '20)


Use the following example SDK code to sign out a user:

© 2021 Vlocity LLC, a Salesforce


company 170
Digital Commerce

// Instantiate the input object for signOutUser to specify parameters


const input = digitalCommerce.createSignOutUserInput();

// Invoke authenticateUser API


digitalCommerce
.signOutUser(input)
.then(response => {
Logger.info(
"Vlocity digital commerce signOutUser: " + JSON.stringify(response)
);
})
.catch(error => {
Logger.info("signOutUser call failed" + error);
});

SDK Usage Examples (Winter '20 version)


This topic and the topics that follow illustrate several examples for instantiating and using the Digital
Commerce SDK.

Example Code
// Instantiate DigitalCommerceConfig for anonymous user
const digitalCommerceConfig =
VlocitySDK.digitalcommerce.createConfigForAnonymousUser();

// Instantiate the SDK itselfconst digitalCommerce =


VlocitySDK.digitalcommerce.getInstance(digitalCommerceConfig);

OR

// Instantiate DigitalCommerceConfig for login user


const digitalCommerceConfig =
VlocitySDK.digitalcommerce.createConfigForLoginUser(salesforceUrl,
sessionToken);

// Instantiate the SDK itself


const digitalCommerce =
VlocitySDK.digitalcommerce.getInstance(digitalCommerceConfig);

// To override the default namespace with your custom namespace


this.digitalCommerce.namespace = "vlocity_cmt"; // use your custom namespace

// To override the default custom api URL with your custom api URL
this.digitalCommerce.apiURL = "YOUR_CUSTOM_API_URL"; // use your custom URL

© 2021 Vlocity LLC, a Salesforce


company 171
Digital Commerce

// To override the default api URL


authTokenthis.digitalCommerce.authToken = "YOUR_CUSTOM_AUTH_TOKEN"; // use
your custom authToken

Note:
digitalCommerce is a Singleton object. Calling
getInstance(digitalCommerceConfig) repeatedly will return the same instance
instantiated the first time when getInstance(digitalCommerceConfig) was called.

// To instantiate a new instance of digitalCommerce, set create to true in the


digitalCommerceConfig object:
digitalCommerceConfig.create = true;
digitalCommerce =
VlocitySDK.digitalcommerce.getInstance(digitalCommerceConfig);```

Possible error conditions:

• "VlocityDigitalCommerce::getInstance: Config object must be given in argument to create an instance the


first time."
• "VlocityDigitalCommerce::constructor: VlocityDigitalCommerce cannot be instantiated properly. Both
datasource and user context objects have to be in Config object as argument."

SDK Example: getCatalogOffers without the contains parameter (Winter '20)


// Instantiate the input object for getCatalogOffers to specify parameters
const input = digitalCommerce.createGetOffersInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offset = 0; // use for pagination - optional
input.pageSize = 5; // use for pagination - optional
input.isLoggedIn = true; // use to fetch offers based on given accountId -
optional
input.secureApiCall = false; // set to true if needs secure api calls without
context parameters and session key.
input.context = '{"accountId":"ACCOUNT ID", "contractId":"CONTRACT ID"}'; //
use to fetch offers based on context params - optional
input.includeAttributes = ["ishidden__c", "customAttribute__c"]; //
includeExtraOfferAttributes as part of the query string of the API which
includes extra passed attributes with default attributes in Offer - optional
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke GetOffersByCatalog API via method getCatalogOffers()


digitalCommerce
.getOffers(input)
.then(result => {
Logger.info("vlocity get offers anonymous user rest call" + result);

© 2021 Vlocity LLC, a Salesforce


company 172
Digital Commerce

})
.catch(error => {
Logger.info("get offers anonymous user rest call failed" + error);
});

Possible error conditions:

"GetOffersInput::getAPIPath() must have catalogCode."

"GetOffersInput::getAnonymousRestUrl() must have catalogCode."

SDK Example: getCatalogOffers with the contains parameter (Winter '20)


// Instantiate the input object for getOffers to specify parameters
const input = digitalCommerce.createGetOffersInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offset = 0; // use for pagination - optional
input.pageSize = 5; // use for pagination - optional
input.contains = "iPhone8"; // find all offers that CONTAIN "iPhone8" -
optional
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys
input.secureApiCall = false; // set to true if needs secure api calls without
context parameters and session key.

// Invoke GetContainsProducts API via method getOffers()


digitalCommerce
.getOffers(input)
.then(result => {
Logger.info("vlocity get offers anonymous user rest call" + result);
})
.catch(error => {
Logger.info("get offers anonymous user rest call failed" + error);
});

Possible error conditions:

"GetOffersInput::getAPIPath() must have catalogCode."

"GetOffersContainsInput::getAPIPath() should not have both sortBy and contains."

"GetOffersInput::getAnonymousRestUrl() must have catalogCode."

"GetOffersContainsInput::getAnonymousRestUrl() should not have both sortBy and contains."

SDK Example: Create and Submit the Order (Winter '20)


Use the following example SDK code to create and submit the order as the final step in the checkout
process:

© 2021 Vlocity LLC, a Salesforce


company 173
Digital Commerce

// Instantiate the input object for submitOrder to specify parameters


const input = digitalCommerce.createSubmitOrderInput();
input.email = "YOUR EMAIL ID";
input.catalogCode = "CATALOG CODE";
input.cartContextKey = "CART CONTEXT KEY";
input.orderId = "ORDER ID"; // optional parameter

// Invoke submitOrder API


digitalCommerce
.submitOrder(input)
.then(response => {
Logger.info(
"Vlocity digital commerce submitOrder: " + JSON.stringify(response)
);
})
.catch(error => {
Logger.info("submitOrder apexrest call failed" + error);
});

Possible error conditions:

"SubmitOrderInput::getRequestPayload() must have email."

"SubmitOrderInput::getRequestPayload() must have catalogCode."

"SubmitOrderInput::getRequestPayload() must have cartContextKey."

SDK Example: Get List of Promotions or Promotions associated with a Product


(Winter '20)
Use the following example SDK code to retrieve all promotions or promotions that are associated with a
product:

// Instantiate the input object for getOffers to specify parameters.


const input = digitalCommerce.createGetOffersInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offerCode = "iPhoneX"; // If offerCode value is passed return all
associated promotions for that product.If offerCode not passed return all
promotions associated to products. - optional

// Invoke GetOffersByCatalog API via method getPromotions()


digitalCommerce
.getPromotions(input)
.then(result => {
Logger.info("vlocity get promotions anonymous user rest call" + result);
})

© 2021 Vlocity LLC, a Salesforce


company 174
Digital Commerce

.catch(error => {
Logger.info("get promotions anonymous user rest call failed" + error);
});

Possible error conditions:

"GetCatalogOffersInput::getAPIPath() must have catalogCode."

"GetCatalogOffersInput::getAnonymousRestUrl() must have anonymousSiteUrl."

"GetCatalogOffersContainsInput::getAPIPath() should not have both sortBy and contains.

"GetCatalogOffersContainsInput::getAnonymousRestUrl() should not have both sortBy and contains."

SDK Example: getOfferDetails via API (Winter '20)

SDK Example Code


// Instantiate the input object for getOfferDetails to specify parameters
const input = digitalCommerce.createGetOfferInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offerCode = "iPhoneXS"; // use your Offer Code
input.cacheable = false; // Optional Flag to indicate if the sdk call should
be cached. Default is false.
input.reload = false; // Optional Boolean flag to discard cache and call the
api again. Default is false.
input.isLoggedIn = true; // use to fetch offers based on given accountId -
optional
input.context = '{"accountId":"ACCOUNT ID"}'; // use to fetch offers based on
given context params - optional
input.customFields = ["customAttribute__c"]; // optional field which returns
your custom attributes or any given keys

// Invoke GetOfferDetails API via method getOfferDetails()


digitalCommerce
.getOffer(input)
.then(response => {
Logger.info("vlocity get offer anonymous user rest call" + response);
})
.catch(error => {
Logger.info("get offer anonymous user rest call failed" + error);
});

Possible error conditions:

"GetOfferInput::getAPIPath() must have catalogCode."

© 2021 Vlocity LLC, a Salesforce


company 175
Digital Commerce

"GetOfferInput::getAPIPath() must have offerCode."

SDK Example: ValidateOffer (Winter '20)


// Instantiate the input object for validateOffer to specify parameters
const input = digitalCommerce.createValidateOfferInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offerCode = "iPhoneX"; // use your Offer Code

// input.offerConfiguration: use digitalCommerce.getSelectedOffer(offerCode)


input.offerConfiguration = digitalCommerce.getSelectedOffer(offerCode);
input.customFields = ["customAttribute__c"]; // optional field which returns
your custom attributes or any given keys
input.secureApiCall = false; // set to true if needs secure api calls without
context parameters and session key.
// Invoke ConfigureOfferDetails API via method validateOffer()
digitalCommerce
.validateOffer(input)
.then(response => {
Logger.info(
"vlocity validate offer for anonymous user" + JSON.stringify(response)
);
})
.catch(error => {
Logger.info("vlocity validateOffer for anonymous user failed" + error);
});

Possible error conditions:

"ValidateOfferInput::getAPIPath() must have catalogCode."

"ValidateOfferInput::getAPIPath() must have offerCode."

"ValidateOfferInput::getPostBody() must have productConfiguration."

SDK Example: Add to Cart with Configuration Changes (Winter '20)


Use the following example SDK code to add an already configured item to a cart:

//
```javascript
const addToCartInput = digitalCommerce.createAddToCartInput();
addToCartInput.catalogCode = "Phones";
addToCartInput.offerConfiguration =
digitalCommerce.getSelectedOffer(offerCode);
addToCartInput.customFields = ["customAttribute__c"]; // optional field
which returns custom fields for given keys
input.basketAction = "AddAfterConfig";

© 2021 Vlocity LLC, a Salesforce


company 176
Digital Commerce

return digitalCommerce.addToCart(addToCartInput);
})
.then(addToCartResponse => {
Logger.info(addToCartResponse.orderId);
})
.catch(error => {
Logger.info("addToCart login user dual fail: " + error);
});

SDK Example: Add to Cart with No Configuration Changes (Winter '20)


Use the following example SDK code to add an already configured item to a cart:

// Instantiate the input object for addToCart to specify parameters


const input = digitalCommerce.createAddToCartInput();
input.catalogCode = "Mobiles"; // use your Catalog Code
input.basketAction = "AddWithNoConfig"; // adding an offer that has not been
configured (no change in its json structure from getOfferDetails) to cart
input.offerCode = "iPhone8Offer"; // use your Offer Code to be added to cart
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke Cart API via method addToCart()


digitalCommerce
.addToCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToCart with basketAction=AddWithNoConfig
for anonymous user: " +
JSON.stringify(response)
);
return response;
})
.catch(error => {
Logger.error(
"addToCart() with basketAction=AddWithNoConfig failed" + error
);
});

Possible error conditions:

"AddTocartInput::getAPIPath() must have catalogCode."

"AddTocartInput::getAnonymousSiteRestUrl() must have catalogCode."

"AddTocartInput::getRequestPayload() must have basketAction."

"AddTocartInput::getRequestPayload() must have offerCode."

© 2021 Vlocity LLC, a Salesforce


company 177
Digital Commerce

"AddTocartInput::getRequestPayload() must have offer when basketAction is 'AddWithNoConfig'."

SDK Example: Delete From Basket (Winter '20)


Use the example code below to addToBasket with basketAction=DeleteFromBasket. The call must have
deleteBundleNumber as an input parameter.

// Instantiate the input object for the addToBasket method to specify


parameters.
const input = digitalCommerce.createAddToBasketInput();
// Use your AWS gateway.
input.anonymousSiteUrl = "https://mubnr8cjgl.execute-api.us-
west-2.amazonaws.com/prod/dc";
// Use your Catalog Code.
input.catalogCode = "Mobiles";
// Delete an offer that was added to basket.
input.basketAction = "DeleteFromBasket";
input.forceInvalidateCache = true;

// The basket item list grows from the bottom up. For example: if you add
products A, B, and C in that order,
// the JSONResult.records list would be C,B,A with respective numbering as
0,1,2.
// The 0 item will always be the most recent addition.
input.deleteBundleNumber = 0;

// Invoke the Basket API via the addToBasket() method.


digitalCommerce
.addToBasket(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToBasket with basketAction=DeleteFromBasket
for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info(
"addToBasket with basketAction=DeleteFromBasket for anonymous user rest
call failed" +
error
);
});

Possible error conditions:

"AddToBasketInput::getAPIPath() must have catalogCode."

© 2021 Vlocity LLC, a Salesforce


company 178
Digital Commerce

"AddToBasketInput::getAnonymousRestUrl() must have anonymousSiteUrl."

"AddToBasketInput::getAnonymousSiteRestUrl() must have catalogCode."

"AddToBasketInput::getPostBody() must have basketAction."

"AddToBasketInput::getPostBody() must have deleteBundleNumber when basketAction is


'DeleteFromBasket'."

SDK Example: Add a Child Product to the Basket (Winter '20)


Use the following example SDK code to add a child product to a basket:

// Instantiate the input object for AddToCartInput to specify parameters


const input = digitalCommerce.createAddToCartInput();
input.catalogCode = "Mobiles"; // use your Catalog Code
input.basketAction = "AddChildProduct"; // deleting an offer that was added to
cart
input.basketKey = "01tf2000007Rb9JAAS"; // use your basketKey
input.actionParams = {
rootProductCode: "iPhoneX", // use your rootProductCode
parentLineKey: "c3a4590a2d231e7022e04e5eba539ead", // use your parentLineKey
parentHierarchyPath: "01tf2000007Rb9JAAS", // use your parentHierarchyPath
offer: "DeclineEquipmentProtection", // use your offer_code
cartContextkey: "d80b2927f07938aefdc7e2e349e2ede7", // use your
cartContextKey
bundleContextKey: "c3a4590a2d231e7022e04e5eba539ead" // use your
bundleContextKey};
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke Basket API via method addToBasket()digitalCommerce


.addToCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToCart with basketAction=AddChildProduct
for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info(
"addToBasket with basketAction=AddChildProduct for anonymous user rest
call failed" +
error
);
});

© 2021 Vlocity LLC, a Salesforce


company 179
Digital Commerce

Possible error conditions:

"AddToCartInput::getAPIPath() must have catalogCode."

"AddToCartInput::getAnonymousSiteRestUrl() must have catalogCode."

"AddToCartInput::getRequestPayload() must have basketAction."

"AddToCartInput::getRequestPayload() must have rootProductCode when basketAction is


'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have parentLineKey when basketAction is 'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have parentHierarchyPath when basketAction is


'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have offer when basketAction is 'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have cartContextkey when basketAction is 'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have bundleContextKey when basketAction is


'AddChildProduct'."

SDK Example: Delete a Child Product from the Basket (Winter '20)
Use the following example SDK code to delete a child product from a basket:

// Instantiate the input object for AddToCartInput to specify parameters


const input = digitalCommerce.createAddToCartInput();
input.catalogCode = "Mobiles"; // use your Catalog Code
input.basketAction = "DeleteChildProduct"; // deleting an offer that was added
to cart
input.actionParams = {
lineItemKey: "d83f475a776049d21054c105e9d53ee9", // use your lineItemKey
cartContextkey: "d80b2927f07938aefdc7e2e349e2ede7", // use your
cartContextKey
bundleContextKey: "c3a4590a2d231e7022e04e5eba539ead" // use your
bundleContextKey};
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke Basket API via method addToBasket()


digitalCommerce
.addToCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToCart with basketAction=DeleteChildProduct
for anonymous user: " +
JSON.stringify(response)

© 2021 Vlocity LLC, a Salesforce


company 180
Digital Commerce

);
})
.catch(error => {
Logger.info(
"addToBasket with basketAction=DeleteChildProduct for anonymous user
rest call failed" +
error
);
});

Possible error conditions:

"AddToCartInput::getAPIPath() must have catalogCode."

"AddToCartInput::getAnonymousSiteRestUrl() must have catalogCode."

"AddToCartInput::getRequestPayload() must have basketAction."

"AddToCartInput::getRequestPayload() must have lineItemKey when basketAction is 'DeleteChildProduct'."

"AddToCartInput::getRequestPayload() must have cartContextkey when basketAction is


'DeleteChildProduct'."

"AddToCartInput::getRequestPayload() must have bundleContextKey when basketAction is


'DeleteChildProduct'."

SDK Example: Update Items in Basket (Winter '20)


Use the following example SDK code to update items in a basket:

// Instantiate the input object for AddToCartInput to specify parameters


let input = Object.assign(
this.digitalCommerceSDK.createUpdateItemsInCartInput(),
{
catalogCode: "Phones",
basketkey: "01tf2000007Rb9JAAS",
basketAction: "updateBasket",
bundleContextKey: "",
lineItemKey: "",
quantity: 2,
customFields: ["customAttribute__c"]
}
);
this.digitalCommerceSDK
.updateItemsInCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce updateItemsInCart for anonymous user: " +
JSON.stringify(response)

© 2021 Vlocity LLC, a Salesforce


company 181
Digital Commerce

);
})
.catch(error => {
Logger.info("updateItemsInCart action failed: ", error);
});

Possible error conditions:

"UpdateItemsInCart::getAPIPath() must have catalogCode."

"UpdateItemsInCart::getAnonymousSiteRestUrl() must have catalogCode."

"UpdateItemsInCart::getRequestPayload() must have basketAction."

"UpdateItemsInCart::getRequestPayload() must have lineItemKey when basketAction is 'updateBasket'."

"UpdateItemsInCart::getRequestPayload() must have basketkey when basketAction is 'updateBasket'."

"UpdateItemsInCart::getRequestPayload() must have bundleContextKey when basketAction is


'updateBasket'."

SDK Example: Get Cart Details (Winter '20)


Use the following example SDK code to obtain details about a cart:

// Instantiate the input object for getItemsInCart to specify parameters


const input = digitalCommerce.createGetItemsInCartInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.cartContextKey = "01tf2000007Rb9JAAS"; // use your cart_context_key
input.cacheable = true; // Optional boolean flag to indicate if the sdk call
should be cached. Default is false.
input.reload = true; // Optional boolean flag to discard cache and call the
api again Default is false.
input.customFields = ["customAttribute__c"]; // optional field which returns
your custom attributes or any given keys

// Invoke get basket API via method getItemsInCart()


digitalCommerce
.getItemsInCart(input)
.then(response => {
Logger.info("vlocity get cart items anonymous user rest call" + response);
})
.catch(error => {
Logger.info("get cart items anonymous user rest call failed" + error);
});

Possible error conditions:

© 2021 Vlocity LLC, a Salesforce


company 182
Digital Commerce

"GetItemsInCartInput::getAPIPath() must have catalogCode."

"GetItemsInCartInput::getAPIPath() must have cartContextKey."

SDK Example: Checkout Cart (Winter '20)


Use the following example SDK code to check out a cart:

// Instantiate the input object for checkoutCart to specify parameters


const input = digitalCommerce.checkoutCartInput();
input.catalogCode = "Mobiles"; // use your Catalog Code
input.accountId = "001f200001eSlhe"; // use your account Id
input.cartContextKey = "d5ff11cccd19472ca7c21fa80bc93d2a";

// Used in Checkout process to persist shopping cart content into SF Database


digitalCommerce
.checkoutCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce checkout cart for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info("checkout cart for anonymous user rest call failed" + error);
});

Possible error conditions:

"checkoutCartInput::getAPIPath() must have catalogCode."

"checkoutCartInput::getAPIPath() must have accountId."

"checkoutCartInput::getAnonymousSiteRestUrl() must have catalogCode."

"checkoutCartInput::getAnonymousSiteRestUrl() must have accountId."

"checkoutCartInput::getRequestPayload() must have cartContextKey."

SDK Example: Create a Basket from an Asset (Winter '20)


Use the following example SDK code to create a basket from an existing asset:

// Instantiate the input object for assetToBasket to specify parameters


const input = digitalCommerce.createAssetToBasketInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.basketAction = "assetToBasket";
input.isLoggedIn = true;
input.canCreateBasket = false; // optional - default is false

© 2021 Vlocity LLC, a Salesforce


company 183
Digital Commerce

input.context = '{"accountId":"YOUR ACCOUNT ID", "contractId":"YOUR CONTRACT


ID"}';
input.validatePrice = true; // optional - default is true
input.validateAction = true; // optional - default is true
input.rootAssetIds = "02i4P000009ion5QAA,02i4P000009ion6QAA";
input.requestDateTime = "2019-08-10T00:00:000z"; // date or date time in UTC
format.

// Invoke assetToBasket API via method assetToBasket()


digitalCommerce
.assetToBasket(input)
.then(response => {
Logger.info(
"Vlocity digital commerce assetToBasket: " + JSON.stringify(response)
);
})
.catch(error => {
Logger.info("assetToBasket apexrest call failed" + error);
});

Possible error conditions:

"AssetToBasketInput::getAPIPath() must have catalogCode."

"AssetToBasketInput::getAPIPath() must have context."

"AssetToBasketInput::getAPIPath() must have set isLoggedIn=true."

"AssetToBasketInput::getRequestPayload() must have rootAssetIds."

"AssetToBasketInput::getRequestPayload() must have basketAction."

"AssetToBasketInput::getRequestPayload() must have valid requestDateTime input."

SDK Example: Authenticate a User (Winter '20)


Use the following example SDK code to sign in or sign up a user and authenticate:

// Instantiate the input object for authenticateUser to specify parameters


const input = digitalCommerce.createAuthenticateUserInput();
input.email = "YOUR EMAIL ID";
input.password = "YOUR PASSWORD";
input.phoneNumber = "1234567889";
input.firstName = "YOUR FIRST NAME";
input.lastName = "YOUR LAST NAME";
input.signUp = true; // optional - default is false

© 2021 Vlocity LLC, a Salesforce


company 184
Digital Commerce

// Invoke authenticateUser API


digitalCommerce
.authenticateUser(input)
.then(response => {
Logger.info(
"Vlocity digital commerce authenticateUser: " + JSON.stringify(response)
);
})
.catch(error => {
Logger.info("authenticateUser apexrest call failed" + error);
});

Possible error conditions:

"AuthenticateUserInput::getRequestPayload() must have email."

"AuthenticateUserInput::getRequestPayload() must have password."

"AuthenticateUserInput::getRequestPayload() must have phoneNumber."

"AssetToBasketInput::getRequestPayload() must have rootAssetIds."

"AuthenticateUserInput::getRequestPayload() must have firstName."

"AuthenticateUserInput::getRequestPayload() must have lastName.

SDK Example: Update Billing and Shipping Details (Winter '20)


Use the following example SDK code to update user account billing and shipping details:

// Instantiate the input object for updateBillingDetails to specify parameters


const input = digitalCommerce.createUpdateBillingDetailsInput();
input.email = "YOUR EMAIL ID";
input.billingCity = "Bengaluru";
input.billingState = "KA";
input.billingAddress = "Vlocity, Cessna Business Tech Park";
input.billingZipCode = "560103";
input.shippingCity = "Bengaluru";
input.shippingState = "KA";
input.shippingAddress = "Vlocity, Cessna Business Tech Park";
input.shippingZipCode = "560103";

// Invoke updateBillingDetails API


digitalCommerce
.updateBillingDetails(input)
.then(response => {

© 2021 Vlocity LLC, a Salesforce


company 185
Digital Commerce

Logger.info(
"Vlocity digital commerce updateBillingDetails: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info("updateBillingDetails apexrest call failed" + error);
});

Possible error conditions:

"UpdateBillingDetailsInput::getRequestPayload() must have email."

"UpdateBillingDetailsInput::getRequestPayload() must have billingCity."

"UpdateBillingDetailsInput::getRequestPayload() must have billingState."

"UpdateBillingDetailsInput::getRequestPayload() must have billingAddress."

"UpdateBillingDetailsInput::getRequestPayload() must have billingZipCode."

"UpdateBillingDetailsInput::getRequestPayload() must have shippingCity."

"UpdateBillingDetailsInput::getRequestPayload() must have shippingState."

"UpdateBillingDetailsInput::getRequestPayload() must have shippingAddress."

"UpdateBillingDetailsInput::getRequestPayload() must have shippingZipCode."

SDK Example: Save the Cart (Winter '20)


Use the following example SDK code to save the cart by creating an order for the specified basket:

// Instantiate the input object for saveCart to specify parameters


const input = digitalCommerce.createSaveCartInput();
input.email = "YOUR EMAIL ID";
input.catalogCode = "CATALOG CODE";
input.cartContextKey = "CART CONTEXT KEY";

// Invoke saveCart API


digitalCommerce
.saveCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce saveCart: " + JSON.stringify(response)
);
})

© 2021 Vlocity LLC, a Salesforce


company 186
Digital Commerce

.catch(error => {
Logger.info("saveCart apexrest call failed" + error);
});

Possible error conditions:

"SaveCartInput::getRequestPayload() must have email."

"SaveCartInput::getRequestPayload() must have catalogCode."

"SaveCartInput::getRequestPayload() must have cartContextKey."

SDK Example: Get Filtered List of Products and Promotions (Winter '20)
Use the following example SDK code to retrieve a filtered list of products and promotions:

// Instantiate the input object for getOffers to specify parameters.


const input = digitalCommerce.createGetOffersInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.returnPromotion = true; // If undefined return both products and
promotions, If true return only promotions, If false return only products -
optional

// Invoke GetOffersByCatalog API via method getFilteredOffersList()


digitalCommerce
.getFilteredOffersList(input)
.then(result => {
Logger.info(
"vlocity get catalog filtered offers list anonymous user rest call" +
result
);
})
.catch(error => {
Logger.info("get catalog offers anonymous user rest call failed" + error);
});

Possible error conditions:

"GetCatalogOffersInput::getAPIPath() must have catalogCode."

"GetCatalogOffersInput::getAnonymousRestUrl() must have anonymousSiteUrl."

"GetCatalogOffersContainsInput::getAPIPath() should not have both sortBy and contains."

"GetCatalogOffersContainsInput::getAnonymousRestUrl() should not have both sortBy and contains."

© 2021 Vlocity LLC, a Salesforce


company 187
Digital Commerce

Setting Up the Pubsub SDK (Winter '20)


The Vlocity Digital Commerce SDK includes the pubsub SDK, which supports communication between
Digital Commerce components, including Digital Commerce Lightning Web Components, Digital Commerce
Web Components, JavaScript-based framework, and so on. For more details, see the PubSub SDK
reference.

Registering an Event
Use the following example Digital Commerce pubsub register method to add a callback function to the
list of subscribers for a particular event:

// registering pub-sub event


this.callbackEventHandler = {
result: this.callbackFunction.bind(this)
};
callbackFunction(data) {/* callback triggered by the pubsub event */}
this.digitalCommerceSDK.register("event-name",this.callbackEventHandler);

Firing an Event
Use the following example fire method to publish the occurrence of an event:

this.digitalCommerceSDK.fire("event-name",action,payloadObject);

Unregistering an Event
Use the following example unregister method to cancel subscription of an event:

// un-registering pub-sub event


this.digitalCommerceSDK.unregister("event-name",this.callbackEventHandler);

SDK Usage Examples (Fall '19 version)


This topic and the topics that follow illustrate several examples for instantiating and using the Digital
Commerce SDK.

Example Code
// Instantiate DigitalCommerceConfig for anonymous user
const digitalCommerceConfig =
VlocitySDK.digitalcommerce.createConfigForAnonymousUser();

// Instantiate the SDK itselfconst digitalCommerce =


VlocitySDK.digitalcommerce.getInstance(digitalCommerceConfig);

OR

// Instantiate DigitalCommerceConfig for login user


const digitalCommerceConfig =
VlocitySDK.digitalcommerce.createConfigForLoginUser(salesforceUrl,

© 2021 Vlocity LLC, a Salesforce


company 188
Digital Commerce

sessionToken);

// Instantiate the SDK itself


const digitalCommerce =
VlocitySDK.digitalcommerce.getInstance(digitalCommerceConfig);

// To override the default namespace with your custom namespace


this.digitalCommerce.namespace = "vlocity_cmt"; // use your custom namespace

// To override the default custom api URL with your custom api URL
this.digitalCommerce.apiURL = "YOUR_CUSTOM_API_URL"; // use your custom URL

// To override the default api URL


authTokenthis.digitalCommerce.authToken = "YOUR_CUSTOM_AUTH_TOKEN"; // use
your custom authToken

Note:
digitalCommerce is a Singleton object. Calling
getInstance(digitalCommerceConfig) repeatedly will return the same instance
instantiated the first time when getInstance(digitalCommerceConfig) was called.

// To instantiate a new instance of digitalCommerce, set create to true in the


digitalCommerceConfig object:
digitalCommerceConfig.create = true;
digitalCommerce =
VlocitySDK.digitalcommerce.getInstance(digitalCommerceConfig);```

Possible error conditions:

• "VlocityDigitalCommerce::getInstance: Config object must be given in argument to create an instance the


first time."
• "VlocityDigitalCommerce::constructor: VlocityDigitalCommerce cannot be instantiated properly. Both
datasource and user context objects have to be in Config object as argument."

SDK Example: getCatalogOffers without the contains parameter (Fall '19)


// Instantiate the input object for getCatalogOffers to specify parameters
const input = digitalCommerce.createGetOffersInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offset = 0; // use for pagination - optional
input.pageSize = 5; // use for pagination - optional
input.isLoggedIn = true; // use to fetch offers based on given accountId -
optional
input.context = '{"accountId":"ACCOUNT ID", "contractId":"CONTRACT ID"}'; //
use to fetch offers based on context params - optional
input.includeAttributes = ["ishidden__c", "customAttribute__c"]; //
includeExtraOfferAttributes as part of the query string of the API which

© 2021 Vlocity LLC, a Salesforce


company 189
Digital Commerce

includes extra passed attributes with default attributes in Offer - optional


input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke GetOffersByCatalog API via method getCatalogOffers()


digitalCommerce
.getOffers(input)
.then(result => {
Logger.info("vlocity get offers anonymous user rest call" + result);
})
.catch(error => {
Logger.info("get offers anonymous user rest call failed" + error);
});

Possible error conditions:

"GetOffersInput::getAPIPath() must have catalogCode."

"GetOffersInput::getAnonymousRestUrl() must have catalogCode."

SDK Example: getCatalogOffers with the contains parameter (Fall '19)


// Instantiate the input object for getOffers to specify parameters
const input = digitalCommerce.createGetOffersInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offset = 0; // use for pagination - optional
input.pageSize = 5; // use for pagination - optional
input.contains = "iPhone8"; // find all offers that CONTAIN "iPhone8" -
optional
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke GetContainsProducts API via method getOffers()


digitalCommerce
.getOffers(input)
.then(result => {
Logger.info("vlocity get offers anonymous user rest call" + result);
})
.catch(error => {
Logger.info("get offers anonymous user rest call failed" + error);
});

Possible error conditions:

"GetOffersInput::getAPIPath() must have catalogCode."

"GetOffersContainsInput::getAPIPath() should not have both sortBy and contains."

© 2021 Vlocity LLC, a Salesforce


company 190
Digital Commerce

"GetOffersInput::getAnonymousRestUrl() must have catalogCode."

"GetOffersContainsInput::getAnonymousRestUrl() should not have both sortBy and contains."

SDK Example: getOfferDetails via API (Fall '19)

SDK Example Code


// Instantiate the input object for getOfferDetails to specify parameters
const input = digitalCommerce.createGetOfferInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offerCode = "iPhoneXS"; // use your Offer Code
input.cacheable = false; // Optional Flag to indicate if the sdk call should
be cached. Default is false.
input.reload = false; // Optional Boolean flag to discard cache and call the
api again. Default is false.
input.isLoggedIn = true; // use to fetch offers based on given accountId -
optional
input.context = '{"accountId":"ACCOUNT ID"}'; // use to fetch offers based on
given context params - optional
input.customFields = ["customAttribute__c"]; // optional field which returns
your custom attributes or any given keys

// Invoke GetOfferDetails API via method getOfferDetails()


digitalCommerce
.getOffer(input)
.then(response => {
Logger.info("vlocity get offer anonymous user rest call" + response);
})
.catch(error => {
Logger.info("get offer anonymous user rest call failed" + error);
});

Possible error conditions:

"GetOfferInput::getAPIPath() must have catalogCode."

"GetOfferInput::getAPIPath() must have offerCode."

SDK Example: ValidateOffer (Fall '19)


// Instantiate the input object for validateOffer to specify parameters
const input = digitalCommerce.createValidateOfferInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.offerCode = "iPhoneX"; // use your Offer Code

// input.offerConfiguration: use digitalCommerce.getSelectedOffer(offerCode)

© 2021 Vlocity LLC, a Salesforce


company 191
Digital Commerce

input.offerConfiguration = digitalCommerce.getSelectedOffer(offerCode);
input.customFields = ["customAttribute__c"]; // optional field which returns
your custom attributes or any given keys
// Invoke ConfigureOfferDetails API via method validateOffer()
digitalCommerce
.validateOffer(input)
.then(response => {
Logger.info(
"vlocity validate offer for anonymous user" + JSON.stringify(response)
);
})
.catch(error => {
Logger.info("vlocity validateOffer for anonymous user failed" + error);
});

Possible error conditions:

"ValidateOfferInput::getAPIPath() must have catalogCode."

"ValidateOfferInput::getAPIPath() must have offerCode."

"ValidateOfferInput::getPostBody() must have productConfiguration."

SDK Example: Add a Configured Offer to the Cart (Fall '19)


Use the following example SDK code to add a previously configured offer to a cart:

```javascript
const addToCartInput = digitalCommerce.createAddToCartInput();
addToCartInput.catalogCode = "Phones";
addToCartInput.offerConfiguration =
digitalCommerce.getSelectedOffer(offerCode);
addToCartInput.customFields = ["customAttribute__c"]; // optional field
which returns custom fields for given keys
return digitalCommerce.addToCart(addToCartInput);
})
.then(addToCartResponse => {
Logger.info(addToCartResponse.orderId);
})
.catch(error => {
Logger.info("addToCart login user dual fail: " + error);
});

SDK Example: Add to Cart with No Configuration Changes (Fall '19)


Use the following example SDK code to add an already configured item to a cart:

// Instantiate the input object for addToCart to specify parameters


const input = digitalCommerce.createAddToCartInput();

© 2021 Vlocity LLC, a Salesforce


company 192
Digital Commerce

input.catalogCode = "Mobiles"; // use your Catalog Code


input.basketAction = "AddWithNoConfig"; // adding an offer that has not been
configured (no change in its json structure from getOfferDetails) to cart
input.offerCode = "iPhone8Offer"; // use your Offer Code to be added to cart
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke Cart API via method addToCart()


digitalCommerce
.addToCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToCart with basketAction=AddWithNoConfig
for anonymous user: " +
JSON.stringify(response)
);
return response;
})
.catch(error => {
Logger.error(
"addToCart() with basketAction=AddWithNoConfig failed" + error
);
});

Possible error conditions:

"AddTocartInput::getAPIPath() must have catalogCode."

"AddTocartInput::getAnonymousSiteRestUrl() must have catalogCode."

"AddTocartInput::getRequestPayload() must have basketAction."

"AddTocartInput::getRequestPayload() must have offerCode."

"AddTocartInput::getRequestPayload() must have offer when basketAction is 'AddWithNoConfig'."

SDK Example: Add to Cart with Configuration Changes (Fall '19)


Use the following example SDK code to add an already configured item to a cart:

```javascript
const addToCartInput = digitalCommerce.createAddToCartInput();
addToCartInput.catalogCode = "Phones";
addToCartInput.offerConfiguration =
digitalCommerce.getSelectedOffer(offerCode);
addToCartInput.customFields = ["customAttribute__c"]; // optional field
which returns custom fields for given keys
input.basketAction = "AddAfterConfig";

© 2021 Vlocity LLC, a Salesforce


company 193
Digital Commerce

return digitalCommerce.addToCart(addToCartInput);
})
.then(addToCartResponse => {
Logger.info(addToCartResponse.orderId);
})
.catch(error => {
Logger.info("addToCart login user dual fail: " + error);
});

SDK Example: Delete From Basket (Fall '19)


Use the example code below to addToBasket with basketAction=DeleteFromBasket. The call must have
deleteBundleNumber as an input parameter.

// Instantiate the input object for the addToBasket method to specify


parameters.
const input = digitalCommerce.createAddToBasketInput();
// Use your AWS gateway.
input.anonymousSiteUrl = "https://mubnr8cjgl.execute-api.us-
west-2.amazonaws.com/prod/dc";
// Use your Catalog Code.
input.catalogCode = "Mobiles";
// Delete an offer that was added to basket.
input.basketAction = "DeleteFromBasket";
input.forceInvalidateCache = true;

// The basket item list grows from the bottom up. For example: if you add
products A, B, and C in that order,
// the JSONResult.records list would be C,B,A with respective numbering as
0,1,2.
// The 0 item will always be the most recent addition.
input.deleteBundleNumber = 0;

// Invoke the Basket API via the addToBasket() method.


digitalCommerce
.addToBasket(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToBasket with basketAction=DeleteFromBasket
for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info(
"addToBasket with basketAction=DeleteFromBasket for anonymous user rest
call failed" +

© 2021 Vlocity LLC, a Salesforce


company 194
Digital Commerce

error
);
});

Possible error conditions:

"AddToBasketInput::getAPIPath() must have catalogCode."

"AddToBasketInput::getAnonymousRestUrl() must have anonymousSiteUrl."

"AddToBasketInput::getAnonymousSiteRestUrl() must have catalogCode."

"AddToBasketInput::getPostBody() must have basketAction."

"AddToBasketInput::getPostBody() must have deleteBundleNumber when basketAction is


'DeleteFromBasket'."

SDK Example: Delete a Child Product from the Basket (Fall '19)
Use the following example SDK code to delete a child product from a basket:

// Instantiate the input object for AddToCartInput to specify parameters


const input = digitalCommerce.createAddToCartInput();
input.catalogCode = "Mobiles"; // use your Catalog Code
input.basketAction = "DeleteChildProduct"; // deleting an offer that was added
to cart
input.actionParams = {
lineItemKey: "d83f475a776049d21054c105e9d53ee9", // use your lineItemKey
cartContextkey: "d80b2927f07938aefdc7e2e349e2ede7", // use your
cartContextKey
bundleContextKey: "c3a4590a2d231e7022e04e5eba539ead" // use your
bundleContextKey};
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke Basket API via method addToBasket()


digitalCommerce
.addToCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToCart with basketAction=DeleteChildProduct
for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info(
"addToBasket with basketAction=DeleteChildProduct for anonymous user

© 2021 Vlocity LLC, a Salesforce


company 195
Digital Commerce

rest call failed" +


error
);
});

Possible error conditions:

"AddToCartInput::getAPIPath() must have catalogCode."

"AddToCartInput::getAnonymousSiteRestUrl() must have catalogCode."

"AddToCartInput::getRequestPayload() must have basketAction."

"AddToCartInput::getRequestPayload() must have lineItemKey when basketAction is 'DeleteChildProduct'."

"AddToCartInput::getRequestPayload() must have cartContextkey when basketAction is


'DeleteChildProduct'."

"AddToCartInput::getRequestPayload() must have bundleContextKey when basketAction is


'DeleteChildProduct'."

SDK Example: Add a Child Product to the Basket (Fall '19)


Use the following example SDK code to add a child product to a basket:

// Instantiate the input object for AddToCartInput to specify parameters


const input = digitalCommerce.createAddToCartInput();
input.catalogCode = "Mobiles"; // use your Catalog Code
input.basketAction = "AddChildProduct"; // deleting an offer that was added to
cart
input.actionParams = {
rootProductCode: "iPhoneX", // use your rootProductCode
parentLineKey: "c3a4590a2d231e7022e04e5eba539ead", // use your parentLineKey
parentHierarchyPath: "01tf2000007Rb9JAAS", // use your parentHierarchyPath
offer: "DeclineEquipmentProtection", // use your offer_code
cartContextkey: "d80b2927f07938aefdc7e2e349e2ede7", // use your
cartContextKey
bundleContextKey: "c3a4590a2d231e7022e04e5eba539ead" // use your
bundleContextKey};
input.customFields = ["customAttribute__c"]; // optional field which returns
custom fields for given keys

// Invoke Basket API via method addToBasket()digitalCommerce


.addToCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce addToCart with basketAction=AddChildProduct
for anonymous user: " +
JSON.stringify(response)

© 2021 Vlocity LLC, a Salesforce


company 196
Digital Commerce

);
})
.catch(error => {
Logger.info(
"addToBasket with basketAction=AddChildProduct for anonymous user rest
call failed" +
error
);
});

Possible error conditions:

"AddToCartInput::getAPIPath() must have catalogCode."

"AddToCartInput::getAnonymousSiteRestUrl() must have catalogCode."

"AddToCartInput::getRequestPayload() must have basketAction."

"AddToCartInput::getRequestPayload() must have rootProductCode when basketAction is


'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have parentLineKey when basketAction is 'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have parentHierarchyPath when basketAction is


'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have offer when basketAction is 'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have cartContextkey when basketAction is 'AddChildProduct'."

"AddToCartInput::getRequestPayload() must have bundleContextKey when basketAction is


'AddChildProduct'."

SDK Example: Update Items in Basket (Fall '19)


Use the following example SDK code to update items in a basket:

// Instantiate the input object for AddToCartInput to specify parameters


let input = Object.assign(
this.digitalCommerceSDK.createUpdateItemsInCartInput(),
{
catalogCode: "Phones",
basketkey: "01tf2000007Rb9JAAS",
basketAction: "updateBasket",
bundleContextKey: "",
lineItemKey: "",
quantity: 2,
customFields: ["customAttribute__c"]
}

© 2021 Vlocity LLC, a Salesforce


company 197
Digital Commerce

);
this.digitalCommerceSDK
.updateItemsInCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce updateItemsInCart for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info("updateItemsInCart action failed: ", error);
});

Possible error conditions:

"UpdateItemsInCart::getAPIPath() must have catalogCode."

"UpdateItemsInCart::getAnonymousSiteRestUrl() must have catalogCode."

"UpdateItemsInCart::getRequestPayload() must have basketAction."

"UpdateItemsInCart::getRequestPayload() must have lineItemKey when basketAction is 'updateBasket'."

"UpdateItemsInCart::getRequestPayload() must have basketkey when basketAction is 'updateBasket'."

"UpdateItemsInCart::getRequestPayload() must have bundleContextKey when basketAction is


'updateBasket'."

SDK Example: Get Cart Details (Fall '19)


Use the following example SDK code to obtain details about a cart:

// Instantiate the input object for getItemsInCart to specify parameters


const input = digitalCommerce.createGetItemsInCartInput();
input.catalogCode = "Phones"; // use your Catalog Code
input.cartContextKey = "01tf2000007Rb9JAAS"; // use your cart_context_key
input.cacheable = true; // Optional boolean flag to indicate if the sdk call
should be cached. Default is false.
input.reload = true; // Optional boolean flag to discard cache and call the
api again Default is false.
input.customFields = ["customAttribute__c"]; // optional field which returns
your custom attributes or any given keys

// Invoke get basket API via method getItemsInCart()


digitalCommerce
.getItemsInCart(input)
.then(response => {
Logger.info("vlocity get cart items anonymous user rest call" + response);
})

© 2021 Vlocity LLC, a Salesforce


company 198
Digital Commerce

.catch(error => {
Logger.info("get cart items anonymous user rest call failed" + error);
});

Possible error conditions:

"GetItemsInCartInput::getAPIPath() must have catalogCode."

"GetItemsInCartInput::getAPIPath() must have cartContextKey."

SDK Example: Checkout Cart (Fall '19)


Use the following example SDK code to check out a cart:

// Instantiate the input object for checkoutCart to specify parameters


const input = digitalCommerce.checkoutCartInput();
input.catalogCode = "Mobiles"; // use your Catalog Code
input.accountId = "001f200001eSlhe"; // use your account Id
input.cartContextKey = "d5ff11cccd19472ca7c21fa80bc93d2a";

// Used in Checkout process to persist shopping cart content into SF Database


digitalCommerce
.checkoutCart(input)
.then(response => {
Logger.info(
"Vlocity digital commerce checkout cart for anonymous user: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info("checkout cart for anonymous user rest call failed" + error);
});

Possible error conditions:

"checkoutCartInput::getAPIPath() must have catalogCode."

"checkoutCartInput::getAPIPath() must have accountId."

"checkoutCartInput::getAnonymousSiteRestUrl() must have catalogCode."

"checkoutCartInput::getAnonymousSiteRestUrl() must have accountId."

"checkoutCartInput::getRequestPayload() must have cartContextKey."

© 2021 Vlocity LLC, a Salesforce


company 199
Digital Commerce

Setting Up the Pubsub SDK (Winter '20)


The Vlocity Digital Commerce SDK includes the pubsub SDK, which supports communication between
Digital Commerce components, including Digital Commerce Lightning Web Components, Digital Commerce
Web Components, JavaScript-based framework, and so on. For more details, see the PubSub SDK
reference.

Registering an Event
Use the following example Digital Commerce pubsub register method to add a callback function to the
list of subscribers for a particular event:

// registering pub-sub event


this.callbackEventHandler = {
result: this.callbackFunction.bind(this)
};
callbackFunction(data) {/* callback triggered by the pubsub event */}
this.digitalCommerceSDK.register("event-name",this.callbackEventHandler);

Firing an Event
Use the following example fire method to publish the occurrence of an event:

this.digitalCommerceSDK.fire("event-name",action,payloadObject);

Unregistering an Event
Use the following example unregister method to cancel subscription of an event:

// un-registering pub-sub event


this.digitalCommerceSDK.unregister("event-name",this.callbackEventHandler);

Digital Commerce SDK Troubleshooting


This topic provides hints and tips for troubleshooting and fixing common issues while using the Vlocity SDK.

Example 1: SDK returns 0 or null, or does not return correct data


In the following code sample, the SDK does not return correct data even though the fields have data in the
Salesforce cache:

© 2021 Vlocity LLC, a Salesforce


company 200
Digital Commerce

The API response is as follows:

© 2021 Vlocity LLC, a Salesforce


company 201
Digital Commerce

Solution
The root cause of this issue is that the SDK maps fields in the following format:

namespace__fieldname

You should ensure that the namespace specified in the SDK matches the one defined for the org.

this.digitalCommerceSDK.namespace = "vlocity_cmt";

After setting the correct namespace, the SDK will return correct values from related fields.

© 2021 Vlocity LLC, a Salesforce


company 202
Digital Commerce

ServerSDK Overview
The ServerSDK is a reference implementation that serves as a middle layer between the user interface and
the Digital Commerce APIs. ServerSDK runs the SDK methods on any Node.js supported server and
provides REST APIs that you can interact with.

ServerSDK provides the following advantages:

• Provides support for third-party authentication systems.


• Avoids exposure of Salesforce account IDs to the UI.
• Avoids exposure of org details such as namespace, remote site URL and authorization tokens for off-
platform users.
• Provides protected endpoint URLs.
• Supports the isloggedin input parameter for all Digital Commerce APIs.
• iOS and Android native clients can reuse the same application logic in the SDK that other UI platforms
have been using to implement Digital Commerce.

© 2021 Vlocity LLC, a Salesforce


company 203
Digital Commerce

NOTE
Additional information:

• Additional server-side configuration and setup are required to support serving with
clustering and HTTP/2.
• An SSL certificate is required to serve as HTTP/2 protocol
• The server enables Redis or another central caching mechanism when serving with a
cluster.
• Heroku does not support HTTP/2 protocol.

ServerSDK Architecture
The ServerSDK reference app consists of three layers: Authentication Layer, SF connection Layer, and App
Business Layer, as shown in the following illustration:

© 2021 Vlocity LLC, a Salesforce


company 204
Digital Commerce

Authentication Layer
The authentication layer is responsible for validating the identity of a user. Currently, the reference
implementation uses Firebase as an authentication strategy; however, a different third-party authentication
system may be used by creating a custom authentication strategy. To develop your own authentication
strategy, follow the steps below:

1. Create a folder inside the strategies directory and inside that folder create a file and Implement
IAuthenticationStrategy interface. The implementing class should define the properties with the
corresponding method of the third-party authentication system.
For example, the implementation of the signIn method should have the signIn logic of your third-party
authentication system that you want to use.
2. Once you have created your custom authentication strategy, open the
AuthenticationStrategy.ts file, import your customized strategy, and initialize it inside the
constructor.

Connection layer
To request access to the Salesforce data ServerSDK, the reference app has a connection layer that is
responsible for connecting the app to the Salesforce connected app using JWT OAuth Flow. The
jsonwebtoken generator is used internally to create a JSON Web Token (JWT) using the RS256 algorithm.
RS256 is an open standard that defines a compact and self-contained way to securely transmit information
between parties as a JSON object.

App Business layer


The app business layer is the layer that determines how the application’s endpoints (URIs) respond to client
requests.In this layer, the Digital Commerce SDK is imported from Node.js modules, which use its methods
to define the route logic of the None.js application. The ServerSDK Reference app may be divided into two
flows; Auth flow and accessing the protected URLs, described below:

Auth flow
Once a request is made to the /signIn or /signUp endpoints of the ServerSDK reference application, the
authentication layer is reached. Here, the user's identity is authenticated or created. If the user-provided
details that are incorrect or incomplete, authentication fails and an error message is sent back to the client.
However, If the authentication succeeds, a connection to Salesforce connected app is built using the
connection layer of the application and an account id of the signedIn user is created and fetched from the
Salesforce app. The accountId is then stored in the session object of the user’s session on the Node
application. Express-session is used as session middleware.

Accessing the protected URLs


The ServerSDK reference app has protected endpoint URLs that have a customizable validateUser
middleware that catches invalid requests to the APIs. Therefore, if a user tries to access a protected URL
without authentication, a 401-Unauthorised error will be returned. Only after the user has successfully
signed in would they be able to access the protected endpoint URLs.

© 2021 Vlocity LLC, a Salesforce


company 205
Digital Commerce

Pros and Cons of running Digital Commerce SDK on a server

Table 8. Running the Digital Commerce SDK on a Server


Pros Cons
Running the Digital Commerce SDK on a server is an advantage for clients that have An extra API layer exists between the
configuration limitations (such as disk space limitations, lack of computation power or user interface and the Digital
memory) because computation cycles are moved to the server and won't use client Commerce APIs. However, this
resources. overhead may be reduced by optimizing
the server.
Client sensitive information such as access_token, account Id, and namespace are stored
on the server and are therefore not passed to the client. There is an additional cost to running
and maintaining a server.
The URL of the Digital Commerce APIs is hidden from the client because the user calls
server endpoints. Setting up clustering and HTTP/2 might
require devOps (Development and
Using REST calls, native iOS and Android mobile apps can reuse application logic in the Operations) expertise.
Digital Commerce SDK when running on the server.

Digital Commerce SDK running on the server may be used as an API warmer. Calling an
API the first time has a latency delay, invoking the Digital Commerce API using the SDK
once every hour can eliminate API latency.

Server-to-server Enterprise Integration

Pros and Cons of Running the Server on the Client

Table 9. Running the Digital Commerce SDK on the client.


Because the SDK is running on the client, there are no Clients running on less powerful devices, such as mobile devices,
additional cost associated with running and maintaining a might see slower responses because the SDK is using the client’s
server. resources.

Clients with high configuration (disk, computation power and Sensitive information such as access_token, accountId, and
memory) would see response time improvement as the client namespace might be exposed on the client side.
would be communicating directly with the v3 API.
The Digital Commerce API endpoint URL might be exposed on the
network tab of the browser.

APIs supported by ServerSDK


When running the SDK on a server, 21 REST APIs are available for use with the translation SDK, account
SDK and digital Commerce SDK to accommodate different requirements.

• /fetchtranslations
• /getoffers
• /getfilteredofferslist
• /getoffer
• /validateoffer
• /getselectedoffer
• /addtocart
• /getpromotions
• /updateitemsincart

© 2021 Vlocity LLC, a Salesforce


company 206
Digital Commerce

• /getitemsincart
• /authenticateuser
• /signIn
• /signOut
• /updateDetails
• /createOrder
• /submitOrder
• /getcontracts
• /getassets
• /getassetsbyaccount
• /getaccountoffers

SDK implementation
You can easily integrate the ServerSDK with the Digital Commerce UI by using the Proxy SDK library. The
Proxy SDK is very light weight and shares the same signatures as the other Digital Commerce client SDKs,
requiring no changes to UI code.

1. Import ProxySDK from node_modules to the UI:

<script src="node_modules/@vlocity-cme-sdk/digitalcommerce-sdk/proxy/
digitalcommerce/proxy.sdk.js"></script>
<script src="node_modules/@vlocity-cme-sdk/translation-sdk/proxy/
translation/proxy.sdk.js"></script>
<script src="node_modules/@vlocity-cme-sdk/account-sdk/proxy/account/
proxy.sdk.js"></script>
2. Meta tag config

<meta name="vlocity-dc-secure-server-url"
value="your_node.js_server_URL_running_serverSDK" />
<meta name="vlocity-dc-secure-server-request-credentials"
value="include" />
meta name="vlocity-dc-enable-proxy-sdk" value="enable" />
3. Call Proxy SDK methods

let input = Object.assign(this.digitalCommerceSDK.createGetOffersInput(),


{"input" : "inputValue"});
this.digitalCommerceSDK.getOffers(input).then(response => {

Server SDK Installation


After running the steps in this topic, you can host or deploy the ServerSDK to a Node.js server, or you can
run ServerSDK in local mode.

1. Navigate to the Vlocity Industry Process Library and download the serverSDK reference app zip file
from the VPL.
2. Unzip the folder and add it to your IDE.

© 2021 Vlocity LLC, a Salesforce


company 207
Digital Commerce

Navigate to vop_server_sdk/secure-server-reference-app; this will be the root folder.


3. Set up the org.
ServerSDK uses OAuth 2.0 JSON Web Token (JWT) bearer flow to authenticate the server. Therefore,
you must generate a public/private key pair and create a Connected App. See https://github.com/
lekkimworld/salesforce-jwt-generator.
a. Generate a public/private key pair.
Generate a public/private key pair using openssl and fill in the required information when you
generate the certificate, as shown here:

openssl req -newkey rsa:2048 -nodes -keyout private_key.pem -x509 -days


365 -out certificate.pem
openssl x509 -outform der -in certificate.pem -out public_key.der
openssl x509 -in certificate.pem -pubkey > public_key.pem
b. Create connected APP and upload the CER (certificate) file to SFDC.
In Salesforce, create a Connected App using the App Manager in Setup and upload the public key
(public_key.cer) to the app. Be sure to select the offline_access scope as well as other required
scopes. Save the Connected App and make a note of the consumer key (issuer_id).
4. Configure Authentication
The ServerSDK application has an authentication layer which is responsible for validating a user
identity against an authentication server such as Firebase, Cognito and so on. A reference
implementation using Firebase as an authentication strategy has been used in the app by default.
However, you may easily swap Firebase for any other third-party authentication system by creating a
custom authentication strategy.
• Create a folder in the vop_server_sdk/secure-server-reference-app/authentication/
strategies directory. In the folder, create a file and Implement the IAuthenticationStrategy
interface. The implementing class should define the properties with the corresponding method of the
third-party authentication system. For example, the implementation of sign-In method should have
the sign-In logic of the third-party authentication system you want to use.
• After you have created your custom authentication strategy, open the
AuthenticationStrategy.ts file and import your customize strategy and initialize it inside the
constructor.
5. Set up the config.json file.
Locate the config.json file in vop_server_sdk/secure-server-reference-app/
config.json

a. Enter the consumer key (issuer_id) that you noted in step 2.


b. In the org Id field, enter the username of the salesforce user.org namespace.

© 2021 Vlocity LLC, a Salesforce


company 208
Digital Commerce

c. In the org.namespace field, enter the SF org namespace.


6. Configure the sdkConfig.ts file.
Locate the sdkConfig.ts file located in vop_server_sdk/secure-server-reference-app/
sdkConfig.ts.
Make the following changes in the section indicated:
strategyConfig - If you are using Firebase as the authentication server then set a strategyConfig object.
jwtConfig - Paste the private_key.pem and public_key.pem files generated from step2 in
vop_server_sdk/secure-server-reference-app/certificates folder for JWT sign
remoteSite - For anonymous users, the URL is an anonymous URL of the org and namespace will be
the org namespace.
allowlist - When you are requesting from a CORS domain, you must specify the domain here.

7. Configure the package.json file.

© 2021 Vlocity LLC, a Salesforce


company 209
Digital Commerce

In the vop_server_sdk/secure-server-reference-app/package.json file, under the


dependencies object, update SDKs with version 109, as shown here:

NOTE
Ensure that you add the .npmrc file. The .npmrc file is required to authenticate with
the Vlocity private npm registry. For public access, use the default access token.

Running ServerSDK on a local computer (optional)


If desired, follow the steps in this section to run the ServerSDK on a local computer.

1. Using a command line terminal, open the root directory: vop_server_sdk/secure-server-


reference-app).
2. Run $ npm install to install all dependencies.
3. Run the following commands:
a. $ npm run build - This command will take few seconds to compile and build the typescript files.
Once successful, the /dist folder is created in the root directory.
b. Run $ npm start to start the server.
By default, the server will start listening to port 3000. The base API URL will be: http://
localhost:3000/v1/serversdk
To test whether the API is working, navigate to http://localhost:3000/v1/serversdk/
getcurrencydetail in a browser. The default currency details are displayed, as shown here:

© 2021 Vlocity LLC, a Salesforce


company 210
Digital Commerce

NOTE
Ensure that you comment out the lines in vop_server_sdk/secure-server-
reference-app/app.ts . These settings are required only when you host using a
third-party server such as Heroku.

Running SDK Server in a Heroku Environment


You can deploy/host this ServerSDK application in any node supported server. one of famous server is
heroku below are steps to deploy/host in same

1. Log in to your Heroku account.


2. Click the New button and select Create a new App from Dashboard.
3. Enter an app name and click the Create app button.
4. Navigate to the Deploy tab. Follow the steps to install the Heroku CLI, create a new Git repository, and
deploy your application.

© 2021 Vlocity LLC, a Salesforce


company 211
Digital Commerce

After following the previous step, a folder is created containing the Heroku cloned/setup. You now must
copy the ServerSDK into the Heroku cloned/setup folder. Copy all of the files located in
vop_server_sdk/secure-server-reference-app. There is no need to copy the dist and
node_modules folders.
5. Paste the following into the Procfile file:

web: npm run start-prod-server

The code runs the ServerSDK in Heroku after a code push.


6. Open the Heroku cloned/setup folder in a terminal, commit and push the files to Heroku using the
following commands:

$ git add .
$ git commit -am "make it better"
$ git push heroku master
7. After you push the code, Heroku automatically detects it as a Node.JS app. Your log should look
similar to the following after you push:

akodaganur:server-sdk-109-pref aminkodaganur$ heroku login


heroku: Press any key to open up the browser to login or q to exit:
Opening browser to https://cli-auth.heroku.com/auth/cli/browser/
658be33b-6251-4700-ba48-1f5319f3a978?
requestor=SFMyNTY.g3QAAAACZAAEZGF0YW0AAAAMNDkuMzcuMTY1Ljg2ZAAGc2lnbmVkbgYA1
4ka5HQB.G2_9GKq-Q_Lz8L7oFvJplCMG1MMVhr20pcscL6a48jU
Logging in... done
Logged in as [email protected]
akodaganur:server-sdk-109-pref aminkodaganur$ git add .

© 2021 Vlocity LLC, a Salesforce


company 212
Digital Commerce

akodaganur:server-sdk-109-pref aminkodaganur$ git commit -m "Intial commit"


[master 2492e4e] Intial commit
1 file changed, 1 insertion(+), 1 deletion(-)
akodaganur:server-sdk-109-pref aminkodaganur$ git push heroku master
Enumerating objects: 8, done.
Counting objects: 100% (8/8), done.
Delta compression using up to 8 threads
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 593 bytes | 593.00 KiB/s, done.
Total 6 (delta 4), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Node.js app detected
remote:
remote: -----> Creating runtime environment
remote:
remote: NPM_CONFIG_LOGLEVEL=error
remote: NODE_ENV=production
remote: NODE_MODULES_CACHE=true
remote: NODE_VERBOSE=false
remote:
remote: -----> Installing binaries
remote: engines.node (package.json): 12.16.3
remote: engines.npm (package.json): 6.14.4
remote:
remote: Resolving node version 12.16.3...
remote: Downloading and installing node 12.16.3...
remote: npm 6.14.4 already installed with node
remote:
remote: -----> Restoring cache
remote: - node_modules is checked into source control and cannot be
cached
remote:
remote: -----> Installing dependencies
remote: Prebuild detected (node_modules already exists)
remote: Rebuilding any native modules
remote:
remote: > [email protected] postinstall /tmp/build_527a1f8d/
node_modules/protobufjs
remote: > node scripts/postinstall
remote:
remote:
remote: > [email protected] postinstall /tmp/build_527a1f8d/
node_modules/core-js
remote: > node -e "try{require('./postinstall')}catch(e){}"

© 2021 Vlocity LLC, a Salesforce


company 213
Digital Commerce

remote:
remote:
remote: > [email protected] install /tmp/build_527a1f8d/node_modules/
fsevents
remote: > node install.js
remote:
remote:
remote: Skipping 'fsevents' build as platform linux is not supported
remote:
remote: > [email protected] postinstall /tmp/build_527a1f8d/
node_modules/nodemon
remote: > node bin/postinstall || exit 0
remote:
remote: Love nodemon? You can now support the project via the open
collective:
remote: > https://opencollective.com/nodemon/donate
remote:
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/
@types/compression
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/
@types/express
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/
@types/body-parser
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/
@types/connect
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/@types/
node
remote: @types/[email protected] /tmp/build_527a1f8d/
node_modules/@types/express-serve-static-core
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/@types/qs
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/
@types/range-parser
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/
@types/serve-static
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/@types/
mime
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/
@types/cookie-parser
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/@types/
cors
remote: @types/[email protected] /tmp/build_527a1f8d/
node_modules/@types/express-session
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/
@types/jsonwebtoken
remote: @types/[email protected] /tmp/build_527a1f8d/
node_modules/@types/request-promise

© 2021 Vlocity LLC, a Salesforce


company 214
Digital Commerce

remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/


@types/bluebird
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/
@types/request
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/
@types/caseless
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/
@types/tough-cookie
remote: [email protected] /tmp/build_527a1f8d/node_modules/form-data
remote: [email protected] /tmp/build_527a1f8d/node_modules/asynckit
remote: [email protected] /tmp/build_527a1f8d/node_modules/
combined-stream
remote: [email protected] /tmp/build_527a1f8d/node_modules/
delayed-stream
remote: [email protected] /tmp/build_527a1f8d/node_modules/mime-
types
remote: [email protected] /tmp/build_527a1f8d/node_modules/mime-db
remote: @types/[email protected] /tmp/build_527a1f8d/node_modules/@types/
spdy
remote: @vlocity-cme-sdk/[email protected] /tmp/
build_527a1f8d/node_modules/@vlocity-cme-sdk/digitalcommerce-sdk
remote: @vlocity-cme-sdk/[email protected] /tmp/
build_527a1f8d/node_modules/@vlocity-cme-sdk/translation-sdk
remote: [email protected] /tmp/build_527a1f8d/node_modules/body-
parser
remote: [email protected] /tmp/build_527a1f8d/node_modules/bytes
remote: [email protected] /tmp/build_527a1f8d/node_modules/content-
type
remote: [email protected] /tmp/build_527a1f8d/node_modules/debug
remote: [email protected] /tmp/build_527a1f8d/node_modules/ms
remote: [email protected] /tmp/build_527a1f8d/node_modules/depd
remote: [email protected] /tmp/build_527a1f8d/node_modules/http-
errors
remote: [email protected] /tmp/build_527a1f8d/node_modules/inherits
remote: [email protected] /tmp/build_527a1f8d/node_modules/
setprototypeof
remote: [email protected] /tmp/build_527a1f8d/node_modules/statuses
remote: [email protected] /tmp/build_527a1f8d/node_modules/
toidentifier
remote: [email protected] /tmp/build_527a1f8d/node_modules/iconv-
lite
remote: [email protected] /tmp/build_527a1f8d/node_modules/safer-
buffer
remote: [email protected] /tmp/build_527a1f8d/node_modules/on-
finished
remote: [email protected] /tmp/build_527a1f8d/node_modules/ee-first

© 2021 Vlocity LLC, a Salesforce


company 215
Digital Commerce

remote: [email protected] /tmp/build_527a1f8d/node_modules/qs


remote: [email protected] /tmp/build_527a1f8d/node_modules/raw-body
remote: [email protected] /tmp/build_527a1f8d/node_modules/unpipe
remote: [email protected] /tmp/build_527a1f8d/node_modules/type-is
remote: [email protected] /tmp/build_527a1f8d/node_modules/gcs-
resumable-upload/node_modules/is-stream
remote: [email protected] /tmp/build_527a1f8d/node_modules/gcs-
resumable-upload/node_modules/node-fetch
remote: [email protected] /tmp/build_527a1f8d/node_modules/@google-cloud/
storage/node_modules/mime
remote: [email protected] /tmp/build_527a1f8d/node_modules/
@google-cloud/storage/node_modules/readable-stream
remote: [email protected] /tmp/build_527a1f8d/node_modules/@google-
cloud/storage/node_modules/xdg-basedir
remote: [email protected] /tmp/build_527a1f8d/node_modules/nodemon
remote: [email protected] /tmp/build_527a1f8d/node_modules/nodemon/
node_modules/debug
remote: [email protected] /tmp/build_527a1f8d/node_modules/nodemon/
node_modules/ms
remote: Installing any new modules (package.json)
remote: removed 1 package and audited 626 packages in 4.606s
remote:
remote: 33 packages are looking for funding
remote: run `npm fund` for details
remote:
remote: found 25 vulnerabilities (19 low, 6 high)
remote: run `npm audit fix` to fix them, or `npm audit` for
details
remote:
remote: -----> Build
remote: Running build
remote:
remote: > [email protected] build /tmp/build_527a1f8d
remote: > tsc
remote:
remote:
remote: -----> Caching build
remote: - node_modules
remote:
remote: -----> Pruning devDependencies
remote: removed 210 packages and audited 412 packages in 4.776s
remote:
remote: 33 packages are looking for funding
remote: run `npm fund` for details
remote:
remote: found 24 vulnerabilities (19 low, 5 high)

© 2021 Vlocity LLC, a Salesforce


company 216
Digital Commerce

remote: run `npm audit fix` to fix them, or `npm audit` for
details
remote:
remote: -----> Build succeeded!
remote: -----> Discovering process types
remote: Procfile declares types -> web
remote:
remote: -----> Compressing...
remote: Done: 48.3M
remote: -----> Launching...
remote: Released v28
remote: https://server-sdk-109-pref.herokuapp.com/ deployed to
Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/server-sdk-109-pref.git
455a853..2492e4e master -> master
akodaganur:server-sdk-109-pref aminkodaganur$

Notice that the base API URL is logged at the end: https://server-sdk-109-pref.herokuapp.com/. Once
you pushed and deployed successfully, the base URL becomes: https://<your-app-
name>.herokuapp.com/v1/serversdk. You can also find the name in the Heroku Dashboard > Settings
> Domains.

NOTE
/v1/serversdk is a default API prefix which can be changed to:
vop_server_sdk/secure-server-reference-app/sdkConfig.ts/

To verify whether the Heroku setup is working, open a browser and navigate to https://&lt;your-
app-name&gt;.herokuapp.com/v1/serversdk/getcurrencydetails. The default currency
details are displayed.

ServerSDK Client Setup and Usage


ServerSDK may be configured for use with the client-side SDK or with the proxy server SDK.

Client-Side SDK
Using the client-side implementation, the Digital Commerce APIs are called directly from the client for guest
users. After signing in, all Digital Commerce APIs are called from ServerSDK.

Proxy SDK
Using the Proxy SDK, all Digital Commerce APIs are called from ServerSDK. The Proxy SDK library is very
light weight and shares the same signatures as the other Digital Commerce client SDK, requiring no code
changes in the user interface.

© 2021 Vlocity LLC, a Salesforce


company 217
Digital Commerce

Digital Commerce Web Component Setup


Follow the steps in this section to configure ServerSDK to take advantage of the Digital Commerce Web
Components.

1. Add SDK and digitalcommerce-components-src in your package.json file., as shown here:

2. Add the .npmrc file. The .npmrc file is required to authenticate with the Vlocity private npm registry.
For public access, use the default access token. Contact the Vlocity Project Team to obtain the
authorization token.

3. In the index.html file, add and define the meta tag as shown here:

Meta name definitions:

Table 10.
Meta tag name attribute Description
vlocity-dc-remote-site-url Contains the content attribute, which may be a SalesForce instance URL for known users
or an AWS URL for anonymous users.
vlocity-dc-remote-method- Contains an attribute value that specifies the logon method, which can be either
type "knownUser" for known users or "anonymousUser" for anonymous users.
vlocity-dc-org-namespace Contains value attributes that specify the org namespace.
vlocity-dc-payment-url Contains value attributes that specify the checkout payment URL.
vlocity-dc-secure-server- Contains value attributes that specify the URL where ServerSDK is hosted.
url

© 2021 Vlocity LLC, a Salesforce


company 218
Digital Commerce

Meta tag name attribute Description


vlocity-dc-secure-server- Contains value attributes that specify a value indicating whether the user agent should
request-credentials) send cookies to the secure server if it is hosted on another domain in the case of cross-
origin requests. Possible values are: include, omit and same-origin (default value)
vlocity-dc-enable-proxy- Contains value attributes that specify the value “enable”. If set to enable, the Digital
sdk Commerce, Account, and Translation Proxy SDK instance will be created.
4. In your index.html file, import the SDK using the script tag, as shown here:
• If using the Client-Side SDK:

• If using the Proxy SDK

5. To initialize a Firebase SDK strategy in your Web Component application, you must configure Firebase
authorization details. You can initialize Firebase from any component simply by importing vlocity-
dc-authentication-util and passing Firebase authorization configuration to the
initAuthConfig method.

NOTE
You can configure a custom authentication by creating your own authorization strategy
and then importing it and passing it as an input parameter to the
configureAuthentication method of the vlocity-dc-authentication-
util component. Once configured, you can initialize it and use your custom
authorization strategy.

© 2021 Vlocity LLC, a Salesforce


company 219
Digital Commerce

6. From your JS file, import the SDK-util file:

import { digitalCommerceSDKInstance } from "@vlocity-cme-wc/


digitalcommerce-components-src/vlocity-dc-utils/vlocity-dc-sdk-utils";

Get the SDK instance:

this.digitalCommerceSDK = digitalCommerceSDKInstance().digitalCommerce;

Call the SDK methods:

let input = this.digitalCommerceSDK.createGetOffersInput()


this.digitalCommerceSDK.getOffers(input).then(response => {});

Digital Commerce Lightning Web Component Setup


Add Digital Commerce Lightning Web Component client setup information (on-Platform customers can also
use ServerSDK to log in using third-rd party authentication server).

• Edit your LWC component HTML include file <c-dc-sample-app></c-dc-sample-app> component


with the attributes shown here:

<c-dc-sample-app
checkout-api-url=""
secure-server-api-request-credentials=""
checkout-payment-url=""
enable-proxy-sdk=""
auth-configuration=""
>
</c-dc-sample-app>

Table 11. Attribute descriptions


Attribute Description
checkout-api-url Contains a value that specifies the URL where ServerSDK is hosted.
secure-server- Contains a value that specifies a value indicating whether the user agent should send cookies to the
api-request- secure server if it is hosted on another domain in the case of cross-origin requests. Possible values are:
credentials include,omit and same-origin (default value)
checkout-payment- Contains a value that specifies the checkout payment URL.
url
enable-proxy-sdk Contains a boolean value (true or false). The default valus is false. If set to true, the Digital Commerce,
Account, Translation Proxy SDK instances will be created.
auth-configuration Contains your Firebase or custom auth configuration details. You can create custom auth config by
overriding dcCustomAuthenticationUtil.

Redirect Authentication Reference Application


The redirect-authentication-reference-app is an example Node.js application that provides authentication
using a redirection mechanism. The reference demonstration app is created for use cases where both
authentication logic and the UI are present on the server side rather than the client side.

© 2021 Vlocity LLC, a Salesforce


company 220
Digital Commerce

The redirection strategy provides the following features:

• Authentication logic is abstracted from the client application.


• A custom authentication UI is provided

The following figure illustrates the redirection architecture.

The redirect-authentication-reference-app consists os two layers:

• The Authentication Logic Layer


• The UI Layer (Views)

Authentication Logic Layer


The authentication layer is responsible for validating the identity of a user. Currently, the reference
implementation uses Firebase authorization libraries for authentication logic; however, any third-party
authentication library may be used by simply replacing the Firebase library.

UI Layer (Views)
The UI layer is responsible for providing a UI for authentication. The default UI provided by firebase is used
for the reference implementation but it could be easily swapped for any custom authorization UI.

Authorization Flow
When a request is made to the login endpoint of the server, the server redirects the user to the custom
authorization UI screen. The user then enters the authorization credentials and clicks Submit. If the
credentials provided by the user are correct the user is logged in and the user details are sent to the client
using a WebSocket.

© 2021 Vlocity LLC, a Salesforce


company 221
Digital Commerce

For this reference application, web sockets are used to communicate between the client and the server
upon successful login. However, callbacks or any other mechanism could also be used.

Note that both the Digital Commerce Web Components and the Digital Commerce Lightning Web
Components have components that could be used in conjunction with this reference implementation.

VlocityDCFirebaseRedirectStrategy and DCCustomAuthentication are the custom


components respectively for Web Components and Lightning Web Components that are created as a
reference implementation and could be used to interact with the server hosting the redirect-
authentication-reference-app.

© 2021 Vlocity LLC, a Salesforce


company 222
Digital Commerce

Digital Commerce Lightning Web Components

Digital Commerce Lightning Web Components supplement Vlocity Lightning Web Components by
incorporating calls to the set of Digital Commerce cacheable APIs. Digital Commerce APIs are RESTful
Web APIs that are designed to enable client applications such as consumer-facing web and mobile apps to
shop for products and services. Vlocity Communications API Caching is optimized for consumer shopping
use cases where the user is often anonymous until well into the check-out process.

This topic describes the Digital Commerce Lightning Web Components, which are intended for use on the
Salesforce platform and follow the same standards as Salesforce's Lightning Web Components.

Vlocity Lightning Web Components are custom components and widgets built on Web Component
standards that work with all modern browsers and can be distributed with any JavaScript library or
framework. Web components allow you to create new custom, reusable, encapsulated HTML tags to use in
your web pages or applications.

For the Digital Commerce Web Components developer reference see https://docs.vlocity.com/devdocs/lwc/
index.html. For the Spring '20 version of the Digital Commerce Web Components developer reference see:
https://docs.vlocity.com/devdocs/archive/lwc/107.0/.

Table 12. List of Digital Commerce Lightning Web Components


Component Description
DCAppliedPromotionList Render all the applied promotions.
DCAssetAttributes Lists all asset attributes.
DCAssetDetails Renders each asset.
DCAssetItemDetails Displays asset details for each asset.
DCAssetsList Displays all assets.
DCBaseComponent A base class that is extended by other lightning web components
dcBaseMixin • A wrapper for DCBaseComponent that help implement your custom UI and leverage the Digital
Commerce SDK
• Extends omniscriptBaseMixin
• Enables a custom Salesforce URL for logged-in users by specifying the value of the
salesforceCustomDomainUrl variable
• Provides methods to get an SDK instance, update custom URLs, load a CSS into custom LWCs,
update OmniScript data, and other capabilities
• Supports the getTranslatedLabels translation method and its parameters: language and labels
DCCatalog Render the specified catalog list.
DCCheckOut Supports the checkout workflow, including payment and submitting the order
DCCheckoutPayment Supports payment features
DCChildCatalogs Render the specified catalog child list.
DCCustomAuthentication Reference implementation for sign-in or sign-up using redirect mechanism.
DCFilter Render offer prices in the offer list.
DCGlobalHeader Renders a global header available across all components except checkout.
DCMediaViewer Render a media carousel that cycles through media resources.

© 2021 Vlocity LLC, a Salesforce


company 223
Digital Commerce

Component Description
DCMyAccount Renders user account.
DCOfferAddons Supports add-on offers and displays the child bundle options
DCOfferAttributeConfig Render attribute values and allow users to choose a predefined set of options.
DCOfferColorConfig Render color options for an offer.
DCOfferConfig Retrieve the selected offer details using the getOffer() API. The offer can also be configured in this
component.
DCOfferConfigDetails Render configuration details for an offer.
DCOfferConfigurations Render non-configurable offer attributes.
DCOfferGridView Render offers in a grid.
DCOfferGroup Render offers in a group.
DCOfferGroupSections Render the first child bundle options (optional).
DCOfferGroupSelection Segment offer groups
DCOfferInputConfig Supports custom input
DCOfferListViewAttribute Render offer attributes in an offer list.
DCOfferListViewImage Render offer images in an offer list.
DCOfferListViewPrice Render offer prices in an offer list.
DCOfferPaymentConfig Render payment options for an offer.
DCOffersList Retrieve the offers for the specified catalog-code using the getOffers() API. DCOffersList is a base
class which is extended by all lightning web components.
DCOffersListView Render offers in a list view.
DCProgressIndicator Render a progress icon or a progress bar.
DCPromotionList Render all available promotions.
DCReviewOrder Render all the order details so that the user can review them before submitting the order.
DCSampleApp Container class where all components are rendered conditionally.
DCShoppingCart Render the offers that are being added to the cart. The cart may be updated before checkout.
DCShoppingcartNestedOffer Render child bundles of the offer that is being added to the cart.
DCShoppingCartOfferDetails Render details of the offers that are being added to cart.
DCSignIn Supports sign up and sign in
DCTotalBar Render total cart prices.
DCUpdateBillingAddress Supports updates to billing and shipping addresses

Working With Digital Commerce Lightning Web Components in a


Managed Package
When using Digital Commerce Lightning Web Components (LWCs) in a managed package, you cannot
display or read the source code, nor can you directly edit or change the HTML, CSS, or JavaScript.
However, several options are available for developers to customize code by following the instructions
below.

Changing the Theme or the CSS


You can modify the theme or the CSS if you use the Newport Design System (NDS) library to contain the
definitions of all of your CSS classes. To change the theme, you can change the CSS class definition at one
location and all LWCs that use HTML with that CSS class name will change.

© 2021 Vlocity LLC, a Salesforce


company 224
Digital Commerce

You can generate updated NDS files using the following command. Then, upload the file as a static
resource to your org:

npm run build

After uploading the file as a static resource, configure your Custom Settings with the static resource URL.
Refer to the following figures:

Replacing or Overriding the LWC HTML Template


You can replace or override the HTML template provided that the LWC meta.xml file contains the following
command (which is already done for all Digital Commerce LWC managed packages):

© 2021 Vlocity LLC, a Salesforce


company 225
Digital Commerce

isExposed=true

Because isExposed=true is set, you can extend the LWC class (using object-oriented inheritance) and
replace the original template with your own template.

Modifying a Small Portion of the LWC HTML Template


You can modify a select portion of the LWC HTML template without replacing all of the HTML.

Because isExposed=true in the meta.xml file, you can use placeholders in the original HTML source, called
slots, and replace the placeholder code with your own HTML modifications. Slots are documented in the
reference section.

© 2021 Vlocity LLC, a Salesforce


company 226
Digital Commerce

Replacing or Overriding LWC css if not using an NDS library


Using object-oriented inheritance, you can extend the LWC class and override the LWC css file. Refer to
the following figures.

© 2021 Vlocity LLC, a Salesforce


company 227
Digital Commerce

Overriding a Specific LWC JavaScript Method


You can replace or override a specific Digital Commerce Lightning Web Component JavaScript method.
You can then extend (using object-oriented inheritance) the LWC class and override the particular
JavaScript method. All Javascript methods are documented in the reference documentation.

© 2021 Vlocity LLC, a Salesforce


company 228
Digital Commerce

Configuring the SDK That is Used by All Digital Commerce LWCs


You can configure the SDK used by all Digital Commerce Lightning Web Components. You can extend
(using object-oriented inheritance) the getDigitalCommerceSDKInstance() LWC class and override the
JavaScript method that initializes the SDK. You can then configure the SDK before it is used.

Reading the LWC HTML Source Code


Although the Digital Commerce Lightning Web Component HTML is hidden, you can view the code in the
zip file stored in the VPL library.

© 2021 Vlocity LLC, a Salesforce


company 229
Digital Commerce

Reading the LWC CSS


All Digital Commerce CSS files are stored in an NDS library, which you can download from https://
github.com/vlocityinc/newport-design-system/blob/master/README.md.

© 2021 Vlocity LLC, a Salesforce


company 230
Digital Commerce

Reading the LWC JavaScript


Before customizing the JavaScript methods, you should first review the technical documentation, which lists
and describes all of the LWC methods. For information about a particular method, you can examine the
code using the Chrome inspector. The modules are listed by LWC name in the source tab of the code
inspector.

© 2021 Vlocity LLC, a Salesforce


company 231
Digital Commerce

© 2021 Vlocity LLC, a Salesforce


company 232
Digital Commerce

Digital Commerce Web Components

Vlocity Digital Commerce Web Components are built on Web Component standards that work with all
modern browsers and can be distributed with any JavaScript library or framework. Web components allow
you to create new custom, reusable, encapsulated HTML tags to use in your web pages or applications.

Use Vlocity Digital Commerce Web Components to implement an eCommerce solution. These components
support all of the major phases of any eCommerce solution, namely browse phase, configure phase, cart
phase, and checkout. You can use these web components as-configured or they can be customized based
on client requirements.

The Vlocity Digital Commerce reference app is available to Vlocity customers and partners as a working
sample to learn more about the Vlocity Digital Commerce solution.

Current Vlocity customers and partners can explore how Vlocity Digital Commerce web components work
with the Digital Commerce SDK by accessing the Digital Commerce Web Component Reference App which
is located in a zip file in a VPL. See Digital Commerce Lightning Web Component Artifacts for information
and links to the VPL.

The reference implementation showcases preconfigured SDK and web component dependencies, sample
apps, and build/deploy scripts for off-platform development.

Vlocity Digital Commerce Web Components were developed using a Google library called LitElement,
which is a simple base class for creating fast, lightweight web components. Vlocity's Web Components are
encapsulated. You can develop your applications using any library and any tool that supports Web
Standards. There are no dependencies on Google Polymer, however, and because of its foundation on
LitElement, Vlocity Digital Commerce Web Components provides full support for a shadow DOM.

You can use Vlocity Digital Commerce Web Components to develop Single-Page-Applications (SPAs) and
non-SPA applications. Each web component comes with defined methods to retrieve data and a Newport
style template to render data.

See: Digital Commerce Web Components developer reference.

For the Spring '20 version of the Digital Commerce Web Components developer reference see: https://
docs.vlocity.com/devdocs/archive/wc/107.0/

Table 13. List of Digital Commerce Web Components


Component Description
VlocityAssetAttributes Render asset attributes.
VlocityDCAppliedPromotionList Render all the applied promotions.
VlocityDCAssetDetails Render each asset.
VlocityDCAssetItemDetails Display asset details for each asset.
VlocityDCAssetsList Display all the assets.

© 2021 Vlocity LLC, a Salesforce


company 233
Digital Commerce

Component Description
VlocityDCBaseComponent Base class extended by all DC components. This class contains common logic of all
components.
VlocityDCCatalog Render the specified catalog list.
VlocityDCCheckout Supports the checkout workflow, including payment and submitting the order.
VlocityDCChildCatalog Render the specified catalog child list.
VlocityDCEditModal Supports basket updates.
VlocityDCFilter Render offer prices in the list of offers.
VlocityDCFirebaseRedirectStrategy Used for sign-in or sign-up using redirect mechanism.
VlocityDCGlobalHeader Renders a global header which is available across all components except checkout.
VlocityDCHomePage Render the home screen during the browse phase.
VlocityDCMain Contains internal navigation logic between different screens/phases.
VlocityDCMediaViewer Render a media carousel that cycles through media resources.
VlocityDCModal Render a modal popup.
VlocityDCMyAccount Render user account.
VlocityDCOfferAddons Supports add-on offers and displays the child bundle options.
VlocityDCOfferAttributeConfig Render attribute values and allow users to choose a predefined set of options.
VlocityDCOfferColorConfig Render color options for an offer.
VlocityDCOfferConfig Retrieve the selected offer details using the getOffer() API. The offer can also be
configured in this component.
VlocityDCOfferConfigDetails Render configuration details for an offer.
VlocityDCOfferConfigurations Render non-configurable offer attributes.
VlocityDCOfferGridView Render offers in a grid.
VlocityDCOfferGroup Render offers in a group.
VlocityDCOfferGroupSections Render the first child bundle options.
VlocityDCOfferGroupSelection Segment offer groups.
VlocityDCOfferInputConfig Supports custom input.
VlocityDCOfferListView Render a list of all the offers.
VlocityDCOfferListViewAttribute Render offer attributes in an offer list.
VlocityDCOfferListViewImage Render offer images in an offer list.
VlocityDCOfferListViewPrice Render offer prices in an offer list.
VlocityDCOfferPaymentConfig Render payment options for an offer.
VlocityDCOffersList Retrieve the offers for the specified catalog-code using the getOffers() API.
DCOffersList is a base class which is extended by all web components.
VlocityDCPromotionList Render all available promotions.
VlocityDCReviewOrder Render all the order details so that the user can review them before submitting the
order.
VlocityDCShoppingCart Render the offers that are being added to the cart. The cart may be updated before
checkout.
VlocityDCShoppingNestedOffer Render child bundles of the offer that is being added to the cart.
VlocityDCShoppingOfferDetails Render details of the offers that are being added to cart.
VlocityDCSignin Supports sign up and sign in.
VlocityDCToast Render toast messages.
VlocityDCTotalbar Render total cart prices.

© 2021 Vlocity LLC, a Salesforce


company 234
Digital Commerce

Component Description
VlocityDCUpdateBillingAddress Supports updates to the billing and shipping addresses.

For training on Vlocity Digital Commerce solutions and Digital Commerce Web Components, see Vlocity
University.

© 2021 Vlocity LLC, a Salesforce


company 235
Digital Commerce

Digital Commerce API Context Rules for Logged In Users

These topics provide a brief explanation of Digital Commerce API Eligibility Context Rules for logged in
users, along with some assumptions for DC API context rules, Cart API rules portability to DC API rules,
and the differences between Cart-Based APIs and DC API rules with an explanation of how DC API context
rules work.

The API anatomy of a logged-in DC API user is:

EXAMPLE API : /services/apexrest/vlocity_cmt/v3/catalogs/ROOT/offers?


context={"contractId":"8001j0000000Kxh","accountId":"0011j000006IgfF","rootAsse
tIds":["02i1U000000kqSo"]}&amp;isloggedIn=true

The context of the API is:

context={"contractId":"8001j0000000Kxh","accountId":"0011j000006IgfF","rootAsse
tIds":["02i1U000000kqSo"]}

DC API Eligibility Rules for a logged-in user mainly operate in the given context of the API that determines
the results of the API request. Therefore, the contents of this parameter are important in determining
eligibility.

This context parameter of the API can have a maximum of four fields. These fields populate dimension
values that the context rule conditions use.

• The contractId represents the contract object and populates all the dimensions that start their source
expression with the Contract object.
• The accountId represents the account object and populates all the dimensions that start their source
expression with Account or User object. This object helps you extract the user object.
• rootAssetIds represent the root assets of the provided account. Root assets allow you to generate all
the assets present under that root asset and based on that you can generate the context key.
You should send only one root asset ID in the context parameter. Sending more than one root asset ID
might lead to performance issues.
• The cartContextKey represents the Cart Context Key.

Context Dimensions
This topic explains how the Context Dimension population works for the provided context in Cart-Based
APIs vs Digital Commerce APIs.

Assuming we have the following context dimensions:

• ContractCluster: In the following setup for the ContractCluster dimension, we retrieve the
Contract.Cluster_di_adesione__c field from the Order object.

© 2021 Vlocity LLC, a Salesforce


company 236
Digital Commerce

• AccountSla: In the following setup for the AccountSla dimension, we retrieve the Account.vSLA__c
field from the Order object.

© 2021 Vlocity LLC, a Salesforce


company 237
Digital Commerce

For V2 Context Rules, there is a single context scope object passed from the API, for example, Order in
getProducts or Order in getPromotions. Since we have an order scope object, we can retrieve all the
required dimension details in a single query as follows:

© 2021 Vlocity LLC, a Salesforce


company 238
Digital Commerce

"Order orderContextScopeObject = [Select Account.vSLA__c,


Contract.Cluster_di_adesione__c From Order Where id=:orderId];"

In DC API Context Rules, there is not a single context scope object such as Order. Instead, there are
multiple scope objects, such as Contract, Account, and User.

For example,
context={"contractId":"8001j0000000Kxh","accountId":"0011j000006IgfF"} has two
scope objects:

• Account: [Select vSLA__c From Account Where id=:accountId]


• Contract: [Select Cluster_di_adesione__c From Contract Where id=:contractId]

You can populate all the dimensions whose EntityPath or Entity has Contract or Account. In this case,
dimensions for all the rules from the above example are available and the results are evaluated based on
those dimensions.

As another example, assume we have context={"contractId":"8001j0000000Kxh"}. There is only one scope


object, which is Contract. Therefore, you can populate all the dimensions whose EntityPath or Entity has
Contract.

The query for one scope objects is Contract : [Select Cluster_di_adesione__c From
Contract Where id=:contractId].

In this case, the dimension of AccountSlaGold rule is not available, so while processing the rule expression
("AccountSla" == "Gold"), the expression value is set to the Default Expression Value field on
RuleCondition, which is false in this case.

• AccountSla Dimension => Not populated


• Rule expression : ("AccountSla" == "Gold")
• Dimension not found so fall back to default rule condition expression => ("AccountSla" == "Gold") =>
false

The ContractBillingCluster rule condition contains a dimension value. The rule expression is evaluated
normally as follows:

• ContractBillingCluster Dimension = "FW1023"


• Rule expression: (ContractBillingCluster == "FW1017")
• Final Expression: ("FW1023" == "FW1017") => false

Digital Commerce API Caching Mechanism


Digital Commerce logged-in user APIs use a progressive caching mechanism to cache the API response
and quickly serve results that can be consumed by the DC API. The DC API Caching Mechanism for
logged in users ensures response time remains consistent. This caching mechanism involves key
generation (Group Context Key) and response generation if the generated key is not found in cache, which
stores the API results with different context inputs.

© 2021 Vlocity LLC, a Salesforce


company 239
Digital Commerce

The Group Context key should represent the following entities:

• Context rules, which include Dimension Based rule conditions and Function-Based rule conditions.
• Input context objects.

Context Shapes
For representing context rules as part of the caching mechanism, we mark context dimensions as
cacheable. To achieve this, the Group Context Key generation consists of several major components as
described below. These standard context shapes are widely used in dimensioncontext rules or function-
based context rules.

Account Shape
• context={"accountId":"89ddsdjsh7D00M"}
• Context Param : accountId
• Mandatory : false
• Object : Account

Context Dimensions fetch CacheableFields on account objects with cacheable mode set to True.
Dimension scope should have Account either in the Entity path or in the entity of the Context Scope that
belongs to this dimension.

The Entity field for AccountScope can be either Account or Order.

© 2021 Vlocity LLC, a Salesforce


company 240
Digital Commerce

Based on the Account Object and the cacheable fields obtained from cacheable context dimensions, you
can generate a context string such as {vSla__c:Gold, Status:Active}.

Contract Shape
• context={"contractId":"89ddsdjsh7D00M"}
• Context Param : contractId
• Mandatory : false
• Object : Contract

Context Dimensions fetch CacheableFields on contract objects with cacheable mode set to True.
Dimension scope should have Contract either in the Entity path or in the entity of the Context Scope that
belongs to this dimension.

© 2021 Vlocity LLC, a Salesforce


company 241
Digital Commerce

The Entity field for ContractStatus can be either Contract or Order.

© 2021 Vlocity LLC, a Salesforce


company 242
Digital Commerce

Based on the Contract Object and the cacheable fields, you can generate a context string such
as {Status:Active}.

User Shape
• context={"accountId":"89ddsdjsh7D00M"}
• Context Param : accountId
• Mandatory : false
• Object : Account, User

Basket Shape
• context={"cartContextKey":"e08faf1e2bdc907e409b7d0c1dd47634"}
• Context Param : cartContextKey
• Mandatory : false
• Object : NONE

This key should be provided by the user and is usually available from the Basket APIs.

Assets Shape
• context={"accountId":"89ddsdjsh7D00M","rootAssetIds":["id"]}
• Context Param : rootAssetIds,accountId
• Mandatory : accountId : true, rootAssetIds : false
• Object : Account, Asset

Context Dimensions fetch CacheableFields on Asset objects with cacheable mode set to True. Dimension
scope should have Asset either in the Entity path or in the entity of the Context Scope that belongs to this
dimension.

© 2021 Vlocity LLC, a Salesforce


company 243
Digital Commerce

Based on the Account Object, you can retrieve the asset bundle for the rootAssetId provided. Using
cacheable fields, you can generate context strings for all the assets. The Group Context Mechanism makes
sure that for every given context, if the data set is similar, the same key is generated. Otherwise, unique
keys are produced.

Best Practices
• To generate the shape generation of each object type, use values of cacheable dimensions.
• If there are complex fields that could not be expressed as part of the fieldset, you can write a post-hook
to the shape generator that enables you to add complex fields.
• If there are range operators such as (<>) you want to include as part of the shape generator, you can
convert them to a Boolean or text custom formula field and add them as part of the EcommCachingFS
fieldset.
You can also use post hooks for the shape generator to include. For example, you can convert
CPQ_Ageing_Loyalty > 12 to AgeingLoyaltyGT12(Boolean field).

© 2021 Vlocity LLC, a Salesforce


company 244
Digital Commerce

• Do not include Id fields as part of any object shape, or it results in a cache miss and might lead to an
increase in response time. Use Codes instead.
• While adding fields to an object shape, consider all your rules and function logic so you can add fields for
caching.
• Since GetOffers uses eligibility context rules, if no context is provided in the URL then eligibility rules fail
since there are no populated context dimensions.
• If any context dimension value is not populated, then the rule expression is evaluated to false by default.
• If you are using hook services for any rules with functions, make sure you rewrite the logic for DC APIs.

© 2021 Vlocity LLC, a Salesforce


company 245
Digital Commerce

Digital Commerce Artifacts

Vlocity provides several example applications and source code to help you create your own Digital
Commerce experience. The topics in this section contain instructions for accessing and downloading the
files and components to enable the Digital Commerce Web Components, Digital Commerce Lightning Web
Components, Lightning Web Component OmniScript Datapack, and the Digital Commerce Software
Development Toolkit (SDK).

You can use the samples as a starting point for making your own Digital Commerce web site. You are free
to modify and enhance the examples to fit your requirements; however, the examples are not meant to be
used in a production environment.

For information about how to download the Vlocity Web Components or Vlocity Lightning Web Components
artifacts, see Digital Commerce Lightning Web Component Artifacts.

For example, using Vlocity Web Components or Vlocity Lightning Web Components, you can create
applications similar to those shown below.

© 2021 Vlocity LLC, a Salesforce


company 246
Digital Commerce

© 2021 Vlocity LLC, a Salesforce


company 247
Digital Commerce

The Vlocity Digital Commerce Software Development Toolkit (SDK) allows access to the components you
need to develop your own applications. For information about how to download the SDK.

You can also use Vlocity OmniScripts to create your application. For information about how to download the
Digital Commerce Lightning Web Components Sample OmniScript data pack.

© 2021 Vlocity LLC, a Salesforce


company 248
Digital Commerce

Digital Commerce Lightning Web Component Artifacts


You can use the Digital Commerce Lightning Web Components as a guide to creating your own digital
commerce application. The artifacts include a Digital Commerce Guided Process that allows users to
browse, configure, and add offers to a basket, and then begin a checkout process.

Both the explore and checkout processes are built using Digital Commerce Lightning Web Components
(LWC), which allow customers to browse and configure products as well as convert their baskets to a
Salesforce Order by providing the ability to log in to CRM as an identified user (Account), optionally call a
payment gateway system, and submit their order. Customer Service Agents can see the items in a
customer's cart based on the order ID.

The information on this page describes how to download and install the Digital Commerce Lightning Web
Component artifacts.

NOTE
The dcCheckoutPayment component in the sample app contains a link to the Braintree
payment service provider. The link is for demonstration purposes only; you must replace
the link with your own Braintree link or other payment gateway.

© 2021 Vlocity LLC, a Salesforce


company 249
Digital Commerce

Depending on your requirements, you can download the modules best suited to your particular needs. The
choices are as follows:

Digital Commerce Lightning Web Components only


If you need the Digital Commerce Lightning Web Components only (without OmniScript support), follow this
link:

Explore and Checkout Using Digital Commerce LWC

• Installation guide, which provides instructions for deploying each of the artifacts and how to download
and use the NDS file.
• A zip file containing HTML and meta.xml files of corresponding DC LWC's in the managed package.
• A datapack file containing the VIP for the checkout process
• A DX file containing data to be imported into your org to run the sample DC LWC Application.

Digital Commerce Lightning Web Components With OmniScript support


If you need the Digital Commerce Lightning Web Components with OmniScript support, follow this link:

Explore and Checkout Using Digital Commerce LWC OmniScript

• Installation guide, which provides instructions for deploying each of the artifacts and how to download
and use the NDS file.
• A zip file containing HTML and meta.xml files of corresponding DC LWC's in the managed package.
• A datapack file containing sample Omniscript that embeds DC LWC to implement the purchase flow.
• A DX file containing data to be imported into your org to run Sample the OmniScript that embeds DC
LWC to implement the purchase flow.

Digital Commerce Web Components and SDK for Off-Platform Use


If you need the Digital Commerce Lightning Web Components with OmniScript support, follow this link:

Explore and Checkout for Off-Platform Use

• Installation guide, which provides instructions for how to deploy each of the artifacts, how to download
and use NDS, instructions for how to download DC WC and DC SDK using NPM (without a password).
• A zip file containing the reference application that showcases how DC WC can be customized.
• A datapack file containing the VIP for the checkout process.
• A DX file containing data to be imported into your org to run the sample DC WC application.

© 2021 Vlocity LLC, a Salesforce


company 250
Digital Commerce

Digital Commerce Gateway (DCG) Overview

NOTICE
The documentation in this and the following sections is applicable only for customers who
have purchased the Digital Commerce Gateway license. The instructions provided will not
work without the Digital Commerce Gateway license.

The Digital Commerce Gateway provides communications and media companies additional scalability for
peak traffic events, such as mobile device roll-out or pay-per-view specials.

The Digital Commerce Gateway uses the Amazon API Gateway to provide additional scalability and a
reduction in response times. Cacheable API calls are responded to from the API Gateway itself, reducing
traffic to Salesforce, enabling peak traffic management, and providing consistent and fast API response
times.

API cache misses are routed by the Digital Commerce Gateway to the Salesforce platform for execution,
and responses, if cacheable, are cached on the on-platform API Caching layer and the Digital Commerce
Gateway. The Digital Commerce Gateway is hosted on the AWS cloud platform.

DCG Setup

NOTICE
The documentation in this and the following sections is applicable only for customers who
have purchased the Digital Commerce Gateway license. The instructions provided will not
work without the Digital Commerce Gateway license.

Setting up the Digital Commerce Gateway ensures that the steps required to use the gateway are in place
and configured correctly.

Follow the steps below:

1. Identify or Create a Salesforce User


2. Create a Salesforce connected application.

© 2021 Vlocity LLC, a Salesforce


company 251
Digital Commerce

a. For information about creating a connected application see https://help.salesforce.com/


articleView?id=sf.connected_app_overview.htm&amp;type=5.
b. For information about creating a connected application for Vlocity Digital Commerce, see DCG
Connected App Setup.
c. Copy the Connected Application Consumer Key (client_id) and paste it into a temporary file. The
key is required later.
d. Copy the authorized user name (the name created in step 1). The name is required in the steps
that follow.
3. Create a ticket with Vlocity Success by providing the following information:
a. The environment name (such as dev1, uat, preprod, prod, and so on). Use this name when
creating any future related support requests.
b. The organization type (such as test.salesforce.com or login.salesforce.com, and so on).
c. The connected application consumer key (also known as client_id).
d. The authorized user name to use the connected application. Note that it is not necessary to
provide the password or consumer secret.
e. Provide the version of the Vlocity Managed Package, including the major number and minor
number. To find the version numbers, navigate to the following documentation page to verify the
Vlocity Manage package that you have installed in your Salesforce Org: Vlocity CME Release
Summary. Copy the name shown in the Version column (for example, 109.1.900.393).
After the ticket has been received by Vlocity Success, the following three items will be delivered:
• Public Certificate for the Connected Application
• Digital Commerce Gateway End-Point (API URL)
• Digital Commerce Gateway OAUTH2 credentials
4. Import the Public Certificate into the Connected App. See Upload the Certificate to SFDC here: DCG
Connected App Setup.
5. Perform a test to ensure you have access to the Digital Commerce Gateway. Note that the Digital
Commerce Gateway can be accessed only using OAuth2. For more information, refer to the DCG
OAuth2 Setup and Usage.

Additional Resources
• For troubleshooting information, see DCG Troubleshooting
• For API reference information, see Digital Commerce API Swagger Reference.
• For information about Digital Commerce Gateway Cache Migration, see Updating the AWS Cache.

DCG Connected App Setup

NOTICE
The documentation in this and the following sections is applicable only for customers who
have purchased the Digital Commerce Gateway license. The instructions provided will not
work without the Digital Commerce Gateway license.

© 2021 Vlocity LLC, a Salesforce


company 252
Digital Commerce

This topic guides you through the creation of a Salesforce Connected Application to be used by the Digital
Commerce Gateway (also known as DCG application, formerly known as Vlocity Digital Commerce Tier -
VDCT).

Prerequisites
To create the connected application, you must have an admin account within the Salesforce organization.
The callback URL to configure in the connected application will differ depending on the type of Salesforce
instance used (test or standard),

• For sandbox / test instances: https://test.salesforce.com/services/oauth2/success


• For production / standard instances: https://login.salesforce.com/services/oauth2/
success

The DCG application relies on the OAuth2.0 JWT Bearer Token authentication flow which requires a private
key and certificate to work. Vlocity creates them and provides you with the public certificate to add to the
connected application at a later stage. You do not need this certificate to create the connected application.

DCG requires a dedicated user who is authorized to use the connected application. The user must be
assigned to a Profile with sufficient permissions for the DCG application to work. The “System
Administrator” profile is the recommended one for DCG; however, its permissiveness is generally not
recommended for production environments. Vlocity can provide assistance with creating a dedicated
profile.

Creating the application


Follow these instructions from Salesforce to create the connected application: https://help.salesforce.com/
articleView?id=connected_app_create.htm&amp;type=5

After you reach the application creation page, configure it as follows:

• Provide a name for the application similar to: “Digital Commerce Application - {ENV}” (replacing {ENV}
with the appropriate environment name / nickname).
• Provide an email address where you can receive notifications related to the connected application.
• Check Enable OAuth settings.
• Fill in the Callback URL (refer to the Prerequisites section above for possible values).
• For now, skip setting Use digital signatures until after setup when Vlocity has sent you the connected
application certificate.
• Add the following Oauth Scopes (or permissions) to the Selected Oauth Scopes:
• API
• refresh_token, offline_access

© 2021 Vlocity LLC, a Salesforce


company 253
Digital Commerce

Example

© 2021 Vlocity LLC, a Salesforce


company 254
Digital Commerce

Authorize the User to Access the Connected Application


DCG requires a user who is authorized to use the connected application. This user must be assigned to a
Profile with sufficient permissions for the DCG application to work. The “System Administrator” profile is the
most commonly used and supported by Vlocity.

Preferred method: OAuth policy configuration for the Connected App


This option is preferred as it works in every situation. The alternative method requires having access to an
admin user for the organization.

1. Open the connected application menu, find the connected application for Digital Commerce and click
Manage and select Edit Policies.
2. Under Oauth2 Policies, set Permitted users option to Admin approved users are pre-authorized.

© 2021 Vlocity LLC, a Salesforce


company 255
Digital Commerce

3. Click Save. You now see a Profiles section in the Edit Policies page.
4. Add the profile of the DCG assigned user to the Profiles section of the connected application.

© 2021 Vlocity LLC, a Salesforce


company 256
Digital Commerce

© 2021 Vlocity LLC, a Salesforce


company 257
Digital Commerce

5. Click Manage Profiles and select the profile you selected above (System Administrator is
recommended) from the list.

6. Save the selected profile.

© 2021 Vlocity LLC, a Salesforce


company 258
Digital Commerce

Validation
In Manage App > Connected Apps, find the application you just created and ensure the settings are as
below:

Alternative method: login-based authorization


This method requires specific permissions for the user validating the connected app. It may fail in some
cases where the permissions are restrictive, thus we recommend the preferred method above.

1. From the Connected Application in the section "API (Enable OAuth Settings)", retrieve the “Consumer
Key” and “Callback URL”
• YOUR_CLIENT_ID : Consumer Key
• YOUR REDIRECT_URL : Callback URL
2. Depending on where to use the connected app, build a URL based on one of the following:
• If the connected app is in the Sandbox/Test salesforce domain:

https://test.salesforce.com/services/oauth2/authorize?
response_type=token&client_id=<YOUR_CLIENT_ID>&redirect_uri=<YOUR_REDIRECT
_URL>
• If using the standard salesforce domain:

https://login.salesforce.com/services/oauth2/authorize?
response_type=token&client_id=<YOUR_CLIENT_ID>&redirect_uri=<YOUR_REDIRECT
_URL>

© 2021 Vlocity LLC, a Salesforce


company 259
Digital Commerce

After the URL is built, open it in your browser. The link redirects to the Salesforce login page. Log in
using the salesforce username and password which will be provided to Vlocity and authorize the
access.

Send the connected application information to Vlocity


Update the ticket with the following required information from the Connected Application:

• The Salesforce username authorized in the application


• The Connected Application API Oauth Consumer Key

NOTE
It is not necessary to send either the Salesforce password for the username or the
Connected Application API Oauth Consumer Secret.

Post Setup Steps


After Vlocity has finalized the creation of your environment and has sent you the public certificate, proceed
with the post setup instructions here.

• Upload the Public Certificate to the Connected Application.


The public certificate may be sent to you in PEM or DER format. Both are accepted by Salesforce
Connected Applications.
When the certificate is nearing expiration, a new one will be generated and provided to you by Vlocity.
To add or replace the certificate, follow these steps:
1. Log in to the Salesforce Org and navigate to Setup
2. Navigate to Menu > Create > Apps > Connected Apps.
3. Locate the app you created for this environment.
4. Click on the Edit link for your App
5. Locate and check the setting Use digital signatures in the API section.
6. Click Browse… and upload the public certificate file you received from Vlocity.
7. Click Save.

© 2021 Vlocity LLC, a Salesforce


company 260
Digital Commerce

You can display the certificate’s properties using the following command (subject, issuer and
expiration date):

> openssl x509 -in myenv-connected-app-public-certificate.pem -subject -


dates -issuer -noout

Example output:
subject= /C=US/ST=CA/L=San Mateo/O=Vlocity/OU=CE/
CN=myenv.auth.vlocity.comnotBefore=Mar 14 09:08:08 2019 GMTnotAfter=Apr
17 09:08:08 2020 GMTissuer= /C=US/ST=CA/L=San Mateo/O=Vlocity/OU=CE/
CN=myenv.auth.vlocity.com

DCG OAuth2 Setup and Usage

NOTICE
The documentation in this and the following sections is applicable only for customers who
have purchased the Digital Commerce Gateway license. The instructions provided will not
work without the Digital Commerce Gateway license.

This document provides a general overview and a technical explanation of OAuth2 authentication for the
Digital Commerce Gateway.

Prerequisites
To use the information in this document, you must have previously requested and obtained a DCG
environment. After the environment is provisioned, the Vlocity team sends you the following information:

• The DCG Endpoint


• Format: api.{myenv}.{customername}.dc.vloc-dev.com
or

© 2021 Vlocity LLC, a Salesforce


company 261
Digital Commerce

api.{myenv}.{customername}.dc.vloc-prod.com
• The OAuth2 Server
• Format: vlocity-dc-{customername}-{platform}.auth.{region}.awscognito.com.com
• Four sets of OAuth2 credentials for this environment:
• admin
• cmig
• ops
• user

List of the DCG endpoints and associated scopes


# App clients and matching scopes access
oauth2-{env}-admin = [admin, ops, user, cmig]
oauth2-{env}-cmig = [cmig]
oauth2-{env}-ops = [ops, user]
oauth2-{env}-user = [user]

# Scopes
- admin
- cmig
- ops
- user

You will find the mapping between app clients, scopes, and endpoints below.For each endpoint, you will
find the list of methods authorized with which app client and scopes.

# Digital Commerce
/dc/app-status
OPTIONS no-auth (AWS Mock 200)
ANY oauth2-{env}:[admin, ops]
/dc/app-diagnostic
OPTIONS no-auth (AWS Mock 200)
ANY oauth2-{env}:[admin, ops]
/dc/{proxy}+
OPTIONS no-auth (AWS Mock 200)
DELETE oauth2-{env}:[admin, ops]
PATCH oauth2-{env}:[admin, ops]
ANY oauth2-{env}:[admin, ops, user]

# Cache Migration
/cm/app-status
OPTIONS no-auth (AWS Mock 200)
ANY oauth2-{env}: [admin, ops]
/cm/app-diagnostic
OPTIONS no-auth (AWS Mock 200)
ANY oauth2-{env}: [admin, ops]

© 2021 Vlocity LLC, a Salesforce


company 262
Digital Commerce

/cm/{proxy}+
OPTIONS no-auth (AWS Mock 200)
DELETE oauth2-{env}: [admin, cmig]
PATCH oauth2-{env}: [admin, cmig]
ANY oauth2-{env}: [admin, cmig, ops]

# Cache Administration
/admin/cache/status
OPTIONS no-auth (AWS Mock 200)
GET oauth2-{env}: [admin, ops]

/admin/cache/list
OPTIONS no-auth (AWS Mock 200)
GET oauth2-{env}: [admin, ops]

/admin/cache/flush
OPTIONS no-auth (AWS Mock 200)
POST oauth2-{env}: [admin, ops]

OAuth2 Description

Components and credentials overview


“Cognito Application Clients” customer keys and secrets are:

© 2021 Vlocity LLC, a Salesforce


company 263
Digital Commerce

• Used to request an OAuth2 JWT to the AWS Cognito OAuth2 server.


• Generated by Vlocity and provided to the customer.
• Specific to each environment.

OAuth2 JWT (JSON Web Token):

• The OAuth2 JWT are temporary authorization code used to access the DCG API Endpoints.
• These are obtained from the AWS Cognito OAuth2 server by a trusted client application.
• The DCG OAuth2 JWT can be reused multiple times until its expiration date and can be shared by
several application clients to connect to the same API.
• The expiration time of the JWT is 3600 seconds (1 hour) and cannot be changed at the moment (AWS
Cognito constraint).

Anatomy of an OAuth2 JWT token


The JSON Web Token or Bearer Token received from the OAuth2 server (also known as the AWS Cognito
server) contains the following (among other things):

• A string identifying the customer application used to deliver the token


• A timestamp and expiration date
• A scope or list of scopes that this token grants access to
• A signature (to prevent JWT forgery)

You can find more information about OAuth2 JWT here: https://oauth.net/2/jwt/

Scopes Overview
DCG uses OAuth2 Scopes to control the access to the protected resource.

Each Application Client is granted a list of scopes represented by arbitrary strings. The protected resources
are assigned one or more scopes for specific paths. The scope, being part of the JWT content, the
protected resource can validate whether the client has access to and/or requested access to this specific
resource.

Implementation of OAuth2 for Digital Commerce


Below is a sample procedure with example calls to obtain and consequently use an OAuth2 JWT token
against a sample test deployment.

Obtaining an OAuth2 JWT access token


Obtaining an OAuth2 JWT access token requires making a POST HTTPS request to the AWS OAuth2
Cognito endpoint using a specific set of credentials which Vlocity has created and provided.These
credentials are referred to as customer application secrets.

Multiple sets of secrets with different access levels are provided.

As depicted in action 2b of the diagram:

# "Cognito Application Clients": customer application secrets


customer_app_key="6gi8...imprk"

© 2021 Vlocity LLC, a Salesforce


company 264
Digital Commerce

customer_app_secret="1dh9t...4iu2rn"

# cognito_oauth2_server (provided by Vlocity, below is an example)


cognito_oauth2_server="vl-dc-test.auth.eu-central-1.amazoncognito.com"

# Template curl call to retrieve an oauth2 token


curl -s -X POST --user "${customer_app_key}:${customer_app_secret}" \
-H 'Content-Type: application/x-www-form-urlencoded' \

"https://${cognito_oauth2_server}/oauth2/token?grant_type=client_credentials"

# Response template:
{
"access_token": "[...]",
"expires_in": 3600,
"token_type": "Bearer"}

# Example call
curl -s -X POST --user "6gi88ku...9imprk:1dh9to...0j4iu2rn" \
-H 'Content-Type: application/x-www-form-urlencoded' \
"https://vl-dc-test.auth.eu-central-1.amazoncognito.com/oauth2/token?
grant_type=client_credentials"

# Example response:
{"access_token":"eyJraWQiOiJQbGkyTkJcL3NBczBabkVWaXdPS0ZhQ0JsbWpHcUxXblFOMlo0Rm
E1d09Ecz0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI2Z2k4OGt1bmdkbmI0NDB0OWdpYzlpbXByayIs
InRva2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoiZGMtdGVzdC1hcGlcL2FkbWluIGRjLXRlc3QtYXB
pXC9yZWFkIGRjLXRlc3QtYXBpXC93cml0ZSIsImF1dGhfdGltZSI6MTU2MzM3NjMxNiwiaXNzIjoiaH
R0cHM6XC9cL2NvZ25pdG8taWRwLmV1LWNlbnRyYWwtMS5hbWF6b25hd3MuY29tXC9ldS1jZW50cmFsL
TFfelJHb2dweHc4IiwiZXhwIjoxNTYzMzc5OTE2LCJpYXQiOjE1NjMzNzYzMTYsInZlcnNpb24iOjIs
Imp0aSI6IjFmYTU5YWQ1LTIwNDEtNDAyZS04NGIxLTExNjFjMWIxMmQ1YyIsImNsaWVudF9pZCI6IjZ
naTg4a3VuZ2RuYjQ0MHQ5Z2ljOWltcHJrIn0.awj5M4AvLXbL7TJrPIQguEUv2ifFurmZnqZraoNy5g
9UP365_vknj-
hJrgFzZ4OtOYlopQTdMgD-8m1n7vVqwUPfywr8qK2bJHOS8Dm9WycNypnsiFYC4eIDHjLd2526-
G63w6shTj4B53QmtpCzJF8lIvB9rGcsiQgxIlRNK9ZRSmc0opHZSLnts0xeLUvHCW5eb5Uys7eIY_MP
tc6GAMca0A6AObxADdklHMYLLagvEZdPPtj-A-
HG04jLuNCwcS3lpuhtmw7W0F0hgGhIIuI0ZQez7TxzdeaV2B3v9_P_dLPe18-3mD1BV0kZyjYqcZYqF
o4nHSg-UT33FLByWg","expires_in":3600,"token_type":"Bearer"}

Using an OAuth2 JWT


In this section, we’ll explore how the resource protected by OAuth2 tokens can be accessed after we have
retrieved a valid OAuth2 bearer token (also known as a JWT).

Procedure
As depicted in action 3 of the diagram:

© 2021 Vlocity LLC, a Salesforce


company 265
Digital Commerce

# Obtain the FQDN of the resource to access / protect (in this case the DCG
API)api_fqdn="api-test-cognito.platform.customer.dc.vloc-dev.com"

# Example of URL path of the resource to be accessed


url_path="/dc/app-status"
url_path="/dc/v3/catalogs/CATALOG_CODE/offers"

# The OAuth2 response from cognito is stored in the oauth2_cognito_response


oauth2_cognito_response='{"access_token":"[...]","expires_in":3600,"token_type"
:"Bearer"}'

# The OAuth2 token is stored in the variable oauth2_token


# Example of extraction of the access_token from oauth2_cognito_response via
Python’s jq tool
oauth2_token="$(echo -e "$oauth2_cognito_response" | jq -r .access_token )"

# Template for calls made to the protected resource:


curl -s -i -X GET -H "authorization: Bearer ${oauth2_token}" \
-H "Content-Type: application/json; charset=UTF-8" \
"https://${api_fqdn}${url_path}" ; echo -e "\n\nCurl returned $?"

# Example:
# - Setting variables and contextapi_fqdn="api-test-
cognito.platform.customer.dc.vloc-dev.com"

url_path="/dc/app-status"

oauth2_token="eyJraWQiOiJQbGkyTkJcL3NBczBabkVWaXdPS0ZhQ0JsbWpHcUxXblFOMlo0RmE1d
09Ecz0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI2Z2k4OGt1bmdkbmI0NDB0OWdpYzlpbXByayIsInR
va2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoiZGMtdGVzdC1hcGlcL2FkbWluIGRjLXRlc3QtYXBpXC
9yZWFkIGRjLXRlc3QtYXBpXC93cml0ZSIsImF1dGhfdGltZSI6MTU2MzM3NjMxNiwiaXNzIjoiaHR0c
HM6XC9cL2NvZ25pdG8taWRwLmV1LWNlbnRyYWwtMS5hbWF6b25hd3MuY29tXC9ldS1jZW50cmFsLTFf
elJHb2dweHc4IiwiZXhwIjoxNTYzMzc5OTE2LCJpYXQiOjE1NjMzNzYzMTYsInZlcnNpb24iOjIsImp
0aSI6IjFmYTU5YWQ1LTIwNDEtNDAyZS04NGIxLTExNjFjMWIxMmQ1YyIsImNsaWVudF9pZCI6IjZnaT
g4a3VuZ2RuYjQ0MHQ5Z2ljOWltcHJrIn0.awj5M4AvLXbL7TJrPIQguEUv2ifFurmZnqZraoNy5g9UP
365_vknj-
hJrgFzZ4OtOYlopQTdMgD-8m1n7vVqwUPfywr8qK2bJHOS8Dm9WycNypnsiFYC4eIDHjLd2526-
G63w6shTj4B53QmtpCzJF8lIvB9rGcsiQgxIlRNK9ZRSmc0opHZSLnts0xeLUvHCW5eb5Uys7eIY_MP
tc6GAMca0A6AObxADdklHMYLLagvEZdPPtj-A-
HG04jLuNCwcS3lpuhtmw7W0F0hgGhIIuI0ZQez7TxzdeaV2B3v9_P_dLPe18-3mD1BV0kZyjYqcZYqF
o4nHSg-UT33FLByWg"

# - Running the command


curl -s -i -X GET -H "authorization: Bearer ${oauth2_token}" \
-H "Content-Type: application/json; charset=UTF-8" \
"https://${api_fqdn}${url_path}" ; echo -e "\n\nCurl returned $?"

© 2021 Vlocity LLC, a Salesforce


company 266
Digital Commerce

# - Received response
HTTP/2 200
date: Mon, 10 Aug 2020 15:36:32 GMT
content-type: application/vnd.spring-boot.actuator.v2+json;charset=UTF-8
content-length: 586
x-amzn-requestid: 4c427148-f29e-4d34-b909-00594a31728d
x-amz-apigw-id: RD1r8GTePHcF4Yw=
x-amzn-lambda-integration-tag: 457b37f4-324c-4ba3-a405-e87945962669
vloc-op-cache: NOT_APPLICABLE
x-amzn-trace-id: Root=1-5f31697f-895fde273e05332417fd3f41

{"status":"UP","details":{"health":{"status":"UP","details":
{"app_name":"Vlocity V3 Edge API","version":"1.0-
SNAPSHOT","build_time":"2020-06-11T14:03:37Z","build_info":
{"commit":"f925489","buildInfo":"tblanchard@tblanchard","branch":"v17","date":"
2020-06-11T14:03:37Z"},"salesforce_last_contact":"","app_start_time":"2020-08-1
0T15:09:58.058Z","jks_expire_ms":"2022-03-22T09:16:52+0000"}},"redis":
{"status":"UP","details":
{"redis":"UP","hits":55516102,"misses":7363576,"evicted":0,"expired":178034,"hi
t_ratio":0.88,"con_active":0,"con_idle":0,"con_wait":0,"redis_pool_size":8}}}}

Understanding scopes with different endpoints and app-clients


In this section, we’ll explore how the resource protected by OAuth2 tokens can be accessed once we have
retrieved a valid oauth2 bearer token.

Not all app-clients give access to all resources; this allows you to share or use different app clients
depending on your users.

You will find the complete list of endpoints and scope access in the next section.

Example with the following 2 app clients

oauth2-myenv-ops scope access: ops and user


oauth2-myenv-user scope access: user

The url path /dc/app-status is accessible by all scopes (admin, ops, user).

The url path /dc/v3/catalogs/CATALOG_CODE/offers is accessible only by the admin and ops
scopes.

Procedure
cognito_oauth2_server="vl-dc-test.auth.eu-central-1.amazoncognito.com"

# We’ve created a second "Cognito Application Clients" with different scopes


# Retrieve and store a different JWT with each set of credentials
# Template curl call to retrieve an oauth2 token

© 2021 Vlocity LLC, a Salesforce


company 267
Digital Commerce

curl -s -X POST --user "${customer_app_key}:${customer_app_secret}" -H


'Content-Type: application/x-www-form-urlencoded'
"https://${cognito_oauth2_server}/oauth2/token?grant_type=client_credentials"

# "Cognito Application Clients" oauth2-myenv-ops with ops and user scopes


customer_app_key="6gi88ku...9imprk"
customer_app_secret="1dh9to...0j4iu2rn"

oauth2_token_ops=[...]

# "Cognito Application Clients" oauth2-myenv-user with only user scope


customer_app_key="7j2o4n...4u97ri"
customer_app_secret="10m997...inlejh"

oauth2_token_user=[...]

Responses received using the oauth2_token_user JWT from the oauth2-myenv-user app client:

• /dc/v3/catalogs/CATALOG_CODE/offers should return 200 unauthorized


• /dc/app-status should return 401

api_fqdn="api-test-cognito.platform.customer.dc.vloc-dev.com"

url_path="/dc/v3/catalogs/CATALOG_CODE/offers"
curl -s -i -X GET -H "authorization: Bearer ${oauth2_token_user}" -H
"Content-Type: application/json; charset=UTF-8" "https://${api_fqdn}$
{url_path}"
HTTP/2 200
date: Mon, 22 Jul 2019 14:13:38 GMT
content-type: application/json;charset=ISO-8859-1
content-length: 12332
x-amzn-requestid: e65a90de-ac8a-11e9-93cd-9d8d58cb662d
x-amzn-remapped-content-length: 12332x-amz-apigw-id: dOum1EZeFiAFg8Q=
x-amzn-trace-id: Root=1-5d35c492-6dbf677d7c12525a746c90fe;Sampled=0

[...body...]

api_fqdn="api-test-cognito.platform.customer.dc.vloc-dev.com"
url_path="/dc/app-status"
curl -s -i -X GET -H "authorization: Bearer ${oauth2_token_user}" -H
"Content-Type: application/json; charset=UTF-8" "https://${api_fqdn}$
{url_path}"

HTTP/2 401
date: Mon, 22 Jul 2019 14:13:32 GMT
content-type: application/json
content-length: 26

© 2021 Vlocity LLC, a Salesforce


company 268
Digital Commerce

x-amzn-requestid: e2bf9017-ac8a-11e9-b915-3f49f14f8dec
x-amzn-errortype: UnauthorizedException
x-amz-apigw-id: dOul5H4YFiAFsxQ=

{"message":"Unauthorized"}

Responses received using the oauth2_token_ops JWT from the oauth2-myenv-ops app client:

• /dc/v3/catalogs/CATALOG_CODE/offers should return 200


• /dc/app-status should return 200

api_fqdn="api-test-cognito.platform.customer.dc.vloc-dev.com"

url_path=""
curl -s -i -X GET -H "authorization: Bearer ${oauth2_token_ops}" -H
"Content-Type: application/json; charset=UTF-8" "https://${api_fqdn}$
{url_path}"

HTTP/2 200
date: Mon, 22 Jul 2019 14:30:16 GMT
content-type: application/json
content-length: 19
x-amzn-requestid: 3929aeba-ac8d-11e9-b4cd-11d6a4139ed9
x-amz-apigw-id: dOxCwFxMliAFZkw=

{"statusCode": 200}
api_fqdn="api-test-cognito.platform.customer.dc.vloc-dev.com"
url_path="/dc/app-status"
curl -s -i -X GET -H "authorization: Bearer ${oauth2_token_user}" -H
"Content-Type: application/json; charset=UTF-8" "https://${api_fqdn}$
{url_path}"

HTTP/2 200
date: Mon, 22 Jul 2019 14:32:38 GMT
content-type: application/json;charset=ISO-8859-1
content-length: 697
x-amzn-requestid: 8e0c7ccc-ac8d-11e9-b742-815dfc2c8abc
x-amzn-remapped-content-length: 697x-amz-apigw-id: dOxZBGEXliAFheg=
x-amzn-trace-id: Root=1-5d35c906-d3704ba9ad66385d1f8c14c6;Sampled=0

Troubleshooting and validation


Validation
If the application returns an HTTP status code other than 200 or 401, it may not be related with OAuth2
setup. For example 403, 404 and 500 HTTP status codes are generally not related with OAuth2 setup or
usage.

© 2021 Vlocity LLC, a Salesforce


company 269
Digital Commerce

Error code 401


Access denied, see next section “Common 401 HTTP status code and errors returned by oauth2 auth“ for
the different scenarios.

Error code 403


If you receive a code 403 from the DCG application, it generally means that there is a problem with the
configuration of your client. It can be any of the following:

• Wrong URL or path.


• Missing or misspelled headers.
• Client IP outside access list when allow list has been configured (endpoints are opened to the world by
default).

Error code 5xx


These errorsgenerally indicate an issue with the DC API request itself or the data sets retrieved. Please get
in touch with Customer Support or Professional Services to solve them.

Common 401 HTTP status code and errors returned by oauth2 auth

Expired token

# - declaring an expired token


oauth2_token="eyJraWQiOiJQbGkyTkJcL3NBczBabkVWaXdPS0ZhQ0JsbWpHcUxXblFOMlo0RmE1d
09Ecz0iLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI2Z2k4OGt1bmdkbmI0NDB0OWdpYzlpbXByayIsInR
va2VuX3VzZSI6ImFjY2VzcyIsInNjb3BlIjoiZGMtdGVzdC1hcGlcL2FkbWluIGRjLXRlc3QtYXBpXC
9yZWFkIGRjLXRlc3QtYXBpXC93cml0ZSIsImF1dGhfdGltZSI6MTU2MzM3NjMxNiwiaXNzIjoiaHR0c
HM6XC9cL2NvZ25pdG8taWRwLmV1LWNlbnRyYWwtMS5hbWF6b25hd3MuY29tXC9ldS1jZW50cmFsLTFf
elJHb2dweHc4IiwiZXhwIjoxNTYzMzc5OTE2LCJpYXQiOjE1NjMzNzYzMTYsInZlcnNpb24iOjIsImp
0aSI6IjFmYTU5YWQ1LTIwNDEtNDAyZS04NGIxLTExNjFjMWIxMmQ1YyIsImNsaWVudF9pZCI6IjZnaT
g4a3VuZ2RuYjQ0MHQ5Z2ljOWltcHJrIn0.awj5M4AvLXbL7TJrPIQguEUv2ifFurmZnqZraoNy5g9UP
365_vknj-
hJrgFzZ4OtOYlopQTdMgD-8m1n7vVqwUPfywr8qK2bJHOS8Dm9WycNypnsiFYC4eIDHjLd2526-
G63w6shTj4B53QmtpCzJF8lIvB9rGcsiQgxIlRNK9ZRSmc0opHZSLnts0xeLUvHCW5eb5Uys7eIY_MP
tc6GAMca0A6AObxADdklHMYLLagvEZdPPtj-A-
HG04jLuNCwcS3lpuhtmw7W0F0hgGhIIuI0ZQez7TxzdeaV2B3v9_P_dLPe18-3mD1BV0kZyjYqcZYqF
o4nHSg-UT33FLByWg"

# - Running the command


curl -s -i -X GET -H "authorization: Bearer ${oauth2_token}" -H "Content-Type:
application/json; charset=UTF-8" "https://${api_fqdn}${url_path}" ; echo -e "\n
\nCurl returned $?"

# - Received response
HTTP/2 401
date: Thu, 04 Jul 2019 12:35:15 GMT
content-type: application/json

© 2021 Vlocity LLC, a Salesforce


company 270
Digital Commerce

content-length: 44
x-amzn-requestid: 2cd359f0-9e58-11e9-a702-3b62603f614d
x-amzn-errortype: UnauthorizedException
x-amz-apigw-id: cTLUlGjdliAFbig=

{"message":"The incoming token has expired"}

Malformed token
Example: remove some characters from the end of the base64 oauth2 token, in effect corrupting the
signature.

# - Received response
HTTP/2 403
date: Mon, 22 Jul 2019 13:39:21 GMT
content-type: application/json
content-length: 27
x-amzn-requestid: 1c7a8f4b-ac86-11e9-b10d-e70db1458280
x-amzn-errortype: AccessDeniedException
x-amz-apigw-id: dOpleEcSFiAFdxg=

{"Message":"Access Denied"}

Invalid token
The token is not authorized to access this request (e.g. the scope of the Application Client does not grant
access to a specific resource).

# - Received response
HTTP/2 401
date: Wed, 03 Jul 2019 15:00:06 GMT
content-type: application/json
content-length: 26
x-amzn-requestid: 3ec26cce-9da3-11e9-8211-2d7edd287f91
x-amzn-errortype: UnauthorizedException
x-amz-apigw-id: cQNmlFoEFiAFppA=

{"message":"Unauthorized"}

See Also
Basic authorization

• https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization

Bearer token

• https://oauth.net/2/bearer-tokens/
• https://swagger.io/docs/specification/authentication/bearer-authentication/

© 2021 Vlocity LLC, a Salesforce


company 271
Digital Commerce

• Difference between OAuth2 ID token, Access token and Refresh token: https://docs.aws.amazon.com/
cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-with-identity-providers.html
• AWS Cognito advanced usage (e.g. refresh token): https://docs.aws.amazon.com/cognito/latest/
developerguide/token-endpoint.html

DCG Troubleshooting

NOTICE
The documentation in this and the following sections is applicable only for customers who
have purchased the Digital Commerce Gateway license. The instructions provided will not
work without the Digital Commerce Gateway license.

Troubleshooting helps you resolve errors you might encounter while using the Digital Commerce Gateway.

Health check endpoints used for validation and troubleshooting


# Digital Commerce application
/dc/app-status
/dc/app-diagnostic

# Cache Migration application


/cm/app-status
/cm/app-diagnostic

# Cache Management
/admin/cache/status

Troubleshooting Steps
Attempt to reproduce your call with a simple client, such as Curl or Postman. The example below uses the
Curl client on the command line (Mac OS X).

• Ensure you can successfully connect to the application:

NOTE
To obtain the OAuth2 JWT, please review the DCG Oauth2 GuideDCG OAuth2 Setup
and Usage.

auth_header=(obtain OAuth2 JWT)


curl -si -H "Content-Type: application/json; charset=UTF-8" \

© 2021 Vlocity LLC, a Salesforce


company 272
Digital Commerce

-H "authorization: Bearer ${auth_header}" \


"https://api.envName.{customer}.dc.vloc-dev.com/dc/app-status"

HTTP/2 200
date: Thu, 04 Feb 2021 13:20:56 GMT
content-type: application/json
content-length: 754
x-amzn-requestid: f54bddd7-7974-4130-8ee9-85c26ede1d99
access-control-allow-origin: *
access-control-allow-headers:
Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token
x-amz-apigw-id: aOMsrHPKFiAFh-g=
access-control-allow-methods: DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT
x-amzn-trace-id: Root=1-601bf4b7-190d8465428dce9b6de9e065;Sampled=0

HTTP Status Codes and Meanings


Depending on the returned HTTP status code, the error may be with the client configuration, the DCG
deployment, or the data itself.

HTTP Status code 200


The DCG application is properly configured and working. If the body contains an error, then the issue lies in
the configuration products, offers etc. in Salesforce.

Error code 401


Access denied. The credentials are invalid for this endpoint. Refer to the DCG OAuth2 Setup and Usage,

Error code 403


If you receive a code 403 from the DCG application, it generally means that there is a problem with the
configuration of your client. It might be one of the following:

• Wrong URL / path


• Missing or misspelled headers
• Client IP outside access list when allow list has been configured (endpoints are opened to the world by
default).

{"message":"Authorization header requires 'Credential' parameter.


Authorization header requires 'Signature' parameter. Authorization header
requires 'SignedHeaders' parameter. Authorization header requires existence
of either a 'X-Amz-Date' or a 'Date' header. Authorization=..."}

Error code 500


These codes generally indicate an issue with the DC API request itself or the data sets retrieved. You will
find the most common setup-related error messages below with typical resolution actions. If the error
message is not listed below, and the issue is not self explanatory, feel free to contact Customer Support or
Professional Services.

© 2021 Vlocity LLC, a Salesforce


company 273
Digital Commerce

case: {"message":null}
There is an issue with DCG Setup; please contact customer Support.

case: invalid_client - invalid client credentials


The JWT public certificate in the Salesforce Connected Application does not match the private key used by
DCG.

Solution: Ensure you have uploaded the correct public certificate for the environment (check issuer and
expiration date). You can ask Customer Support to re-send you the public certificate if you’re not sure.

Sample Message:

{"timestamp":1550215547892,"status":500,"error":"Internal Server
Error","message":"V3 API Exception : \"SFDC-Client: getOfferDetails API Error
\" error_description: \"V3 API Exception : \"invalid_client\"
error_description: \"invalid client credentials\"\"","path":"/dc/v3/catalogs/
CATALOG_ID/offers/OFFER_ID"}

case: invalid_grant - invalid assertion


The JWT public certificate is missing from the Salesforce Connected Application. Please retrieve the public
certificate sent by the Vlocity Customer Support team and add it to the connected application.Refer to the
DCG Setup guide.

Sample Message:

{"timestamp":1557490004994,"status":500,"error":"Internal Server
Error","message":"V3 API Exception : \"SFDC-Client: getOffers API Error \"
error_description: \"V3 API Exception : \"invalid_grant\" error_description:
\"invalid assertion\"\"","path":"/dc/v3/catalogs/PHONES/offers"}

case: invalid_grant - user hasn't approved this consumer


The Salesforce User username is invalid (for exanoke, a typo, ) or the Salesforce Org type is incorrect
(sandbox/test vs standard/login). Ensure the username and Salesforce Org type communicated are the
correct.

Sample Message:

{"timestamp":1570183058235,"status":500,"error":"Internal Server
Error","message":"V3 API Exception : \"SFDC-Client: getOffers API Error\"
error_description: \"V3 API Exception : \"invalid_grant\" error_description:
\"user hasn't approved this consumer\"\"","path":"/dc/v3/catalogs/PHONES/
offers"}

case: invalid_grant - audience is invalid


The OAuth2 JWT server URL is incorrect: contact Customer Support to confirm the Salesforce Org type
and domain configuration. Also see:

© 2021 Vlocity LLC, a Salesforce


company 274
Digital Commerce

• https://help.salesforce.com/articleView?id=remoteaccess_oauth_flow_errors.htm&amp;type=5
• https://salesforce.stackexchange.com/questions/214850/how-to-determine-the-correct-audience-and-uri-
when-using-oauth-2-0-json-web

Sample Message:

{..."invalid_grant" error_description: "audience is invalid"

case: invalid_client_id - client identifier invalid


There is an internal issue with the DCG applications configuration, please contact our customer support.

Sample Message:

{..."status_api_message":"V3 API Exception :


\"invalid_client_id\" error_description: \"client identifier invalid\""}

case: HTTP ERROR 404 - Could not find a match for URL
The DCG application is misconfigured. Contact Customer Support to review the Vlocity package installation
method and Salesforce Organization type.

Sample Message:

{"timestamp":1570717059452,"status":500,"error":"Internal Server
Error","message":"V3 API Exception : \"SFDC-Client: getOffers API Error\"
error_description: \"HTTP ERROR : Status Code: HTTP/1.1 404 Not Found,
Response: [{\"errorCode\":\"NOT_FOUND\",\"message\":\"Could not find a match
for URL\"}]\"","path":"/dc/v3/catalogs/SAMPLE_CATALOG/offers"}

© 2021 Vlocity LLC, a Salesforce


company 275

You might also like