v0.5 Sneak Peek: WooCommerce Integration - Bringing Solana Payments to E-Commerce
v0.5 Sneak Peek: WooCommerce Integration - Bringing Solana Payments to E-Commerce The e-commerce revolution is here, and it's powered by Solana. Wi...
v0.5 Sneak Peek: WooCommerce Integration - Bringing Solana Payments to E-Commerce
The e-commerce revolution is here, and it's powered by Solana. With v0.5, we're taking InstantPay beyond simple payment pages and into the heart of online commerce. Our WooCommerce integration represents a monumental step forward in our mission to become the digital payment infrastructure for the entire internet—one transaction at a time.
The E-Commerce Revolution
WooCommerce powers over 28% of all online stores worldwide, making it the most popular e-commerce platform on the planet. When you combine that with WordPress's 43% market share, you get a massive ecosystem of merchants who are ready to embrace the future of payments.
Traditional payment methods have served us well, but they come with limitations:
- High transaction fees (2.9% + $0.30 per transaction)
- Slow settlement times (2-5 business days)
- Geographic restrictions and currency conversion hassles
- Chargeback risks and fraud concerns
Solana changes all of that. With ~400ms transaction times and ~$0.00025 average fees, we're not just offering an alternative—we're offering a revolution.
Real-Time Exchange Rate System: The Foundation
One of the most critical challenges in bringing cryptocurrency payments to e-commerce is handling price volatility and currency conversion. Customers think in fiat currencies (USD, EUR, GBP), but they pay in SOL. We needed a robust, real-time exchange rate system that merchants and customers could trust.
CoinGecko API Integration
We chose CoinGecko as our exchange rate provider for its reliability, comprehensive coverage, and developer-friendly API. Our system fetches rates for:
- SOL/USD (updated every 15 minutes)
- EUR/USD, GBP/USD, TRY/USD, JPY/USD, CAD/USD (updated every 30 minutes)
Here's how we built it:
/**
* Fetch SOL/USD rate from CoinGecko
*/
export async function fetchSOLUSD(): Promise<number | null> {
try {
const response = await fetch(
`${COINGECKO_API_BASE}/simple/price?ids=solana&vs_currencies=usd`,
{
method: 'GET',
headers: {
'Accept': 'application/json',
},
next: { revalidate: 0 }, // Always fetch fresh data
}
);
if (!response.ok) {
console.error(`[CoinGecko] Failed to fetch SOL/USD: ${response.status}`);
return null;
}
const data = await response.json();
const rate = data.solana?.usd;
if (!rate || typeof rate !== 'number') {
return null;
}
return rate;
} catch (error) {
console.error('[CoinGecko] Error fetching SOL/USD:', error);
return null;
}
}
Supabase Exchange Rates Table
All exchange rates are stored in a dedicated Supabase table for fast, reliable access:
CREATE TABLE IF NOT EXISTS public.exchange_rates (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
currency_pair TEXT NOT NULL UNIQUE,
rate NUMERIC(20, 8) NOT NULL,
last_updated TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL
);
This table is publicly readable (with RLS policies) so that WooCommerce checkout pages can fetch rates without authentication, while updates are restricted to our service role.
Automated Cron Job System
Keeping exchange rates fresh is critical. We implemented a cron job system that runs every 15 minutes:
// Cron job endpoint: /api/cron/update-exchange-rates
export async function GET(request: NextRequest) {
// Verify cron secret for security
const authHeader = request.headers.get('authorization');
const cronSecret = process.env.CRON_SECRET;
if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Update SOL/USD (every 15 minutes)
const solRate = await fetchSOLUSD();
if (solRate !== null) {
await supabase
.from('exchange_rates')
.upsert({
currency_pair: 'SOL/USD',
rate: solRate,
last_updated: new Date().toISOString(),
}, { onConflict: 'currency_pair' });
}
// Update fiat rates (every 30 minutes, conditional)
// ...
}
The system intelligently updates fiat rates only when needed (every 30 minutes), reducing API calls while maintaining accuracy.
WooCommerce Payment Gateway: Native Integration
Building a native WooCommerce payment gateway was a fascinating challenge. We needed to integrate seamlessly with WooCommerce's order management system while maintaining the security and reliability that merchants expect.
Gateway Class Architecture
Our payment gateway extends WooCommerce's WC_Payment_Gateway class, giving us full access to WooCommerce's payment processing infrastructure:
class WC_Gateway_InstantPay extends WC_Payment_Gateway {
public function __construct() {
$this->id = 'instantpay_sol';
$this->method_title = __( 'InstantPay (Pay with SOL)', 'instantpay-solana-payments' );
$this->method_description = __( 'Accept Solana (SOL) payments directly to your wallet.', 'instantpay-solana-payments' );
// Load settings
$this->init_form_fields();
$this->init_settings();
// Define configuration
$this->wallet_address = $this->get_option( 'wallet_address' );
$this->min_amount = $this->get_option( 'min_amount', '0.001' );
}
public function process_payment($order_id) {
$order = wc_get_order($order_id);
// Get transaction signature from checkout
$transaction_signature = sanitize_text_field($_POST['instantpay_transaction_signature']);
// Store transaction data
$order->update_meta_data('_instantpay_tx_hash', $transaction_signature);
$order->update_status('processing', __( 'InstantPay payment received. Verifying...', 'instantpay-solana-payments' ));
// Verify transaction asynchronously
$this->verify_transaction($order_id, $transaction_signature);
return array(
'result' => 'success',
'redirect' => $this->get_return_url($order),
);
}
}
Admin Configuration
Merchants can configure the gateway directly from WooCommerce settings:
- Enable/Disable toggle
- Wallet Address (where payments are received)
- Minimum Order Amount (default: 0.001 SOL)
- Test Mode (for Solana devnet testing)
All settings are validated and sanitized using WordPress best practices.
Price Staleness Protection: A Critical Innovation
One of the most interesting challenges in cryptocurrency e-commerce is price staleness. What happens if a customer opens the checkout page, waits 30 minutes, and the SOL price changes significantly?
We implemented a multi-layered protection system:
1. Automatic Rate Refresh
The checkout page automatically refreshes exchange rates every 10 minutes:
// Initialize rates and set up auto-refresh
async function initializeRates() {
// Fetch initial rates
await refreshRates();
// Set up 10-minute refresh interval
state.refreshInterval = setInterval(function() {
refreshRates();
}, 10 * 60 * 1000); // 10 minutes
}
2. Pre-Transaction Rate Check
Before sending a transaction, we always check the latest rate:
async function sendTransaction() {
// Re-check exchange rate before sending
var rates = await fetchExchangeRates();
if (rates) {
var newSolAmount = calculateSOLAmount(rates);
// If rate changed significantly, ask user to confirm
if (Math.abs(newSolAmount - state.solAmount) > 0.0001) {
var confirmed = confirm(
'Exchange rate has changed. New amount: ' + newSolAmount.toFixed(9) + ' SOL\n' +
'Previous amount: ' + state.solAmount.toFixed(9) + ' SOL\n\n' +
'Do you want to proceed with the new amount?'
);
if (!confirmed) return;
state.solAmount = newSolAmount;
updateSOLDisplay(newSolAmount);
}
}
// Proceed with transaction...
}
This ensures customers are always aware of price changes and can make informed decisions.
3. Real-Time SOL Calculation
The checkout page calculates SOL amounts in real-time based on the order total and current exchange rates:
function calculateSOLAmount(rates) {
var orderTotal = parseFloat(config.orderTotal.replace(/[^0-9.-]+/g, ''));
var currency = config.currency.toUpperCase();
var solUsdRate = rates['SOL/USD'];
// Convert to USD if needed
var usdAmount = orderTotal;
if (currency !== 'USD') {
var currencyRate = rates[currency + '/USD'];
usdAmount = orderTotal * currencyRate;
}
// Convert USD to SOL
var solAmount = usdAmount / solUsdRate;
// Round to 9 decimal places (SOL precision)
solAmount = Math.round(solAmount * 1000000000) / 1000000000;
return solAmount;
}
Transaction Verification & Security: Enterprise-Grade Protection
Security is non-negotiable in e-commerce. We implemented comprehensive verification and protection mechanisms to ensure every transaction is legitimate and secure.
Helius RPC Verification
Every transaction is verified on-chain using Helius RPC (our preferred Solana RPC provider for reliability and speed):
export async function verifyTransaction(
signature: string,
expectedAmountSOL: number,
recipientAddress: string
): Promise<boolean> {
const connection = new Connection(
process.env.NEXT_PUBLIC_HELIUS_RPC_URL!,
'confirmed'
);
// Fetch transaction from blockchain
const tx = await connection.getTransaction(signature, {
maxSupportedTransactionVersion: 0,
});
if (!tx || !tx.meta || tx.meta.err) {
return false; // Transaction failed or not found
}
// Verify recipient address
const recipientPubkey = new PublicKey(recipientAddress);
const accountKeys = tx.transaction.message.getAccountKeys();
const recipientIndex = accountKeys.findIndex(key =>
key.equals(recipientPubkey)
);
if (recipientIndex === -1) {
return false; // Recipient not found
}
// Verify amount
const preBalance = tx.meta.preBalances[recipientIndex] || 0;
const postBalance = tx.meta.postBalances[recipientIndex] || 0;
const amountReceived = postBalance - preBalance;
const expectedLamports = Math.round(expectedAmountSOL * LAMPORTS_PER_SOL);
// Allow small tolerance for rounding
const tolerance = 1000; // 0.000001 SOL
if (Math.abs(amountReceived - expectedLamports) > tolerance) {
return false; // Amount mismatch
}
return true; // Transaction verified
}
Double Payment Protection
We prevent the same transaction from being used for multiple orders:
// Check if transaction signature is already used
$existing_order = wc_get_orders(array(
'limit' => 1,
'meta_key' => '_instantpay_tx_hash',
'meta_value' => $transaction_signature,
'exclude' => array($order_id),
));
if (!empty($existing_order)) {
wc_add_notice(
__( 'This transaction has already been used for another order.', 'instantpay-solana-payments' ),
'error'
);
return array('result' => 'fail');
}
Minimum Amount Validation
We enforce a minimum transaction amount of 0.001 SOL to prevent dust attacks and ensure transactions are economically viable:
$sol_amount_float = floatval($sol_amount);
if ($sol_amount_float < floatval($this->min_amount)) {
wc_add_notice(
sprintf(
__( 'SOL amount (%s) is below minimum required amount (%s SOL).', 'instantpay-solana-payments' ),
$sol_amount,
$this->min_amount
),
'error'
);
return array('result' => 'fail');
}
Network Error Handling & Retry Logic
Network issues are inevitable. We implemented retry logic with exponential backoff:
private function verify_transaction($order_id, $transaction_signature, $sol_amount) {
$max_retries = 3;
$retry_count = 0;
while ($retry_count < $max_retries) {
$response = wp_remote_post(
$this->api_base . '/api/woocommerce/verify-payment',
array(
'body' => array(
'order_id' => $order_id,
'transaction_signature' => $transaction_signature,
'sol_amount' => $sol_amount,
'recipient_address' => $this->wallet_address,
),
'timeout' => 30,
)
);
if (is_wp_error($response)) {
$retry_count++;
if ($retry_count >= $max_retries) {
// Mark order as on-hold for manual review
$order->update_status('on-hold', __( 'Verification failed. Please verify manually.', 'instantpay-solana-payments' ));
return;
}
sleep($retry_count); // Exponential backoff
continue;
}
// Process response...
break;
}
}
Wallet Address Validation
We validate Solana wallet addresses to prevent configuration errors:
private function is_valid_solana_address($address) {
if (empty($address)) {
return false;
}
// Basic Solana address validation
if (strlen($address) < 32 || strlen($address) > 44) {
return false;
}
// Check for base58 characters only
if (!preg_match('/^[1-9A-HJ-NP-Za-km-z]+$/', $address)) {
return false;
}
return true;
}
Frontend Checkout Experience: Seamless UX
The checkout experience is where everything comes together. We built a user-friendly interface that guides customers through the payment process step-by-step.
Phantom Wallet Integration
Customers connect their Phantom wallet directly from the checkout page:
async function connectWallet() {
if (!isPhantomInstalled()) {
alert('Phantom wallet is not installed. Please install from https://phantom.app');
return;
}
try {
var response = await solana.connect();
state.publicKey = response.publicKey;
state.walletConnected = true;
// Update UI
connectWalletBtn.style.display = 'none';
walletStatusDiv.style.display = 'block';
walletStatusDiv.textContent = 'Wallet connected: ' +
state.publicKey.toString().substring(0, 8) + '...';
} catch (error) {
console.error('[InstantPay] Wallet connection error:', error);
alert('Failed to connect wallet. Please try again.');
}
}
Transaction Sending & Confirmation
Once the wallet is connected, customers can send the transaction:
async function sendTransaction() {
// Create Solana connection
var connection = new solanaWeb3.Connection(rpcUrl, 'confirmed');
// Create transaction
var recipient = new solanaWeb3.PublicKey(config.walletAddress);
var lamports = Math.round(state.solAmount * 1000000000);
var transaction = new solanaWeb3.Transaction().add(
solanaWeb3.SystemProgram.transfer({
fromPubkey: state.publicKey,
toPubkey: recipient,
lamports: lamports,
})
);
// Get recent blockhash
var { blockhash } = await connection.getLatestBlockhash();
transaction.recentBlockhash = blockhash;
transaction.feePayer = state.publicKey;
// Send transaction
var signature = await solana.sendTransaction(transaction, connection);
// Store signature for WooCommerce
transactionSignatureInput.value = signature;
// Poll for confirmation (30 seconds timeout)
var confirmed = false;
var attempts = 0;
var maxAttempts = 15; // 15 attempts * 2 seconds = 30 seconds
while (!confirmed && attempts < maxAttempts) {
await new Promise(function(resolve) {
setTimeout(resolve, 2000); // Wait 2 seconds
});
var status = await connection.getSignatureStatus(signature);
if (status && status.value && !status.value.err) {
confirmed = true;
alert('Transaction confirmed! You can now submit your order.');
}
attempts++;
}
}
Loading States & Error Handling
We provide clear feedback at every step:
- "Calculating..." while fetching exchange rates
- "Connecting wallet..." during wallet connection
- "Sending transaction..." during transaction submission
- "Confirming transaction..." during blockchain confirmation
- Error messages for any failures (network errors, insufficient funds, etc.)
Technical Architecture: Scalable & Maintainable
Our architecture is designed for scale, reliability, and maintainability. Here's how the pieces fit together:
API Endpoints
Public Exchange Rates API:
GET /api/public/exchange-rates
Returns current exchange rates with CORS enabled for WooCommerce checkout pages.
Transaction Verification API:
POST /api/woocommerce/verify-payment
Verifies Solana transactions and updates WooCommerce order status.
Transaction Status Check API:
GET /api/woocommerce/check-transaction?signature=...
Allows frontend polling for transaction confirmation.
Database Schema
Exchange Rates Table:
- Stores current rates for all supported currency pairs
- Public read access (RLS policy)
- Service role write access only
WooCommerce Order Meta:
_instantpay_tx_hash: Transaction signature_instantpay_sol_amount: SOL amount paid_instantpay_payment_method: Payment method identifier
Error Handling Strategy
We handle errors at multiple levels:
- API Level: Graceful error responses with clear messages
- Gateway Level: Order status updates (on-hold for manual review)
- Frontend Level: User-friendly error messages and retry options
- Network Level: Retry logic with exponential backoff
Vision: The Future of Digital Payments
This WooCommerce integration is more than just a feature—it's a statement of intent. We're not building a payment method; we're building the digital payment infrastructure for the entire internet.
The Path Forward
Our roadmap extends far beyond WooCommerce:
- Shopify Integration: Bringing Solana payments to the second-largest e-commerce platform
- Magento Extension: Enterprise e-commerce support
- API & SDK: Developer tools for custom integrations
- Multi-Currency Support: Display prices in any currency, pay in SOL
- Advanced Analytics: Merchant dashboards with transaction insights
- Subscription Payments: Recurring Solana payments for SaaS and memberships
Global Reach, Decentralized Infrastructure
The internet is global, but payment systems are fragmented. We're building a unified, decentralized payment layer that works everywhere:
- No geographic restrictions: Anyone, anywhere can accept payments
- No currency conversion fees: Pay in SOL, display in any currency
- No settlement delays: Instant confirmation, instant access to funds
- No chargebacks: Blockchain transactions are final and irreversible
Web3 Meets E-Commerce
We're at the intersection of Web3 and traditional e-commerce. This integration proves that:
- Cryptocurrency payments can be user-friendly and merchant-friendly
- Blockchain technology can enhance existing platforms, not replace them
- Decentralized systems can integrate seamlessly with centralized infrastructure
The future of e-commerce is fast, global, and decentralized. With v0.5, we're making that future available to millions of merchants today.
What's Next
v0.5 is just the beginning. Here's what's coming:
Immediate Roadmap
- Shopify App: Native Shopify integration with app store distribution
- Magento 2 Extension: Full-featured Magento 2 payment gateway
- Advanced Analytics: Merchant dashboards with sales insights
- Multi-Token Support: Accept USDC, USDT, and other SPL tokens
Long-Term Vision
- Payment Link Generator: Create shareable payment links for any amount
- Invoice System: Generate and send Solana payment invoices
- Recurring Payments: Subscription and membership payment support
- Fraud Detection: AI-powered fraud prevention for high-value transactions
- Mobile SDK: Native iOS and Android SDKs for mobile apps
Coming Soon
v0.5 and the WooCommerce integration will be released very soon. Merchants will be able to:
- Accept Solana payments alongside traditional payment methods
- Offer customers a faster, cheaper payment option
- Access funds instantly without waiting for settlement
- Reach global customers without currency conversion hassles
The e-commerce revolution starts here. Stay tuned for the official release announcement!
Built with ❤️ by the InstantPay team. Follow our journey as we make Solana payments the infrastructure for the entire internet.