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 🙏

© 2025 – Pkg Stats / Ryan Hefner

ecpay-einvoice-b2c-node

v1.1.1

Published

ECPay e-Invoice API wrapper for Node.js

Readme

ECPay e-Invoice B2C SDK for Node.js

A modern, TypeScript-based SDK for ECPay (綠界科技) B2C e-Invoice API.

繁體中文說明


Features

  • 🚀 Full TypeScript Support: Typed interfaces and Enums for all parameters.
  • 🛡️ Zod Validation: Runtime validation to catch errors before sending to ECPay.
  • 🔒 Security: Automatic AES-128-CBC encryption and decryption of payloads.
  • 📦 Modern Stack: Built with axios, zod, and typescript.
  • High Test Coverage: 100% line coverage, 90%+ branch coverage.

Supported Scope

  • Service: ECPay B2C e-Invoice API (Business-to-Consumer).
  • Environment: Taiwan (ROC) Electronic Invoice System.
  • Unsupported: B2B (Business-to-Business) invoicing is not supported.
  • API Version: Compatible with ECPay e-Invoice API v2.x.

Installation

npm install ecpay-einvoice-b2c-node
# or
pnpm add ecpay-einvoice-b2c-node
# or
yarn add ecpay-einvoice-b2c-node

Quick Start

1. Initialize Client

⚠️ Security Warning: The credentials shown below are ECPay staging/test credentials for demonstration only. Never commit real credentials to version control! Use environment variables in production.

import { EcPayClient } from 'ecpay-einvoice-b2c-node'

// Using environment variables (recommended)
const client = new EcPayClient(
    process.env.ECPAY_SERVER_URL || 'https://einvoice-stage.ecpay.com.tw',
    process.env.ECPAY_HASH_KEY || 'ejCk326UnaZWKisg',   // Test key
    process.env.ECPAY_HASH_IV || 'q9jcZX8Ib9LM8wYk',    // Test IV
    process.env.ECPAY_MERCHANT_ID || '2000132'          // Test MerchantID
)

Using dotenv for local development:

npm install dotenv

Create .env file (add to .gitignore):

ECPAY_SERVER_URL=https://einvoice-stage.ecpay.com.tw
ECPAY_HASH_KEY=your_hash_key
ECPAY_HASH_IV=your_hash_iv
ECPAY_MERCHANT_ID=your_merchant_id

Note: Use https://einvoice.ecpay.com.tw for production.

2. Issue an Invoice (開立發票)

import { EcPayClient, TaxType, PrintMark, Donation, CarrierType } from 'ecpay-einvoice-b2c-node'

const response = await client.issueInvoice({
    RelateNumber: 'INV' + Date.now(),
    CustomerEmail: '[email protected]',
    SalesAmount: 100,
    Print: PrintMark.NO,
    Donation: Donation.NO,
    CarrierType: CarrierType.NONE,
    TaxType: TaxType.DUTIABLE,
    Items: [
        {
            ItemName: 'Test Product',
            ItemCount: 1,
            ItemWord: 'pc',
            ItemPrice: 100,
        }
    ]
})

console.log('Invoice Number:', response.Data?.InvoiceNo)

3. Issue Allowance (開立折讓)

import { AllowanceNotifyType } from 'ecpay-einvoice-b2c-node'

const response = await client.issueAllowance({
    InvoiceNo: 'AB12345678',
    InvoiceDate: '2023-10-01',
    AllowanceNotify: AllowanceNotifyType.EMAIL,
    CustomerName: 'Mr. Wang',
    NotifyMail: '[email protected]',
    AllowanceAmount: 50,
    Items: [
        {
            ItemName: 'Test Product',
            ItemCount: 1,
            ItemWord: 'pc',
            ItemPrice: 50
        }
    ]
})

4. Invalidate Invoice (發票作廢)

await client.invalidInvoice({
    InvoiceNo: 'AB12345678',
    InvoiceDate: '2023-10-01',
    Reason: 'Defective product'
})

5. Query Invoice (查詢發票)

const response = await client.getInvoice({
    InvoiceNo: 'AB12345678',
    InvoiceDate: '2023-10-01'
})
console.log('Invoice Details:', response.Data)

6. Check Love Code (驗證愛心碼)

const response = await client.checkLoveCode({
    LoveCode: '168001'
})
console.log('Is Valid:', response.Data?.IsExist === 'Y')

7. Check Mobile Barcode (驗證手機條碼)

const response = await client.checkBarcode({
    BarCode: '/AB12345'
})
console.log('Is Valid:', response.Data?.IsExist === 'Y')

Supported Operations

| Method | Description | Status | |--------|-------------|--------| | issueInvoice | Issue a new B2C invoice | ✅ | | issueAllowance | Issue an allowance (refund) | ✅ | | invalidInvoice | Void an invoice | ✅ | | getInvoice | Query invoice details | ✅ | | checkLoveCode | Validate love code | ✅ | | checkBarcode | Validate mobile barcode | ✅ |

Enums

The SDK provides typed enums for all ECPay parameters:

import {
    TaxType,        // 應稅類別: DUTIABLE, ZERO, FREE, MIXED
    PrintMark,      // 是否列印: YES, NO
    Donation,       // 是否捐贈: YES, NO
    CarrierType,    // 載具類別: NONE, MEMBER, CITIZEN, CELLPHONE
    ClearanceMark,  // 通關方式: YES, NO
    InvType,        // 發票類別: GENERAL, SPECIAL, ALLOWANCE
    AllowanceNotifyType // 折讓通知: NONE, SMS, EMAIL
} from 'ecpay-einvoice-b2c-node'

Error Handling

The SDK throws errors with descriptive messages for validation failures:

try {
    await client.issueInvoice({ /* invalid data */ })
} catch (error) {
    if (error instanceof Error) {
        console.error('Validation Error:', error.message)
    }
}

API Response

All methods return an EcPayResponse object:

interface EcPayResponse<T = any> {
    RtnCode: number      // 0 = error, 1 = success
    RtnMsg: string       // Response message
    Data?: T             // Decrypted response data
    TransCode?: number   // Transaction code
    TransMsg?: string    // Transaction message
}

Development

# Install dependencies
pnpm install

# Build
pnpm build

# Run tests
pnpm test

# Run tests with coverage
pnpm test:coverage

# Format code
pnpm format

Documentation

Examples

Example files are in the examples/ directory:

| File | Description | |------|-------------| | issue_invoice_example.ts | Issue a new invoice | | issue_allowance_example.ts | Issue an allowance (refund) | | invalid_invoice_example.ts | Void an invoice | | get_invoice_example.ts | Query invoice details | | check_love_code_example.ts | Validate love code | | check_barcode_example.ts | Validate mobile barcode | | error_handling_example.ts | Comprehensive error handling | | custom_config_example.ts | Custom axios, logger, retry config |

Run examples:

npx ts-node examples/issue_invoice_example.ts

License

MIT

Contributing

Contributions are welcome! Please read CONTRIBUTING.md for details.