Skip to content
Cartly Developers

Customer Portal & B2B

Extend and automate the Cartly customer portal: passwordless login, self-serve returns, headless API, portal extensions, B2B company hierarchy with RBAC, and enterprise OIDC SSO.

Overview

Customer Portal Extensibility (v1.6) ships in six phases, each adding a distinct capability layer to the customer-facing side of Cartly:

  1. Phase 1 — Self-Serve Returns (RMA): customer return requests, decided by the merchant in the admin; a Temporal workflow notifies the merchant and expires undecided requests.
  2. Phase 2 — Passwordless Login: OTP via email/SMS and Magic Links.
  3. Phase 3 — Customer Headless API: SAT/CAT-authenticated profile, address, wishlist, and returns endpoints.
  4. Phase 4 — Portal Extension Points: Six slots where apps can inject Liquid, iframe, or remote UI blocks.
  5. Phase 5 — B2B Company Hierarchy: Companies, locations, memberships, RBAC, and Temporal budget-reset cron.
  6. Phase 6 — Enterprise SSO (OIDC): OIDC flow with auto-membership and encrypted client secrets.

Passwordless Login

Customers can log in without a password via a one-time code (OTP) or a signed magic link. Both flows return a Customer Access Token (CAT) identical to the password-based login token.

OTP via email or SMS

javascript
const SAT = 'sat_your_token';
const BASE = 'https://cartly.pro/storefront/v1';

// Step 1: Request OTP (sent via email or SMS)
await fetch(`${BASE}/customer/otp/request`, {
  method: 'POST',
  headers: {
    'X-Shopify-Storefront-Access-Token': SAT,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ identifier: 'user@example.com', channel: 'email' }),
});

// Step 2: Verify OTP — returns Customer Access Token (CAT)
const { access_token } = await fetch(`${BASE}/customer/otp/verify`, {
  method: 'POST',
  headers: {
    'X-Shopify-Storefront-Access-Token': SAT,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ identifier: 'user@example.com', code: '847291' }),
}).then(r => r.json());

SMS delivery requires configuring a provider in SMS_PROVIDER(twilio or sns) with the corresponding credentials. The mock provider logs codes to stdout — useful for local development.

Magic Link

javascript
// Request magic link — sends signed URL to customer email
await fetch(`${BASE}/customer/magic-link/request`, {
  method: 'POST',
  headers: {
    'X-Shopify-Storefront-Access-Token': SAT,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ email: 'user@example.com' }),
});

// Magic link URL format: /storefront.magic-link-verify?token=<signed_jwt>
// Token expires in 15 minutes. On visit, server verifies and issues CAT.

Magic links are signed JWTs with a 15-minute expiry. The storefront route/storefront.otp-verify handles the entry page; magic-link verification happens server-side in the loader before issuing a session cookie.

Customer Headless API

All customer-mutating endpoints under /storefront/v1/customer/ require both a valid SAT (header X-Shopify-Storefront-Access-Token) and a CAT (header Authorization: Bearer <cat>).

javascript
const CAT = 'cat_customer_jwt';

// Update profile
await fetch(`${BASE}/customer/profile`, {
  method: 'PUT',
  headers: {
    'X-Shopify-Storefront-Access-Token': SAT,
    'Authorization': `Bearer ${CAT}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ first_name: 'Jane', last_name: 'Doe', phone: '+12125550100' }),
});

// Add address
await fetch(`${BASE}/customer/addresses`, {
  method: 'POST',
  headers: {
    'X-Shopify-Storefront-Access-Token': SAT,
    'Authorization': `Bearer ${CAT}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    first_name: 'Jane', last_name: 'Doe',
    address1: '123 Main St', city: 'New York',
    province: 'NY', zip: '10001', country_code: 'US',
  }),
});

Available endpoints:

  • PUT /storefront/v1/customer/profile — update name, phone
  • GET/POST/PUT/DELETE /storefront/v1/customer/addresses — address CRUD
  • GET/POST/DELETE /storefront/v1/customer/wishlist — wishlist management
  • GET /storefront/v1/customer/returns — list return requests

App Session Token

When an embedded app needs to act on behalf of a logged-in customer, it exchanges the customer's CAT for a short-lived App Session Token (AST). The AST is then passed to the app backend for server-side verification.

javascript
// Exchange CAT for a short-lived App Session Token (AST, 5 minutes)
// Use when an embedded app needs to act on behalf of the logged-in customer.
const { app_session_token, expires_in, granted_scopes } = await fetch(`${BASE}/customer/app-session`, {
  method: 'POST',
  headers: {
    'X-Shopify-Storefront-Access-Token': SAT,
    'Authorization': `Bearer ${CAT}`,
    'Content-Type': 'application/json',
  },
  // app_id: your OAuth app's id (a UUID, as in /admin/apps/:id), not its client_id.
  // The app must be installed in this shop (a live OAuth token), otherwise 404.
  body: JSON.stringify({ app_id: APP_ID, requested_scopes: ['customer:profile:read'] }),
}).then(r => r.json());

// In your app backend — verify the AST with the OAuth token of the SAME app, in the
// same shop; the token needs the customers:read scope. Any other app or shop gets
// 401 (like an unknown or expired AST); an API key, or a token without
// customers:read, gets 403.
const res = await fetch('https://cartly.pro/apps/api/customer-session/verify', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${APP_OAUTH_TOKEN}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ app_session_token }),
});
if (!res.ok) throw new Error('invalid app session');
// email is present only when the AST was granted customer:profile:read.
const { customer_id, email, scopes } = await res.json();

Portal Extension Points

Apps can inject UI into six named extension points in the customer portal by attaching one of their theme blocks (Liquid, iframe or remote) to a point.

Extension PointLocation
Customer::Account::NavigationAdditional navigation items in the account sidebar
Customer::Account::DashboardWidgets on the account dashboard
Customer::Order::DetailsBlock below the order details
Customer::Order::ActionsAdditional action buttons on an order
Customer::Profile::SectionSection on the profile page
Customer::Return::FormAdditional fields in the return form
javascript
// Attach one of your app's theme blocks (registered first with
// POST /apps/api/theme-extensions, block_type_slug "loyalty-widget") to a portal slot.
// Needs the theme_extensions:write scope and an OAuth app token (API keys can't).
await fetch('https://cartly.pro/apps/api/blocks/loyalty-widget/portal-extensions', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${APP_OAUTH_TOKEN}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    extension_point: 'Customer::Account::Dashboard', // one of the six points below; anything else is a 400
    position: 0,                                     // order within the slot
    config: { title: 'Your points' },                // keys the block's schema declares (settings[].id); ≤ 4 KB JSON, keep it small — your iframe gets it URL-encoded as ?config=
  }),
});

Query active extensions for a given slot viaGET /storefront/v1/portal/extensions?point=Customer::Account::Dashboard. Admin management is available at GET/PUT/DELETE /admin/customer-portal/extensions.

B2B Company Hierarchy

The B2B module introduces three new entities: Company,CompanyLocation, and CompanyMembership. Each membership has a role: admin, buyer, or viewer. The RequireB2BRole middleware enforces access at the handler level.

javascript
// Create a company (admin API)
const { company } = await fetch('https://cartly.pro/admin/companies', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${ADMIN_JWT}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'Acme Corp',
    tax_id: 'US-123456',
    credit_limit: 500000,  // cents
    payment_terms: 'net30',
  }),
}).then(r => r.json());

// Add a location with a budget
await fetch(`https://cartly.pro/admin/companies/${company.id}/locations`, {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${ADMIN_JWT}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    name: 'HQ - New York',
    budget_limit: 200000,   // cents per period
    budget_period: 'monthly',
  }),
});

// Invite a buyer
await fetch(`https://cartly.pro/admin/companies/${company.id}/members`, {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${ADMIN_JWT}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ email: 'buyer@acme.com', role: 'buyer' }),
});

Location budgets reset automatically via a Temporal cron workflow (budget_reset.go). Set budget_period tomonthly, quarterly, or yearly.

Customer-facing B2B endpoints (CAT required):

  • GET /customer/company — company info for the logged-in buyer
  • GET /customer/company/members — member list
  • GET /customer/company/locations — location list with budget status
  • POST /customer/orders/:id/reorder — B2B re-order

Enterprise SSO (OIDC)

Companies can configure an OIDC identity provider so buyers log in via their corporate credentials. Supported providers: Google Workspace, Azure AD, Okta, and any custom OIDC-compliant IdP.

javascript
// Configure OIDC SSO for a company (admin API)
await fetch(`https://cartly.pro/admin/companies/${companyId}/sso`, {
  method: 'PUT',
  headers: {
    'Authorization': `Bearer ${ADMIN_JWT}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    provider: 'google',                              // google | azure | okta | custom
    discovery_url: 'https://accounts.google.com/.well-known/openid-configuration',
    client_id: 'your-google-client-id',
    client_secret: 'your-google-client-secret',     // encrypted at rest
    email_domain: 'acme.com',                       // auto-link members by domain
  }),
});

// Initiate SSO login (storefront)
// Redirect customer to: GET /storefront/v1/sso/init?company_slug=<slug>
// Cartly builds the OIDC authorization URL and redirects to the identity provider.
// On return, GET /storefront/v1/sso/callback issues a one-time code and creates membership.

Client secrets are encrypted at rest using AES-GCM before storage inCompanySSOConfig. On callback, Cartly validates the ID token, creates or updates the customer record, and automatically creates aCompanyMembership for first-time SSO users whose email domain matches.

Self-Serve Returns (RMA)

Customers submit return requests from their account. Each request starts a Temporal RMAWorkflow, which never moves money:

  1. ValidateReturnEligibility — checks the return window and item quantities; an ineligible request is rejected at once
  2. NotifyMerchantReturn — emails the merchant about the new request
  3. Expiry — a request still undecided after 7 days is rejected and the customer is emailed
javascript
// Submit a return request (customer, CAT required)
const { return_request } = await fetch(`${BASE}/customer/returns`, {
  method: 'POST',
  headers: {
    'X-Shopify-Storefront-Access-Token': SAT,
    'Authorization': `Bearer ${CAT}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    order_id: 'order-uuid',
    items: [{ order_item_id: 'item-uuid', quantity: 1, reason: 'wrong_size' }],
    customer_notes: 'Ordered wrong size, need M not L',
  }),
}).then(r => r.json());

// The merchant's decision (admin API): APPROVED → RECEIVED → REFUNDED, or REJECTED.
// expected_status = the status you showed; a 409 means it changed meanwhile.
await fetch(`https://cartly.pro/admin/returns/${return_request.id}`, {
  method: 'PUT',
  headers: {
    'Authorization': `Bearer ${ADMIN_JWT}`,
    'Content-Type': 'application/json',
    'X-Idempotency-Key': crypto.randomUUID(),
  },
  body: JSON.stringify({ status: 'APPROVED', expected_status: 'REQUESTED' }),
});
// Approving moves no money. Refund to the original payment with
// POST /admin/orders/:id/refund first, then mark the return REFUNDED;
// a store-credit return is credited when it is marked REFUNDED.

The merchant decides in the admin. Admin endpoints: GET /admin/orders/:id(the order's returns), POST /admin/orders/:id/returns (create a return for the customer), PUT /admin/returns/:id (status: APPROVED → RECEIVED → REFUNDED, or REJECTED).

Refunds are issued by the merchant, never on approval. For a refund to the original payment, use the order's refund action (POST /admin/orders/:id/refund) first, then mark the return REFUNDED; marking it refunded before the refund covers it is refused. A return refunded as store credit is credited to the customer's account when it is marked REFUNDED.

Customer Account on Liquid

As of v1.19, the /account/* routes are served by the Go Liquid renderer rather than React SSR. Every marketplace theme can now render the customer dashboard, auth screens, order history, and account settings in its own design language — fully customisable by merchants in the code editor.

Every stock theme ships them: Atrium, Balm, Bench, Clarity, Linen, Mono. All 28 customer template files live in the platform embed FS underbackend/internal/theme/embed/customers/ and follow the standard fork-on-write model.

bash
-- Customer Account Liquid templates (28 files)
-- Location: backend/internal/theme/embed/customers/

-- Auth screens
customers/login.liquid         — Login form (email + password, OTP link)
customers/register.liquid      — Registration form
customers/reset-password.liquid — Reset password form (token from email link)
customers/activate.liquid      — Account activation (new invite / first login)

-- Account dashboard & sections
customers/account.liquid            — Dashboard: recent orders, links to sub-sections
customers/account.orders.liquid     — Order list with status badges
customers/account.order.liquid      — Order detail: items, tracking, return button
customers/account.addresses.liquid  — Address book: add/edit/delete/set-default
customers/account.profile.liquid    — Profile editor: name, email, phone
customers/account.communication.liquid — Email preferences and newsletter opt-in
customers/account.wishlist.liquid   — Saved products wishlist
customers/account.b2b.liquid        — B2B company info and location (B2B only)
customers/account.returns.liquid    — Self-serve return request list (RMA)
customers/account.return.liquid     — Return request detail and status

Form conventions — POST-Redirect-Get (303 PRG)

All /customer/account/* form handlers use the PRG pattern to prevent double-submit on browser refresh. After a successful mutation the handler issues a 303 See Other redirect back to the same page. Success and error messages are stored in a Redis flash key and consumed once by the next GET request, available in Liquid as {{ request.flash.success }} and {{ request.flash.error }}.

liquid
{%- comment -%}
  POST-Redirect-Get pattern used by all /customer/account/* form handlers.
  Flash messages are stored in Redis (key: flash:{session_id}) and read
  once by the next GET request via the request global.flash object.
{%- endcomment -%}

<form method="POST" action="/customer/account/profile">
  <input type="hidden" name="_method" value="PUT">

  <label for="first_name">First name</label>
  <input id="first_name" name="first_name" type="text"
         value="{{ customer.first_name | escape }}">

  <label for="last_name">Last name</label>
  <input id="last_name" name="last_name" type="text"
         value="{{ customer.last_name | escape }}">

  <button type="submit">Save changes</button>
</form>

{%- if request.flash.success -%}
  <p class="alert alert--success">{{ request.flash.success }}</p>
{%- endif -%}
{%- if request.flash.error -%}
  <p class="alert alert--error">{{ request.flash.error }}</p>
{%- endif -%}

Eleven form endpoints are wired in the Go handler:

  • POST /customer/account/login
  • POST /customer/account/logout
  • POST /customer/account/register
  • POST /customer/account/reset-password
  • POST /customer/account/activate
  • POST /customer/account/profile
  • POST /customer/account/addresses (create)
  • POST /customer/account/addresses/:id (update / set-default)
  • DELETE /customer/account/addresses/:id
  • POST /customer/account/communication
  • POST /customer/account/returns (create RMA)

Session bridge

javascript
// Session bridge — two cookies coexist so existing sessions are not broken:
//
// __Host-cartly_customer_token  — JWT issued by the new Go Liquid handler.
//   Scoped to the storefront subdomain; used by /customer/account/* routes.
//
// _customer_session — encrypted session cookie used by the legacy React SSR routes
//   (checkout, cart, /storefront.otp-verify). Both are set on login and cleared
//   on logout, so merchants and customers see no difference.
//
// Theme developers: use {{ customer }} object in Liquid — the request pipeline
// resolves either cookie and populates the same customer context object.

Customising account templates

Open the code editor (Admin → Online Store → Themes → Edit Code). The customers/ directory lists all 28 account templates. Click any file to open it read-only, then click Edit file to fork it. After the first save, the file becomes a DB row and the merchant owns it — platform updates no longer override it automatically (but the amber upstream-updated banner will appear if the platform ships a newer version).

Theme developers building a new marketplace theme should provide all templates listed in liquidAccountTemplates above. Missing templates fall back to the platform embed baseline (boilerplate style) rather than failing — but a polished theme should override every customer-facing template.

For the Clarity theme source, see Clarity Theme guide. Clarity ships the most complete customer template set and is the recommended reference implementation.