Integrazione dell’API 4Geeks Payments in un’applicazione Node.js¶
Panoramica¶
4Geeks Payments è una piattaforma Merchant of Record (MoR) che gestisce l’intero ciclo di vita della transazione: dall’accettazione dei pagamenti alla gestione degli abbonamenti, alla conformitĂ fiscale e alla prevenzione delle frodi. Questo tutorial mostra come integrare l’API REST di 4Geeks Payments in un’applicazione Node.js.
In questo tutorial potrai:
- Configura il tuo account 4Geeks Payments e ottieni le chiavi API
- Creare un addebito (pagamento una tantum)
- Creare e gestire i clienti
- Generare collegamenti di pagamento
- Gestire i webhook per gli eventi di pagamento
- Elaborare i rimborsi
Prerequisiti¶
- Un conto 4Geeks Payments attivato (attivare il servizio)
- Node.js 18+ installato
- npm o gestore di pacchetti di filati
- Conoscenza di base delle API REST e Express.js
Passaggio 1: ottieni le chiavi API¶
- Accedi a console.4geeks.io
- Vai a Pagamenti → Impostazioni → Chiavi API
- Fai clic su “Genera chiave API”
- Copia e archivia in modo sicuro:
- Chiave pubblica (per operazioni lato client)
- Chiave segreta (per operazioni lato server: non esporla mai)
Importante: utilizza le chiavi sandbox per i test. Passa alle chiavi di produzione quando sei pronto per la pubblicazione.
Passaggio 2: imposta il tuo progetto¶
Crea la struttura del tuo progetto:
my-payment-app/
├── .env
├── server.js
├── routes/
│ └── payments.js
└── package.json
Passaggio 3: configurare le variabili d’ambiente¶
Crea un file .env:
FOURGEEKS_PAYMENTS_SECRET_KEY=sk_test_your_secret_key_here
FOURGEEKS_PAYMENTS_PUBLIC_KEY=pk_test_your_public_key_here
FOURGEEKS_PAYMENTS_API_URL=https://api.4geeks.io/v1
PORT=3000
Passaggio 4: crea il server Express¶
Crea server.js:
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const paymentRoutes = require('./routes/payments');
const app = express();
app.use(cors());
app.use(express.json());
app.use('/api/payments', paymentRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Passaggio 5: crea percorsi di pagamento¶
Crea routes/payments.js:
const express = require('express');
const axios = require('axios');
const router = express.Router();
const API_URL = process.env.FOURGEEKS_PAYMENTS_API_URL;
const SECRET_KEY = process.env.FOURGEEKS_PAYMENTS_SECRET_KEY;
const api = axios.create({
baseURL: API_URL,
headers: {
'Authorization': `Bearer ${SECRET_KEY}`,
'Content-Type': 'application/json',
},
});
// Create a one-time charge
router.post('/charges', async (req, res) => {
try {
const { amount, currency, customer_id, description } = req.body;
const response = await api.post('/charges', {
amount, // Amount in cents (e.g., 1000 = $10.00)
currency, // e.g., 'USD', 'EUR', 'CRC'
customer_id, // Existing customer ID or create new
description,
capture: true, // Auto-capture the charge
});
res.json({ success: true, charge: response.data });
} catch (error) {
console.error('Charge error:', error.response?.data || error.message);
res.status(error.response?.status || 500).json({
success: false,
error: error.response?.data || 'Failed to create charge',
});
}
});
// Create a customer
router.post('/customers', async (req, res) => {
try {
const { email, name, phone, metadata } = req.body;
const response = await api.post('/customers', {
email,
name,
phone,
metadata, // Optional: custom key-value pairs
});
res.json({ success: true, customer: response.data });
} catch (error) {
res.status(error.response?.status || 500).json({
success: false,
error: error.response?.data || 'Failed to create customer',
});
}
});
// Generate a payment link
router.post('/payment-links', async (req, res) => {
try {
const { amount, currency, description, customer_email, success_url, cancel_url } = req.body;
const response = await api.post('/payment-links', {
amount,
currency,
description,
customer_email,
success_url, // Redirect after successful payment
cancel_url, // Redirect if customer cancels
});
res.json({ success: true, payment_link: response.data });
} catch (error) {
res.status(error.response?.status || 500).json({
success: false,
error: error.response?.data || 'Failed to create payment link',
});
}
});
// Process a refund
router.post('/charges/:charge_id/refund', async (req, res) => {
try {
const { charge_id } = req.params;
const { amount, reason } = req.body;
const response = await api.post(`/charges/${charge_id}/refunds`, {
amount, // Optional: partial refund (in cents). Omit for full refund
reason, // e.g., 'duplicate', 'fraudulent', 'requested_by_customer'
});
res.json({ success: true, refund: response.data });
} catch (error) {
res.status(error.response?.status || 500).json({
success: false,
error: error.response?.data || 'Failed to process refund',
});
}
});
// Get charge details
router.get('/charges/:charge_id', async (req, res) => {
try {
const { charge_id } = req.params;
const response = await api.get(`/charges/${charge_id}`);
res.json({ success: true, charge: response.data });
} catch (error) {
res.status(error.response?.status || 500).json({
success: false,
error: error.response?.data || 'Failed to get charge',
});
}
});
module.exports = router;
Passaggio 6: gestire i webhook¶
I webhook notificano al tuo server gli eventi di pagamento (addebiti riusciti, pagamenti non riusciti, rimborsi, ecc.).
Aggiungi a server.js:
// Webhook endpoint
app.post('/webhooks/payments', express.raw({ type: 'application/json' }), (req, res) => {
const signature = req.headers['x-4geeks-signature'];
const payload = req.body;
// Verify webhook signature (implement verification logic)
// const isValid = verifyWebhookSignature(payload, signature);
// if (!isValid) return res.status(401).send('Invalid signature');
const event = JSON.parse(payload);
switch (event.type) {
case 'charge.succeeded':
console.log('Payment successful:', event.data.charge_id);
// Update order status, send confirmation email, etc.
break;
case 'charge.failed':
console.log('Payment failed:', event.data.charge_id);
// Notify customer, retry logic, etc.
break;
case 'refund.completed':
console.log('Refund processed:', event.data.refund_id);
// Update order status, notify customer, etc.
break;
case 'subscription.created':
console.log('New subscription:', event.data.subscription_id);
// Activate subscription, send welcome email, etc.
break;
default:
console.log('Unhandled event type:', event.type);
}
res.json({ received: true });
});
Passaggio 7: prova la tua integrazione¶
Avvia il server:
Prova con arricciatura:
# Create a customer
curl -X POST http://localhost:3000/api/payments/customers \
-H "Content-Type: application/json" \
-d '{"email": "test@example.com", "name": "John Doe"}'
# Create a charge
curl -X POST http://localhost:3000/api/payments/charges \
-H "Content-Type: application/json" \
-d '{"amount": 1000, "currency": "USD", "customer_id": "cus_xxx", "description": "Test charge"}'
# Generate a payment link
curl -X POST http://localhost:3000/api/payments/payment-links \
-H "Content-Type: application/json" \
-d '{"amount": 2500, "currency": "USD", "description": "Premium Plan", "success_url": "https://yoursite.com/success", "cancel_url": "https://yoursite.com/cancel"}'
Carte di prova¶
Utilizza queste schede di prova in modalitĂ sandbox:
| Numero della carta | Risultato |
|---|---|
| 4242 4242 4242 4242 | Pagamento riuscito |
| 4000 0000 0000 9995 | Rifiutato (fondi insufficienti) |
| 4000 0000 0000 0002 | Richiede l’autenticazione 3D Secure |
| 4000 0000 0000 0010 | Richiede la verifica CVC |
Migliori pratiche¶
Sicurezza¶
- Non esporre mai la tua chiave segreta nel codice lato client
- Utilizza variabili di ambiente per tutte le credenziali
- Verifica le firme dei webhook per prevenire eventi falsificati
- Implementare chiavi di idempotenza per la creazione di addebiti per evitare duplicati
Gestione degli errori¶
- Controlla sempre “error.response?.data” per messaggi di errore dettagliati
- Implementare la logica dei tentativi per errori temporanei
- Registra tutti gli eventi di pagamento per il controllo
- Gestisci i reindirizzamenti 3D Secure con garbo
ConformitĂ ¶
- 4Geeks Payments è conforme PCI DSS: i dati delle carte non toccano mai i tuoi server
- La conformitĂ fiscale viene gestita automaticamente (IVA, imposta sulle vendite, GST)
- In qualitĂ di commerciante registrato, 4Geeks gestisce la responsabilitĂ di riaddebito
Qual è il prossimo passo?¶
- Ulteriori informazioni sulla Fatturazione ricorrente dell’abbonamento
- Esplora Implementazione 3D Secure
- Leggi informazioni sul Pagamento multivaluta
- Consulta la riferimento API completa
Hai bisogno di aiuto?¶
- Documentazione: docs.4geeks.io/en/payments
- Riferimento API: docs.4geeks.io/en/api
- Discord: Discord
- Supporto: disponibile tramite il dashboard della console
Hai ancora domande? Richiedi supporto or explore tutoriali