Buyer accounts: two-step signup, login, the signed-in buyer's bookings and orders, the guest order page, addresses, and marketing consent. Previous: Guide 19 | Next: Guide 23

Reference - This guide is a tutorial. For exhaustive, always-current signatures and field lists, see the auto-generated reference:

Prerequisites

Sign up (two steps)

Signup takes two steps, and no session exists between them, so nobody can set a password on an address they do not control.

TypeScript
await lynkow.customers.register({ email: '[email protected]' })

// One message for every outcome
show('Check your inbox. If this address can be registered, a link is on its way.')

register() takes the email only and resolves the same way whether or not the address already has an account. Show one message and do not branch on the result: a different answer would tell a visitor which addresses have accounts. An invalid email throws 'VALIDATION_ERROR'. A locale in the second argument sets the language of the email.

The email links to https://<site domain>/account/activate/<token>, valid for 24 hours. To host the account pages elsewhere on your domain, set Account pages URL in Settings > E-commerce > Store: the link becomes that URL followed by /activate/<token>.

Step 2: activate and set the password

Serve a page at that path. It collects the password, the terms acceptance and the optional profile, then calls activation.confirm():

TypeScript
// app/account/activate/[token]/page.tsx, on submit
const { customer, token } = await lynkow.customers.activation.confirm({
  token: tokenFromTheUrl,          // the last segment of the link
  password: 'a-strong-passphrase', // 8 to 100 characters
  acceptsTerms: true,              // ticked on this page, by this buyer
  firstName: 'Alice',              // optional
  marketingOptIn: true,            // optional, unchecked by default
  locale: 'fr',                    // optional: the language of this page
})

saveToken(token) // see "Keep the buyer signed in"

Activation verifies the email and signs the buyer in: the client stores the token, so no login() follows. Without acceptsTerms: true, it throws 'VALIDATION_ERROR' and activates nothing. When the site has a terms page, the account records the version the buyer accepted.

  • firstName, lastName and phone fill only the fields the record does not hold yet.

  • locale becomes the buyer's preferred language (Buyer language).

  • marketingOptIn: true opts the buyer in on every channel with no earlier choice.

An invalid, expired or already used link throws 'BAD_REQUEST' with apiCode 'VERIFICATION_LINK_INVALID', the same answer in every case. Send the buyer to sign in with wording that fits all of them, such as "This link is invalid or has already been used. If you already set your password, sign in."

Log in

TypeScript
const { customer, token } = await lynkow.customers.login({
  email: '[email protected]',
  password: 'a-strong-passphrase',
})
saveToken(token)

Every failure throws 'UNAUTHORIZED' with apiCode 'CUSTOMER_AUTH_REQUIRED': an unknown email, a wrong password, or an account never activated. After five failed attempts for one email, or ten failed attempts from one client, further attempts throw 'TOO_MANY_REQUESTS' (apiCode 'RATE_LIMIT_EXCEEDED') for up to 15 minutes (all the per-buyer limits). The client count also includes invalid activation, verification and reset links. Successful attempts never count.

Keep the buyer signed in

The session token is valid for 30 days, and the SDK keeps it in memory only. Persist it yourself, in an HttpOnly cookie for example, and pass it back when you create the buyer's client:

TypeScript
const lynkow = createClient({
  // siteId and publishableKey as in Guide 22
  customerToken: savedToken,
})

With @lynkow/next, setCustomerCookie() stores the token and createBuyerClient() reads it back on each request (Guide 24). The SDK never stores or logs the token.

Calls from your server

When your server signs buyers in, for example from a Server Action, every call reaches Lynkow from your server's address. Without forwarding, all your buyers then share the limits above, and one person's mistyped passwords block sign-in for everyone. Set LYNKOW_SERVER_KEY to the site's server key: with @lynkow/next 0.7.3, createBuyerClient() then forwards each buyer's IP on its own.

A client you create with createClient() takes the pair from resolveBuyerForwarding():

TypeScript
import { headers } from 'next/headers'
import { resolveBuyerForwarding } from '@lynkow/next/server'

const lynkow = createClient({
  // siteId and publishableKey as in Guide 22
  ...resolveBuyerForwarding(await headers()), // { serverKey, clientIp } or {}
})

The key, the CDN case, how to check it works and the other server stacks are in Server Key and Buyer IP.

The current buyer and their bookings

TypeScript
// customer (partial): { email, firstName, preferredLocale }
// each booking (partial): { reference, startsAt, status }
const { customer, bookings } = await lynkow.customers.me()

me() needs a stored session and is never cached. It lists up to 100 bookings, latest start first, including the guest bookings made earlier with the same email. A booking's status is 'pending', 'confirmed', 'cancelled', 'completed' or 'no_show'. A booking made while signed in (Guide 19) appears at once.

Order history

TypeScript
// Each order (partial): { id, orderNumber, status, totalCents, currency }
const { data: orders, meta } = await lynkow.customers.orders({ page: 1, limit: 10 })

for (const order of orders) {
  console.log(`#${order.orderNumber}: ${order.status}, ${(order.totalCents / 100).toFixed(2)} ${order.currency}`)
}
const hasMore = meta.currentPage < meta.lastPage

Orders come newest first, in every status, 'cancelled' included. limit goes up to 100 and defaults to 20. Guest orders placed earlier with the account's email are listed too. Amounts are integers in cents.

One order

TypeScript
import { isLynkowError } from 'lynkow'

try {
  const order = await lynkow.customers.order(orderId) // an ord_... id
  for (const item of order.items) {
    console.log(`${item.quantity} x ${item.buyerTitle ?? item.title}`)
  }
} catch (error) {
  if (isLynkowError(error) && error.apiCode === 'ORDER_NOT_FOUND') {
    // Not one of this buyer's orders: show a 404 page
  } else {
    throw error
  }
}
  • An order that is not this buyer's throws 'NOT_FOUND' with apiCode 'ORDER_NOT_FOUND'. Both calls answer the same while order history or customer accounts are not enabled on the site.

  • Without a session, or with an expired one, they throw 'UNAUTHORIZED'.

  • Display a line's name as buyerTitle ?? title: buyerTitle is the name in the order's language.

The shipping and VAT figures of an order are described in Guide 23.

The guest order page

A guest has no account. While order history is on, the order emails sent to a guest link to /order/<token> on your site, under the locale prefix of the order's language: /order/<token> in the default language, /fr/order/<token> in French.

tsx
// app/[locale]/order/[token]/page.tsx
import type { Metadata } from 'next'
import { cookies } from 'next/headers'
import { notFound } from 'next/navigation'
import { isLynkowError, type Order } from 'lynkow'
import { createBuyerClient } from '@lynkow/next/server'
import { config } from '@/lib/config'

// The URL carries a secret: keep it out of search engines and of the Referer header
export const metadata: Metadata = {
  robots: { index: false, follow: false },
  referrer: 'no-referrer',
}

export default async function GuestOrderPage({
  params,
}: {
  params: Promise<{ locale: string; token: string }>
}) {
  const { locale, token } = await params

  let order: Order
  try {
    order = await createBuyerClient(config, await cookies(), { locale }).orders.getGuest(token)
  } catch (error) {
    if (isLynkowError(error) && (error.code === 'NOT_FOUND' || error.code === 'VALIDATION_ERROR')) {
      notFound()
    }
    throw error
  }

  return (
    <article>
      <h1>Order #{order.orderNumber}</h1>
      <p>Status: {order.status}</p>
      <ul>
        {order.items.map((item, index) => (
          <li key={index}>{item.quantity} x {item.buyerTitle ?? item.title}</li>
        ))}
      </ul>
      <p>Total: {(order.totalCents / 100).toFixed(2)} {order.currency}</p>
    </article>
  )
}
  • Read the order on the server, uncached, on every request: it changes as the merchant works on it. The buyer client sends every read with cache: 'no-store'. Without @lynkow/next, use a client created with fetchOptions: { cache: 'no-store' }, never one with a revalidating cache, which would keep serving the order and its address after the link is revoked.

  • The SDK sends the token in a request header, never in the URL, and never sends a customer session with it.

  • The token is a secret: anyone holding the link reads the order and its address. Keep it out of logs and analytics.

  • The link does not expire. An unknown or revoked token throws 'NOT_FOUND' with apiCode 'ORDER_NOT_FOUND', and so does any token while order history is off. A token over 128 characters throws 'VALIDATION_ERROR'. Too many lookups throw 'TOO_MANY_REQUESTS'.

The order has the shape customers.order() returns.

Buyer language

customer.preferredLocale is the language of the account emails, such as the password reset, or null for the site's default language. Activation sets it from its locale, and updateMe() changes it:

TypeScript
const customer = await lynkow.customers.updateMe({ preferredLocale: 'pt-BR' })
await lynkow.customers.updateMe({ preferredLocale: null }) // back to the site's default

preferredLocale is the only field and is required. Any language tag is accepted and stored normalized ('pt_br' becomes 'pt-BR'). An account whose email is not verified gets 'FORBIDDEN' with apiCode 'CUSTOMER_EMAIL_NOT_VERIFIED'.

An order's emails follow the language of its cart instead, which cart.setLocale() sets (Guide 24). A booking's emails follow the booking's locale (Guide 19).

Address book

TypeScript
// CustomerAddress (partial): { id, city, isDefaultShipping }
const address = await lynkow.customers.addresses.create({
  firstName: 'Alice',
  lastName: 'Martin',
  address1: '12 rue des Lilas',
  city: 'Lyon',
  postalCode: '69003',
  countryCode: 'FR', // ISO 3166-1 alpha-2
  isDefaultShipping: true,
})

const addresses = await lynkow.customers.addresses.list() // every page, as one array
await lynkow.customers.addresses.update(address.id, { city: 'Villeurbanne' })
await lynkow.customers.addresses.remove(address.id)

Every call needs a stored session. Setting an address as the default unsets the previous default, so read list() again after the change.

TypeScript
// Each entry: { channel, optedIn }, one per channel ('email', 'whatsapp')
const { channels } = await lynkow.customers.marketingConsent.list()

// Opt out of one channel, or pass channel: 'all'
const after = await lynkow.customers.marketingConsent.update({ channel: 'email', optIn: false })

optedIn is the buyer's latest choice on that channel, and false when there is none. On an opt-in, the optional locale and consentVersion record the language and the version of the consent text the buyer saw. An account whose email is not verified gets 'FORBIDDEN' with apiCode 'CUSTOMER_EMAIL_NOT_VERIFIED' on update().

Forgotten password

TypeScript
await lynkow.customers.passwordReset.request({ email: '[email protected]' })

// On the page the emailed link opens, /account/reset-password/<token> by default
await lynkow.customers.passwordReset.confirm({
  token: tokenFromTheUrl,
  password: 'a-new-strong-passphrase',
})

request() resolves the same way whether or not the address has an account. The link is valid for 60 minutes. confirm() signs out every session of the buyer and does not sign them in: they log in with the new password. An invalid, expired or used link throws 'BAD_REQUEST' with apiCode 'VERIFICATION_LINK_INVALID'.

Log out

TypeScript
await lynkow.customers.logout() // forget the token on this client, no request
await lynkow.customers.logout({ everywhere: true }) // also end every session of the buyer

Delete your own stored copy of the token at the same time (clearBuyerCookies() with @lynkow/next).

Next Steps