### Install VNPay with NPM Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/02_installation.md Use NPM to install the VNPay library. This is a standard installation command. ```bash $ npm install vnpay ``` -------------------------------- ### Install vnpayjs Source: https://github.com/lehuygiang28/vnpay/blob/main/README.md Install the vnpayjs library using NPM, Yarn, or PNPM. ```bash # NPM npm install vnpay # Yarn yarn add vnpay # PNPM pnpm install vnpay ``` -------------------------------- ### Install VNPay with PNPM Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/02_installation.md Use PNPM to install the VNPay library. This is an alternative package manager installation command. ```bash $ pnpm install vnpay ``` -------------------------------- ### Install VNPay with Yarn Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/02_installation.md Use Yarn to add the VNPay library to your project dependencies. This command is equivalent to the NPM installation. ```bash $ yarn add vnpay ``` -------------------------------- ### Query Transaction Result with Logger - VNPAY SDK Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/07_query-dr.md This example demonstrates how to query transaction results with custom logging enabled. Initialize the VNPay SDK with `enableLog: true` and provide a `loggerFn` to handle log data. Ensure the date is in GMT+7 and formatted correctly. ```typescript import { QueryDr, QueryDrResponse, getDateInGMT7, dateFormat } from 'vnpay'; /* ... */ /** * Ngày phải ở múi giờ GMT+7 * Và được định dạng theo `yyyyMMddHHmmss` * Sử dụng các hàm `getDateInGMT7` và `dateFormat` để chuyển đổi */ const date = dateFormat(getDateInGMT7(new Date('2024/05/21'))); const res: QueryDrResponse = await vnpay.queryDr( { vnp_RequestId: generateRandomString(16), vnp_IpAddr: '1.1.1.1', vnp_TxnRef: '1716257871703', vnp_TransactionNo: 14422574, vnp_OrderInfo: 'Thanh toan don hang', vnp_TransactionDate: date, vnp_CreateDate: date, } as QueryDr, { logger: { type: 'all', loggerFn: (data) => { console.log(data.message); // Hoặc gửi log đến server, cơ sở dữ liệu, v.v. }, }, }, ); ``` -------------------------------- ### Frontend Type Usage Example Source: https://context7.com/lehuygiang28/vnpay/llms.txt Illustrates how to use types for frontend development (React/Vue/Angular) by defining an interface that picks specific properties from the `BuildPaymentUrl` type. Note that the `VNPay` class should not be imported on the frontend. ```typescript // Sử dụng types cho frontend (React/Vue/Angular) // QUAN TRỌNG: Không import VNPay class ở frontend vì nó dùng Node.js modules interface PaymentFormData extends Pick { orderId: string; } const formData: PaymentFormData = { orderId: '123', vnp_Amount: 100000, vnp_OrderInfo: 'Thanh toan don hang 123', }; ``` -------------------------------- ### Get Bank List with VNPay SDK Source: https://context7.com/lehuygiang28/vnpay/llms.txt Fetches a list of banks supported by VNPay for payment. Use this to populate a user's bank selection dropdown. Requires VNPay SDK initialization with merchant credentials. ```typescript import { VNPay } from 'vnpay'; import type { Bank } from 'vnpay'; const vnpay = new VNPay({ tmnCode: '2QXUI4B4', secureSecret: 'SCSECRET0123456789', testMode: true, }); async function displayBankList() { const banks: Bank[] = await vnpay.getBankList(); console.log('Danh sách ngân hàng:'); banks.forEach((bank) => { console.log({ code: bank.bank_code, // 'NCB', 'VIETCOMBANK', ... name: bank.bank_name, // 'Ngân hàng NCB', ... logo: bank.logo_link, // URL logo ngân hàng type: bank.bank_type, // Loại ngân hàng order: bank.display_order, // Thứ tự hiển thị }); }); // Output: // { code: 'NCB', name: 'Ngan hang NCB', logo: 'https://...', type: 1, order: 1 } // { code: 'VIETCOMBANK', name: 'Ngan hang Vietcombank', logo: 'https://...', type: 1, order: 2 } // ... return banks; } ``` -------------------------------- ### Express.js IPN Handling Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/05_ipn/02_verify-ipn-call.md This section provides a comprehensive example of how to handle and verify VNPay IPN requests within an Express.js application. It covers routing, verification, order lookup, status updates, and error handling. ```APIDOC ## POST /vnpay-ipn (Express.js Example) ### Description Handles VNPay IPN requests in an Express.js application, including verification, order processing, and status updates. ### Method POST ### Endpoint /vnpay-ipn ### Parameters (See 'Verify IPN Call' section for query parameters) ### Request Body (Not applicable, uses query parameters) ### Request Example ```typescript title="controllers/payment.controller.ts" import { IpnFailChecksum, IpnOrderNotFound, IpnInvalidAmount, InpOrderAlreadyConfirmed, IpnUnknownError, IpnSuccess, VerifyReturnUrl // Assuming VerifyReturnUrl is the correct type for req.query } from 'vnpay'; /* ... */ app.post('/vnpay-ipn', async (req, res) => { try { const verify: VerifyReturnUrl = vnpay.verifyIpnCall(req.query); if (!verify.isVerified) { return res.json(IpnFailChecksum); } if (!verify.isSuccess) { return res.json(IpnUnknownError); } // Find the order in the database const foundOrder = await findOrderById(verify.vnp_TxnRef); // Implement this method // If order not found or order ID mismatch if (!foundOrder || verify.vnp_TxnRef !== foundOrder.orderId) { return res.json(IpnOrderNotFound); } // If payment amount does not match if (verify.vnp_Amount !== foundOrder.amount) { return res.json(IpnInvalidAmount); } // If order has already been confirmed if (foundOrder.status === 'completed') { return res.json(InpOrderAlreadyConfirmed); } /** * After successful order verification, * update the order status in your database */ foundOrder.status = 'completed'; await updateOrder(foundOrder); // Implement this method // Then update VNPay to confirm order processing return res.json(IpnSuccess); } catch (error) { /** * Handle exceptions * e.g., insufficient data, invalid data, database update errors */ console.log(`verify error: ${error}`); return res.json(IpnUnknownError); } }); ``` ### Response #### Success Response (200) - **IpnSuccess**: Indicates successful IPN processing. - **IpnFailChecksum**: Indicates a checksum failure during verification. - **IpnOrderNotFound**: Indicates the order was not found. - **IpnInvalidAmount**: Indicates the payment amount is invalid. - **InpOrderAlreadyConfirmed**: Indicates the order was already confirmed. - **IpnUnknownError**: Indicates an unknown error occurred. #### Response Example ```json { "message": "success" } ``` ``` -------------------------------- ### Incorrect Frontend VNPAY Import - Causes Build Errors Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/20_examples.md Avoid instantiating the VNPay class directly in the browser, as it may rely on Node.js modules like 'fs' and cause build failures. This example shows an incorrect approach. ```typescript // 🚫 SẼ GÂY LỖI BUILD! import { VNPay } from 'vnpay'; // Error: Module not found: Can't resolve 'fs' const MyComponent = () => { const vnpay = new VNPay(config); // ❌ Không thể làm trong browser! return
Payment
; }; ``` -------------------------------- ### Generate QR Code Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/05_generate-qr.md This endpoint generates a QR code for payment processing. It requires a set of parameters similar to the payment URL creation, and it sends a GET request to the VNPay payment gateway. The response is a JSON object containing a code, message, and the QR content. ```APIDOC ## POST /api/generate-qr ### Description Generates a QR code for payment processing by interacting with the VNPay gateway. ### Method GET ### Endpoint `/paymentv2/vpcpay.html` (VNPay Gateway) ### Parameters #### Query Parameters - **vnp_Command** (string) - Required - Must be `genqr`. - **vnp_TmnCode** (string) - Required - Merchant's terminal code. - **vnp_TxnRef** (string) - Required - Unique transaction reference. - **vnp_Amount** (number) - Required - Transaction amount (multiplied by 100 by VNPay). - **vnp_OrderInfo** (string) - Required - Information about the order. - **vnp_OrderType** (string) - Required - Type of order (e.g., `ProductCode.Other`). - **vnp_ReturnUrl** (string) - Required - URL to redirect after payment. - **vnp_Locale** (string) - Optional - Language of the response (e.g., `VnpLocale.VN`). - **vnp_CreateDate** (string) - Required - Transaction creation date in `yyyyMMddHHmmss` format. - **vnp_ExpireDate** (string) - Required - Transaction expiration date in `yyyyMMddHHmmss` format. - **vnp_SecureHash** (string) - Required - Signature hash of the parameters. ### Request Example ```typescript import { ProductCode, VnpLocale, dateFormat } from 'vnpay'; const start = new Date(); const end = new Date(start.getTime() + 15 * 60 * 1000); const result = await vnpay.generateQr({ vnp_Amount: 10000, vnp_IpAddr: '192.168.1.1', vnp_TxnRef: 'ORD-123456', vnp_OrderInfo: 'Thanh toan don hang ORD-123456', vnp_OrderType: ProductCode.Other, vnp_ReturnUrl: 'https://merchant.example.com/return', vnp_Locale: VnpLocale.VN, vnp_CreateDate: dateFormat(start), vnp_ExpireDate: dateFormat(end), }); if (result.code === '00' && result.qrcontent) { // Draw QR or deep-link from result.qrcontent } else { // result.qrcontent is usually empty on error } ``` ### Response #### Success Response (200) - **code** (string) - `00` indicates success. The QR content is in `qrcontent`. - **message** (string) - Description of the result or error. - **qrcontent** (string) - The string to render the QR code or a deep-link. This field will be empty if `code` is not `00`. #### Response Example ```json { "code": "00", "message": "Success", "qrcontent": "VNQR://..." } ``` #### Error Response Example ```json { "code": "01", "message": "Invalid amount", "qrcontent": "" } ``` ### Error Handling - If the HTTP request fails, a network error occurs, or the JSON response is unreadable, the promise will reject. - Detailed error codes and messages can be found in the VNPay Merchant Hosted QR documentation. ``` -------------------------------- ### Initialize VNPay Instance Source: https://github.com/lehuygiang28/vnpay/blob/main/README.md Instantiate the VNPay client with required configuration like `tmnCode`, `secureSecret`, and `vnpayHost`. Optional configurations include `testMode`, `hashAlgorithm`, `enableLog`, `loggerFn`, and custom `endpoints`. ```typescript import { VNPay, ignoreLogger } from 'vnpay'; const vnpay = new VNPay({ // ⚡ Cấu hình bắt buộc tmnCode: '2QXUI4B4', secureSecret: 'your-secret-key', vnpayHost: 'https://sandbox.vnpayment.vn', // 🔧 Cấu hình tùy chọn testMode: true, // Chế độ test hashAlgorithm: 'SHA512', // Thuật toán mã hóa enableLog: true, // Bật/tắt log loggerFn: ignoreLogger, // Custom logger // 🔧 Custom endpoints endpoints: { paymentEndpoint: 'paymentv2/vpcpay.html', queryDrRefundEndpoint: 'merchant_webapi/api/transaction', getBankListEndpoint: 'qrpayauth/api/merchant/get_bank_list', }, }); ``` -------------------------------- ### Initialize VNPay Object with Configuration Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/02_installation.md Initializes the VNPay client with necessary configuration options including API keys, host URLs, and optional settings for logging and hash algorithm. Ensure 'YOUR_TMNCODE' and 'YOUR_SECURE_SECRET' are replaced with actual credentials. ```typescript import { VNPay, ignoreLogger } from 'vnpay'; const vnpay = new VNPay({ tmnCode: 'YOUR_TMNCODE', secureSecret: 'YOUR_SECURE_SECRET', vnpayHost: 'https://sandbox.vnpayment.vn', queryDrAndRefundHost: 'https://sandbox.vnpayment.vn', // tùy chọn, trường hợp khi url của querydr và refund khác với url khởi tạo thanh toán (thường sẽ sử dụng cho production) testMode: true, // tùy chọn, ghi đè vnpayHost thành sandbox nếu là true hashAlgorithm: 'SHA512', // tùy chọn /** * Bật/tắt ghi log * Nếu enableLog là false, loggerFn sẽ không được sử dụng trong bất kỳ phương thức nào */ enableLog: true, // tùy chọn /** * Hàm `loggerFn` sẽ được gọi để ghi log khi enableLog là true * Mặc định, loggerFn sẽ ghi log ra console * Bạn có thể cung cấp một hàm khác nếu muốn ghi log vào nơi khác * * `ignoreLogger` là một hàm không làm gì cả */ loggerFn: ignoreLogger, // tùy chọn /** * Tùy chỉnh các đường dẫn API của VNPay * Thường không cần thay đổi trừ khi: * - VNPay cập nhật đường dẫn của họ * - Có sự khác biệt giữa môi trường sandbox và production */ endpoints: { paymentEndpoint: 'paymentv2/vpcpay.html', queryDrRefundEndpoint: 'merchant_webapi/api/transaction', getBankListEndpoint: 'qrpayauth/api/merchant/get_bank_list', }, // tùy chọn }); ``` -------------------------------- ### Get Bank List Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/03_get-bank-list.md This endpoint retrieves a list of banks that can be used for the `vnp_BankCode` parameter when creating a payment URL. ```APIDOC ## GET /api/bank/list ### Description Retrieves a list of available banks for VNPay payment processing. ### Method GET ### Endpoint /api/bank/list ### Parameters This endpoint does not require any path or query parameters. ### Request Body This endpoint does not accept a request body. ### Response #### Success Response (200) - **data** (array) - An array of bank objects. #### Response Example ```json [ { "bank_code": "string", "bank_name": "string", "logo_link": "string", "bank_type": "number", "display_order": "number" } ] ``` ## Bank Object Properties ### Description Details the properties of the `Bank` object returned in the API response. ### Properties - **bank_code** (string) - Required - The unique code for the bank. - **bank_name** (string) - Required - The name of the bank. - **logo_link** (string) - Required - The URL to the bank's logo. - **bank_type** (number) - Required - The type or category of the bank. - **display_order** (number) - Required - The order in which the bank should be displayed. ``` -------------------------------- ### Get VNPay Bank List Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/03_get-bank-list.md Use this function to retrieve an array of `Bank` objects. This list is required for the `vnp_BankCode` parameter when generating payment URLs. ```typescript import { Bank } from 'vnpay'; /* ... */ const bankList: Bank[] = await vnpay.getBankList(); ``` -------------------------------- ### Frontend Payment Initiation with React/Next.js Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/20_examples.md This React component demonstrates how to initiate a VNPay payment from the frontend by calling a backend API. It uses 'types-only' imports for types and avoids direct VNPay library usage on the client side. ```typescript // frontend/components/PaymentButton.tsx import { useState } from 'react'; import type { VerifyReturnUrl } from 'vnpay/types-only'; // ✅ Chỉ import types interface PaymentButtonProps { amount: number; orderInfo: string; onPaymentResult?: (result: VerifyReturnUrl) => void; } export const PaymentButton: React.FC = ({ amount, orderInfo, onPaymentResult }) => { const [loading, setLoading] = useState(false); const handlePayment = async () => { setLoading(true); try { // ✅ Gọi API backend thay vì import trực tiếp const response = await fetch('/api/payments/create', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ amount, orderInfo }), }); const data = await response.json(); if (data.success) { // Chuyển hướng đến VNPay window.location.href = data.paymentUrl; } else { alert('Lỗi tạo thanh toán'); } } catch (error) { console.error('Payment error:', error); alert('Lỗi kết nối'); } finally { setLoading(false); } }; return ( ); }; ``` -------------------------------- ### Get Current Time in GMT+7 Source: https://context7.com/lehuygiang28/vnpay/llms.txt Retrieves the current date and time adjusted to the GMT+7 timezone. Useful for time-sensitive operations requiring a specific timezone. ```typescript // Lấy thời gian hiện tại theo GMT+7 const gmt7Date = getDateInGMT7(); console.log('GMT+7:', gmt7Date); ``` -------------------------------- ### Get VNPay Response Message by Status Code Source: https://context7.com/lehuygiang28/vnpay/llms.txt Retrieves a human-readable message corresponding to a given VNPay response status code. Supports both Vietnamese (VN) and English (EN) locales. ```typescript // Lấy message theo response code const message = getResponseByStatusCode('00', VnpLocale.VN); console.log('Message:', message); // 'Giao dịch thành công' const messageEn = getResponseByStatusCode('00', VnpLocale.EN); console.log('Message EN:', messageEn); // 'Transaction successful' ``` -------------------------------- ### Import VNPay Library Modules Source: https://context7.com/lehuygiang28/vnpay/llms.txt Shows how to import the VNPay library using different strategies: full import, module-specific imports for classes, enums, constants, and utilities, and types-only imports for TypeScript. ```typescript // Import đầy đủ (backward compatible) import { VNPay, HashAlgorithm, ProductCode, dateFormat } from 'vnpay'; ``` ```typescript // Import theo module (khuyến nghị - giảm 80% bundle size) import { VNPay } from 'vnpay/vnpay'; import { HashAlgorithm, ProductCode, VnpLocale, RefundTransactionType } from 'vnpay/enums'; import { VNP_VERSION, PAYMENT_ENDPOINT, IpnSuccess, IpnFailChecksum } from 'vnpay/constants'; import { dateFormat, parseDate, consoleLogger, ignoreLogger } from 'vnpay/utils'; ``` ```typescript // Types-only import (0KB runtime cho TypeScript) import type { VNPayConfig, BuildPaymentUrl, Bank, VerifyReturnUrl, VerifyIpnCall, QueryDr, QueryDrResponse, Refund, RefundResponse, ReturnQueryFromVNPay, IpnResponse, } from 'vnpay/types-only'; ``` -------------------------------- ### Import VNPay Library for Backend Usage Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/02_installation.md Demonstrates importing the VNPay library for use in a Node.js backend environment. You can import the entire library or specific modules. ```typescript // Import toàn bộ (backward compatible) import { VNPay } from 'vnpay'; // Hoặc import module cụ thể (khuyến nghị cho bundle size nhỏ hơn) import { VNPay } from 'vnpay/vnpay'; ``` -------------------------------- ### Import Entire Library Source: https://github.com/lehuygiang28/vnpay/blob/main/README.md Import all necessary components from the vnpayjs library. This is a backward-compatible import option. ```typescript import { VNPay, HashAlgorithm, ProductCode } from 'vnpay'; ``` -------------------------------- ### Build Payment URL with Console Logger Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/04_create-payment-url.md Use this snippet to generate a payment URL with default console logging enabled. Ensure 'vnpay' is imported and configured. ```typescript import { ProductCode, VnpLocale, consoleLogger } from 'vnpay'; /* ... */ const paymentUrl = vnpay.buildPaymentUrl( { vnp_Amount: 10000, vnp_IpAddr: '1.1.1.1', vnp_TxnRef: '123456', vnp_OrderInfo: 'Thanh toan don hang 123456', vnp_OrderType: ProductCode.Other, vnp_ReturnUrl: `http://localhost:3000/vnpay-return`, // Đường dẫn nên là của frontend }, { logger: { type: 'all', loggerFn: consoleLogger, }, }, ); ``` -------------------------------- ### Import by Module (Recommended) Source: https://github.com/lehuygiang28/vnpay/blob/main/README.md Import specific modules from vnpayjs for better tree-shaking and smaller bundle sizes. This is the recommended import method for v2.4.0+. ```typescript import { VNPay } from 'vnpay/vnpay'; import { HashAlgorithm, ProductCode } from 'vnpay/enums'; import { VNP_VERSION, PAYMENT_ENDPOINT } from 'vnpay/constants'; import { resolveUrlString, dateFormat } from 'vnpay/utils'; ``` -------------------------------- ### API generateQr Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/05_generate-qr.md Định nghĩa hàm `generateQr` nhận dữ liệu giao dịch và tùy chọn phản hồi, trả về một Promise chứa thông tin phản hồi từ VNPay. ```typescript generateQr( data: BuildPaymentUrl, options?: GenerateQrResponseOptions ): Promise ``` -------------------------------- ### Utility Functions Source: https://context7.com/lehuygiang28/vnpay/llms.txt A collection of utility functions for date formatting, parsing, validation, logging, and generating random strings. ```APIDOC ## Utility Functions ### Description Provides various helper functions for common tasks such as date manipulation, logging, and generating random data. ### Functions #### Date Formatting - **dateFormat(date: Date): string** - Description: Formats a Date object into the VNPay date format (yyyyMMddHHmmss). - Example: ```javascript const now = new Date(); const vnpayDate = dateFormat(now); console.log(vnpayDate); // '20240815143052' ``` #### Date Parsing - **parseDate(vnpayDateString: string | number, type: 'local' | 'utc'): Date** - Description: Parses a date string or number in VNPay format into a JavaScript Date object. - Parameters: - **vnpayDateString** (string | number) - The date string or number to parse. - **type** ('local' | 'utc') - Specifies whether to parse as local time or UTC. - Example: ```javascript const date = parseDate('20240815143052', 'local'); console.log(date); // Date object representing 2024-08-15 14:30:52 ``` #### Date Validation - **isValidVnpayDateFormat(value: string | number): boolean** - Description: Checks if a given value is a valid VNPay date format. - Example: ```javascript const isValid = isValidVnpayDateFormat('20240815143052'); console.log(isValid); // true ``` #### Timezone Conversion - **getDateInGMT7(): Date** - Description: Returns the current date and time in GMT+7 timezone. - Example: ```javascript const gmt7Date = getDateInGMT7(); console.log(gmt7Date); // Date object in GMT+7 ``` #### Response Message Retrieval - **getResponseByStatusCode(code: string, locale: VnpLocale): string** - Description: Retrieves a human-readable message for a given VNPay response status code and locale. - Parameters: - **code** (string) - The VNPay response status code (e.g., '00'). - **locale** (VnpLocale) - The desired locale for the message (e.g., VnpLocale.VN, VnpLocale.EN). - Example: ```javascript const message = getResponseByStatusCode('00', VnpLocale.VN); console.log(message); // 'Giao dịch thành công' ``` #### Random String Generation - **generateRandomString(length: number, options?: { onlyNumber?: boolean }): string** - Description: Generates a random string of a specified length. Can optionally generate only numbers. - Parameters: - **length** (number) - The desired length of the random string. - **options** ({ onlyNumber?: boolean }) - Optional configuration. If `onlyNumber` is true, generates only numeric characters. - Example: ```javascript const randomId = generateRandomString(16); console.log(randomId); // 'aB3dE5fG7hI9jK1l' const randomNumber = generateRandomString(8, { onlyNumber: true }); console.log(randomNumber); // '12345678' ``` #### Logging Functions - **consoleLogger(data: object): void** - Description: Logs data to the console. - Example: ```javascript consoleLogger({ message: 'Payment created', orderId: '123' }); ``` - **fileLogger(data: object, filePath: string): void** - Description: Logs data to a specified file. - Parameters: - **data** (object) - The data to log. - **filePath** (string) - The path to the log file. - Example: ```javascript fileLogger({ message: 'Payment created' }, '/var/log/vnpay.log'); ``` - **ignoreLogger(data: object): void** - Description: A placeholder logger function that does nothing. Useful for disabling logging. - Example: ```javascript const vnpay = new VNPay({ tmnCode: 'xxx', secureSecret: 'xxx', loggerFn: ignoreLogger }); ``` ``` -------------------------------- ### Initiate a Refund Request Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/08_refund.md Use this snippet to send a refund request to the VNPAY system. Ensure dates are in GMT+7 and formatted correctly. Contact VNPAY for sandbox environment access. ```typescript import { Refund, RefundResponse, dateFormat, getDateInGMT7, VnpTransactionType, VnpLocale, } from 'vnpay'; /* ... */ /** * Ngày phải ở múi giờ GMT+7 * Và được định dạng theo `yyyyMMddHHmmss` * Sử dụng các hàm `getDateInGMT7` và `dateFormat` để chuyển đổi */ const refundRequestDate = dateFormat(getDateInGMT7(new Date('2024/05/26'))); const orderCreatedAt = dateFormat(getDateInGMT7(new Date('2024/05/21'))); const result: RefundResponse = await vnpay.refund({ vnp_Amount: 10000, vnp_CreateBy: 'giang', vnp_CreateDate: refundRequestDate, vnp_IpAddr: '127.0.0.1', vnp_OrderInfo: 'Test order', vnp_RequestId: '123456', vnp_TransactionDate: orderCreatedAt, vnp_TransactionType: VnpTransactionType.FULL_REFUND, vnp_TxnRef: '123456', vnp_Locale: VnpLocale.EN, // vnp_TransactionNo: 123456, // optional } as Refund); ``` -------------------------------- ### Frontend Warning: Direct VNPay Import Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/02_installation.md This code block illustrates an incorrect way to import the VNPay library in a frontend environment. It highlights the potential build errors due to Node.js module dependencies. ```typescript // 🚫 SẼ GÂY LỖI BUILD! import { VNPay } from 'vnpay'; // Error: Module not found: Can't resolve 'fs' // Error: Module not found: Can't resolve 'crypto' const MyComponent = () => { const vnpay = new VNPay(config); // ❌ Không thể làm trong browser! return
Payment
; }; ``` -------------------------------- ### Build VNPay Payment URL Source: https://github.com/lehuygiang28/vnpay/blob/main/README.md Generate a payment URL using the `buildPaymentUrl` method. This requires parameters such as amount, IP address, return URL, transaction reference, and order information. ```typescript const paymentUrl = vnpay.buildPaymentUrl({ vnp_Amount: 100000, // 100,000 VND vnp_IpAddr: '192.168.1.1', vnp_ReturnUrl: 'https://yourapp.com/return', vnp_TxnRef: 'ORDER_123', vnp_OrderInfo: 'Thanh toán đơn hàng #123', }); console.log('Payment URL:', paymentUrl); ``` -------------------------------- ### Xác thực IPN với thư viện VNPay Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/05_ipn/02_verify-ipn-call.md Sử dụng hàm `verifyIpnCall` từ thư viện VNPay để xác thực dữ liệu IPN nhận được từ yêu cầu. Đảm bảo bạn đã import `VerifyIpnCall`. ```typescript import { VerifyIpnCall } from 'vnpay'; /* ... */ const verify: VerifyIpnCall = vnpay.verifyIpnCall(req.query); ``` -------------------------------- ### Xây dựng URL thanh toán với vnpay-sdk Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/04_create-payment-url.md Sử dụng hàm `buildPaymentUrl` từ thư viện `vnpay` để tạo URL thanh toán. Cần cung cấp các thông tin cơ bản về đơn hàng và người dùng. Các ngày hết hạn và tạo có thể được tùy chọn. ```typescript import { ProductCode, VnpLocale, dateFormat } from 'vnpay'; /* ... */ const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); const paymentUrl = vnpay.buildPaymentUrl({ vnp_Amount: 10000, vnp_IpAddr: '13.160.92.202', vnp_TxnRef: '123456', vnp_OrderInfo: 'Thanh toan don hang 123456', vnp_OrderType: ProductCode.Other, vnp_ReturnUrl: 'http://localhost:3000/vnpay-return', vnp_Locale: VnpLocale.VN, // 'vn' hoặc 'en' vnp_CreateDate: dateFormat(new Date()), // tùy chọn, mặc định là thời gian hiện tại vnp_ExpireDate: dateFormat(tomorrow), // tùy chọn }); ``` -------------------------------- ### Backend VNPay Integration with Express Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/20_examples.md This snippet shows how to integrate the VNPay library on the backend using Express. It includes creating a payment URL and verifying the return URL. Ensure VNPay library is imported only on the backend. ```typescript // backend/routes/payment.ts import { VNPay } from 'vnpay'; // ✅ Import đầy đủ trên backend const vnpay = new VNPay({ tmnCode: process.env.VNP_TMNCODE!, secureSecret: process.env.VNP_SECRET!, testMode: true, }); // Tạo URL thanh toán app.post('/api/payments/create', async (req, res) => { try { const { amount, orderInfo } = req.body; const paymentUrl = vnpay.buildPaymentUrl({ vnp_Amount: amount, vnp_IpAddr: req.ip, vnp_ReturnUrl: `${process.env.APP_URL}/payment/callback`, vnp_TxnRef: `ORDER_${Date.now()}`, vnp_OrderInfo: orderInfo, }); res.json({ success: true, paymentUrl }); } catch (error) { res.status(500).json({ success: false, error: error.message }); } }); // Xác thực kết quả thanh toán app.get('/api/payments/verify', (req, res) => { const verification = vnpay.verifyReturnUrl(req.query); res.json(verification); }); ``` -------------------------------- ### Xác thực URL trả về với vnpay Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/06_verify-return-url.md Sử dụng hàm `verifyReturnUrl` từ thư viện vnpay để xác thực dữ liệu trả về từ VNPay. Cần import `VerifyReturnUrl` trước khi sử dụng. ```typescript import { VerifyReturnUrl } from 'vnpay'; /* ... */ const verify: VerifyReturnUrl = vnpay.verifyReturnUrl(req.query); ``` -------------------------------- ### Tùy chọn GenerateQrResponseOptions Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/05_generate-qr.md Tùy chọn `GenerateQrResponseOptions` tương tự như `LoggerOptions` được sử dụng trong các API khác, cho phép cấu hình thêm các tùy chọn cho phản hồi. ```plaintext Giống logger các API khác: [LoggerOptions](/create-payment-url#logger-options). ``` -------------------------------- ### Generate QR Code (generateQr) Source: https://context7.com/lehuygiang28/vnpay/llms.txt Generates a QR code for customers to scan and pay via their banking application. This method calls the VNPay API and returns the QR code content. ```APIDOC ## POST /api/generateQr ### Description Generates a QR code for customers to scan and pay via their banking application. ### Method POST ### Endpoint /api/generateQr ### Parameters #### Request Body - **vnp_Amount** (number) - Required - The transaction amount. - **vnp_IpAddr** (string) - Required - The IP address of the client. - **vnp_TxnRef** (string) - Required - The unique transaction reference ID. - **vnp_OrderInfo** (string) - Required - Information about the order. - **vnp_ReturnUrl** (string) - Required - The URL to redirect to after payment. ### Request Example ```json { "vnp_Amount": 50000, "vnp_IpAddr": "127.0.0.1", "vnp_TxnRef": "QR_1678886400000", "vnp_OrderInfo": "Thanh toan QR don hang 123", "vnp_ReturnUrl": "https://yourapp.com/vnpay-return" } ``` ### Response #### Success Response (200) - **code** (string) - The response code. '00' indicates success. - **message** (string) - The response message. - **qrcontent** (string) - The content of the QR code to be rendered. ``` -------------------------------- ### Generate QR Code for Payment Source: https://context7.com/lehuygiang28/vnpay/llms.txt Use this function to create a QR code for customer payments via banking apps. It calls the VNPay API and returns the QR code content. Ensure the VNPay SDK is initialized with your credentials. ```typescript import { VNPay, consoleLogger } from 'vnpay'; const vnpay = new VNPay({ tmnCode: '2QXUI4B4', secureSecret: 'SCSECRET0123456789', testMode: true, }); async function createQrPayment() { try { const result = await vnpay.generateQr( { vnp_Amount: 50000, vnp_IpAddr: '127.0.0.1', vnp_TxnRef: `QR_${Date.now()}`, vnp_OrderInfo: 'Thanh toan QR don hang 123', vnp_ReturnUrl: 'https://yourapp.com/vnpay-return', }, { logger: { type: 'pick', fields: ['code', 'message', 'qrcontentLength'], loggerFn: consoleLogger, }, }, ); console.log('QR Result:', { code: result.code, // '00' = thành công message: result.message, // 'Success' qrcontent: result.qrcontent, // Nội dung QR để render }); // Sử dụng qrcontent để tạo hình ảnh QR // Ví dụ với thư viện qrcode // import QRCode from 'qrcode'; // const qrImage = await QRCode.toDataURL(result.qrcontent); return result; } catch (error) { console.error('Generate QR Error:', error); throw error; } } ``` -------------------------------- ### Build Payment URL with Custom Logger Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/04_create-payment-url.md Generate a payment URL with a custom logger function for specific field logging. Requires defining 'returnUrl' and 'logToDatabase'. ```typescript import { ProductCode, VnpLocale } from 'vnpay'; /* ... */ const paymentUrl = vnpay.buildPaymentUrl( { vnp_Amount: 10000, vnp_IpAddr: '1.1.1.1', vnp_TxnRef: '123456', vnp_OrderInfo: 'Thanh toan don hang 123456', vnp_OrderType: ProductCode.Other, vnp_ReturnUrl: returnUrl, // Đường dẫn nên là của frontend }, { logger: { type: 'pick', // Chế độ chọn trường ghi log, có thể là 'pick', 'omit' hoặc 'all' fields: ['createdAt', 'method', 'paymentUrl'], // Chọn các trường để ghi log loggerFn: (data) => logToDatabase(data), // Hàm ghi log vào cơ sở dữ liệu, bạn cần tự triển khai }, }, ); ``` -------------------------------- ### Correct Frontend Import for Types Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/02_installation.md For frontend applications, only import types from 'vnpay/types-only' to ensure type safety without causing runtime errors. Actual payment processing must be handled by a backend. ```typescript import type { VNPayConfig, BuildPaymentUrl, Bank, VerifyReturnUrl } from 'vnpay/types-only'; ``` -------------------------------- ### Bật Ghi Log VNPay Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/23_troubleshooting.md Kích hoạt tính năng ghi log của thư viện VNPay để theo dõi các yêu cầu và phản hồi. Cấu hình một hàm callback để xử lý dữ liệu log, có thể ghi ra console hoặc lưu vào tệp. ```typescript const vnpay = new VNPay({ // ... cấu hình khác enableLog: true, loggerFn: (data) => { console.log(JSON.stringify(data, null, 2)); // Hoặc lưu vào tệp/cơ sở dữ liệu }, }); ``` -------------------------------- ### Handle VNPAY IPN Call - Backend Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/20_examples.md This backend route handles VNPAY IPN requests. It verifies the payment status and updates the order accordingly. Ensure the `vnpay.verifyIpnCall` function is correctly implemented. ```typescript // backend/routes/ipn.ts app.post('/api/payment/ipn', (req, res) => { try { const verification = vnpay.verifyIpnCall(req.body); if (verification.isSuccess) { // ✅ Thanh toán thành công - cập nhật database console.log('Payment successful:', verification.vnp_TxnRef); // Cập nhật order status trong database // updateOrderStatus(verification.vnp_TxnRef, 'PAID'); res.status(200).json({ RspCode: '00', Message: 'success' }); } else { // ❌ Thanh toán thất bại console.log('Payment failed:', verification.message); res.status(200).json({ RspCode: '01', Message: 'fail' }); } } catch (error) { console.error('IPN processing error:', error); res.status(500).json({ RspCode: '99', Message: 'error' }); } }); ``` -------------------------------- ### Tạo mã QR thanh toán với ngày hết hạn Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/05_generate-qr.md Sử dụng hàm `generateQr` để tạo mã QR. Cần cung cấp các thông tin giao dịch cơ bản và thiết lập thời gian tạo, hết hạn cho mã QR. Thư viện sẽ tự động ký yêu cầu và xử lý phản hồi từ VNPay. Kiểm tra `result.code` và `result.qrcontent` để xác định thành công hay thất bại. ```typescript import { ProductCode, VnpLocale, dateFormat } from 'vnpay'; const start = new Date(); const end = new Date(start.getTime() + 15 * 60 * 1000); // ví dụ: hết hạn sau 15 phút const result = await vnpay.generateQr({ vnp_Amount: 10000, vnp_IpAddr: '192.168.1.1', vnp_TxnRef: 'ORD-123456', vnp_OrderInfo: 'Thanh toan don hang ORD-123456', vnp_OrderType: ProductCode.Other, vnp_ReturnUrl: 'https://merchant.example.com/return', vnp_Locale: VnpLocale.VN, vnp_CreateDate: dateFormat(start), vnp_ExpireDate: dateFormat(end), }); if (result.code === '00' && result.qrcontent) { // Vẽ QR hoặc deep-link từ result.qrcontent } else { // result.qrcontent thường rỗng khi lỗi } ``` -------------------------------- ### Cấu trúc phản hồi GenerateQrResponse Source: https://github.com/lehuygiang28/vnpay/blob/main/docs/docs/05_generate-qr.md Mô tả các trường trong đối tượng `GenerateQrResponse` trả về từ hàm `generateQr`. Bao gồm mã trạng thái (`code`), thông điệp (`message`), và nội dung QR (`qrcontent`). ```plaintext code: `00`: thành công, nội dung QR ở `qrcontent` message: Thông tin mô tả (lỗi / trạng thái) qrcontent: Chuỗi QR; **rỗng** khi không thành công ```