line-pay-online-v4
v1.7.0
Published
Modern, type-safe LINE Pay Online V4 API SDK for Node.js & Bun. Features Builder Pattern, full TypeScript support, ESM/CJS dual modules, zero dependencies, and 100% test coverage. Supports Taiwan, Japan, and Thailand regions.
Maintainers
Readme
line-pay-online-v4
LINE Pay V4 API SDK for Node.js - Type-safe, modern, and production-ready.
✨ Features
- 🚀 Modern TypeScript - Built with TypeScript 5.7+ and strict type checking
- 🛠 Builder Pattern - Fluent interface for constructing payment requests
- 📦 Dual Module Support - Works with both ESM and CommonJS
- 🔒 Type-Safe - Full type definitions for all Requests and Responses
- ⚡ Lightweight - Minimal dependencies (only
node:cryptoandfetch) - 🧪 100% Test Coverage - Thoroughly tested and reliable
📦 Installation
# npm
npm install line-pay-online-v4
# yarn
yarn add line-pay-online-v4
# pnpm
pnpm add line-pay-online-v4
# bun
bun add line-pay-online-v4🚀 Usage
1. Initialize Client
import { LinePayClient } from 'line-pay-online-v4'
const client = new LinePayClient({
channelId: 'YOUR_CHANNEL_ID',
channelSecret: 'YOUR_CHANNEL_SECRET',
env: 'sandbox', // or 'production'
timeout: 5000 // optional, default 20000ms
})2. Request Payment
Use the RequestPayment builder to construct payment requests with built-in validation.
The builder automatically validates:
- Required fields (amount, currency, orderId, packages, redirectUrls)
- Total amount matches sum of package amounts
- Each package amount matches sum of product amounts
import { Currency } from 'line-pay-online-v4'
try {
// Use client.payment() factory method (recommended)
const response = await client.payment()
.setAmount(100)
.setCurrency(Currency.TWD)
.setOrderId('ORDER_20231201_001')
.addPackage({
id: 'PKG_1',
amount: 100,
products: [
{
name: 'Premium Plan',
quantity: 1,
price: 100
}
]
})
.setRedirectUrls(
'https://example.com/confirm', // Your server confirm URL
'https://example.com/cancel' // Your server cancel URL
)
.setOptions({ display: { locale: 'en' } }) // Optional
.send()
// Get Payment URL and Transaction ID
const paymentUrl = response.info.paymentUrl.web
const transactionId = response.info.transactionId
console.log('Payment URL:', paymentUrl)
console.log('Transaction ID:', transactionId)
// Redirect user to paymentUrl...
} catch (error) {
console.error('Payment Request Failed:', error)
}Alternative: You can also use
new RequestPayment(client)directly if preferred.
3. 💳 Complete Online Payment Flow
Referencing the LINE Pay Online API Guide, the standard flow consists of 3 main steps:
Step 1: Request Payment & Redirect User
Your backend server calls the requestPayment API to get a paymentUrl, then redirects the user's browser to that URL.
// Backend Code (Node.js/Express Example)
app.post('/api/checkout', async (req, res) => {
const orderId = `ORDER_${Date.now()}`
// 1. Call LINE Pay API
const result = await client.payment()
.setAmount(100)
.setCurrency(Currency.TWD)
.setOrderId(orderId)
.addPackage({
id: 'pkg-1',
amount: 100,
products: [{ name: 'Product A', quantity: 1, price: 100 }]
})
.setRedirectUrls(
'https://your-domain.com/pay/confirm', // Redirect here after approval
'https://your-domain.com/pay/cancel'
)
.send()
// 2. Return paymentUrl to frontend or redirect directly
// Note: Store transactionId in your DB to verify later
res.json({
url: result.info.paymentUrl.web,
transactionId: result.info.transactionId
})
})Step 2: User Authorization
The user confirms the payment on the LINE Pay payment page. Upon success, LINE Pay redirects the user back to your confirmUrl with transactionId and orderId parameters:
https://your-domain.com/pay/confirm?transactionId=123456789&orderId=ORDER_...
Payment Flow Diagram
sequenceDiagram
participant User
participant Server as Merchant Server
participant LINE as LINE Pay API
User->>Server: 1. Click Checkout
Server->>LINE: 2. Request Payment API
LINE-->>Server: Return paymentUrl & transactionId
Server-->>User: 3. Redirect to paymentUrl
User->>LINE: 4. Approve Payment (on LINE App/Web)
LINE-->>User: 5. Redirect to confirmUrl
User->>Server: 6. Callback (transactionId & orderId)
Server->>LINE: 7. Confirm API
LINE-->>Server: Payment Completed
Server-->>User: 8. Show Success PageStep 3: Confirm Payment
When the user returns to your confirmUrl, you MUST call the Confirm API to finalize the transaction. If not called within the expiration window, the transaction will lapse.
// Backend Code (Handle confirmUrl route)
app.get('/pay/confirm', async (req, res) => {
const { transactionId, orderId } = req.query
try {
// 3. Call Confirm API to complete transaction
const response = await client.confirm(transactionId as string, {
amount: 100, // Must match the amount requested
currency: Currency.TWD
})
if (response.returnCode === '0000') {
// Success
console.log('Transaction Completed:', response.info)
res.redirect('/payment/success')
} else {
console.error('Payment Failed:', response.returnMessage)
res.redirect('/payment/failure')
}
} catch (error) {
console.error('API Error:', error)
res.redirect('/payment/error')
}
})4. Other Operations
Capture Payment
For "AUTHORIZATION" flows where capture is manual.
await client.capture(transactionId, {
amount: 100,
currency: Currency.TWD
})Void Payment
Void an authorized but not yet captured payment.
await client.void(transactionId)Refund Payment
Refund a completed payment.
// Full Refund
await client.refund(transactionId)
// Partial Refund
await client.refund(transactionId, { refundAmount: 50 })Get Payment Details
Query transaction history.
const details = await client.getDetails({
transactionId: ['123456789'],
fields: 'transactionId,amount,currency'
})Check Payment Status
Check the status of a specific transaction.
const status = await client.checkStatus(transactionId)5. Utilities
The SDK provides a LinePayUtils class for common tasks.
Parse Callback Parameters
Extract transactionId and orderId from the Confirm URL query.
import { LinePayUtils } from 'line-pay-online-v4'
// In your callback handler (e.g. Express)
const { transactionId, orderId } = LinePayUtils.parseConfirmQuery(req.query)Verify HMAC Signature
If you need to verify signatures (e.g. for custom webhooks).
const isValid = LinePayUtils.verifySignature(channelSecret, body, signature)🏗️ Project Structure
line-pay-online-v4/
├── src/ # Source code
├── examples/ # Usage examples
│ └── nextjs-demo/ # Next.js App Router example
├── tests/ # Test files
└── dist/ # Build output🎮 Examples
Check out the Next.js Example for a complete integration with App Router.
📄 License
MIT
