Behio Storefront SDK
Advanced

B2B Features

Customer prices, partner account registration and approval, quote requests, cookie consent, and return requests

Customer prices throughout the purchase

Catalog, cart and checkout resolve the customer's active groups and currency before pricing. Explicit per-product price-list entries take precedence over the group's default percentage discount. If several eligible lists contain the same product, the lowest explicit price wins. Computed group discounts respect the merchant's margin floor and price-ending policy; manually entered prices remain merchant decisions. Eligible quantity tiers can lower that customer price, price rules apply next, and an active early-bird price may lower the result again.

Shipping thresholds and checkout review use the customer's current cart prices, including bundle totals. Do not calculate a customer price by subtracting a percentage in the template. Display the API's price and revalidate after changes.

Use the authenticated request-scoped client for the first HTML of product lists, details and recommendations. Disable shared response caching for these reads. A public singleton must never hold a visitor's auth token or cart session. The API hides prices for gated guests and rejects attempts to obtain them through cart or shipping calculations. Hidden prices must also hide quantity-tier prices.

Delivery-country rules must also be resolved in the first HTML. SDK 1.20 accepts country: 'SK' when creating a request-scoped client, or client.setCountry('SK'). This default reaches catalog lists, details, featured products, collections, recommendations and bundles. An explicit per-call country takes precedence. The Next.js adapter reads behio_country (or countryCookieName) for each request. Write that cookie only after cart.setDestination() succeeds and refresh the server render. setCountry() changes catalog context only, never the cart. Guest response cache keys must include currency and country; customer responses must remain private. Do not replace server prices from a browser-wide price cache.

Variant priceFrom uses the same variant price-list entries, category rules, cost guards and early-bird price as the detail. Variant availability uses only the warehouses selected for the shop. Internal costs never leave the API. Recommendations expose variantsOnly and priceFrom too; show a "from" label for these families and use the returned price's own currency. Featured products, collections and recommendations also apply the shop's FX rate and margin.

Before adding the first product or bundle, initialize an empty cart with the visitor's validated display currency and known destination. A cookie can outlive the previous cart. cart.setCurrency() and cart.setDestination() retain the returned cart session, including when either call creates the cart. Stop the purchase action if context initialization fails. Never add an item at the shop's default price and silently repair its destination after displaying success.

B2B registration and approval

A shop can take applications for a partner (wholesale) account and let the merchant approve each one (SDK 2.40.0). Approval is what grants the partner rights: the customer joins the merchant's company record and its customer group, and the group's prices apply from the next request. Your storefront never calculates any of that. It sends the application, shows the status and displays the prices the API returns.

Keep two things apart in every form. Company details on their own mean "send my invoices to a company" and never apply for anything. The application is a separate, explicit choice of the visitor.

Modes

Read the mode from getShopInfo(). b2b is optional, because a cached payload from before SDK 2.40.0 may still be served; treat a missing value as OFF.

const {data: shop} = await client.getShopInfo();
const mode = shop?.b2b?.approvalMode ?? 'OFF';
const formSlug = shop?.b2b?.applicationFormSlug ?? null;
approvalModeWhat an applicant gets
OFFThe shop takes no applications. Hide every "apply" control and the register prefill button. Registration works as a plain retail one.
ACCOUNT_FIRSTA working account right away, logged in, at regular prices. Partner prices start after approval.
BLOCKEDAn account that cannot log in until the merchant approves. Registration returns no tokens.

approvalMode is the mode that applies, already combined with the older "approve every registration" setting. checkout.requireRegistrationApproval is true only when every new registration waits for the merchant: that older setting, or a partners only shop (b2bMode) whose mode is BLOCKED. In a mixed shop it is false and only applicants wait.

Who is an applicant

A registration becomes an application in exactly three cases:

  • the visitor asked for it with applyForB2b: true;
  • the shop sells to partners only (b2bMode: true) and its mode is not OFF;
  • the shop approves every registration (checkout.requireRegistrationApproval).

applyForB2b: false cannot opt out of the last two. In mode OFF the flag is ignored and nothing is created.

Offer the "I want a partner (wholesale) account" control only when the mode is not OFF, the shop is not partners only and applicationFormSlug is null. In a partners only shop there is nothing to choose, so tell the visitor that the registration will be reviewed.

const {data, error} = await client.auth.register({
  email: '[email protected]',
  password: '...',
  firstName: 'Jana',
  lastName: 'Novakova',
  // Required with applyForB2b: true (be.storefront.b2bCompanyRequired).
  company: 'ACME s.r.o.',
  companyId: '27074358',
  vatId: 'CZ27074358',
  country: 'CZ',
  applyForB2b: true,
  // Details for the merchant's decision. Stored with the application only.
  phone: '+420 777 000 000',
  street: 'Hlavni 1',
  city: 'Praha',
  zip: '110 00',
  note: 'We supply twelve cafes.',
  // Language of the decision e-mail.
  locale: 'cs',
});
if (error) return showError(errorMessage(error, 'cs'));

if (data.pendingApproval) {
  // BLOCKED: no tokens, no session. Show "your application is waiting".
} else if (data.b2bApplicationStatus === 'PENDING') {
  // ACCOUNT_FIRST: logged in. Send the customer to the account page,
  // where the status banner says what applies until the decision.
}

A new application is always PENDING; there is no automatic approval. pendingEmailVerification is independent and can come together with either result.

A blocked applicant who tries to log in gets 401 with be.storefront.b2bApprovalPending, or be.storefront.b2bApplicationRejected after a declined application. Both are revealed only after a correct password. Show their own sentence instead of "wrong e-mail or password".

Statuses

customer.getB2bStatus() and customer.getProfile().b2b return the same object.

const {data: b2b} = await client.customer.getB2bStatus();
// {status, companyName, rejectionReason, appliedAt, decidedAt,
//  emailVerificationRequired, canApply}
statusMeaningWhat to show
NONENo partner account and no open application.Nothing, or an invitation to apply when canApply is true.
PENDINGThe application waits for the merchant."Waiting for approval", and what applies meanwhile.
APPROVEDThe partner account is active.The company (companyName). With emailVerificationRequired: true, ask for the e-mail confirmation instead.
REJECTEDThe last application was declined.rejectionReason, the text the merchant wrote for the applicant. A new application when canApply is true.
SUSPENDEDThe merchant paused the company account.Partner prices do not apply; point the customer to the shop.

canApply is true when the shop accepts applications and the status is NONE or REJECTED. While PENDING or REJECTED, companyName is the name the applicant typed.

profile.isApproved is a purchase gate, not the partner status. It is false only when this customer cannot see prices or order right now: a partners only shop and a status of PENDING, REJECTED or SUSPENDED. An applicant of a mixed shop keeps isApproved: true and shops at regular prices until the decision. A customer with hidden prices gets 403 (not 401, the session is valid) with be.storefront.b2bApprovalPending, be.storefront.b2bApplicationRejected or be.storefront.b2bAccountSuspended on cart, shipping quote and checkout calls. The SDK does not refresh tokens on a 403. Do not present it as an outage or as a missing login: say the reason and link to the account.

Apply from an existing account

const {data: b2b, error} = await client.customer.applyForB2b({
  company: 'ACME s.r.o.', // required
  country: 'CZ',          // required, ISO-2
  companyId: '27074358',
  vatId: 'CZ27074358',
  phone: '+420 777 000 000',
  street: 'Hlavni 1',
  city: 'Praha',
  zip: '110 00',
  note: 'We supply twelve cafes.',
  locale: 'cs',
});
// b2b.status === 'PENDING'

An application from an existing account never locks that account, in any mode. An EU VAT ID is checked in VIES, but an invalid one does not refuse the application.

Mailbox proof

Partner rights are bound to a mailbox that was proven to belong to the applicant. When the merchant approves an account whose e-mail was never confirmed, the status is APPROVED with emailVerificationRequired: true and the partner prices wait. The approval e-mail carries one button:

  • Set your password, https://<shop host>/reset-password?token=..., for an account that the approval created (a guest applied through the form). Setting the password also confirms the e-mail.
  • Confirm your e-mail, https://<shop host>/verify?token=..., for a self-registered account that is not confirmed yet.
  • Open your account, https://<shop host>/account, when nothing is left to do.

Your storefront must serve these three addresses. /verify calls client.auth.verifyEmail(token), /reset-password calls client.auth.resetPassword(token, newPassword). The welcome e-mail of a registration uses the same /verify address. Each token works once.

The merchant's own application form

When shop.b2b.applicationFormSlug is set, the merchant collects applications through a form built in the admin (extra questions, file uploads). The built in paths are then closed: applyForB2b: true and customer.applyForB2b() answer be.storefront.b2bApplicationFormRequired. Link to the form instead and submit it as any other form:

const {data: form} = await client.forms.get(shop.b2b.applicationFormSlug);
const {data: result, error} = await client.forms.submit(form.slug, {data: values, consent: true});

Since SDK 2.40.0 forms.submit and forms.uploadFile send the customer token when the client has one, so a logged in visitor's application is bound to the account. Use the session bound client for that submit. The API reads the session as optional: an expired token files the application as a guest's, so renew or check the session before a logged in customer submits.

A guest may apply through the form as well. The answer then carries no submission id, so it never tells whether that address applied before.

The merchant does not map fields by hand. Roles come from the field keys, compared without case and underscores (company_name and companyName are the same):

RoleField keys
E-mail (required)email, or the first field of type email
Company (required)company, companyName, firma
Registration numbercompanyId, registrationNo, ico
VAT IDvatId, dic
Countrycountry, zeme
First name, last namefirstName, jmeno; lastName, prijmeni
Phonephone, telefon
Street, city, postal codestreet, ulice; city, mesto; zip, psc
Messagenote, poznamka

Company register prefill

const {data: company, error} = await client.shop.lookupCompany({
  country: 'CZ',
  registrationNo: '27074358',
});
// {name, companyId, vatId, street, city, zip, country, legalForm}

The lookup reads national company registers and exists for four countries: CZ, SK, FR and NO. Other countries, EU ones included, are not supported and answer be.storefront.companyLookupCountryNotSupported; there is no VIES fallback. Show the prefill button only for these countries and only when shop.b2b.approvalMode is not OFF. It is a public call (no customer token) limited to 10 lookups per minute per visitor, with hourly budgets per shop and per IP on top. Call it from the server with the visitor's IP, as every other limited public action.

A failed lookup must never block the form. The visitor types the data by hand.

Errors

KeyStatusWhen
be.storefront.b2bApprovalPending401 login, 403 purchaseThe application waits for the merchant.
be.storefront.b2bApplicationRejected401 login, 403 purchaseThe application was declined.
be.storefront.b2bAccountSuspended403 purchaseThe company account is paused.
be.storefront.b2bCompanyRequired400applyForB2b: true without company.
be.storefront.b2bApplicationFormRequired400The shop uses its own application form.
be.storefront.b2bApplicationsDisabled400Mode OFF: apply and the register lookup are closed.
be.storefront.b2bApplicationExists409Already a partner, or an application is waiting. error.code is CONFLICT.
be.storefront.companyLookupNotFound400Unknown or malformed registration number.
be.storefront.companyLookupCountryNotSupported400No register for this country.
be.storefront.companyLookupBusy429The lookup budget is used up. Let the visitor type the data.
be.storefront.companyLookupUnavailable503The register does not answer.

errorMessage(error, locale) has a sentence for each of them in Czech, Slovak and English. With throwOnAvailabilityError the 429 and 503 are thrown, so wrap the lookup in try/catch.

React hooks

import {useB2bStatus, useApplyForB2b, useCompanyLookup} from '@behio/storefront-sdk/react';

const {data: b2b} = useB2bStatus({initialData: profile.b2b});
const apply = useApplyForB2b();     // apply.mutateAsync({company, country, ...})
const lookup = useCompanyLookup();  // lookup.mutateAsync({country, registrationNo})

useApplyForB2b writes the new status into the cache of useB2bStatus and useCustomer. useAuth().register(input) resolves with the RegisterResult since 2.40.0 (also kept in registerResult), so a browser-managed form can read pendingApproval and b2bApplicationStatus. In a server rendered storefront keep these calls in Server Actions and render the status in the first HTML.

Quote Requests

Allow B2B customers to request custom pricing. The contact email is the ownership gate for reading and accepting a quote (quotes carry contact PII and negotiated prices), so keep it available on the confirmation page.

const { data: quote, error } = await client.quotes.submit({
  contactName: 'Jan Novak',
  contactEmail: '[email protected]',
  contactPhone: '+420123456789',
  companyName: 'ACME Corp',
  message: 'We need bulk pricing for Q3',
  items: [
    { productId: 'product-1', quantity: 100, requestedPrice: 80 },
    { productId: 'product-2', quantity: 50 },
  ],
});
// quote.status: PENDING | QUOTED | ACCEPTED | REJECTED | EXPIRED

Check Status

const { data: status } = await client.quotes.getStatus('quote-id', '[email protected]');
// { id, status, quotedTotal, quotedCurrency, quotedNote, expiresAt, items, ... }

Accept Quote

Only a quote in QUOTED status can be accepted; accepting twice is idempotent and an expired quote flips to EXPIRED:

const { data: accepted } = await client.quotes.accept('quote-id', '[email protected]');

Return Requests (EU Withdrawal Button)

EU Directive 2023/2673 (effective 19 June 2026) requires an easy, clearly labelled online way to withdraw from the contract. Build a public /returns page with this three-step flow. No customer login is needed; the email used on the order is the ownership gate.

1. Look Up the Order

The customer enters their order number and email; you get back the internal ids and per-item returnable quantities:

const { data: order, error } = await client.returns.lookupOrder(
  '2026-0042',
  '[email protected]',
);
// order.items: [{ orderItemId, productName, quantity, returnableQuantity }]

Cap each quantity input at returnableQuantity and skip items where it is 0 (already claimed by an active return).

2. Submit the Withdrawal

const { data: returnRequest, error } = await client.returns.submit({
  orderId: order.orderId,
  email: '[email protected]', // must match the order email
  reason: 'CHANGED_MIND',      // the 14-day EU default; see all reasons below
  customerNote: 'Optional note',
  items: [
    { orderItemId: 'item-id', productName: 'Product name', quantity: 1 },
  ],
});

Reasons: CHANGED_MIND, DEFECTIVE, WRONG_ITEM, NOT_AS_DESCRIBED, TOO_LATE, DUPLICATE_ORDER, OTHER. The platform immediately sends the acknowledgement email the directive requires; show returnRequest.id to the customer as their reference number.

3. Check Return Status

const { data: status, error } = await client.returns.getStatus(
  'return-id',
  '[email protected]',
);
// status.status: REQUESTED | APPROVED | SHIPPED_BACK | RECEIVED |
//                REFUNDED | REJECTED | CLOSED
// also: refundAmount, refundedAt, returnTrackingNumber, items

Run all three calls from Server Actions (or your backend) so the customer's email never appears in a URL.

The consent log is append-only (GDPR audit trail); get returns the latest active consent and resolves to null when none was recorded yet. Since SDK 0.36.0 it calls the 200-always /consent/:visitorId/status endpoint, so a first-time visitor no longer produces a 404 in the browser console.

// Record consent (visitorId = your anonymous cookie/fingerprint id, 8-128 chars)
await client.consent.record({
  visitorId: 'visitor-uuid',
  analytics: true,
  marketing: false,
  preferences: true,
});

// Get the latest active consent, data is null when none exists
const { data: consent } = await client.consent.get('visitor-uuid');

// Revoke (idempotent)
await client.consent.revoke('visitor-uuid');

On this page