Skip to content

Recipes ​

These pages show a complete payment flow instead of loose snippets: reserve the payment, confirm it when the user comes back, reconcile when the outcome is unknown, and finish in a background job.

All recipes share one framework-independent core: examples/payment-service.ts. It depends only on the library and a very small OrderStore interface, so whether you use Express, Next.js, NestJS or something else, only the layer that turns results into HTTP responses changes. The core has tests and is type-checked in CI; the Express and Web-standard handler examples are only type-checked, with no tests of their own; the code on the NestJS and Next.js pages is a sketch and is not checked.

The states of an order ​

The payment flow is a state machine. Making "in progress" an explicit state is what lets it converge when the outcome is unknown:

StateMeaning
createdThe order exists and has not been sent to LINE Pay.
awaiting-approvalrequest was made; the user is approving in LINE Pay.
confirmingconfirm was sent and there is no answer yet (or the answer is unknown).
paidPaid.
needs-attentionUnclear for a long time; a person has to check the Merchant Center.

OrderStore needs one special method: transition(id, when, to, patch). It must be an atomic conditional update (in SQL: UPDATE … WHERE status = ANY($status) AND ($claimId IS NULL OR claim_id = $claimId)). That is what lets only one of two simultaneous requests go on to confirm; the claimId is what stops a slow request from giving back the newer claim of another.

ts
import type { ReconcileContext } from 'line-pay-merchant'

export type OrderStatus =
  /** Not sent to LINE Pay yet. */
  | 'created'
  /** Reserved at LINE Pay; the user is approving it. */
  | 'awaiting-approval'
  /** Confirm was sent and has not been answered (yet). */
  | 'confirming'
  | 'paid'
  /** A person has to look at it, in the LINE Pay Merchant Center. */
  | 'needs-attention'

export interface OrderItem {
  name: string
  quantity: number
  price: number
}

export interface Order {
  id: string
  items: OrderItem[]
  /** In TWD. Always taken from here, never from the URL. */
  total: number
  status: OrderStatus
  /**
   * Returned by `request`; also what LINE Pay puts on the confirmUrl. Text, never
   * a number: it has 19 digits, which a JavaScript number cannot hold exactly. In
   * SQL a `TEXT` or `VARCHAR(19)` column, not `BIGINT`.
   */
  transactionId?: string
  /**
   * The order ID that was sent to `request` for the current reservation. LINE
   * Pay reports it back with the payment, and an order is only marked paid when
   * the payment carries this one. Text as well: it may have leading zeros.
   */
  linePayOrderId?: string
  /**
   * Who holds the order while it is `confirming`: a random token, new for every
   * claim. A request that took the order can release it; one that was slow and
   * whose claim has been replaced cannot.
   */
  claimId?: string
  /** Written down before confirm is sent, so a sweeper can reconcile it later. */
  pendingConfirm?: ReconcileContext
  updatedAt: Date
}

/** What an order has to be like for a change to be made. */
export interface Expect {
  status: OrderStatus | readonly OrderStatus[]
  /** Only the holder of this claim. */
  claimId?: string
  /**
   * Only while the order has this transaction ID (`null`: while it has none).
   * Whoever read the order and reserves a payment for it says which reservation
   * it saw, so that of two reservations made at once only one is kept.
   */
  transactionId?: string | null
}

export interface OrderStore {
  find(id: string): Promise<Order | undefined>
  findByTransactionId(transactionId: string): Promise<Order | undefined>
  /** Orders that have been in `status` since before `before`. */
  findStale(status: OrderStatus, before: Date): Promise<Order[]>
  /**
   * Change the order only if it is still as `when` says, and say whether it was.
   * Two requests for the same order must not both win: in SQL this is
   * `UPDATE orders SET status = $to WHERE id = $id AND status = ANY($status)
   * AND ($claimId IS NULL OR claim_id = $claimId)
   * AND ($check_tx = false OR transaction_id IS NOT DISTINCT FROM $transactionId)`.
   */
  transition(
    id: string,
    when: Expect,
    to: OrderStatus,
    patch?: Partial<
      Pick<
        Order,
        'transactionId' | 'linePayOrderId' | 'pendingConfirm' | 'claimId'
      >
    >
  ): Promise<Order | undefined>
}

/** An in-memory store, for the examples and the tests. Use your database. */
export function createMemoryOrderStore(orders: Order[] = []): OrderStore {
  const byId = new Map(orders.map(order => [order.id, order]))

  return {
    find: id => Promise.resolve(byId.get(id)),

    findByTransactionId: transactionId =>
      Promise.resolve(
        [...byId.values()].find(order => order.transactionId === transactionId)
      ),

    findStale: (status, before) =>
      Promise.resolve(
        [...byId.values()].filter(
          order => order.status === status && order.updatedAt < before
        )
      ),

    transition(id, when, to, patch) {
      const order = byId.get(id)
      const statuses: readonly OrderStatus[] =
        typeof when.status === 'string' ? [when.status] : when.status
      if (
        order === undefined ||
        !statuses.includes(order.status) ||
        (when.claimId !== undefined && order.claimId !== when.claimId) ||
        (when.transactionId !== undefined &&
          (order.transactionId ?? null) !== when.transactionId)
      ) {
        return Promise.resolve(undefined)
      }
      const next: Order = {
        ...order,
        ...patch,
        status: to,
        updatedAt: new Date()
      }
      byId.set(id, next)
      return Promise.resolve(next)
    }
  }
}

What the core does ​

ts
/** Reserve the payment at LINE Pay. Send the user to the URL it returns. */
async function startCheckout(orderId: string): Promise<string> {
  const order = await orders.find(orderId)
  // "awaiting-approval" too: the user who cancelled at LINE Pay, or closed the
  // page, comes back and pays again. The reservation they leave behind is not
  // the order's any more, so it is never confirmed, and it expires.
  if (order?.status !== 'created' && order?.status !== 'awaiting-approval') {
    throw new Error(`Order ${orderId} cannot be paid`)
  }

  // A new one for every try. If this request ends without an answer, LINE Pay
  // may have kept the order ID, and asking again with the same one would be
  // refused as a duplicate (1172), however often it is repeated.
  const linePayOrderId = `${order.id}-${crypto.randomUUID().slice(0, 8)}`
  const { body } = await linePay.request({
    amount: order.total,
    currency: 'TWD',
    orderId: linePayOrderId,
    packages: [
      {
        id: order.id,
        amount: order.total,
        products: order.items.map(({ name, quantity, price }) => ({
          name,
          quantity,
          price
        }))
      }
    ],
    redirectUrls: {
      confirmUrl: `${siteUrl}/line-pay/confirm`,
      cancelUrl: `${siteUrl}/line-pay/cancel`
    }
  })

  // The transaction ID is the key for confirm, refund and reconcile, and it
  // is what LINE Pay puts on the confirmUrl.
  const reserved = await orders.transition(
    order.id,
    {
      status: ['created', 'awaiting-approval'],
      // The reservation this request saw. Of two that are made at once, only
      // the first finds the order as it read it.
      transactionId: order.transactionId ?? null
    },
    'awaiting-approval',
    { transactionId: body.info.transactionId, linePayOrderId }
  )
  // Two clicks at once: the other request was first, and its transaction is
  // the one that counts. This one is never confirmed, and expires.
  if (reserved === undefined) {
    throw new Error(`Order ${orderId} is already being paid`)
  }
  return body.info.paymentUrl.web
}
ts
/** Call it with the query of the confirmUrl, when the user comes back. */
async function confirmPayment(
  source: ConfirmQuerySource
): Promise<ConfirmResult> {
  // The query comes from the user's browser. This refuses everything that is
  // not a single string of 1 to 19 digits.
  const { transactionId } = parseConfirmQuery(source)

  const order = await orders.findByTransactionId(transactionId)
  if (order === undefined) return { kind: 'unknown-order' }
  if (order.status === 'paid') return { kind: 'paid', order }
  if (order.status !== 'awaiting-approval') {
    return { kind: 'in-progress', order }
  }

  // Write down what is about to happen *before* it happens, and let only one
  // request through. If this process dies before LINE Pay answers, there is
  // no error to look at: settlePending reconciles from this record instead.
  const pendingConfirm: ReconcileContext = {
    operation: 'confirm',
    startedAt: new Date(),
    channelId,
    transactionId,
    amount: order.total,
    currency: 'TWD'
  }
  const claimed = await orders.transition(
    order.id,
    { status: 'awaiting-approval' },
    'confirming',
    { pendingConfirm, claimId: crypto.randomUUID() }
  )
  if (claimed === undefined) return { kind: 'in-progress', order }

  let paidOrderId: string
  try {
    // The amount is the one of our order, never one that came with the URL.
    const { body } = await linePay.confirm({
      transactionId,
      amount: claimed.total,
      currency: 'TWD'
    })
    paidOrderId = body.info.orderId
  } catch (error) {
    return afterFailedConfirm(claimed, error)
  }
  return markPaid(claimed, paidOrderId)
}
ts
/** The order as its holder knows it: still `confirming`, and still its claim. */
const held = (order: Order): Expect =>
  order.claimId === undefined
    ? { status: 'confirming' }
    : { status: 'confirming', claimId: order.claimId }

/**
 * What LINE Pay shows is the fact, and the order follows it wherever it is
 * now: a sweeper may have given it back (confirming → awaiting-approval) while
 * we were still looking.
 */
async function markPaid(
  order: Order,
  paidOrderId: string
): Promise<ConfirmResult> {
  // The payment is for the order ID this order was reserved with. A payment
  // that carries another one is not this order's, whatever its transaction ID
  // says: money moved and it is not clear for what, so a person looks.
  if (
    order.linePayOrderId !== undefined &&
    paidOrderId !== order.linePayOrderId
  ) {
    const flagged = await orders.transition(
      order.id,
      { status: ['confirming', 'awaiting-approval'] },
      'needs-attention'
    )
    return {
      kind: 'in-progress',
      order: flagged ?? (await orders.find(order.id)) ?? order
    }
  }

  const paid = await orders.transition(
    order.id,
    { status: ['confirming', 'awaiting-approval', 'needs-attention'] },
    'paid'
  )
  // Only the process that made the order paid fulfils it.
  if (paid !== undefined) await onPaid?.(paid)
  // Someone else may have been first, which is fine if it ends up paid.
  const current = paid ?? (await orders.find(order.id)) ?? order
  return current.status === 'paid'
    ? { kind: 'paid', order: current }
    : { kind: 'in-progress', order: current }
}

async function afterFailedConfirm(
  order: Order,
  error: unknown
): Promise<ConfirmResult> {
  // Not an error of this library, so a bug of ours. Leave the order
  // "confirming": settlePending looks at it later.
  if (!isLinePayError(error)) throw error

  if (needsReconcile(error)) {
    // A timeout, a cut connection, an internal error of LINE Pay, or
    // "duplicate": the payment may well have gone through.
    const result = await linePay.reconcile(error)
    if (result.status === 'applied' && result.operation === 'confirm') {
      return markPaid(order, result.body.info.orderId)
    }
    // Not even "not-applied" lets the user try at once. One look at the
    // payment details right after a timeout proves little: they can be late.
    // settlePending looks again, minutes later, and gives the order back if
    // there is still nothing.
    return { kind: 'in-progress', order }
  }

  // Sent, and no answer, but nothing to look the call up with: settlePending
  // has the context that was written down before the call.
  if (error.outcome === 'unknown') return { kind: 'in-progress', order }

  // Never sent, or refused by LINE Pay: it did not happen. Give the order back,
  // but only if it is still ours: a request that was slow must not release the
  // claim of a newer one.
  const released =
    (await orders.transition(order.id, held(order), 'awaiting-approval')) ??
    order
  if (isLinePayApiError(error)) {
    return { kind: 'declined', order: released, returnCode: error.returnCode }
  }
  return { kind: 'retry', order: released }
}

The points to note:

  1. Write it down, then send it. The claim stores a ReconcileContext in the same step, so even if the process is killed before the answer arrives, there is something to reconcile from later.
  2. The amount comes from the order (claimed.total), not from the URL.
  3. A failure takes one of three paths: unknown outcome (even a reconcile that says not-applied) → the order stays confirming, and the background job looks once more later; provably did not take effect (never sent, refused) → give the order back to the user, and only the holder of the claim (claimId) may; not an error of this library → rethrow.
  4. The payment is the fact, but it has to be this order's. markPaid makes the order paid whether it is confirming, awaiting-approval or needs-attention: the background job may already have given it back while the request was still looking. Before it does, it compares the orderId that LINE Pay reports with the linePayOrderId stored at request, and hands a mismatch to a person. Fulfilment (onPaid) runs once, in the process that made the order paid.
  5. The database write after a success is outside the try. If it fails, the order stays confirming, and the background job discovers from the payment details that it was paid.
  6. Every request gets a new orderId. After a timeout LINE Pay may have kept the ID, and asking again with the same one is refused as a duplicate (1172), so the order could never be paid. The other request of a double click is not sent to pay a transaction nobody recorded either. (That holds for request only: for payPreapproved it is the opposite, a retry must use the same orderId, because a new one is a new payment.)

Pick your framework ​

Released under the MIT License. An independent library, not made or endorsed by LINE Pay.