Skip to main content
Version: v0.9

Node.js Integration Example (v0.9)

This example demonstrates how to integrate Cryptofuse payments into a Node.js application using the v0.9 API.

Prerequisites

  • Node.js 12.x or higher
  • npm or yarn
  • A Cryptofuse API key

Setting Up

First, create a new project and install the required dependencies:

mkdir cryptofuse-example
cd cryptofuse-example
npm init -y
npm install axios express body-parser dotenv

Create a .env file to store your API key:

CRYPTOFUSE_API_KEY=your_api_key_here

Basic Client

Here's a simple client for interacting with the Cryptofuse API:

// cryptofuse.js
const axios = require('axios');
require('dotenv').config();

class CryptofuseClient {
constructor(apiKey) {
this.apiKey = apiKey || process.env.CRYPTOFUSE_API_KEY;
this.baseUrl = 'https://api.cryptofuse.io/v0';
this.client = axios.create({
baseURL: this.baseUrl,
headers: {
'Content-Type': 'application/json',
'X-API-Key': this.apiKey
}
});
}

async createPayment(params) {
try {
const response = await this.client.post('/payments', params);
return response.data;
} catch (error) {
this.handleError(error, 'Error creating payment');
}
}

async getPayment(paymentId) {
try {
const response = await this.client.get(`/payments/${paymentId}`);
return response.data;
} catch (error) {
this.handleError(error, 'Error getting payment');
}
}

async listPayments(params = {}) {
try {
const response = await this.client.get('/payments', { params });
return response.data;
} catch (error) {
this.handleError(error, 'Error listing payments');
}
}

handleError(error, prefix = 'API Error') {
if (error.response) {
// The request was made and the server responded with an error status
console.error(`${prefix}: ${error.response.status}`, error.response.data);
throw new Error(`${prefix}: ${error.response.data.message || error.response.statusText}`);
} else if (error.request) {
// The request was made but no response was received
console.error(`${prefix}: No response received`, error.request);
throw new Error(`${prefix}: No response received from server`);
} else {
// Something happened in setting up the request
console.error(`${prefix}: ${error.message}`);
throw error;
}
}
}

module.exports = CryptofuseClient;

Simple Express Server

Create a basic Express server to handle payments:

// server.js
const express = require('express');
const bodyParser = require('body-parser');
const CryptofuseClient = require('./cryptofuse');

const app = express();
const port = process.env.PORT || 3000;
const cryptofuse = new CryptofuseClient();

// Middleware
app.use(bodyParser.json());
app.use(express.static('public'));

// Routes
app.post('/create-payment', async (req, res) => {
try {
const { amount, blockchain = 'ETH' } = req.body;

if (!amount || isNaN(amount) || amount <= 0) {
return res.status(400).json({ error: 'Valid amount is required' });
}

// Validate blockchain
const supportedBlockchains = ['ETH', 'BSC', 'BTC', 'TRX'];
if (!supportedBlockchains.includes(blockchain)) {
return res.status(400).json({ error: 'Invalid blockchain. Supported options: ETH, BSC, BTC, TRX' });
}

const params = {
amount_usd: parseFloat(amount),
blockchain: blockchain,
custom_id: `ORDER-${Date.now()}`,
callback_url: `${req.protocol}://${req.get('host')}/payment-callback`
};

const payment = await cryptofuse.createPayment(params);
res.json(payment);
} catch (error) {
console.error('Create payment error:', error);
res.status(500).json({ error: error.message });
}
});

app.get('/check-payment/:paymentId', async (req, res) => {
try {
const { paymentId } = req.params;
const payment = await cryptofuse.getPayment(paymentId);
res.json(payment);
} catch (error) {
console.error('Check payment error:', error);
res.status(500).json({ error: error.message });
}
});

app.post('/payment-callback', (req, res) => {
try {
console.log('Payment callback received:', req.body);

const payment = req.body;

// Process the payment based on status
switch (payment.status) {
case 'completed':
// Payment is confirmed - fulfill the order
fulfillOrder(payment.custom_id);
break;
case 'expired':
// Payment expired - notify user
console.log(`Payment ${payment.payment_id} expired`);
break;
case 'failed':
// Payment failed - notify user
console.log(`Payment ${payment.payment_id} failed`);
break;
}

// Always respond with 200 OK to acknowledge receipt
res.status(200).json({ received: true });
} catch (error) {
console.error('Callback error:', error);
// Still return 200 to avoid retries
res.status(200).json({ received: true, error: error.message });
}
});

app.get('/recent-payments', async (req, res) => {
try {
const payments = await cryptofuse.listPayments({
per_page: 10,
page: 1
});
res.json(payments);
} catch (error) {
console.error('List payments error:', error);
res.status(500).json({ error: error.message });
}
});

// Helper functions
function fulfillOrder(customId) {
// This function would contain your order fulfillment logic
console.log(`Fulfilling order ${customId}`);
// Examples: Update database, send confirmation email, etc.
}

// Start server
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

Simple Frontend

Create a basic HTML frontend in the public folder:

<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cryptofuse Payment Example</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.container {
border: 1px solid #ddd;
padding: 20px;
border-radius: 5px;
}
.payment-info {
margin-top: 20px;
display: none;
}
.payment-address {
background: #f5f5f5;
padding: 10px;
margin: 10px 0;
border-radius: 5px;
word-break: break-all;
}
button {
background: #4CAF50;
color: white;
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background: #45a049;
}
.blockchain-selector {
margin: 10px 0;
}
.status-pending { color: #f39c12; }
.status-confirming { color: #3498db; }
.status-completed { color: #2ecc71; }
.status-expired { color: #e74c3c; }
.status-failed { color: #e74c3c; }
</style>
</head>
<body>
<h1>Cryptofuse Payment Example</h1>

<div class="container">
<h2>Create a Payment</h2>
<div>
<label for="amount">Amount (USD):</label>
<input type="number" id="amount" min="1" step="0.01" value="10.00">

<div class="blockchain-selector">
<label for="blockchain">Blockchain:</label>
<select id="blockchain">
<option value="ETH">Ethereum (ETH)</option>
<option value="BSC">Binance Smart Chain (BSC)</option>
<option value="BTC">Bitcoin (BTC)</option>
<option value="TRX">TRON (TRX)</option>
</select>
</div>

<button id="create-payment-btn">Pay with Crypto</button>
</div>

<div id="payment-info" class="payment-info">
<h3>Payment Information</h3>
<p>Please send <strong id="crypto-amount"></strong> to the following address:</p>

<div class="payment-address">
<code id="payment-address"></code>
<button id="copy-btn">Copy</button>
</div>

<p>Network: <span id="blockchain-display"></span></p>
<p>Payment expires: <span id="expiry-time"></span></p>

<p>Status: <span id="payment-status" class="status-pending">Pending</span></p>
</div>
</div>

<script>
document.getElementById('create-payment-btn').addEventListener('click', createPayment);
document.getElementById('copy-btn').addEventListener('click', copyAddress);

let paymentId;
let statusCheckInterval;

async function createPayment() {
const amount = document.getElementById('amount').value;
const blockchain = document.getElementById('blockchain').value;

try {
const response = await fetch('/create-payment', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ amount, blockchain })
});

if (!response.ok) {
throw new Error('Failed to create payment');
}

const data = await response.json();
displayPaymentInfo(data);

// Start checking status
paymentId = data.payment_id;
startStatusCheck();
} catch (error) {
console.error('Error:', error);
alert('Failed to create payment: ' + error.message);
}
}

function displayPaymentInfo(payment) {
document.getElementById('payment-info').style.display = 'block';
document.getElementById('crypto-amount').textContent = `${payment.crypto_amount} ${payment.token}`;
document.getElementById('payment-address').textContent = payment.address;
document.getElementById('blockchain-display').textContent = formatBlockchain(payment.blockchain);
document.getElementById('expiry-time').textContent = formatDate(payment.expiry_time);
}

function formatBlockchain(blockchain) {
const map = {
'ETH': 'Ethereum (ETH)',
'BSC': 'Binance Smart Chain (BSC)',
'BTC': 'Bitcoin (BTC)',
'TRX': 'TRON (TRX)'
};
return map[blockchain] || blockchain;
}

function formatDate(dateString) {
return new Date(dateString).toLocaleString();
}

function copyAddress() {
const address = document.getElementById('payment-address').textContent;
navigator.clipboard.writeText(address);
alert('Address copied to clipboard');
}

function startStatusCheck() {
// Clear any existing interval
if (statusCheckInterval) {
clearInterval(statusCheckInterval);
}

// Check immediately
checkPaymentStatus();

// Then check every 30 seconds
statusCheckInterval = setInterval(checkPaymentStatus, 30000);
}

async function checkPaymentStatus() {
if (!paymentId) return;

try {
const response = await fetch(`/check-payment/${paymentId}`);

if (!response.ok) {
throw new Error('Failed to check payment status');
}

const payment = await response.json();
updatePaymentStatus(payment);

// Stop checking if payment is in final state
if (['completed', 'expired', 'failed'].includes(payment.status)) {
clearInterval(statusCheckInterval);
}
} catch (error) {
console.error('Error checking payment status:', error);
}
}

function updatePaymentStatus(payment) {
const statusElement = document.getElementById('payment-status');
statusElement.textContent = formatStatus(payment.status);
statusElement.className = `status-${payment.status}`;
}

function formatStatus(status) {
const statusMap = {
'pending': 'Pending - Waiting for payment',
'confirming': 'Confirming - Payment detected, waiting for confirmation',
'completed': 'Completed - Payment successful',
'expired': 'Expired - Payment time limit exceeded',
'failed': 'Failed - Payment processing failed'
};

return statusMap[status] || status;
}
</script>
</body>
</html>

Running the Example

Start your server:

node server.js

Visit http://localhost:3000 in your browser to see the payment form.

Blockchain-Specific Considerations

Bitcoin (BTC)

When accepting Bitcoin payments:

const btcPayment = await cryptofuse.createPayment({
amount_usd: 100.00,
blockchain: "BTC",
callback_url: "https://your-server.com/cryptofuse/webhook",
custom_id: "ORDER-BTC-12345"
});

Bitcoin transactions require only 2 confirmations to be considered completed, which is faster than other blockchains.

TRON (TRX)

For TRON-based USDT payments:

const tronPayment = await cryptofuse.createPayment({
amount_usd: 100.00,
blockchain: "TRX",
callback_url: "https://your-server.com/cryptofuse/webhook",
custom_id: "ORDER-TRX-12345"
});

TRON transactions require 30 confirmations, so they take longer to fully confirm.

Complete Code Structure

The final project structure should look like this:

cryptofuse-example/
├── .env # Environment variables
├── cryptofuse.js # Cryptofuse API client
├── package.json # npm package configuration
├── public/ # Static files
│ └── index.html # Frontend interface
└── server.js # Express server

Next Steps

This example provides a basic integration. For production use, consider:

  1. Adding proper error handling and logging
  2. Implementing database storage for payments
  3. Adding user authentication
  4. Implementing proper order fulfillment logic
  5. Adding additional security measures

For a more advanced integration or any questions, please contact our support team at support@cryptofuse.io.