Express
Read the recipes overview first to see what createPaymentService does. This page only deals with HTTP.
Routes
ts
// What this leaves out, and a shop needs: signing the user in and checking that the
// order is theirs, CSRF protection on the POST, and who may refund (see the security
// guide). It shows the part that is about LINE Pay.
export function createApp(payments: PaymentService) {
const app = express()
// The user pays an order: reserve it at LINE Pay and send them there.
app.post('/orders/:id/pay', async (req, res) => {
const paymentUrl = await payments.startCheckout(req.params.id)
res.redirect(303, paymentUrl)
})
// LINE Pay sends the user back here with ?transactionId=...&orderId=...
app.get('/line-pay/confirm', async (req, res) => {
const result = await payments.confirmPayment(req.query)
switch (result.kind) {
case 'paid':
res.redirect(303, `/orders/${encodeURIComponent(result.order.id)}`)
break
case 'in-progress':
res.status(202).send('We are confirming your payment. Please wait.')
break
case 'declined':
case 'retry':
res.redirect(
303,
`/orders/${encodeURIComponent(result.order.id)}?payment=failed`
)
break
case 'unknown-order':
res.sendStatus(404)
break
}
})
app.get('/line-pay/cancel', (_req, res) => {
res.redirect(303, '/cart')
})
// Express 5 passes the rejections of async handlers here.
app.use(
(error: unknown, _req: Request, res: Response, _next: NextFunction) => {
if (isLinePayValidationError(error)) {
res.status(400).send('Bad request')
return
}
console.error(error)
res.status(500).send('Something went wrong')
}
)
return app
}req.querygoes straight toconfirmPayment, which checks it withparseConfirmQuery. Express parses repeated parameters into arrays and nested keys into objects; both are refused.- Express 5 passes the rejections of async handlers to the error-handling middleware. Express 4 needs a wrapper (
express-async-errors, or a manualtry/catch). - A
LinePayValidationErrorbecomes a 400; the rest goes to your normal error handling. in-progressanswers 202: the payment may already have succeeded, you just do not know yet. The page can refresh itself, or poll the order state. Do not tell the user the payment failed.
Putting it together
ts
// An unset variable is the empty string, which createLinePayClient refuses by name.
const channelId = process.env.LINE_PAY_CHANNEL_ID ?? ''
const linePay = createLinePayClient({
channelId,
channelSecretKey: process.env.LINE_PAY_CHANNEL_SECRET ?? '',
env: 'sandbox'
})
const payments = createPaymentService({
linePay,
orders: createMemoryOrderStore(), // your database
siteUrl: 'https://shop.example',
channelId
})
createApp(payments).listen(3000)
// Settle the confirms that never got an answer. One run at a time: a run that is
// slow (LINE Pay is) must not be joined by the next one.
let sweeping = false
setInterval(() => {
if (sweeping) return
sweeping = true
payments
.settlePending({ olderThanMs: 5 * 60_000, giveUpAfterMs: 60 * 60_000 })
.catch((error: unknown) => console.error('settlePending failed', error))
.finally(() => {
sweeping = false
})
}, 60_000)The last part is the background job: once a minute it settles the confirm calls that never got an answer. See Background reconcile.
Several instances
It is safe to run several instances, and several background jobs at the same time: every transition is a conditional update, and only one wins.