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

@redonvn/vnpost-sdk

v0.2.0

Published

TypeScript SDK chuẩn hóa cho Tổng Công ty Bưu điện Việt Nam (VNPost / EMS) API

Readme

@redonvn/vnpost-sdk

TypeScript SDK chuẩn hóa giao tiếp với hệ sinh thái API Tổng Công ty Bưu điện Việt Nam (VNPost / EMS), tích hợp sẵn trong nền tảng RedAI.

SDK được xây dựng dựa trên đặc tả chuẩn từ Project Schema VNPost (projects/4d5e6f7a-8b9c-4d0e-1f2a-3b4c5d6e7f8a), bao quát toàn bộ 14 công cụ bưu chính bưu điện.


Tính năng nổi bật

  • 100% Type-Safe: Viết bằng TypeScript với định nghĩa kiểu dữ liệu hoàn chỉnh cho request và response.
  • Bao phủ 100% API Project Schema: Cung cấp đầy đủ 5 phân hệ dịch vụ đại diện cho 14 công cụ nghiệp vụ của VNPost.
  • Quản lý xác thực chuẩn mực: Tự động inject header Token: <token> và Content-Type: application/json.
  • Khả năng phục hồi cao: Tích hợp cơ chế tự động thử lại (Retry với Exponential Backoff) khi gặp sự cố mạng hoặc lỗi 5xx, cùng Timeout kiểm soát qua AbortController.
  • Xử lý lỗi thông minh: Phân loại mã lỗi VnpostErrorCode kèm các hàm kiểm tra tiện ích (isUnauthorized(), isOrderNotFound(), isInvalidAddress(), isRateLimited(), isServerError()).

Bảng đối chiếu Project Schema & SDK Methods

| STT | Tool Name trong Schema | Endpoint | Phương thức HTTP | Phân hệ SDK (Service) | Method trong SDK | |:---:|:---|:---|:---:|:---|:---| | 1 | vnpost_list_provinces | /categories/provinces | GET | masterData | vnpost.masterData.getProvinces() | | 2 | vnpost_list_districts | /categories/districts | GET | masterData | vnpost.masterData.getDistricts(params) | | 3 | vnpost_list_wards | /categories/wards | GET | masterData | vnpost.masterData.getWards(params) | | 4 | vnpost_postal_code_lookup | /postal-code/lookup | GET | masterData | vnpost.masterData.lookupPostalCode(params) | | 5 | vnpost_postoffices_list | /categories/post-offices | GET | masterData | vnpost.masterData.getPostOffices(params) | | 6 | vnpost_list_services | /categories/services | GET | masterData | vnpost.masterData.getServices() | | 7 | vnpost_calculate_fee | /order/calculate-fee | POST | orders | vnpost.orders.calculateFee(data) | | 8 | vnpost_order_create | /order/create | POST | orders | vnpost.orders.create(data) | | 9 | vnpost_order_print | /order/print | POST | orders | vnpost.orders.getPrintUrl(data) | | 10 | vnpost_order_tracking | /order/tracking | GET | orders | vnpost.orders.track(params) | | 11 | vnpost_order_cancel | /order/cancel | POST | orders | vnpost.orders.cancel(data) | | 12 | vnpost_pickup_schedule | /pickup/schedule | POST | pickup | vnpost.pickup.schedule(data) | | 13 | vnpost_claim_ticket | /ticket/create | POST | tickets | vnpost.tickets.create(data) | | 14 | vnpost_cod_reconciliation | /cod/reconciliation | GET | cod | vnpost.cod.getReconciliation(params) |


Cài đặt

npm install @redonvn/vnpost-sdk
# hoặc
pnpm add @redonvn/vnpost-sdk
# hoặc
yarn add @redonvn/vnpost-sdk

Hướng dẫn sử dụng

1. Khởi tạo Client

import { VnpostClient } from '@redonvn/vnpost-sdk';

const vnpost = new VnpostClient({
  token: process.env.VNPOST_API_TOKEN,
  environment: 'production', // 'production' hoặc 'staging'
  timeout: 30000,            // 30 giây
  retries: 2,                // Tự động thử lại 2 lần khi gặp lỗi mạng/5xx
});

Dành cho hệ thống nhiều người dùng (Multi-tenant / Dynamic User Token):

Nếu hệ thống backend của bạn phục vụ nhiều người dùng khác nhau và mỗi người cấu hình Token VNPost riêng, bạn có thể áp dụng 2 cách cực kỳ tiện lợi:

Cách A: Dùng Scoped Client với .withToken(token) (Khuyên dùng - Clean & Thread-Safe):

// Khởi tạo một singleton base client duy nhất trong ứng dụng:
export const vnpost = new VnpostClient({ environment: 'production' });

// Trong Controller/Service của từng user request:
const userClient = vnpost.withToken(user.vnpostToken);
const order = await userClient.orders.create({ ... });

Cách B: Truyền trực tiếp token qua options ở từng lời gọi hàm:

// Mọi hàm trong SDK đều nhận `options?: RequestOptions` ở tham số cuối cùng
const order = await vnpost.orders.create(orderPayload, {
  token: user.vnpostToken,
});
const tracking = await vnpost.orders.track(
  { itemCode: 'EM123456789VN' },
  { token: user.vnpostToken }
);

2. Danh mục hành chính & Bưu chính (masterData)

// 1. Danh sách 63 tỉnh / thành phố
const provinces = await vnpost.masterData.getProvinces();
console.log('Tỉnh/thành:', provinces.result);

// 2. Danh sách quận / huyện theo tỉnh
const districts = await vnpost.masterData.getDistricts({ provinceCode: '01' });

// 3. Danh sách phường / xã theo quận
const wards = await vnpost.masterData.getWards({ districtCode: '001' });

// 4. Tra cứu mã bưu chính quốc gia (Zip Code)
const postalCode = await vnpost.masterData.lookupPostalCode({
  address: 'Số 1 Đinh Lễ, Tràng Tiền, Hoàn Kiếm, Hà Nội',
});

// 5. Tra cứu danh sách bưu cục gần nhất
const postOffices = await vnpost.masterData.getPostOffices({
  provinceCode: '01',
  districtCode: '001',
});

// 6. Danh mục dịch vụ bưu chính VNPost / EMS
const services = await vnpost.masterData.getServices();

3. Vận đơn & Vận chuyển (orders)

// 1. Tính cước bưu chính
const feeEstimate = await vnpost.orders.calculateFee({
  senderProvinceId: '01',
  senderDistrictId: '001',
  receiverProvinceId: '79',
  receiverDistrictId: '760',
  weight: 650, // gram
  serviceCode: 'EMS',
  codAmount: 350000,
});
console.log(`Cước tạm tính: ${feeEstimate.result?.fee} VNĐ`);

// 2. Tạo đơn gửi bưu phẩm mới
const newOrder = await vnpost.orders.create({
  senderName: 'Kho Hàng RedON',
  senderPhone: '0901234567',
  senderAddress: 'Số 1 Đinh Lễ, Hoàn Kiếm, Hà Nội',
  receiverName: 'Nguyễn Văn A',
  receiverPhone: '0987654321',
  receiverAddress: '123 Lê Lợi, Bến Nghé, Quận 1, TP.HCM',
  weight: 650,
  serviceCode: 'EMS',
  codAmount: 350000,
  orderCode: 'DON-20261014-001',
  contentNote: 'Quần áo thời trang nam',
});
const trackingCode = newOrder.result?.trackingCode;

// 3. Lấy link in phiếu gửi bưu chính A5
if (trackingCode) {
  const printSheet = await vnpost.orders.getPrintUrl({
    itemCodes: [trackingCode],
  });
  console.log(`Link in phiếu A5: ${printSheet.result?.printUrl}`);

  // 4. Định vị theo dõi hành trình bưu kiện
  const trackingInfo = await vnpost.orders.track({
    itemCode: trackingCode,
  });
  console.log('Trạng thái bưu gửi:', trackingInfo.result);

  // 5. Hủy vận đơn chưa bàn giao
  const cancelResult = await vnpost.orders.cancel({
    itemCode: trackingCode,
  });
  console.log('Kết quả hủy:', cancelResult.message);
}

4. Đặt lịch thu gom tận nơi (pickup)

const pickupResult = await vnpost.pickup.schedule({
  pickupAddress: 'Tầng 5, Tòa nhà RedON, Cầu Giấy, Hà Nội',
  pickupPhone: '0901234567',
  pickupDate: '2026-10-15',
  packageCount: 15,
  pickupContactName: 'Anh Nam - Quản kho',
  note: 'Bưu tá đến lấy vào buổi chiều sau 14h',
});
console.log('Đặt lịch thu gom:', pickupResult.result);

5. Khiếu nại & Hỗ trợ bưu gửi (tickets)

const ticketResult = await vnpost.tickets.create({
  itemCode: 'EM123456789VN',
  claimContent: 'Bưu gửi chậm hơn cam kết 3 ngày, đề nghị kiểm tra định vị và phát lại sớm cho khách.',
  claimType: 'DELAY',
});
console.log('Mã phiếu hỗ trợ:', ticketResult.result?.ticketId);

6. Báo cáo đối soát tiền thu hộ COD (cod)

const reconciliation = await vnpost.cod.getReconciliation({
  fromDate: '2026-10-01',
  toDate: '2026-10-14',
  status: 'PAID',
});
console.log('Kỳ đối soát COD:', reconciliation.result);

7. Xử lý lỗi chuẩn mực

import { VnpostClient, VnpostApiError, VnpostErrorCode } from '@redonvn/vnpost-sdk';

const vnpost = new VnpostClient({ token: 'invalid_token' });

try {
  await vnpost.orders.track({ itemCode: 'INVALID_CODE' });
} catch (error) {
  if (error instanceof VnpostApiError) {
    console.error(`HTTP Status: ${error.statusCode}`);
    console.error(`Error Code: ${error.errorCode}`);

    if (error.isUnauthorized()) {
      console.error('Cảnh báo: Token API VNPost không hợp lệ hoặc đã hết hạn!');
    } else if (error.isOrderNotFound()) {
      console.error('Không tìm thấy mã bưu phẩm tương ứng!');
    } else if (error.isRateLimited()) {
      console.error('Bị giới hạn tần suất gọi API, vui lòng thử lại sau ít phút.');
    }
  }
}

Giấy phép

Phát hành theo giấy phép MIT. Bản quyền thuộc về Redon Development Team.