codeEmporix Java SDK

A comprehensive Java SDK for integrating with Emporix Commerce APIs.

Built for Spring Boot applications with powerful authentication management, type-safe API clients, and convenient token handling.

The Emporix Java SDK is available under emporix-sdkarrow-up-right maven repository and provides:

  • Type-safe API clients for all Emporix services

  • Automatic Spring Boot configuration with @EnableEmporixAutoConfiguration

  • Comprehensive token management with EmporixTokenService

  • Automatic token caching and refresh for service tokens

  • Exception handling with Emporix error response parsing

  • Multi-credential support for multi-tenant scenarios

Prerequisites

Before you begin, ensure you have the following installed and configured:

  • Java 21 or higher

  • Spring Boot 3.x

  • Gradle 8.5+ or Maven 3.9+

Quick start

This quick start shows how to add the Emporix Java SDK to your Spring Boot project, enable auto-configuration, set up credentials, and run a first API call.

1

Add the dependency to your project

Gradle:

dependencies {
    implementation 'io.emporix:emporix-sdk:1.1.0'
}

Maven:

<dependency>
  <groupId>io.emporix</groupId>
  <artifactId>emporix-sdk</artifactId>
  <version>1.1.0</version>
</dependency>
2

Enable the SDK by adding the annotation to your Spring Boot application

import io.emporix.config.EnableEmporixAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableEmporixAutoConfiguration  // ← Add this
public class MyApplication {

  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
  }
}
3

Configure your credentials

Recommended: Use environment variables

export EMPORIX_TENANT=your-tenant-id
export EMPORIX_API_CREDENTIALS_BACKEND_CLIENT_ID=your-backend-client-id
export EMPORIX_API_CREDENTIALS_BACKEND_SECRET=your-backend-secret
export EMPORIX_API_CREDENTIALS_STOREFRONT_CLIENT_ID=your-storefront-client-id
export EMPORIX_API_CREDENTIALS_STOREFRONT_SECRET=your-storefront-secret

Alternatively, use application.yml:

emporix:
  tenant: your-tenant-id
  api:
    credentials:
      backend:
        client-id: your-backend-client-id
        secret: your-backend-secret
      storefront:
        client-id: your-storefront-client-id
        secret: your-storefront-secret
4

Use the SDK in your code

import io.emporix.auth.service.EmporixTokenService;
import io.emporix.auth.dto.ServiceTokenResponse;
import io.emporix.product.ProductClient;
import io.emporix.product.dto.response.ProductResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ProductService {

  @Autowired
  private ProductClient productClient;

  @Autowired
  private EmporixTokenService tokenService;

  public List<ProductResponse> getAllProducts() {
    // 1. Get service token (with all available scopes)
    ServiceTokenResponse token = tokenService.getServiceToken();

    // 2. Get Bearer token (null-safe and idempotent)
    String authorization = token.bearerAccessToken();

    // 3. Call client with authorization
    return productClient.getProducts(
        null, null, null, 1, 20, "name:asc", true, "en", authorization
    ).getBody();
  }
}

Result: Setup is complete — the Emporix SDK is configured and working in your application.

Configuration

The SDK is configured through application.yml, application.properties, or environment variables.

Complete configuration example:

Property details

Property
Required
Default
Description

emporix.tenant

Yes

-

Your Emporix tenant name. All API requests are scoped to this tenant.

emporix.api.host

No

https://api.emporix.io

Base URL for Emporix API.

emporix.api.credentials.backend.client-id

Yes

-

OAuth2 client ID for backend operations (service tokens).

emporix.api.credentials.backend.secret

Yes

-

OAuth2 client secret for backend operations.

emporix.api.credentials.storefront.client-id

Yes

-

OAuth2 client ID for storefront operations (customer/anonymous tokens).

emporix.api.credentials.storefront.secret

Yes

-

OAuth2 client secret for storefront operations.

emporix.api.credentials.custom.*

No

-

Additional custom credential sets for integration scenarios.

emporix.api.timeouts.connect-timeout-ms

No

10000

Connection timeout in milliseconds (time to establish connection).

emporix.api.timeouts.read-timeout-ms

No

60000

Read timeout in milliseconds (time to wait for response data).

emporix.api.timeouts.connection-request-timeout-ms

No

5000

Connection request timeout in milliseconds (time to wait for connection from pool).

emporix.cache.enabled

No

true

Enable/disable token caching using Caffeine.

emporix.cache.max-size

No

1000

Maximum number of tokens to cache.

emporix.cache.expiration-buffer-seconds

No

60

Seconds before expiration to consider token expired (safety buffer).

emporix.cache.service-token-max-age-seconds

No

60

Maximum age for cached service tokens in seconds.

emporix.cache.max-lifetime-seconds

No

3600

Maximum lifetime for any cached token in seconds (Caffeine expireAfterWrite).

emporix.exception-handler.enabled

No

false

Enable automatic exception handling for Emporix API errors.

circle-check

Environment variables

All properties can be set via environment variables (recommended for production):

circle-check

Enabling the SDK

The SDK provides two usage modesL DTOs only and full SDK.

DTOs only - with no configuration

Simply add the SDK as a dependency to use the data transfer objects (DTOs). No additional configuration needed.

Full SDK - with auto-configuration

To enable API clients and authentication services, add the annotation:

This automatically configures:

  • All API clients (ProductClient, CategoryClient, PriceClient, etc.)

  • Token management (EmporixTokenService)

  • Token caching with automatic refresh

  • Exception handling (EmporixErrorHandler)

  • All required Spring beans

circle-exclamation

Available services

The SDK provides type-safe clients for the following Emporix services:

Product & catalog

Service
Client
Description
Key Operations

Product

ProductClient

Product management

CRUD, bulk operations, search, filtering

Product Template

ProductTemplateClient

Product templates

Manage product templates

Brand

BrandClient

Brand management

CRUD for brands

Catalog

CatalogClient

Catalog management

Manage catalogs

Category

Service
Client
Description
Key Operations

Category

CategoryClient

Category hierarchy

Create, update, manage hierarchy

Category Assignment

CategoryAssignmentClient

Product-category links

Assign products to categories

Category Tree

CategoryTreeClient

Tree navigation

Retrieve category trees

Price

Service
Client
Description
Key Operations

Price

PriceClient

Price management

Create, update prices

Price List

PriceListClient

Price lists

Manage price lists

Price List Price

PriceListPriceClient

Price list entries

Manage prices in lists

Price Model

PriceModelClient

Pricing strategies

Configure pricing models

Price Match

PriceMatchClient

Price calculation

Calculate best prices

Cart & checkout

Service
Client
Description
Key Operations

Cart

CartClient

Shopping cart management

Create, update, retrieve carts

Cart Items

CartItemsClient

Cart item operations

Add, update, remove cart items

Cart Discount

CartDiscountClient

Cart-level discounts

Apply and manage cart discounts

Checkout

CheckoutClient

Checkout process

Process checkouts, create orders

Order

Service
Client
Description
Key Operations

Order

OrderClient

Order operations

Retrieve, update orders

Order Management

OrderManagementClient

Order administration

Full order lifecycle management

Customer

Service
Client
Description
Key Operations

Customer

CustomerClient

Customer operations

Retrieve customer data

Customer Management

CustomerManagementClient

Customer administration

Create, update, delete customers

Customer Address

CustomerAddressClient

Customer addresses

Retrieve customer addresses

Customer Address Mgmt

CustomerAddressManagementClient

Address administration

Create, update, delete addresses

Customer Credentials

CustomerCredentialsClient

Password & email management

Password reset, email change

Customer Double Opt-In

CustomerDoubleOptInClient

Email verification

Manage double opt-in flow

Company (B2B)

Service
Client
Description
Key Operations

Legal Entity

LegalEntityClient

B2B company management

Create, update legal entities

Location

LocationClient

Company locations

Manage business locations

Contact Assignment

ContactAssignmentClient

Contact relationships

Assign contacts to entities

Shipping

Service
Client
Description
Key Operations

Shipping Methods

ShippingMethodsClient

Shipping methods

Manage shipping methods

Shipping Zones

ShippingZonesClient

Shipping zones

Define shipping zones

Shipping Groups

ShippingGroupsClient

Shipping groups

Manage shipping groups

Shipping Cost

ShippingCostClient

Shipping cost calculation

Calculate shipping costs

Customer Group Relations

CustomerGroupRelationsClient

Customer group mappings

Manage customer group relations

Delivery Windows

DeliveryWindowsClient

Delivery time windows

Define delivery windows

Delivery Sites

DeliverySitesClient

Delivery locations

Manage delivery sites

Delivery Cycles

DeliveryCyclesClient

Delivery cycles

Manage delivery cycles

Delivery Times Management

DeliveryTimesManagementClient

Delivery times administration

Manage delivery times

Delivery Times Slots Mgmt

DeliveryTimesSlotsManagementClient

Delivery time slots

Manage delivery time slots

Coupon

Service
Client
Description
Key Operations

Coupon Management

CouponManagementClient

Coupon administration

Create, update, delete coupons

Coupon Redemption

CouponRedemptionClient

Coupon usage

Redeem and manage coupon usage

Coupon Validation

CouponValidationClient

Coupon validation

Validate coupon eligibility

Referral Coupon Management

ReferralCouponManagementClient

Referral coupons

Manage referral coupon programs

Tax

Service
Client
Description
Key Operations

Tax

TaxClient

Tax configuration

Manage tax settings, calculate taxes

Configuration

Service
Client
Description
Key Operations

Configuration

ConfigurationClient

Tenant configuration

Tenant settings

Client Configuration

ClientConfigurationClient

Client-scoped config

Client-specific settings

Session context

Service
Client
Description
Key Operations

Session Context

SessionContextClient

Session management

Manage session context

Own Session Context

OwnSessionContextClient

Own session operations

Manage own session context

Authentication

The SDK provides comprehensive token management through EmporixTokenService and direct client invocation patterns.

circle-exclamation

Scope constants

All API clients provide scope constants through a nested Scopes interface.

triangle-exclamation

Example:

Benefits:

  • Type safety - compile-time errors for typos

  • IDE autocomplete - discover available scopes

  • Refactoring support - rename scopes safely

  • Documentation - JavaDoc for each scope

Authentication overview

Emporix supports several token types:

Token Type
Use Case
Credentials Used
How to Obtain

Service Token

Backend operations, admin tasks

backend credentials

tokenService.getServiceToken()

Scoped Service Token

Backend with specific permissions

backend credentials

tokenService.getServiceToken(Set.of(SCOPES))

Custom Service Token

Integration/partner with full access

custom credentials

tokenService.getServiceToken("integration")

Custom Scoped Token

Integration/partner with limited scopes

custom credentials

tokenService.getServiceToken(Set.of(SCOPES), "integration")

Customer Token

Authenticated user operations

storefront credentials

tokenService.getCustomerToken(email, password, anonymousToken)

Anonymous Token

Guest browsing, public access

storefront credentials

tokenService.getAnonymousToken()

B2B Token

Business customer operations

storefront credentials

tokenService.getB2bToken(customerToken, legalEntityId)

circle-exclamation

Token caching

The SDK automatically caches service and custom credential tokens for optimal performance:

  • Service tokens - Cached by scope set AND credential name, auto-refreshed on expiration

  • Custom credential tokens - Each credential set has its own cache

  • Customer tokens - NOT cached (managed by your application)

  • Anonymous tokens - NOT cached (each user needs unique token)

Token management

The SDK uses a direct token management approach. All API clients accept an authorization header parameter (typically the last parameter in each method). You obtain tokens using EmporixTokenService and pass them to client methods.

Basic token flow

1

Obtain a token

Get the token using EmporixTokenService.

2

Get the Bearer token

Get the token using token.bearerAccessToken() (null-safe and idempotent).

3

Pass the Bearer token to the client method

Typically it's passed as the last parameter.

Example:

Using service tokens - backend operations

Service tokens are used for backend/administrative operations and are automatically cached by the SDK.

Available Methods:

  • getServiceToken() - Get token with all available scopes (simplest, recommended for most cases)

  • getServiceToken(Set<String> scopes) - Get token with specific scopes (least privilege principle)

  • getServiceToken(String credentialName) - Get token with custom credentials and all scopes

  • getServiceToken(Set<String> scopes, String credentialName) - Get token with custom credentials and specific scopes

Example: Service token usage

Using custom credentials

Custom credentials are additional OAuth2 clients configured in Emporix with specific scopes. Use them for:

  • External integrations with limited permissions

  • Partner access with read-only or specific operations

  • Third-party systems that need controlled access

Configuration for custom credentials:

Using anonymous tokens - guest browsing

Anonymous tokens are used for public/guest browsing sessions.

Using customer tokens - authenticated users

Customer tokens are for authenticated user operations. The SDK automatically preserves shopping sessions when logging in.

circle-exclamation

Available Methods:

  • getCustomerToken(email, password, AnonymousTokenResponse) - Login with anonymous token object Recommended

  • getCustomerToken(email, password, String) - Login with anonymous bearer string Recommended

  • getCustomerToken(email, password) - Works but creates new session Loses cart/session context

Typical Flow:

spinner

Token cache management

The SDK automatically caches service tokens for performance. You can clear the cache when needed:

circle-exclamation

Usage examples

Example 1: Product management

Example 2: Category management

Example 3: Multi-client operations with custom credentials

This example shows how to use multiple OAuth2 clients (configured in Emporix) with different permission levels.

Configuration:

Each custom credential corresponds to an OAuth2 client configured in your Emporix tenant with specific scopes.

circle-info

Each OAuth2 client (integration, partner, thirdparty) must be created in your Emporix tenant settings with the appropriate scopes assigned.

Example 4: REST controller

Advanced configuration

Custom client beans

Override default client configuration by providing your own beans:

ClientConfig options

Custom REST client with timeout

Modern Apache HttpClient 5.6+ approach with custom timeouts:

Key points:

  • Uses Apache HttpClient 5.6+ (no deprecated APIs)

  • ConnectionConfig for connection-level timeouts (connect, socket)

  • RequestConfig for request-level timeouts (connection request, response)

  • PoolingHttpClientConnectionManager for better connection pooling control

Exception handling

Global exception handler

Enable automatic exception handling:

This provides automatic handling of:

  • EmporixApiException - Emporix API errors

  • Standard HTTP errors (400, 401, 403, 404, 500, etc.)

  • Validation errors

  • Structured error responses

Manual exception handling

Best practices

Use appropriate scopes

Choose the right method based on your security requirements:

Recommended: For specific operations (least privilege):

For full backend access (simpler, when you need multiple operations):

Avoid: requesting all scopes when you only need one:

When to use each:

  • Use getServiceToken() for internal backend services that perform multiple operations

  • Use getServiceToken(Set.of(SCOPES)) for external integrations or when following strict least-privilege security

Preserve anonymous tokens on login

Always pass the anonymous token when logging in customers to preserve shopping cart and session.

Recommended:

Avoid: (loses session context):

Reuse service tokens

Service tokens are automatically cached by the SDK. Reuse the same EmporixTokenService instance.

Recommended:

Handle errors gracefully

Always handle API exceptions appropriately.

Recommended:

Use custom credentials for integrations and partners

Leverage custom credentials (separate OAuth2 clients configured in Emporix) for integrations, partners, or systems with limited permissions.

Recommended:

Each custom credential corresponds to an OAuth2 client created in your Emporix tenant with specific scopes.

Manage customer tokens in your application

The SDK does NOT cache customer tokens. Store them securely in your application.

Recommended:

Recommended:

Enable token caching

Keep token caching enabled in production for better performance.

Troubleshooting

Check the solutions for the most common issues.

Issue: "Bean of type ProductClient could not be found"

Cause: SDK auto-configuration is not enabled.

Solution: Add @EnableEmporixAutoConfiguration to your main application class:

Issue: "401 Unauthorized"

Possible Causes:

  • Invalid credentials

  • Missing or malformed authorization header

  • Expired token

  • Token with insufficient scopes

Solutions:

  • Verify credentials in Emporix Portal

  • Check environment variables are set correctly:

  • Ensure you're passing the authorization header:

Issue: "Tenant must be configured"

Cause: Missing tenant configuration.

Solution: Set tenant via environment variable or application.yml:

Or:

Issue: "Custom credentials 'xxx' not found"

Cause: Requesting a token with custom credential name that doesn't exist in configuration.

Example Error:

Solution: Configure custom credentials in application.yml:

Important: The OAuth2 client must also be created in your Emporix tenant with appropriate scopes assigned.

Issue: "403 Forbidden" or "Insufficient Scopes"

Cause: Token doesn't have required OAuth2 scopes for the operation.

Solutions:

  • Request token with appropriate scopes:

  • Verify credentials in Emporix Portal have the required scopes.

  • Check if you need to use custom credentials with different scope permissions.

Token caching not working

Symptom: Every request creates a new token.

Solution: Service tokens are automatically cached. If you're seeing new tokens:

  • Check if you're requesting different scopes (each scope set gets its own cache entry).

  • Check if you're using different credential names.

  • Customer and anonymous tokens are NOT cached by design.

Debugging tips

Enable debug logging:

Clear token cache:

Inspect token details:

Last updated

Was this helpful?