Vai al contenuto

🤖 Spiega con IA

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

  1. Accedi a console.4geeks.io
  2. Vai a Pagamenti → Impostazioni → Chiavi API
  3. Fai clic su “Genera chiave API”
  4. Copia e archivia in modo sicuro:
  5. Chiave pubblica (per operazioni lato client)
  6. 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

mkdir my-payment-app && cd my-payment-app
npm init -y
npm install express axios dotenv cors

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:

CODICE_BLOCCO_2

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:

CODICE_BLOCCO_5

Passaggio 7: prova la tua integrazione

Avvia il server:

CODICE_BLOCCO_6

Prova con arricciatura:

CODICE_BLOCCO_7

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?

Hai bisogno di aiuto?


Hai ancora domande? Richiedi supporto or explore tutoriali