Node.js / TypeScript
SDK ufficiale Node.js per il gateway di pagamento Cost+
SDK ufficiale Node.js/TypeScript per il gateway di pagamento Cost+. Semplifica il flusso di reindirizzamento HPP (Pagina di Pagamento Ospitata), la firma dei payload HMAC e la verifica dei webhook.
Caratteristiche
- Zero dipendenze — utilizza solo
cryptoefetchintegrati di Node.js - Tipi TypeScript completi con declaration map
- Generazione firma HMAC-SHA256 e verifica a tempo costante
- Mappatura automatica snake_case/camelCase tra API e SDK
- Analisi webhook + verifica dell'ordine basata su API
- Testato su Node.js 18, 20 e 22
Requisiti
- Node.js 18 o successivo (utilizza
fetchintegrato) - Un account commerciante Cost+ — dashboard.costplus.io
Installazione
npm install nopayn-node-sdkGuida Rapida
1. Inizializza il Client
import { NoPaynClient } from 'nopayn-node-sdk';
const nopayn = new NoPaynClient({
apiKey: 'your-api-key', // From the NoPayn merchant portal
merchantId: 'your-project', // Your project/merchant ID
});2. Crea un Pagamento e Reindirizza all'HPP
const result = await nopayn.generatePaymentUrl({
amount: 1295, // €12.95 in cents
currency: 'EUR',
merchantOrderId: 'ORDER-001',
description: 'Premium Widget',
returnUrl: 'https://shop.example.com/success',
failureUrl: 'https://shop.example.com/failure',
webhookUrl: 'https://shop.example.com/webhook',
locale: 'en-GB',
expirationPeriod: 'PT30M',
});
// Redirect the customer
// result.orderUrl → HPP (customer picks payment method)
// result.paymentUrl → direct link to the first transaction's payment method
// result.signature → HMAC-SHA256 for verification
// result.orderId → NoPayn order UUID3. Gestisci il Webhook
app.post('/webhook', async (req, res) => {
const verified = await nopayn.verifyWebhook(JSON.stringify(req.body));
console.log(verified.order.status); // 'completed', 'cancelled', etc.
console.log(verified.isFinal); // true when the order won't change
if (verified.order.status === 'completed') {
// Fulfil the order
}
res.sendStatus(200);
});Riferimento API
new NoPaynClient(config)
| Parametro | Tipo | Obbligatorio | Predefinito |
|---|---|---|---|
apiKey | string | Sì | — |
merchantId | string | Sì | — |
baseUrl | string | No | https://api.nopayn.co.uk |
client.createOrder(params)
Crea un ordine tramite POST /v1/orders/.
| Parametro | Tipo | Obbligatorio | Descrizione |
|---|---|---|---|
amount | number | Sì | Importo nell'unità valutaria più piccola (centesimi) |
currency | string | Sì | Codice ISO 4217 (EUR, GBP, USD, NOK, SEK) |
merchantOrderId | string | No | Il tuo riferimento interno dell'ordine |
description | string | No | Descrizione dell'ordine |
returnUrl | string | No | Reindirizzamento dopo pagamento riuscito |
failureUrl | string | No | Reindirizzamento in caso di annullamento/scadenza/errore |
webhookUrl | string | No | Notifiche asincrone di cambio stato |
locale | string | No | Lingua HPP (en-GB, de-DE, nl-NL, ecc.) |
paymentMethods | PaymentMethod[] | No | Filtra i metodi HPP |
expirationPeriod | string | No | Durata ISO 8601 (PT30M) |
Metodi di pagamento disponibili: credit-card, apple-pay, google-pay, vipps-mobilepay
client.getOrder(orderId)
Recupera i dettagli dell'ordine tramite GET /v1/orders/{id}/.
client.createRefund(orderId, amount, description?)
Emette un rimborso totale o parziale tramite POST /v1/orders/{id}/refunds/.
client.generatePaymentUrl(params)
Metodo di convenienza che crea un ordine e restituisce:
{
orderId: string; // NoPayn order UUID
orderUrl: string; // HPP URL
paymentUrl?: string; // Direct payment URL (first transaction)
signature: string; // HMAC-SHA256 of amount:currency:orderId
order: Order; // Full order object
}client.generateSignature(amount, currency, orderId)
Genera una firma HMAC-SHA256 esadecimale. Il messaggio canonico è ${amount}:${currency}:${orderId}, firmato con la chiave API.
client.verifySignature(amount, currency, orderId, signature)
Verifica a tempo costante di una firma HMAC-SHA256. Restituisce true se valida.
client.verifyWebhook(rawBody)
Analizza il corpo del webhook, poi chiama GET /v1/orders/{id}/ per verificare lo stato effettivo. Restituisce:
{
orderId: string;
order: Order; // Verified via API
isFinal: boolean; // true for completed/cancelled/expired/error
}client.parseWebhookBody(rawBody)
Analizza e valida il corpo di un webhook senza chiamare l'API.
Utility HMAC Standalone
import { generateSignature, verifySignature } from 'nopayn-node-sdk';
const sig = generateSignature('your-api-key', 1295, 'EUR', 'order-uuid');
const ok = verifySignature('your-api-key', 1295, 'EUR', 'order-uuid', sig);Gestione degli Errori
import { NoPaynApiError, NoPaynError, NoPaynWebhookError } from 'nopayn-node-sdk';
try {
await nopayn.createOrder({ amount: 100, currency: 'EUR' });
} catch (err) {
if (err instanceof NoPaynApiError) {
console.error(err.statusCode); // 401, 400, etc.
console.error(err.errorBody); // Raw API error response
} else if (err instanceof NoPaynError) {
console.error(err.message); // Network or parsing error
}
}Stati dell'Ordine
| Stato | Finale? | Descrizione |
|---|---|---|
new | No | Ordine creato |
processing | No | Pagamento in corso |
completed | Sì | Pagamento riuscito — consegna la merce |
cancelled | Sì | Pagamento annullato dal cliente |
expired | Sì | Link di pagamento scaduto |
error | Sì | Errore tecnico |
Best Practice per i Webhook
- Verifica sempre tramite API — il payload del webhook contiene solo l'ID dell'ordine, mai lo stato. Il metodo
verifyWebhook()dell'SDK lo fa automaticamente. - Restituisci HTTP 200 per confermare la ricezione. Qualsiasi altro codice attiva fino a 10 tentativi (ogni 2 minuti).
- Implementa un poller di backup — per gli ordini più vecchi di 10 minuti che non hanno raggiunto uno stato finale, interroga
getOrder()come rete di sicurezza. - Sii idempotente — potresti ricevere lo stesso webhook più volte.
Carte di Test
Usa queste carte in modalità test Cost+ (sito web sandbox):
| Carta | Numero | Note |
|---|---|---|
| Visa (successo) | 4111 1111 1111 1111 | Qualsiasi CVV |
| Mastercard (successo) | 5544 3300 0003 7 | Qualsiasi CVV |
| Visa (rifiutata) | 4111 1111 1111 1105 | Do Not Honor |
| Visa (fondi insufficienti) | 4111 1111 1111 1151 | Insufficient Funds |
Usa qualsiasi data di scadenza futura e qualsiasi CVC a 3 cifre.
App Demo
Un'app demo basata su Docker è inclusa nel repository GitHub per testare il flusso di pagamento completo:
cd demo
cat > .env << EOF
NOPAYN_API_KEY=your-api-key
NOPAYN_MERCHANT_ID=your-merchant-id
PUBLIC_URL=http://localhost:3000
EOF
docker compose up --buildApri http://localhost:3000 per vedere la pagina di checkout demo.
Supporto
Hai bisogno di aiuto? Contatta il nostro team di supporto a support@costplus.io.