Read a Commerce catalogue from a .NET server
DescribesEbitex.Commerce.Delivery 0.2.xSee the changelog:Ebitex.Commerce.Delivery
Ebitex.Commerce.Delivery is a server-side client for the Commerce Delivery API. It reads a store’s products, prices,
availability and categories, and its live stock, returning each as a typed .NET value. It is the .NET counterpart of
@ebitex/commerce-sdk, and the two are held to each other by shared test cases.
The package targets .NET 10 and depends only on Microsoft.Extensions.Http and Microsoft.Extensions.Options. It
works the same in ASP.NET Core, a worker service or a console app.
Every C# method this page names is in one file, shown in full at the end of the page under The complete example.
Before you start
Section titled “Before you start”You need a server delivery key for a store. In Commerce, open Delivery keys, create a key and leave it
unrestricted. A server key is told exact stock counts, so keep it on your server and out of source control. In
development, .NET user secrets work well (a Commerce:DeliveryKey entry).
A browser-safe key cannot be used here. It only answers requests that carry one of its allowed origins, and a server
sends no Origin header, so every request is refused with 403 origin_denied.
Install
Section titled “Install”dotnet add package Ebitex.Commerce.DeliveryCreate the client
Section titled “Create the client”AddEbitexCommerceDelivery registers CommerceDeliveryClient as a typed client through IHttpClientFactory, which
pools connections and refreshes DNS correctly in a long-running server. Inject CommerceDeliveryClient wherever you
need it. The method returns an IHttpClientBuilder, so you can add handlers or resilience policies to it as usual.
See Configure in the example.
Without dependency injection, construct the client with an HttpClient you own and reuse it for the life of the
process. See Create in the example.
| Option | Default | Meaning |
|---|---|---|
ApiKey |
Required | Your server delivery key. Checked when the client is created. |
BaseUrl |
https://api.ebitex.io |
The API’s origin. The client adds the /commerce/delivery/v1 path itself, so leave it out. |
The client holds no cache and retries nothing. Add either as a handler on the HttpClient.
// The first request: which store does this key read, and in what currency?public static async Task<string> StoreSummaryAsync(CommerceDeliveryClient commerce){ var store = await commerce.GetStoreAsync(); return $"{store.Key} ({store.Currency})";}Prices, listing and paging
Section titled “Prices, listing and paging”A price is whole minor units beside a currency (AmountMinor, Currency), and the same amount as the store’s own
decimal string (Amount). Show Amount; do arithmetic on AmountMinor. A variant with no price has
Price == null: it is unpriced, which is not the same as free.
ListProductsAsync returns one page of a ProductsQuery:
| Property | Meaning |
|---|---|
Search |
Matches the start of a product’s name without regard to case, at most 100 characters. |
Category |
A category path from GetCategoriesAsync. |
Sort |
ProductSort.Name (the default) or ProductSort.CreatedUtc. |
Limit |
1 to 100. |
A request the API would certainly refuse is refused by the client first, with the same error code, as a
CommerceDeliveryException whose IsLocal is true.
ListAllProductsAsync and ListPagesAsync capture the query once and send it unchanged with each page’s cursor,
because a cursor belongs to its query. A rejected cursor surfaces as the exception it is; the iteration never starts over.
GetProductsByKeysAsync reads up to 50 products in one round trip, in the order you asked, with the keys that are not
available in Missing. GetProductAsync returns one product, or null when there is none available; set
ProductOptions.ThrowIfMissing for an exception. GetProductResponseAsync keeps the ETag and sends If-None-Match,
so an unchanged product is ProductStatus.NotModified.
Availability and live stock
Section titled “Availability and live stock”Each variant’s Availability is a status and may be a few minutes old, so use it for display. Before you take an
order, call GetStockAsync: it is never cached. A server key is told Available for each counted variant. It has a
tighter budget than the other reads, so call it when you need it, not on every render.
Errors
Section titled “Errors”A non-success response throws CommerceDeliveryException with StatusCode, ErrorCode (the API’s error code),
RequestId (the reference to quote to support) and, on a 429, RetryAfter. Nothing is retried.
Currencies and carts
Section titled “Currencies and carts”A store may sell in several currencies: GetStoreAsync() lists them in Currencies, the store’s own first, and ProductOptions.Currency or ProductsQuery.Currency prices a read in one of them. A price the merchant set for that currency is returned as set; otherwise the store’s price is converted at the merchant’s rate. A variant that cannot be converted is unpriced.
// Which currencies does the store sell in, and what does a product cost in one of them?public static async Task<string?> PriceInEurosAsync(CommerceDeliveryClient commerce, string productKey){ var store = await commerce.GetStoreAsync(); if (!store.Currencies.Contains("EUR")) { return null; }
var product = await commerce.GetProductAsync(productKey, new ProductOptions { Currency = "EUR" }); return product?.Variants.FirstOrDefault()?.Price?.Amount;}A key made with Allow carts and checkout can run a shopper’s cart. A cart holds SKUs and quantities only: the server prices everything. Every cart call takes the shopper’s visitor token, sent as a header and never in a URL; GetCartAsync returns null for a cart that is not this shopper’s. Quantities are 0 to 99 (0 removes the line), and the client refuses locally, with the API’s own error codes, what the API would refuse.
// Create a cart, add two of a SKU, and say where it goes. The shopper's visitor token is a header, never a URL. The server prices everything.public static async Task<string> StartCartAsync(CommerceDeliveryClient commerce, string visitorToken){ var cart = await commerce.CreateCartAsync(visitorToken); await commerce.SetCartLineAsync(cart.Id, "TR-40", 2, visitorToken); cart = await commerce.SetCartAddressAsync(cart.Id, new CartAddressesUpdate { Delivery = AddressChange.Set(new CartAddress("GB", null, "SW1A 1AA")) }, visitorToken);
// Until there is an address a rate applies to, Tax is null, not zero. Shipping the store cannot do in this currency is reported, never given free. if (cart.Shipping.Status == "unavailable") { return "We cannot ship there in this currency."; }
return cart.Totals is { TaxCalculated: true, Total: { } total } ? $"Total {total.Amount} {total.Currency}" : $"Items {cart.Totals.Items.Amount} {cart.Totals.Items.Currency}";}StartCheckoutAsync turns the cart into an order awaiting payment and answers with the payment provider’s page: send the shopper to RedirectUrl. The server prices the cart afresh, so the shopper pays what the cart shows now; the stock is held for 30 minutes while they pay (not in a store’s test mode, when the order is marked as a test and nothing is charged). A cart that cannot be paid for as it stands is a 409 with a code that says why. Whether the order is paid is not something the shopper’s browser can tell you; your server learns it from the store (the next release reports it).
// Start paying: the cart becomes an order awaiting payment and the answer says where to send the shopper. The shopper enters card details on the provider's page, never on yours.public static async Task<string> PayAsync(CommerceDeliveryClient commerce, Guid cartId, string visitorToken, string email){ var started = await commerce.StartCheckoutAsync(cartId, new CheckoutInput(email, null, "https://shop.example/thanks", "https://shop.example/cart"), visitorToken);
// Send the shopper to started.RedirectUrl. Whether the order is paid is for your server to learn from the store, not from the shopper arriving at the success address. return started.RedirectUrl;}The complete example
Section titled “The complete example”// Examples for the Ebitex.Commerce.Delivery package. Each method is one task from the .NET guide.// The file is compiled against the published package, so every call in it is public API.
using Ebitex.Commerce.Delivery;using Microsoft.Extensions.DependencyInjection;
namespace Northwind.Web;
public static class DocsExamples{ // Register the client once, at startup. Read the key from configuration or a secret store, never from source // control, and use a SERVER key: a browser-safe key is refused from a server. Inject CommerceDeliveryClient where needed. public static IServiceCollection Configure(IServiceCollection services, string deliveryKey) { services.AddEbitexCommerceDelivery(options => options.ApiKey = deliveryKey); return services; }
// Without dependency injection, pass an HttpClient you own and reuse the client for the life of the process. public static CommerceDeliveryClient Create(HttpClient http, string deliveryKey) => new(http, new CommerceDeliveryOptions { ApiKey = deliveryKey });
// #region FirstRequest // The first request: which store does this key read, and in what currency? public static async Task<string> StoreSummaryAsync(CommerceDeliveryClient commerce) { var store = await commerce.GetStoreAsync(); return $"{store.Key} ({store.Currency})"; } // #endregion
// A page of products, with the cheapest variant's price. A price is minor units beside a currency, and the same amount as the store's own string. public static async Task<IReadOnlyList<string>> CheapestPricesAsync(CommerceDeliveryClient commerce) { var page = await commerce.ListProductsAsync(new ProductsQuery { Search = "trail", Sort = ProductSort.Name, Limit = 12 }); return page.Items.Select(product => { var cheapest = product.Variants.Where(v => v.Price is not null).MinBy(v => v.Price!.AmountMinor)?.Price; return cheapest is null ? $"{product.Name}: unpriced" : $"{product.Name}: {cheapest.Amount} {cheapest.Currency}"; }).ToList(); }
// Every product, one at a time. The query is sent unchanged with each page's cursor. public static async Task<int> CountProductsAsync(CommerceDeliveryClient commerce) { var count = 0; await foreach (var _ in commerce.ListAllProductsAsync()) { count++; }
return count; }
// One product, or null when there is none available to this key. public static async Task<string?> AvailabilityAsync(CommerceDeliveryClient commerce, string productKey) { var product = await commerce.GetProductAsync(productKey); return product is null ? null : string.Join(", ", product.Variants.Select(v => $"{v.Sku}: {v.Availability}")); }
// Product reads' availability is for display and may be a few minutes old. Ask for stock itself before you take an order. public static async Task<bool> CanFulfilAsync(CommerceDeliveryClient commerce, IReadOnlyList<string> skus) { var stock = await commerce.GetStockAsync(skus); return stock.Missing.Count == 0 && stock.Items.All(item => item.Status != Availability.OutOfStock); }
// #region Carts // Create a cart, add two of a SKU, and say where it goes. The shopper's visitor token is a header, never a URL. The server prices everything. public static async Task<string> StartCartAsync(CommerceDeliveryClient commerce, string visitorToken) { var cart = await commerce.CreateCartAsync(visitorToken); await commerce.SetCartLineAsync(cart.Id, "TR-40", 2, visitorToken); cart = await commerce.SetCartAddressAsync(cart.Id, new CartAddressesUpdate { Delivery = AddressChange.Set(new CartAddress("GB", null, "SW1A 1AA")) }, visitorToken);
// Until there is an address a rate applies to, Tax is null, not zero. Shipping the store cannot do in this currency is reported, never given free. if (cart.Shipping.Status == "unavailable") { return "We cannot ship there in this currency."; }
return cart.Totals is { TaxCalculated: true, Total: { } total } ? $"Total {total.Amount} {total.Currency}" : $"Items {cart.Totals.Items.Amount} {cart.Totals.Items.Currency}"; } // #endregion
// #region Currency // Which currencies does the store sell in, and what does a product cost in one of them? public static async Task<string?> PriceInEurosAsync(CommerceDeliveryClient commerce, string productKey) { var store = await commerce.GetStoreAsync(); if (!store.Currencies.Contains("EUR")) { return null; }
var product = await commerce.GetProductAsync(productKey, new ProductOptions { Currency = "EUR" }); return product?.Variants.FirstOrDefault()?.Price?.Amount; } // #endregion
// #region Checkout // Start paying: the cart becomes an order awaiting payment and the answer says where to send the shopper. The shopper enters card details on the provider's page, never on yours. public static async Task<string> PayAsync(CommerceDeliveryClient commerce, Guid cartId, string visitorToken, string email) { var started = await commerce.StartCheckoutAsync(cartId, new CheckoutInput(email, null, "https://shop.example/thanks", "https://shop.example/cart"), visitorToken);
// Send the shopper to started.RedirectUrl. Whether the order is paid is for your server to learn from the store, not from the shopper arriving at the success address. return started.RedirectUrl; } // #endregion}