Introduction
In this tutorial, you'll learn how to integrate stablecoin payment infrastructure into a startup's backend using Coinspaid's API. This practical guide will walk you through setting up a payment processing system that accepts stablecoins like USDC and EURC, which is exactly what the partnership between Coinspaid and The Residency aims to enable for early-stage startups.
Stablecoins offer significant advantages for startups: they provide price stability, fast settlement times, and reduced volatility risk compared to traditional cryptocurrencies. This tutorial will show you how to build a basic payment gateway that can process stablecoin transactions using Coinspaid's infrastructure.
Prerequisites
- Basic understanding of Node.js and JavaScript
- Node.js installed (version 14 or higher)
- npm or yarn package manager
- A Coinspaid API key (you'll need to register at coinspaid.com)
- Basic knowledge of REST APIs and HTTP requests
- Development environment with code editor
Step-by-Step Instructions
1. Initialize Your Project
First, create a new directory for your project and initialize it with npm:
mkdir stablecoin-payment-gateway
cd stablecoin-payment-gateway
npm init -y
This creates a new project directory and initializes a package.json file, which will track your dependencies.
2. Install Required Dependencies
You'll need several packages to interact with Coinspaid's API and handle HTTP requests:
npm install axios dotenv express
We're installing axios for making HTTP requests, dotenv for environment variable management, and express to create a simple web server.
3. Set Up Environment Variables
Create a .env file in your project root to store your Coinspaid API credentials:
COINSPAID_API_KEY=your_api_key_here
COINSPAID_API_SECRET=your_api_secret_here
PORT=3000
Keep these credentials secure and never commit them to version control. The API key and secret are required for authenticating with Coinspaid's services.
4. Create the Main Server File
Create an index.js file that will serve as your main application:
const express = require('express');
const axios = require('axios');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware to parse JSON
app.use(express.json());
// Coinspaid API configuration
const COINSPAID_API_URL = 'https://api.coinspaid.com/v1';
const API_KEY = process.env.COINSPAID_API_KEY;
const API_SECRET = process.env.COINSPAID_API_SECRET;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
This sets up your Express server and configures the Coinspaid API endpoint. The server will listen on port 3000 by default.
5. Create a Payment Creation Endpoint
Add a POST endpoint to create stablecoin payments:
app.post('/create-payment', async (req, res) => {
try {
const { amount, currency, description } = req.body;
// Validate input
if (!amount || !currency) {
return res.status(400).json({
error: 'Amount and currency are required'
});
}
const paymentData = {
amount: amount,
currency: currency,
description: description || 'Stablecoin payment',
redirect_url: 'https://yourdomain.com/payment-success',
cancel_url: 'https://yourdomain.com/payment-cancelled'
};
const response = await axios.post(
`${COINSPAID_API_URL}/payment/create`,
paymentData,
{
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
}
}
);
res.json(response.data);
} catch (error) {
console.error('Payment creation error:', error.response?.data || error.message);
res.status(500).json({
error: 'Failed to create payment'
});
}
});
This endpoint creates a payment request with Coinspaid. It validates input, sends the payment data to Coinspaid's API, and returns the payment details including the blockchain address where funds should be sent.
6. Add Payment Status Check Endpoint
Implement a GET endpoint to check payment status:
app.get('/payment-status/:paymentId', async (req, res) => {
try {
const { paymentId } = req.params;
const response = await axios.get(
`${COINSPAID_API_URL}/payment/${paymentId}/status`,
{
headers: {
'Authorization': `Bearer ${API_KEY}`
}
}
);
res.json(response.data);
} catch (error) {
console.error('Status check error:', error.response?.data || error.message);
res.status(500).json({
error: 'Failed to check payment status'
});
}
});
This endpoint allows you to verify whether a payment has been completed and is crucial for confirming transactions in your application.
7. Test Your Payment Gateway
Start your server:
node index.js
Then test with a curl command or Postman:
curl -X POST http://localhost:3000/create-payment \
-H "Content-Type: application/json" \
-d '{"amount": 100, "currency": "USDC", "description": "Product payment"}'
Replace the amount and currency with your desired values. The response will contain payment details including the blockchain address where the stablecoin payment should be sent.
8. Handle Webhook Notifications
For production use, set up webhook handling to automatically process payments:
app.post('/webhook', async (req, res) => {
try {
const { event, data } = req.body;
if (event === 'payment.completed') {
// Process completed payment
console.log('Payment completed:', data);
// Update your database, send confirmation emails, etc.
}
res.status(200).json({ received: true });
} catch (error) {
console.error('Webhook error:', error);
res.status(500).json({ error: 'Webhook processing failed' });
}
});
Webhooks provide real-time notifications when payments are completed, allowing your application to automatically update its state without polling.
Summary
In this tutorial, you've built a stablecoin payment gateway using Coinspaid's infrastructure. You've learned how to:
- Set up a Node.js server with Express
- Integrate with Coinspaid's API to create payments
- Check payment status programmatically
- Handle webhook notifications for real-time payment updates
This system provides startups with a foundation for accepting stablecoin payments, which is exactly what the Coinspaid-The Residency partnership aims to enable. The stablecoin infrastructure you've implemented offers faster settlement times, lower transaction fees, and price stability compared to traditional payment methods.
Remember to secure your API keys, implement proper error handling, and test thoroughly before deploying to production. The modular structure of this code makes it easy to extend with additional features like multi-currency support or advanced payment tracking.



