CME Digital Commerce PDF-en
CME Digital Commerce PDF-en
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
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
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 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 Lightning Web Components With OmniScript support ..................... 250
Digital Commerce Web Components and SDK for Off-Platform Use ............................ 250
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.
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.
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.
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.
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.
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.
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.
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/*
/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
/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
/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 that use a context key must encrypt them.
/carts
Create Cart from Basket
POST /carts
/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
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
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:
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
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.
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.
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.
• 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).
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.
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.
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.
The illustration below shows a sample of the Populate API Cache screen:
• 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.
NOTE
The Populate API Cache screen shows only those catalogs marked as Active.
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
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.
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.
Note that you must include the appropriate Pricebook2 ID in the script shown here:
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.
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.
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:
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.
GetOffers Job
This job populates the cache with the list of offers for individual context combinations.
GetContainsOffers Job
This job populates the cache with the parent offers for individual offers.
GetPrices Job
This job populates the cache with the prices of products. This is used in GetOffers, GetContainsOffers
and GetOfferDetails jobs.
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).
See Also
• Running Digital Commerce Cache Jobs Remotely with API
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.
• 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.
/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:
1. In your sandbox org's UI, click Setup and search for Apex Jobs.
2. Click Apex Jobs.
See Also
• ,Running Maintenance and Digital Commerce Cache Jobs Remotely
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.
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.
• 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).
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:
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.
• 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.
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
• 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.
• 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.
• 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.
• 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.
• 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.
• Ensure that you clear the cache before running the GetOffers batch job (CME Fall '18).
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.
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.
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.
• 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.
• 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
• 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:
/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.
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.
• 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.
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"
},
"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,
"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": [
{
"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"
}
{
"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:
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.
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.
Body
{
"offer": "TelcoResidential",
"basketAction": "AddWithNoConfig"
}
Body
{
"offer": "TelcoResidential",
"basketAction": "AddWithNoConfig",
"multiTransactionKey": "3d719d4a3b14cea4187ea9a5332cff0e"
}
"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",
"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,
"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
=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",
"error": "OK"
}
NOTE
This example has been truncated.
{"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.
DCAPIParamsImplementation
fetchAPIParamsOverride
Input
Output
Sample Implementation
/*
* 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() {}
/*
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;
}
}
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.
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.
• item
• itemDetails
• priceResult
• catalogCtxEligibilityResult
• cartContext
• eligibilityContext
• hierarchyResult
• itemConfig
• orderConfiguration
• item
• itemDetails
• priceResult
• catalogCtxEligibilityResult
• cartContext
• eligibilityContext
• hierarchyResult
• itemConfig
• orderConfiguration
• dataProfileResultItem
• ruleSetCombinationResultItem
• catalogCtxQualificationMap
• item
• itemDetails
• priceResult
• catalogCtxEligibilityResult
• cartContext
• eligibilityContext
• hierarchyResult
• itemConfig
• orderConfiguration
• dataProfileResultItem
• ruleSetCombinationResultItem
• catalogCtxQualificationMap
• groupContext
• basketWrapper
• assetReferenceKey
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.
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.
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.
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.
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.
• 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)
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.
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:
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.
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.
• 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.
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).
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).
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.
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
https://www.getpostman.com/oauth2/callback
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:
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.
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
NOTE
If the API call does not authorize transactions, check that the IP restrictions of the APP are
set correctly.
After filling in the catalog name click Send. The results of the API call are displayed in a Postman window.
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.
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:
Note that the response structure is slightly different and must be trimmed manually. Сopy the full response
from GetOfferDetails:
{
"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.
Modify Basket
You can modify the contents of the basket in several ways as shown in the sections here.
Copy the cartContextKey from the response; it should resemble the following:
"cartContextKey": "c96443b4c5ad00c2f6820a9d8b37f5cb"
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.
Use the values from the actions node to form the request body:
{
"bundleContextKey": "<string>",
"lineItemKey": "<string>",
"basketAction": "<string>"
}
{
"bundleContextKey": "<string>",
"lineItemKey": "<string>",
"basketAction": "<string>",
"Quantity": "<string>",
"attributeCategories": "<string>"
}
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
NOTE
If the Swagger does not render, refresh this page.
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.
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.
• (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.
Examples
In the examples that follow, braces around items ( { } ) indicate replaceable parameters that you specify.
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.
Method: GET
API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
offset=0&pageSize=20
Method: GET
API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
offset=20&pageSize=20
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.
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.
Method: GET
API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
sortby=vlocity_cmt__SequenceNumber__c_ASC
Method: GET
API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
sortby=vlocity_cmt__SequenceNumber__c_ASC,Name_DESC&context={"Status":"Active"}
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.
Examples
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.
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.
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"]}
{"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.
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.
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
Rules Supported
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.
• 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.
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
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
API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
sortby=vlocity_cmt__SequenceNumber__c_ASC&context={"accountId":"{0016A0000053kH
N"}&loggedIn=true
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.
Method: GET
/v3/catalogs/{catalog_code}/offers?contains={product_code}
Example
GET /services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
contains={offer_code}
Method: GET
/v3/catalogs/{catalog_code}/offers?
contains={product_code}&context={"accountId":"{account_ID}"}&loggedIn=true
Example
GET /services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers?
contains={offer_code}?context={"accountId":"{account_ID}"}&loggedIn=true
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
NOTE
Qualification/Context rules for price list entries are supported for known users and not for
anonymous users.
Prerequisites
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 /v3/catalogs/{catalog_code}/offers/{offer_code}
Examples
API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers/{product_code}
API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers/
{promotion_code}
Examples
API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers/
{product_code}?context={"accountId":"0016A0000053kHN"}&isloggedIn=true
API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/offers/
{product_code}?context={"accountId":"0016A0000053kHN"}&isloggedIn=true
The configured product details are cached so that subsequent requests for the same configuration are
retrieved with the data in the current cache layer.
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.
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.
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.
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}
POST
/services/apexrest/vlocity_cmt/v3/catalogs/Mobiles/offers/iPhone8Offer?
forceinvalidatecache=true
NOTE
The forceinvalidatecache parameter is used only for debugging purposes. When
enabled by a server setting, forceinvalidatecache=true forces a cache refresh.
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.
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.
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).
• 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.
GET /services/apexrest/vlocity_cmt/v3/catalogs/Mobile/basket/
bdbe113c6fd2d90835372d104f7a4a8b
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
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
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.
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.
• 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
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": {}}}}
POST /v3/catalogs/{catalog_code}/basket
Method: POST
API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket
Request Body:
{"offer":"iPhone8","basketAction":"AddWithNoConfig"}
Method: POST
API:
/services/apexrest/vlocity_cmt/v3/catalogs/Mobiles/basket/
50ba987c870c64774e24c27787288650
Request Body:
{"basketAction":"AddAfterConfig","productConfig":"{\"offerDetails\":{\"Offer\":
{\"priceResult\":...}
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket?
context={"accountId":"{account_ID}"}&inloggedin=true
Method: POST
API:
/services/apexrest/vlocity_cmt/catalogs/{catalog_code}/basket?
context={"accountId":"{account_ID}"&isloggedin=true
Request Body:
{"offer":"offer_code","basketAction":"AddWithNoConfig"}
Method: POST
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"}
{
"basketAction":"AddAfterConfig",
"productConfig":
"offerDetails":<GetOfferDetails response here>
}
Method: POST
API:
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket?
context={accountId":"{account_ID}"&isloggedin=true
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.
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:
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.
Rules Supported
• Qualification Rules for Products
• Qualification Rules for Promotions
• Response contains base prices only (see Product Pricing)
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
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
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"}
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.
If the API call validation fails, the OfferDetails structure returns with an error message.
Example:
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.
POST
/services/apexrest/vlocity_cmt/v3/catalogs/{catalog_code}/basket
Request body:
{"basketAction":"AddWithNoConfig","offer":"iPhone8Offer",
"transactionKey":"111123mx12223232000"}
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.
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"}
Request body:
{
"parentLineItemKey":"parent line item key",
"parentHierarchyPath":"parent hierarchy path,
"offer":"Family",
"basketAction":"addWithNoConfig",
"bundleContextKey":"bundle context key"
}
Request body:
{
"basketAction":"deleteFromBasket",
"lineItemKey":"line_item_key",
"bundleContextKey":"bundle_context_key"
}
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).
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.
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"
}
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"}
Method: PUT
API:
/services/apexrest/{namespace}/v3/catalogs/{catalog}/basket/{cart_context_key}
Request Body:
{
"lineItemKey":"xxxxxxxxxxxx",
"Quantity":"2"
"bundleContextKey":"xxxxxxxxxxxxx"
}
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"
}
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,
"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,
"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
}
]
}
}
]
}
}
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
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.
Example
When the basket is empty, add an item to a basket without configuring.
Method:
POST
URL:
/services/apexrest/cacheableapis/v3/catalogs/Mobiles/basket
Post body:
{"offer":["iPhone11","iphone12"],"basketAction":"addWithNoConfig"}
{
"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": {
"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
"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
URL:
/services/apexrest/cacheableapis/v3/catalogs/Mobiles/basket
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": "{}",
"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.
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:
The fields in the table below are checked when performing effectivity checking:
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
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 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
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
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
{
"totalSize": 1,
"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",
"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"
]
},
"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
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
Conditions - the response will be similar for both the cases mentioned below
Request URL/services/apexrest/dc_108/v3/catalogs/DTHCatalog/basket/
f4f58e16f583e8843ab5cc7c101b864e?
context={"accountId":"AccountId2"}&isloggedin=true
Request Parameter
{"basketAction":"AddWithNoConfig","offer":"10%OffDTH"}
Response
Once the basket is ineffective, further basket operations (except getBasket) return a response similar to the
response shown below.
Response
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.
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.
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));
}
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
"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"
}
},
"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"
},
{
"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,
"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",
"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,
"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",
"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",
"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",
"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",
"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,
"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,
For information and examples about using the Basket APIs, see: Basket Operations.
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.
• 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.
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"}
https://{salesforce_domain}/services/apexrest/vlocity_cmt/v3/carts
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",
Output
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"}
},
{"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
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
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]"
}
}
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:
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.
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:
For information about reducing the amount of data returned by basket operations, see Use Trim Mode to
Decrease Overhead.
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
For more details about which parameters correspond to the POST body, refer to the API documentation.
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');
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');
The contains parameter in the requestURL is passed as productCode in the input map.
Additional Parameters
String methodName;
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):
Additional Parameters
//Use the key of the bundle under which the line to be deleted
input.put('lineItemKey', 'lineItemKey');
Additional Parameters
// validate and price
input.put('validate', false);
input.put('price', false);
//Use the key of the bundle under which the line to be deleted
input.put('lineItemKey', 'lineItemKey');
//Quantity to be updated
input.put('context','{"accountId":"accountId1", "contractId":"contractId1"}');
input.put('isloggedin','true');
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
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');
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');
Additional Parameters
//Old format:
input.put('catalogCode', 'Mobiles');
input.put('accountId', '001f200001eSlhe');
input.put('JSONResult', '{{AddTobasketResponse}}');
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.
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.
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.
The SDK supports Node.js module delivery. Each module has its own context, cannot interfere with other
modules, or interfere with global scope.
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);
• 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
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
• signOutUser
• Signs out the user from the ServerSDK.
For reference information about the Spring '20 SDK release see https://docs.vlocity.com/devdocs/
archive/sdk/107.0/.
Example Code
// Instantiate DigitalCommerceConfig for anonymous user
const digitalCommerceConfig =
VlocitySDK.digitalcommerce.createConfigForAnonymousUser();
OR
// To override the default custom api URL with your custom api URL
this.digitalCommerce.apiURL = "YOUR_CUSTOM_API_URL"; // use your custom URL
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.
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.
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:
//
```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 => {
// 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;
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:
Example Code
// Instantiate DigitalCommerceConfig for anonymous user
const digitalCommerceConfig =
VlocitySDK.digitalcommerce.createConfigForAnonymousUser();
OR
// To override the default custom api URL with your custom api URL
this.digitalCommerce.apiURL = "YOUR_CUSTOM_API_URL"; // use your custom URL
Note:
digitalCommerce is a Singleton object. Calling
getInstance(digitalCommerceConfig) repeatedly will return the same instance
instantiated the first time when getInstance(digitalCommerceConfig) was called.
})
.catch(error => {
Logger.info("get offers anonymous user rest call failed" + error);
});
.catch(error => {
Logger.info("get promotions anonymous user rest call failed" + error);
});
//
```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 => {
Logger.info("addToCart login user dual fail: " + error);
});
// 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;
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:
);
})
.catch(error => {
Logger.info(
"addToBasket with basketAction=DeleteChildProduct for anonymous user
rest call failed" +
error
);
});
);
})
.catch(error => {
Logger.info("updateItemsInCart action failed: ", error);
});
Logger.info(
"Vlocity digital commerce updateBillingDetails: " +
JSON.stringify(response)
);
})
.catch(error => {
Logger.info("updateBillingDetails apexrest call failed" + error);
});
.catch(error => {
Logger.info("saveCart apexrest call failed" + error);
});
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:
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:
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:
Example Code
// Instantiate DigitalCommerceConfig for anonymous user
const digitalCommerceConfig =
VlocitySDK.digitalcommerce.createConfigForAnonymousUser();
OR
sessionToken);
// To override the default custom api URL with your custom api URL
this.digitalCommerce.apiURL = "YOUR_CUSTOM_API_URL"; // use your custom URL
Note:
digitalCommerce is a Singleton object. Calling
getInstance(digitalCommerceConfig) repeatedly will return the same instance
instantiated the first time when getInstance(digitalCommerceConfig) was called.
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);
});
```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);
});
```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 => {
Logger.info("addToCart login user dual fail: " + error);
});
// 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;
error
);
});
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:
);
})
.catch(error => {
Logger.info(
"addToBasket with basketAction=AddChildProduct for anonymous user rest
call failed" +
error
);
});
);
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);
});
.catch(error => {
Logger.info("get cart items anonymous user rest call failed" + error);
});
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:
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:
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.
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.
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:
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.
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.
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.
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.
• /fetchtranslations
• /getoffers
• /getfilteredofferslist
• /getoffer
• /validateoffer
• /getselectedoffer
• /addtocart
• /getpromotions
• /updateitemsincart
• /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.
<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
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.
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.
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.
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:
$ 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:
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
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://<your-
app-name>.herokuapp.com/v1/serversdk/getcurrencydetails. The default currency
details are displayed.
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.
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:
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
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.
this.digitalCommerceSDK = digitalCommerceSDKInstance().digitalCommerce;
<c-dc-sample-app
checkout-api-url=""
secure-server-api-request-credentials=""
checkout-payment-url=""
enable-proxy-sdk=""
auth-configuration=""
>
</c-dc-sample-app>
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.
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.
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/.
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
You can generate updated NDS files using the following command. Then, upload the file as a static
resource to your org:
After uploading the file as a static resource, configure your Custom Settings with the static resource URL.
Refer to the following figures:
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.
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.
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.
For the Spring '20 version of the Digital Commerce Web Components developer reference see: https://
docs.vlocity.com/devdocs/archive/wc/107.0/
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.
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.
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.
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.
• ContractCluster: In the following setup for the ContractCluster dimension, we retrieve the
Contract.Cluster_di_adesione__c field from the Order object.
• AccountSla: In the following setup for the AccountSla dimension, we retrieve the Account.vSLA__c
field from the Order object.
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:
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:
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.
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.
The ContractBillingCluster rule condition contains a dimension value. The rule expression is evaluated
normally as follows:
• 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.
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.
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.
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).
• 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.
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.
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.
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.
Depending on your requirements, you can download the modules best suited to your particular needs. The
choices are as follows:
• 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.
• 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.
• 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.
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.
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.
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 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),
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.
• 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
Example
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.
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.
5. Click Manage Profiles and select the profile you selected above (System Administrator is
recommended) from the list.
Validation
In Manage App > Connected Apps, find the application you just created and ensure the settings are as
below:
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>
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.
NOTE
It is not necessary to send either the Salesforce password for the username or the
Connected Application API Oauth Consumer Secret.
You can display the certificate’s properties using the following command (subject, issuer and
expiration date):
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
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:
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
# 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]
/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
• 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).
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.
customer_app_secret="1dh9t...4iu2rn"
"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"}
Procedure
As depicted in action 3 of the diagram:
# 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:
# - 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"
# - 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}}}}
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.
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"
oauth2_token_ops=[...]
oauth2_token_user=[...]
Responses received using the oauth2_token_user JWT from the oauth2-myenv-user app client:
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
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:
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
Common 401 HTTP status code and errors returned by oauth2 auth
Expired token
# - Received response
HTTP/2 401
date: Thu, 04 Jul 2019 12:35:15 GMT
content-type: application/json
content-length: 44
x-amzn-requestid: 2cd359f0-9e58-11e9-a702-3b62603f614d
x-amzn-errortype: UnauthorizedException
x-amz-apigw-id: cTLUlGjdliAFbig=
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/
• 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.
# 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).
NOTE
To obtain the OAuth2 JWT, please review the DCG Oauth2 GuideDCG OAuth2 Setup
and Usage.
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
case: {"message":null}
There is an issue with DCG Setup; please contact customer Support.
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"}
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"}
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"}
• https://help.salesforce.com/articleView?id=remoteaccess_oauth_flow_errors.htm&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:
Sample Message:
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"}