Skip to content

Latest commit

 

History

History
493 lines (389 loc) · 29.5 KB

Usage-Guide.md

File metadata and controls

493 lines (389 loc) · 29.5 KB

Usage Guide

This user guide covers more detailed instructions for Xperience By Kentico (XbyK) integration to Kentico Xperience 13 (KX 13) E-Commerce features to create E-Commerce solution on XbyK.

Table of contents

  1. Store API (Kentico Xperience 13)
  2. K13 Ecommerce integration (Xperience by Kentico)
  3. Dancing Goat example - setup
  4. Scenarios

Store API (Kentico Xperience 13)

Store API (library Kentico.Xperience.StoreApi) is a REST API which exposes KX 13 E-Commerce features, and allows them to be consumed from other sources. (primary intended for Xperience By Kentico, but you are completely free to use it any way you want).

API is exposed via Swagger (Open API 3 standard) on relative path /swagger/storeapi/swagger.json

NOTE: To list all current endpoints with their request and response formats, run example project Kentico13_DancingGoat and go to address [Project_URL]/swagger with Swagger UI tool.

We recommend to use this API in combination with Kentico.Xperience.K13Ecommerce library for XByK applications, because there are services to simplify e-commerce integration (such as IShoppingService) and NSwag API client is already generated there.

Authentication

API is intended to use with OAuth 2.0 client credentials flow, when ClientId and ClientSecret are shared between client application (XByK) and KX 13 application. Access tokens are generated in JWT standard (from endpoint /api/store/auth/token). Token request can contain user_email parameter to identify for which user token is generated. The endpoint validates that the user for given email exists, and then embeds it into the token as sub and name claims. All subsequent requests need to be sent with Bearer token in Authorization header.

All API controllers are secured by custom authorization attribute and filter AuthorizeStore. This filter checks user claim and when this user exists and is enabled, is then assigned to MembershipContext.AuthenticatedUser. When specific user email isn't provided, AuthenticatedUser remains as public user.

Products

These endpoints have prefix /api/store/products and cover these domains:

  • Getting product pages based on parameters (returned data can be customized)
  • Getting all product categories for given culture
  • Getting prices and inventory info

Shopping cart

These endpoints have prefix api/store/cart and cover work with current shopping cart. Many actions correspond to functionality in KX 13 CMS.Ecommerce.IShoppingService (adding/removing items to cart, set delivery data, creating order etc.). All endpoints use ShoppingCartGUID parameter sent in HTTP header to identify current shopping cart. Management of this identifier is automatically handled in client (XByK) applications by the Kentico.Xperience.K13Ecommerce package.

All calls internally use IShoppingService with some notable customizations to handle retrieving cart in RESTful manner. These customizations are applied only on request with api/store prefix to not break default e-commerce functionality:

  • Custom IShoppingCartCache - session usage is removed, cache key for cart's cache token identifier (jti claim) is used instead. So cache duration is also determined by current token expiration time and very short time for token expiration can cause more frequent retrieving from database.
  • Custom ICurrentShoppingCartService - session and cookie access is removed, current shopping cart is retrieved from ShoppingCartGUID header value.

In all API responses current ShoppingCartGuid is always sent to ensure correct shopping cart is always saved on client application (XbyK) in cases like user log in/log out.

Discounts

All KX 13 discounts and coupon codes are supported.

Currencies

By default shopping is calculated in main site's currency. Cart's currency can be changed via api/store/cart/set-currency. All enabled currencies can be retrieved from api/store/site/currencies.

Current known limitations

Not all cart's data can be changed, e.g. custom data (properties like ShoppingCartCustomData) cannot be currently changed via API.

Orders

  • Endpoint api/store/order/list for retrieving list of orders for current customer based on request (supports paging)
  • Endpoint api/store/order/admin/list for retrieving list of orders (for all customers) based on request (supports paging) to display in XbyK administration (supports paging)
  • Endpoint api/store/order/detail/{orderID} for retrieving order details for the current customer. If the order belongs to another customer, no order is retrieved
  • Endpoint api/store/order/admin/detail/{orderID} for retrieving order details (without verifying if the order belongs to the current customer)
  • Endpoint api/store/order/statuses/list for retrieving all order statuses
  • Endpoint api/store/order/update for updating orders (update order status, set order payment, etc.). Primarily intended to be used via IOrderService available in the integration API

Customers

  • Endpoint api/store/customer/addresses for retrieving current customer's addresses
  • Endpoint api/store/customer/admin/addresses for retrieving addresses of specific customer to display in XbyK administration

Store site

  • Endpoint api/store/site/cultures returns all enabled site cultures
  • Endpoint api/store/site/currencies returns all enabled site currencies

Members synchronization

When member is created on XbyK (for example when a new customer registers), this member needs to be synchronized to KX 13 as a user. It is subsequently used for API authorization (member/user identity is generated in JWT). Before you start using the Store API, you need to synchronize all website members between the client (XbyK) and your KX 13 application. Complete synchronization is currently not a part of this solution.

  • Endpoint api/store/synchronization/user-synchronization can be used to create a new user in KX 13
    • The client application (XbyK) should use this to ensure that all new members are synchronized to KX 13. This is necessary when client's e-commerce solution allows visitors to sign in. KX 13 users are created with random generated password and are used only for API authorization and assigning to MembershipContext.

NOTE: Please implement double opt-in mechanism for user registration to ensure the users are paired safely between XbyK and KX 13. The current Dancing Goat example does not have a double opt-in mechanism implemented, but we recommend it as a best practice.

Current known limitations

Roles synchronization isn't currently supported. We assume website members to be already synchronized between client (XbyK) and KX app before starting using this API.

Setup

How to set up your Kentico 13 ASP.NET Core application:

Add this package to your Kentico Xperience 13 ASP.NET.Core application (live site or create standalone application when your KX 13 live site is not running)

dotnet add package Kentico.Xperience.StoreApi
  1. Set up your own settings for Store REST API authentication (based on JWT and OAuth client credentials flow)
{
  "CMSStoreApi": {
    "Jwt": {
      "Key": "YourSecretKeyForAuthenticationOfApplicationMustBeAtLeast64CharsLong",
      "Issuer": "yourCompanyIssuer.com",
      "Audience": "XbyK-DancingGoat",
      "TokenExpiresIn": 60
    },
    "ClientId": "3ef7fe1b-696c-4afa-8b56-d3176b7bea95",
    "ClientSecret": "********************"
  }
}

Setting description

Setting Description
Jwt:Key Your unique secret key for signing JWT access tokens (at least 64 chars long)
Jwt:Issuer Fill arbitrary value for this claim (as your domain)
Jwt:Audience Fill arbitrary value for this claim to identify recipients
Jwt:TokenExpiresIn Duration in minutes for token validity
ClientId Fill your value, used for getting token (client credentials OAuth 2.0 flow)
ClientSecret Fill your value, used for getting token (client credentials OAuth 2.0 flow)
  1. Add Store API services to application services and configure Swagger
// Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // ...
    //Store API registration
    services.AddKenticoStoreApi();
    //Registers Swagger generation
    services.AddKenticoStoreApiSwagger();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment environment)
{
    //Registers Swagger endpoint middleware and swagger UI
    app.UseStoreApiSwagger();
}

or in Minimal API approach:

// Program.cs

var builder = WebApplication.CreateBuilder(args);

// ...
//Store API registration
builder.Services.AddKenticoStoreApi();
//Registers Swagger generation
builder.Services.AddKenticoStoreApiSwagger();

var app = builder.Build();

//Registers Swagger endpoint middleware and swagger UI
app.UseStoreApiSwagger();

app.Run();

Library matrix

Library Xperience Version Library Version NET version
Kentico.Xperience.StoreApi >= 13.0.131 1.0.0 >= .NET 6

KX 13 E-Commerce integration in Xperience By Kentico

Library Kentico.Xperience.K13Ecommerce encapsulates Store API calls and exposes several services for KX 13 e-commerce integration on XByK:

  • IProductService
    • Listing products based on parameters, product categories, prices and inventory
    • Service is used e.g in product synchronization or in product list where prices are retrieved for listed products.
  • IShoppingService
    • Actions on shopping cart and order creation:
      • Adding/removing products to/from cart
      • Updating product quantity in cart
      • Adding/removing coupon codes
      • Retrieving cart content and delivery details
      • Retrieving current customer
      • Set shipping option and payment option
      • Set customer, billing and shipping address
      • Validate cart items
      • Change cart's currency
      • Create order
    • Service saves and retrieves the shopping cart identifier (ShoppingCartGuid) to session (uses IShoppingCartSessionStorage) and to browser cookie (uses IShoppingCartClientStorage)
    • See CheckoutController in Dancing Goat example where checkout process is implemented using this service.
  • ICustomerService
  • IOrderService
    • List orders from all customers (for implementing order listings in the administration)
    • List orders for the current customer (based on the request context)
    • Retrieve order details for the current customer (only for orders that belong to the customer)
    • Retrieve order details for administrators (without verifying if the order belongs to the current customer)
    • List all order statuses
    • Update existing orders (order status, payment, etc.)
  • ISiteStoreService
  • ICountryService
    • Countries and states - these objects are already on XByK, there is no Store API call

      NOTE: Countries and states are not synchronized between KX 13 and XbyK. As a result, any modifications or additions to countries and states in KX 13 are currently not supported.

Products synchronization

Library also implements product synchronization to Content hub. These are 3 entities synchronized to reusable content items:

  • Products - Content type K13Store.ProductSKU
    • All products associated with product pages are synced. Standalone SKUs synchronization can be set via StandaloneProductSync setting.
  • Product variants - Content type K13Store.ProductVariant
    • All products variant for parent products
  • Product images - Content type K13Store.ProductImage
    • Main SKU images (from SKUImagePath column)

The synchronization runs in a background thread worker periodically and can be disabled (ProductSyncEnabled setting). Interval can be set in minutes (ProductSyncInterval setting). Synchronized data is updated when source value changes, so data cannot be edited in XbyK safely, but new custom or reusable fields can be added and edited safely. You can decide, whether include standalone SKUs or not (StandaloneProductSync setting).

You can select content item folders where content items are synchronized. Content item folders can be selected independently for each content type in XbyK administration UI. Go to Configuration -> K13Ecommerce -> K13Ecommerce settings. Content items are not moved if root folder is selected.

Once the folder is changed, only new content items are moved to this folder (to not break possible manual structure for old items)

XbyK K13Ecommerce settings

With enabled product page synchronization (see How to enable automatic product page synchronization?) content type K13Store.ProductPage (in chosen website channel) is created for every content item of type K13Store.ProductSKU.

No price data is synced, because catalog prices need calculator evaluation in context of user's cart and standalone requests via IProductService are required.

Limitations

Products are currently synchronized only in default content culture. Same language needs to be enabled in XByK.

Activity logging

When you are using IShoppingService for shopping cart actions, these actions are logged to XByK Online marketing activities for current contact:

Activity display name Activity name Description
Product added to shopping cart custom_productaddedtoshoppingcart Product added to cart
Product removed from shopping cart custom_productremovedfromshoppingcart Product removed from cart
Purchased product custom_purchasedproduct Purchased product (after order is created)
Purchase custom_purchase Order created

You need to ensure these custom activity types are created (via CI restore - see Setup section or manually).

Email notifications

Currently all e-commerce email notifications are sent from KX 13 application. You need to have configured email sending and e-commerce email templates.

Product listing widget

Product listing widget

Setup

Add these packages to your XbyK application using the .NET CLI

dotnet add package Kentico.Xperience.K13Ecommerce
dotnet add package Kentico.Xperience.Store.Rcl
  1. Fill settings to connect your Kentico Xperience 13 instance
{
  "CMSKenticoStoreConfig": {
    "StoreApiUrl": "http://dev.dancinggoat.com:65375",
    "ClientId": "3ef7fe1b-696c-4afa-8b56-d3176b7bea95",
    "ClientSecret": "********************",
    "ProductSyncEnabled": true,
    "StandaloneProductSync": true,
    "ProductSyncInterval": 10
  }
}

Setting description

Setting Description
StoreApiUrl Fill main URL (without path) to KX 13 live app instance
ClientId Fill same value which is defined on KX 13 side
ClientSecret Fill same value which is defined on KX 13 side
ProductSyncEnabled If true, product synchronization is enabled
StandaloneProductSync If this setting along with ProductSyncEnabled is true, standalone SKUs are synchronized as well (if ProductSyncEnabled is false, no products are synchronized).
ProductSyncInterval Interval in minutes specifies how often synchronization is running
  1. Add K13Ecommerce library to the application services
// Program.cs

// Registers Kentico Store API and services for e-commerce support
builder.Services.AddKenticoStoreServices(builder.Configuration);
  1. For the simplest scenario: copy product listing widget from Dancing Goat example project to your project and configure properties to display products from Kentico 13. Sample widget is located here.
  2. For more complex scenario with full e-shop, you can be inspired by implementation of Dancing Goat sample Store on XbyK. Check Dancing Goat example - setup for detailed instructions to configure categories, products and cart steps.
  3. Restore CI repository files to database (reusable content types, custom activities). CI files are located in .\examples\DancingGoat-K13Ecommerce\App_Data\CIRepository\ and you need to copy these files to your application.
dotnet run --kxp-ci-restore
  1. Start to use on your live site

Library matrix

Library Xperience Version Library Version
Kentico.Xperience.Ecommerce.Common >= 29.0.1 1.0.0
Kentico.Xperience.K13Ecommerce >= 29.2.0 1.0.0
Kentico.Xperience.Store.Rcl >= 29.2.0 1.0.0

Dancing Goat example - setup

  1. Go to ./examples/DancingGoat-K13Ecommerce folder and run CI restore for content types and cart pages:
dotnet run --kxp-ci-restore

All content types and custom activities for e-ecommerce events are created.

Except reusable content types used in product synchronization, additional content types for pages are restored:

These content types are restored for Store page, categories and product detail pages:

  • K13Store.StorePage - Main store page
  • K13Store.CategoryPage - Content type for category pages (with linking product pages)
  • K13Store.ProductPage - Content type for product detail page - only linking product SKU from content hub

For checkout process these content types (for pages) are restored:

  • K13Store.CartContent - used for the shopping cart first step
  • K13Store.CartDeliveryDetails- used for the shopping cart second step
  • K13Store.CartSummary - used for the shopping cart third step
  • K13Store.OrderComplete - used for thank you page
  1. Start sample KX 13 Dancing Goat application (Kentico13_DancingGoat in .\examples) configured with your own database

  2. Start Xperience By Kentico Dancing Goat application (DancingGoat in .\examples) configured with your own database.
    Let the product synchronization finish. Check K13-Store product synchronization done. in debug console or check Event log for errors.

  3. Create pages for Store:

    1. Store page (of type K13Store - Store page)
    2. Product pages (of type K13Store - Product page) - for each page select corresponding Product SKU from content hub (or use automatic synchronization as described here).
    3. Categories pages (of type K13Store - Category page) - for each page select product pages in category
    4. Cart/Checkout steps pages
      1. Cart content page
      2. Cart delivery details page
      3. Cart summary page
      4. Order complete page

Scenarios

How to add products onto website?

The product synchronization creates reusable content items for products, product variants and product images. It's on you how to display these product on your website. But you can use the approach from Dancing Goat example:

  1. Create pages for products (e.g. in folder structure) in your web site channel and link them to product content items (of type K13Store.ProductSKU). You can use K13Store.ProductPage content type for this. Link product pages
  2. Create Store page (use K13Store.StorePage content type) which represents entry point for your store. You can display here main categories and Hot tip products. Skip this step when you don't need this type of page.
  3. Create pages for categories (use K13Store.CategoryPage content type) and select product pages in Products in category field. Products in category

How to display products on your website?

  1. For displaying products on your live site, see StoreCategoryController on Dancing Goat example site. Products pages are retrieved for current category and current prices are retrieved for these products via IProductService.
  2. You can also to consider using Product listing widget for simple scenarios like Landing pages with product offer.

How to implement shopping cart / checkout process?

  1. Create pages representing cart steps
    1. Cart content page
    2. Cart delivery details page
    3. Cart summary page
    4. Order complete page
      Set Cart next steps / Cart previous step fields for each step page. Cart steps This approach has the advantage that you can use page builder features for each step.
  2. For shopping cart and checkout process implementation, see CheckoutController

Here are links for some specific parts of shopping cart:

How to enable automatic product page synchronization?

In XbyK administration UI go to Configuration -> K13Ecommerce -> Page Path mapping rules. Here you can manage rules for automatic creating product pages (K13Store.ProductPage) from synchronized content items of type K13Store.ProductSKU.

Synchronization is disabled when rules are empty.

XbyK mapping rules

By creating mapping rule you can specify how KX 13 NodeAliasPath (stored in content item) should be mapped into XbyK page path. Rules are ordered. The first rule that matches NodeAliasPath will be used. You can use wildcards when creating mapping rules. Each rule can contain any number of wildcards (with arbitrary names). See the examples below for details.

The synchronization automatically creates all required folders in the website channel content tree to achieve the desired XbyK page path structure.

Examples:

  1. Direct structure copying from KX 13 to XbyK:

    • Mapping rule:
      • K13 NodeAliasPath: /{Product}
      • XbK Page path: /{Product}
      • Channel name: Dancing Goat Pages
    • The Product wildcard will store the whole NodeAliasPath and as such will be mapped to tree path of created product page. E.g.:
      • /DancingGoatStore/Coffee/Arabica -> /DancingGoatStore/Coffee/Arabica
      • /DancingGoatStore/Grinders/Electric/Grinder_GAGGIA_MD_15 -> /DancingGoatStore/Grinders/Electric/Grinder_GAGGIA_MD_15
  2. Copying only items which are placed in the category folder as a subfolder of DancingGoatStore. Items which are not placed in DancingGoatStore could be mapped e.g. in another folder or website channel:

    • Mapping rule:
      • K13 NodeAliasPath: /DancingGoatStore/{Category}/{Product}
      • XbK Page path: /Store/Products/{Category}/{Product}
      • Channel name: Dancing Goat Pages
    • The Category wildcard will store the first folder after "DancingGoatStore", Product will be rest of path. E.g.:
      • /DancingGoatStore/Coffee/Arabica -> /Store/Products/Coffee/Arabica
      • /DancingGoatStore/Grinders/Electric/Grinder_GAGGIA_MD_15 -> /Store/Products/Grinders/Electric/Grinder_GAGGIA_MD_15
      • /DancingGoatStore/Paper_Filter would not be matched (as the path is not compound from at least two parts of path after "DancingGoatStore")
      • /AnotherStore/Coffee/Robusta would not be matched (as the path does not start with "DancingGoatStore")
  3. When creating a flattened structure, it is possible to omit part of the NodeAliasPath (only once):

    • Mapping rule:
      • K13 NodeAliasPath: /.../{Product}
      • XbK Page path: /Store/{Product}
      • Channel name: Dancing Goat Pages
    • The Product wildcard will store only the last part of the NodeAliasPath (product name) and be mapped to the folder "Store" in XbyK website channel:
      • /DancingGoatStore/Coffee/Arabica -> /Store/Arabica
      • /DancingGoatStore/Paper_Filter -> /Store/Paper_Filter
      • /AnotherStore/Coffee/Robusta -> /Store/Robusta

Known limitations

Avoid creating rules that map the NodeAliasPath of different content items to a single product page tree path. Such rules cause the linked content item to be overwritten for particular pages.

If you change existing mapping rules, already created pages will not be moved accordingly. Instead, they will be created in the new location.

How to handle order payments?

  1. Implement your own payment method.
  2. Retrieve all order statuses using IOrderService if needed.
  3. Use UpdateOrder method of IOrderService to update order status and to set OrderIsPaid flag according to the payment result.