跳到內容

Express ​

先讀範例總覽,了解 createPaymentService 做了什麼。這一頁只處理 HTTP 的部分。

路由 ​

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.query 直接交給 confirmPayment,由 parseConfirmQuery 檢查。Express 把重複的參數解析成陣列、巢狀的鍵解析成物件,這些都會被拒絕。
  • Express 5 會把非同步 handler 的拒絕交給錯誤處理 middleware。Express 4 需要自己包(express-async-errors 或手動 try/catch)。
  • LinePayValidationError 對應 400;其餘交給你原本的錯誤處理。
  • in-progress 回 202:付款可能已經成功,只是還不知道。頁面可以自動重新整理,或用輪詢查訂單狀態。不要告訴用戶付款失敗。

組起來 ​

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)

最後一段是背景工作:每分鐘處理一次沒拿到答案的 confirm。詳見背景對帳。

多個實例 ​

可以放心地同時跑多個實例,也可以同時有多個背景工作:每一個轉換都是條件更新,只有一個會贏。

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