範例
這幾頁示範一個完整的付款流程,而不是零散的片段:預留付款、用戶回來後確認、結果未知時對帳、背景工作收尾。
所有範例共用同一個與框架無關的核心:examples/payment-service.ts。它只依賴函式庫與一個很小的 OrderStore 介面,所以不論你用 Express、Next.js、NestJS 還是別的,變的只有「把結果翻成 HTTP 回應」那一層。核心有測試,CI 也會對它做型別檢查;Express、Web 標準 handler 的範例只做型別檢查,沒有自己的測試;NestJS 與 Next.js 頁面上的程式碼是示意,沒有檢查。
訂單的狀態
付款流程是一個狀態機。把「進行中」寫成明確的狀態,是結果未知時還能收斂的關鍵:
| 狀態 | 意思 |
|---|---|
created | 訂單建立了,還沒送到 LINE Pay。 |
awaiting-approval | 已 request,用戶正在 LINE Pay 核准。 |
confirming | confirm 已送出,還沒有答案(或答案是未知)。 |
paid | 已付款。 |
needs-attention | 久久無法判斷,需要人到商家後台確認。 |
OrderStore 只要求一個特別的方法:transition(id, when, to, patch)。它必須是原子的條件更新(SQL 的 UPDATE … WHERE status = ANY($status) AND ($claimId IS NULL OR claim_id = $claimId))。這是同時湧入兩個請求時,只讓一個去 confirm 的關鍵;claimId 則讓一個慢的請求不能把別人較新的搶佔還回去。
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)
}
}
}核心做了什麼
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 }
}重點:
- **先寫下,再送出。**搶佔訂單時同時存下
ReconcileContext,所以就算行程在拿到回應前被殺掉,事後還有東西可以對帳。 - 金額來自訂單(
claimed.total),不是網址。 - 失敗分三條路:結果未知(連「對帳回
not-applied」也算)→ 訂單留在confirming,由背景工作稍後再看一次;確定沒生效(沒送出、被拒絕)→ 還給用戶,而且只有持有這次搶佔(claimId)的一方能還;不是這個函式庫的錯誤 → 丟出去。 - 付款是事實,但要是這張訂單的。
markPaid不論訂單當時在confirming、awaiting-approval還是needs-attention,都改成paid:背景工作可能在請求還在查的時候,已經把訂單還給用戶了。改之前先比對 LINE Pay 回報的orderId和request時存下的linePayOrderId,不符就轉給人處理。履約(onPaid)只在「把訂單改成paid」的那個行程執行一次。 - **成功後的資料庫寫入在
try之外。**如果寫入失敗,訂單留在confirming,背景工作會從付款明細發現它已付款。 - 每次
request用新的orderId。逾時時 LINE Pay 可能已經留下那個編號,同一個編號再來一次會被當成重複(1172)拒絕,這張訂單就永遠付不了。兩次連點的另一個請求也不會被送去付一筆沒人記得的交易。(這只適用於request:payPreapproved相反,重試要用同一個orderId,換新的就是新的一筆付款。)
選一個你的框架
- Express
- Web 標準 Handler:Next.js、Cloudflare Workers、Bun、Deno、Hono
- NestJS
- 背景對帳:收尾的那一半,和退款