VNPay Library Documentation

website·Indexed 29 days ago

https://vnpay-lib.vercel.app/

An open-source library for integrating the VNPay Payment Gateway. Documentation covers creating payment URLs, generating QR codes, verifying IPN (Instant Payment Notification) calls and return URLs, processing refunds, and querying transaction results via QueryDR. Includes installation guides for NPM and NestJS, security best practices, and full-stack sample projects using Next.js 15.

Tokens
15.5K
Snippets
63
Records
101
Agent score
69%

What's inside VNPay

  1. Overview of the VNPay integration library

    The VNPay library is a free, open-source project designed to simplify and accelerate the integration of VNPay online payment gateways. Key features include a simple API, full TypeScript support, and support for both sandbox and production environments. Starting from version 2.4.0, it supports modular imports to reduce bundle size by up to 80% and utilizes tree-shaking and code splitting for build optimization. The library has minimal dependencies, relying only on dayjs for time processing.
  2. Overview of the VNPay library

    The VNPay library is an open-source project designed to simplify the integration of the VNPay online payment gateway. It provides a simple API, comprehensive TypeScript type definitions, and supports both sandbox and production environments. Starting from version 2.4.0, it supports modular imports to reduce bundle size by up to 80% through tree-shaking and code splitting. The library has minimal dependencies, relying only on dayjs for date handling.
  3. Implement VNPay payment redirect in Express MVC

    In an MVC architecture, the server handles order creation and immediately redirects the user to the generated VNPay URL. The customer is returned to the vnp_ReturnUrl after the transaction.
    app.post('/order', async (req, res) => {
        // 1. Create order
        const order = await createOrder(req.body);
    
        // 2. Create payment URL
        const paymentUrl = vnpay.buildPaymentUrl({
            vnp_Amount: 10000,
            vnp_IpAddr:
                req.headers['x-forwarded-for'] ||
                req.connection.remoteAddress ||
                req.socket.remoteAddress ||
                req.ip,
            vnp_TxnRef: order.orderId,
            vnp_OrderInfo: `Payment for order ${order.orderId}`,
            vnp_OrderType: ProductCode.Other,
            vnp_ReturnUrl: 'http://localhost:3000/vnpay-return',
            vnp_Locale: VnpLocale.VN,
        });
    
        // 3. Redirect customer
        return res.redirect(paymentUrl);
    });
  4. Enable Logging for VNPay Debugging

    You can capture detailed information about requests and responses by enabling the built-in logging features in the VNPay configuration. Use enableLog: true and provide a loggerFn to handle the log data.
    const vnpay = new VNPay({
        // ... other config
        enableLog: true,
        loggerFn: (data) => {
            console.log(JSON.stringify(data, null, 2));
            // Or save to a file/database
        },
    });
  5. Implement VNPay payment flow in a Full-stack architecture

    The vnpay library is designed exclusively for Node.js backends. It cannot be used directly in frontend frameworks (React, Vue, Angular) because it relies on Node.js modules like fs, crypto, and path, and requires a secureSecret that must remain hidden from the client. The recommended architecture is to handle all payment logic on the backend and communicate with the frontend via JSON API calls.
    ┌─────────────────┐    API calls    ┌─────────────────┐
    │   Frontend      │ ──────────────► │   Backend       │
    │                 │                 │                 │
    │ • React/Vue     │                 │ • Node.js       │
    │ • Types only    │                 │ • VNPay library │
    │ • UI components │ ◄────────────── │ • Payment logic │
    └─────────────────┘   JSON response └─────────────────┘
  6. Configure IPN URL for VNPay Sandbox environment

    To receive Instant Payment Notifications (IPN) from VNPay after a payment is completed, you must configure the IPN URL in the VNPay merchant portal. For the Sandbox environment, this can be done via the Terminal configuration page. Note that for Production environments, you must contact VNPay directly for support.
    # Direct link to Terminal configuration (after login)
    https://sandbox.vnpayment.vn/merchantv2/Account/TerminalEdit.htm
  7. Test and deploy VNPay integration to production

    Follow these steps to move from development to a stable production environment:

    Testing Phase:

    • Use the sandbox environment for all initial integration tests.
    • Simulate edge cases including payment failures, successful payments, and refunds.
    • Implement unit and integration tests specifically for the payment logic.

    Production Phase:

    • Monitoring: Track payment statuses and set up alerts for failed payments or unusual transaction volume spikes.
    • Maintenance: Plan for potential VNPay maintenance windows or downtime.
    • Reconciliation: Regularly reconcile transaction records between your internal system and VNPay's records.
  8. Migrate VNPay integration from Sandbox to Production

    If code works in sandbox but fails in production, check the following:

    • Update all configuration values to production credentials.
    • Verify production credentials directly with VNPay.
    • Ensure your production server IP address has been whitelisted in the VNPay production environment.
  9. Get help and support for the VNPay library

    If you encounter issues or have questions regarding the VNPay library, you can seek support through the following channels: open an issue on the official GitHub repository, browse existing community discussions, or review the provided examples directory for implementation guidance.
  10. Implement security best practices for VNPay integration

    To ensure the security of your VNPay integration, follow these critical practices:

    • Secret Management: Never expose the secureSecret in client-side code.
    • IP Validation: Validate and sanitize client IP addresses before transmission to VNPay.
    • Data Integrity: Use the verifyIpnCall and verifyReturnUrl methods to verify the integrity of all data received from VNPay.
    • Business Logic Placement: Execute critical business operations (e.g., updating order status, fulfilling orders) within the IPN (Instant Payment Notification) handler. The return URL should only be used for UI feedback as it can be bypassed by the user.
    • Amount Verification: Always cross-reference the transaction amount returned by VNPay against the expected amount stored in your database.
  11. Manage VNPay transactions and IPN idempotency

    Ensure reliable transaction processing by following these management rules:

    • Unique References: Generate a unique vnp_TxnRef for every transaction (e.g., combining Order ID with a timestamp).
    • Data Persistence: Store all transaction details in your database for reconciliation and support purposes.
    • Idempotency: VNPay may send duplicate IPN notifications. Implement idempotent logic to ensure a single transaction is not processed multiple times.
  12. Generate a VNPay payment URL

    Use the buildPaymentUrl method to create a payment URL containing the necessary transaction information to redirect customers to the VNPay Payment Gateway. The library automatically handles amount calculations (no need to multiply by 100) and secure hash generation.
    import { ProductCode, VnpLocale } from 'vnpay';
    
    const paymentUrl = vnpay.buildPaymentUrl({
        vnp_Amount: 10000,
        vnp_IpAddr: '13.160.92.202',
        vnp_TxnRef: '12345',
        vnp_OrderInfo: 'Payment for order 12345',
        vnp_OrderType: ProductCode.Other,
        vnp_ReturnUrl: 'http://localhost:3000/vnpay-return',
        vnp_Locale: VnpLocale.VN, // 'vn' or 'en'
    });