zalopay-sdk
v1.0.0
Published
A lightweight, modern, and developer-friendly ZaloPay SDK for Node.js using native fetch.
Downloads
154
Maintainers
Readme
ZaloPay Node.js SDK
A lightweight, modern, zero-dependency, and developer-friendly ZaloPay SDK for Node.js written in TypeScript. Fully supports both ES Modules (ESM) and CommonJS (CJS), built on native fetch (Node.js >= 18).
Installation
npm install zalopay-sdkQuick Start
1. Initialize Client
Initialize with your credentials from ZaloPay Merchant Portal. The standard SDK class is ZaloPayModule (consistent with LazadaModule and ShopeeModule conventions). You can also import it as ZaloPay for brevity.
import { ZaloPayModule } from 'zalopay-sdk';
const zalopay = new ZaloPayModule({
appId: 554, // Sandbox App ID
key1: '8NdU5pG5R2spGHGhyO99HN1OhD8IQJBn', // Request Signature Key
key2: 'uUfsWgfLkRLzq6W2uNXTCxrfxs51auny', // Callback Validation Key
env: 'sandbox', // 'sandbox' | 'production'
});Using the ZaloPay alias shorthand:
import { ZaloPay } from 'zalopay-sdk';
// const zalopay = new ZaloPay({ ... });Using CommonJS:
const { ZaloPayModule } = require('zalopay-sdk');
---
## API Reference
### `generateAppTransId(suffix)`
Helper method to generate an `app_trans_id` with the required `yymmdd` prefix matching the Vietnam Timezone (GMT+7).
- **`suffix`**: A unique suffix (e.g. your database order ID).
- **Returns**: Formatted string `yymmdd_suffix` (e.g. `240525_order123`).
```javascript
const appTransId = zalopay.generateAppTransId('order_12345');createOrder(params)
Creates a payment order on ZaloPay and returns payment URLs and Napas VietQR strings.
params:app_user(string, required) - Identification of user.app_trans_id(string, required) - Unique ID matching formatyymmdd_xxxx.amount(number, required) - Payment amount in VND.description(string, required) - Display details.app_time(number, optional) - Defaults toDate.now().item(array/string, optional) - Items purchase details. Automatically stringified.embed_data(object/string, optional) - Extra custom details. Automatically stringified.redirect_url(string, optional) - URL to return to after payment. Automatically updatesembed_data.redirecturl.bank_code(string, optional) - e.g.zalopayapp.
const response = await zalopay.createOrder({
app_user: 'customer_01',
app_trans_id: zalopay.generateAppTransId('order_98765'),
amount: 50000,
description: 'Payment for custom course',
redirect_url: 'https://mywebsite.com/payment-complete',
item: [
{ itemid: 'book_01', itemname: 'Developer Handbook', itemprice: 50000, itemquantity: 1 }
]
});
console.log('Payment URL:', response.order_url);queryOrder(appTransId)
Check order status of a payment.
appTransId: Theapp_trans_idgenerated during payment creation.
const status = await zalopay.queryOrder('240525_order_98765');
if (status.return_code === 1) {
console.log('Payment completed successfully!');
} else if (status.return_code === 3) {
console.log('Payment is processing/pending.');
}refund(params)
Submit a refund request for an already successful transaction.
params:m_refund_id(string, required) - Custom refund ID (yymmdd_appid_xxx).zp_trans_id(string, required) - ZaloPay transaction ID (from callback/query).amount(number, required) - Refund amount in VND.description(string, optional) - Refund reason.timestamp(number, optional) - Defaults toDate.now().
const response = await zalopay.refund({
m_refund_id: '240525_554_ref001',
zp_trans_id: '240525000012345',
amount: 50000,
description: 'Customer requested refund',
});queryRefund(mRefundId, timestamp)
Query status of a submitted refund request.
mRefundId: The custom refund IDm_refund_idused during the refund.
const status = await zalopay.queryRefund('240525_554_ref001');verifyCallback(data, mac)
Verify callback POST requests sent by ZaloPay Server to your webhook URL.
data:req.body.data(JSON string containing payment details).mac:req.body.mac(Signature hash).
// Express.js Webhook Endpoint Example
app.post('/api/zalopay-callback', (req, res) => {
const { data, mac } = req.body;
const isValid = zalopay.verifyCallback(data, mac);
if (!isValid) {
return res.status(400).json({ return_code: -1, return_message: 'Invalid signature' });
}
// Parse callback details
const parsedData = JSON.parse(data);
console.log(`Payment received for order ${parsedData.app_trans_id}`);
// Return success response to ZaloPay
return res.json({
return_code: 1,
return_message: 'success'
});
});Testing
Run unit tests via Vitest:
npm run testBuild files:
npm run build