npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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.

Readme

line-pay-online-v4

npm version CI Coverage License: MIT TypeScript

🌏 English | 繁體中文 | 日本語 | ไทย

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:crypto and fetch)
  • 🧪 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 Page

Step 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