How to Test Crypto Payments Locally Using Blockonomics API and Cloudflare Tunnels
Testing payment gateways on a localhost environment can be a major headache. Because your local server is hidden behind your router, external services like Blockonomics cannot send webhook callbacks to http://localhost:3000.
Historically, developers had to deploy to a staging server just to test a simple payment flow. Today, we can solve this using Cloudflare Tunnels and the Blockonomics Payment Intents API.
This guide will walk you through creating a fully functional, end-to-end crypto checkout page on your local machine, receiving real-time callbacks securely.
Prerequisites
Before you begin, ensure you have:
- A Blockonomics Account.
- VS Code (or your preferred code editor).
Steps to follow:
Step 1: Create your Blockonomics account
- Sign up at blockonomics.co.
- Once logged in, you will be prompted to set up a destination wallet.
Step 2: Connect your Wallet
We will use the Chui Wallet extension for this demo.
- Install the Chui Wallet extension from the Chrome Web Store.
- Create a new wallet.
- Crucial Security Step: The wallet will provide a 12-word seed phrase. Write this down on paper and store it securely. Do not screenshot it.
- Verify the seed phrase to complete the wallet setup.
- Back in your Blockonomics dashboard, go to the Wallets tab, click Connect Wallet, and link your Chui Wallet.
Step 3: Create a store
- Navigate to the Stores tab in Blockonomics.
- At the top of the page, copy your API Key. This is your VIP pass for the API.
- Click Add a Store. Name it (e.g., "Local Test").
- Leave the Callback URL blank for now (we will generate this in Phase 4).
- Toggle the destination wallets for each coin.
- Toggle Testmode ON. This ensures no real funds are moved.
- Click Create Store.
Step 4: Add Blockonomics API endpoints to your code(Sample code in the description)
Step Local Project Setup
Create a new folder, open it in VS Code, and open your integrated terminal.
bash
# Initialize the Node.js project
npm init -y
# Install Express (our web server) and Dotenv (for secret management)
npm install express dotenv
Create three files in your root directory: .env, server.js, and index.html.
File 1: The .env File (Security First)
Never hardcode secrets. Create a .env file to store your credentials securely:
env
BLOCKONOMICS_API_KEY=your_api_key_from_phase_1
CALLBACK_SECRET=a_long_random_string_of_your_choice
File 2: The Backend: server.js
This Express server handles two jobs: creating the Payment Intent via the Blockonomics API and listening for the webhook callback.
javascript
require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json());
// Serve the frontend checkout page
app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'));
// JOB 1: Create a Payment Intent
app.post('/api/create-intent', async (req, res) => {
const { orderId, amount } = req.body;
try {
const response = await fetch('<https://www.blockonomics.co/api/v2/payment_intents>', {
method: 'POST',
headers: {
'Authorization': `Bearer${process.env.BLOCKONOMICS_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
amount: amount, // e.g., "10.00"
currency: 'USD',
extra_data: orderId // Your internal database order reference
})
});
const result = await response.json();
if (!response.ok) {
console.error('Blockonomics API Error:', result);
return res.status(response.status).json({ error: 'Failed to create intent' });
}
console.log('Created intent:', result.data.id, 'for order:', orderId);
res.json({ intent_id: result.data.id });
} catch (error) {
console.error('Server Error:', error.message);
res.status(500).json({ error: 'Internal Server Error' });
}
});
// JOB 2: Receive the Webhook Callback
app.get('/api/payment-callback', (req, res) => {
const { secret, status, value, txid, addr } = req.query;
// Verify the request is actually from Blockonomics
if (secret !== process.env.CALLBACK_SECRET) {
console.log('⚠️ Blocked a callback: Invalid secret');
return res.status(403).send('Forbidden');
}
// According to Blockonomics docs, status >= 2 means 2+ network confirmations
const confirmationStatus = parseInt(status, 10);
if (confirmationStatus >= 2) {
console.log('✅ Payment confirmed!', { txid, addr, value });
// PRODUCTION TIP: Update your database here (e.g., mark order as PAID)
} else {
console.log('Payment detected, waiting for confirmations. Status:', confirmationStatus);
}
// ALWAYS respond with HTTP 200 so Blockonomics stops retrying
res.status(200).send('OK');
});
app.listen(3000, () => console.log('Server running on <http://localhost:3000>'));
File 3: The Frontend: index.html
Blockonomics provides an official checkout.js library. This handles the UI, QR code generation, and live exchange rates, saving you from building a crypto checkout from scratch.
html
<!DOCTYPE html>
<html>
<head>
<title>Demo Checkout</title>
</head>
<body style="font-family: sans-serif; padding: 40px;">
<h2>Demo Store</h2>
<p>Order Total: <strong>$10.00</strong></p>
<button id="pay-btn" style="padding: 10px 20px; cursor: pointer;">Pay with Crypto</button>
<div id="widget-area" style="margin-top:20px;"></div>
<!-- Load the Blockonomics Checkout Script -->
<script src="<https://www.blockonomics.co/js/checkout.js>"></script>
<script>
document.getElementById('pay-btn').onclick = async () => {
try {
// 1. Get the Payment Intent ID from our backend
const res = await fetch('/api/create-intent', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ orderId: 'order-1234', amount: '10.00' })
});
const data = await res.json();
if (!data.intent_id) {
alert("Error creating payment. Check terminal.");
return;
}
// 2. Render the Blockonomics Widget
Blockonomics.checkout({
msg_area: 'widget-area',
intent_id: data.intent_id
});
} catch (err) {
console.error(err);
alert("Network error.");
}
};
</script>
</body>
</html>
Step 5: Adding Cloudflare tunneling
Because your app is running locally, Blockonomics can't reach it. We will use a Cloudflare Quick Tunnel.
- Open a new terminal window in VS Code (keep your server terminal separate).
- The terminal will output a public URL (e.g.,
https://random-words-here.trycloudflare.com). Copy this URL.
Run the tunnel command:bash
npx cloudflared tunnel --url <http://localhost:3000>
(Note: If npx fails, you may need to install Cloudflare globally using winget install --id Cloudflare.cloudflared and restart VS Code).
Step 6: Add the Cloudflare Tunneled Callback URL to Blockonomics Store Settings
- Go back to your Blockonomics Store settings.
- Click Update Store.
In the Callback URL field, paste your Cloudflare URL and append the callback path and secret:text
<https://random-words-here.trycloudflare.com/api/payment-callback?secret=YOUR_SECRET_FROM_ENV>
Step 7: Testing the gateway connection with a test payment
- Open your browser and go to your Cloudflare URL (Testing via the tunnel ensures the whole path works).
- Click Pay with Crypto. The widget will load with a live QR code, BTC address, and timer.
- Do not send real money. Instead, go to your Blockonomics Dashboard and click on Log/Test Bench.
- You will see the BTC address generated by the widget listed there.
- Enter the amount and click Send Test Transaction.
Look at your VS Code terminal. You should see:text
✅ Payment confirmed! { txid: '...', addr: '...', value: '...' }
Start your local server:bash
node server.js
Congratulations! The webhook successfully traveled from Blockonomics, through the Cloudflare Tunnel, and hit your local server.
Note: Quick tunnel URLs change on every restart. Create a free Cloudflare account, route a domain to it, and set up a Named Tunnel for a permanent URL (e.g., pay.yourdomain.com).
Troubleshooting Common Errors
Error: Cannot find module 'express': You forgot to runnpm install express dotenv.401 Unauthorized: Your API key in the.envfile is incorrect, or you are trying to access the API endpoint via a web browser without headers.- Widget says "Missing intent_id": Your backend failed to create an order. Check your VS Code terminal for API errors (usually an invalid API key).
- Callback fails (Timeout/502): Your local server (
node server.js) or your Cloudflare Tunnel is not running.