@w3payments/react
v1.7.0
Published
React component library for universal Web3 payment processing with multi-vendor support
Maintainers
Readme
W3 Payments React
React components for crypto onramping and payments. Currently focused on fiat-to-crypto and crypto-to-crypto onramp flows with MeshPay integration.
Install
npm install @w3payments/react @w3payments/core @w3payments/commonQuick Start
1. Backend Setup (Required)
The widget requires a secure backend to create payment sessions. Create an Express server:
// server.ts
import express from 'express';
import cors from 'cors';
import { W3Payments } from '@w3payments/core';
import type { CreatePaymentOptions } from '@w3payments/common';
const app = express();
app.use(cors());
app.use(express.json());
// Initialize W3Payments with your credentials
const w3payments = new W3Payments({
config: {
environment: 'sandbox', // or 'production'
meshpay: {
clientId: process.env.MESH_CLIENT_ID!,
clientSecret: process.env.MESH_CLIENT_SECRET!,
},
},
});
await w3payments.initialize();
// Create payment endpoint
app.post('/api/payments/create', async (req, res) => {
try {
// Validate request body matches expected CreatePaymentOptions type
const paymentOptions: CreatePaymentOptions = req.body;
const session = await w3payments.paymentIntents.create(paymentOptions);
res.json(session);
} catch (error) {
res.status(500).json({
error: error instanceof Error ? error.message : 'Payment creation failed'
});
}
});
// Payment status endpoint
app.get('/api/payments/:sessionId', async (req, res) => {
try {
const { sessionId } = req.params;
const { vendorId } = req.query;
if (!vendorId || typeof vendorId !== 'string') {
return res.status(400).json({ error: 'vendorId is required' });
}
const status = await w3payments.paymentIntents.retrieve(sessionId, vendorId);
res.json(status);
} catch (error) {
res.status(500).json({
error: error instanceof Error ? error.message : 'Status retrieval failed'
});
}
});
app.listen(3001);Credentials: MeshPay credentials are provided by the W3 Payments team during onboarding.
2. React Integration
Add the payment widget to your React app:
import { W3PaymentsProvider, W3PaymentWidget } from '@w3payments/react';
export function PaymentPage() {
return (
<div style={{ width: '400px', height: '600px' }}>
<W3PaymentsProvider
endpoint="http://localhost:3001/api/payments"
environment="sandbox"
>
<W3PaymentWidget
title="Fund Wallet"
targetCurrency="USDC"
targetNetwork="solana"
destinations={[{
address: "your_wallet_or_contract_address",
networkId: "solana",
symbol: "USDC"
}]}
onComplete={(result) => {
console.log('Payment completed:', result.transactionId);
// Update UI, redirect, etc.
}}
onError={(error) => {
console.error('Payment failed:', error.message);
// Show error to user
}}
/>
</W3PaymentsProvider>
</div>
);
}Configuration
Required Props
destinations - Where payments will be sent:
destinations={[{
address: "contract_or_wallet_address",
networkId: "solana", // bitcoin, ethereum, solana, polygon, etc.
symbol: "USDC" // Currency symbol
}]}Payment Method Filtering
Control which payment options are available:
// Show specific wallet currencies
walletFilter={['BTC', 'ETH', 'USDC']}
// Show specific exchanges
exchangeFilter={['coinbase', 'kraken', 'binance']}
// Show fiat payment methods
fiatFilter={['ACH']}
// Target specific currency (auto-converts if needed)
targetCurrency="USDC"
targetNetwork="solana"Event Handling
<W3PaymentWidget
onInitiate={(data) => {
// User clicked payment button - log for analytics
console.log(`Starting ${data.currency} payment for ${data.amount}`);
}}
onComplete={(data) => {
// Payment successful - update your app state
updateUserBalance(data.amount);
redirectToSuccess();
}}
onError={(error) => {
// Payment failed - show user-friendly error
showErrorMessage(error.message);
}}
/>Use Cases
Crypto Onramping (Coming Soon with IronPay)
// Buy crypto with fiat (ACH, bank transfer) - IronPay integration in progress
<W3PaymentWidget
title="Buy Crypto"
targetCurrency="USDC"
targetNetwork="solana"
fiatFilter={['ACH']} // Will be available with IronPay
destinations={[{ address: userWallet, networkId: "solana", symbol: "USDC" }]}
/>Crypto-to-Crypto Transfers (Available Now)
// Transfer between different cryptocurrencies
<W3PaymentWidget
title="Fund Wallet"
targetCurrency="USDC"
targetNetwork="solana"
walletFilter={['BTC', 'ETH']} // Pay with BTC/ETH, receive USDC
destinations={[{ address: userWallet, networkId: "solana", symbol: "USDC" }]}
/>Coming Soon
// Auto-Converting Payments - COMING SOON
<W3PaymentWidget
title="Pay with Any Currency"
targetCurrency="ETH"
autoConvert={true} // Not yet available
destinations={[{ address: receiverWallet, networkId: "ethereum", symbol: "ETH" }]}
/>
// Staking with Auto-Yield - COMING SOON
<W3PaymentWidget
title="Stake & Earn"
autoYield={true} // Not yet available
destinations={[{ address: stakingContract, networkId: "solana", symbol: "USDC" }]}
/>
// Crypto Offramping - COMING SOON
<W3PaymentWidget
title="Cash Out"
targetCurrency="USD" // Fiat offramp not yet available
destinations={[{ address: bankAccount, networkId: "fiat", symbol: "USD" }]}
/>Current Features
MeshPay Integration
Secure crypto-to-crypto transfers and exchange integrations through MeshPay's infrastructure.
Multi-Currency Support
Support for major cryptocurrencies (BTC, ETH, USDC, SOL) across multiple networks (Bitcoin, Ethereum, Solana).
Smart Payment Routing
Automatically routes payments through the most efficient available methods based on your target currency and network.
Planned Features (Coming Soon)
IronPay Integration
Fiat-to-crypto onramping with ACH bank transfers and direct USD purchasing (integration in progress).
Auto Conversion
Automatic currency conversions between any supported payment methods and target currencies at optimal rates.
Auto Yield
Automatic routing through yield-generating opportunities (staking, lending pools) while maintaining the same user experience.
Cross-Chain Support
Seamless payments across Bitcoin, Ethereum, Solana, Polygon with automatic bridging.
Crypto Offramping
Direct crypto-to-fiat conversions with bank account deposits.
Customization
Widget Branding
Customize the widget appearance with props:
<W3PaymentWidget
title="Your Brand Name"
subtitle="CHOOSE PAYMENT METHOD"
logo="/your-logo.png"
showAmount={false} // Hide amount section
// Logo/title displays automatically when provided
// Description displays when provided, independent of logo
// ... other props
/>Theme Customization
Use the W3Appearance API for consistent theming across all components:
Built-in Themes
import { W3PaymentWidget } from '@w3payments/react';
// Default light theme
<W3PaymentWidget theme="default" />
// Dark theme
<W3PaymentWidget theme="night" />Custom Themes
import type { W3Appearance } from '@w3payments/react';
const customTheme: W3Appearance = {
variables: {
// Brand colors
primary: '#ff6b35', // Orange brand color
// Main layout backgrounds
mainBackground: '#ffffff', // Outer container + footer background
innerBackground: '#f8f9fa', // Inner container (amount/methods section)
cardBackground: '#ffffff', // Payment method row background
// Text colors (component-based)
primaryText: '#2d3748', // Main text color (logo/headers)
secondaryText: '#718096', // Secondary text (method descriptions, USD amounts)
descriptionText: '#718096', // Widget description text
amountText: '#2d3748', // Payment amount text
subtitleText: '#718096', // "CHOOSE A PAYMENT METHOD" text
cardText: '#2d3748', // Payment method card text
cardSecondaryText: '#718096', // Payment method card subtitle text
usdText: '#718096', // USD amount text color
footerText: '#718096', // Footer text color
// QR screen specific colors
qrAddressBackground: '#f8f9fa', // QR address section background
qrAddressText: '#2d3748', // QR address text color
qrInstructionsBackground: '#f8f9fa', // QR instructions background
qrInstructionsText: '#718096', // QR instructions text color
qrCardBackground: '#ffffff', // QR network/token cards background
qrCardText: '#2d3748', // QR network/token cards text
// Status colors
success: '#38a169', // Green
danger: '#e53e3e', // Red
warning: '#dd6b20', // Orange
borderColor: '#e2e8f0', // Borders and dividers
info: '#3182ce', // Info background
// Typography
fontFamily: 'Inter, system-ui, sans-serif',
fontSizeBase: '14px',
fontSizeSmall: '12px',
fontSizeLarge: '32px',
fontWeightNormal: '400',
// Layout
spacingUnit: '4px', // Base spacing unit
borderRadius: '8px', // Default border radius
buttonRadius: '6px' // Button border radius
}
};
<W3PaymentWidget appearance={customTheme} />Dark Theme Example
const darkTheme: W3Appearance = {
variables: {
// Brand colors
primary: '#0085FF', // Blue accent
// Dark layout backgrounds
mainBackground: '#14171D', // Dark outer container + footer
innerBackground: '#1a1d24', // Dark inner container
cardBackground: '#1f222a', // Dark payment method cards
// Light text on dark backgrounds
primaryText: '#C9CED8', // Light headers/logo
secondaryText: '#8C99AD', // Muted light text
descriptionText: '#8C99AD', // Light description text
amountText: '#C9CED8', // Light payment amount
subtitleText: '#8C99AD', // Light subtitle
cardText: '#C9CED8', // Light card text
cardSecondaryText: '#8C99AD', // Muted card text
usdText: '#8C99AD', // Light USD amounts
footerText: '#8C99AD', // Light footer text
// QR screen dark theme
qrAddressBackground: '#2B3039', // Dark QR address section
qrAddressText: '#C9CED8', // Light QR address text
qrInstructionsBackground: '#2B3039', // Dark QR instructions
qrInstructionsText: '#8C99AD', // Light QR instructions text
qrCardBackground: '#1f222a', // Dark QR cards
qrCardText: '#C9CED8', // Light QR card text
// Bright status colors for dark theme
success: '#48bb78', // Bright green
danger: '#F23154', // Bright red
warning: '#ed8936', // Bright orange
borderColor: '#2B3039', // Dark borders
info: '#1e3a5f', // Dark info background
// Typography
fontFamily: 'SF Pro Display, system-ui, sans-serif',
fontSizeBase: '14px',
fontSizeSmall: '12px',
fontSizeLarge: '32px',
fontWeightNormal: '400',
// Layout
spacingUnit: '4px',
borderRadius: '8px',
buttonRadius: '6px'
}
};
<W3PaymentWidget appearance={darkTheme} />Theming with Context
Apply themes globally using the provider:
<W3PaymentsProvider
endpoint="http://localhost:3001/api/payments"
environment="sandbox"
appearance={customTheme} // Applied to all widgets
>
<W3PaymentWidget amount="100.00" />
<W3PaymentWidget amount="50.00" /> {/* Both use customTheme */}
</W3PaymentsProvider>Advanced Theming
Responsive Themes
const useResponsiveTheme = () => {
const [theme, setTheme] = useState<W3Appearance>({
variables: {
primary: '#2563eb',
spacingUnit: window.innerWidth < 768 ? '3px' : '4px',
fontSizeBase: window.innerWidth < 768 ? '13px' : '14px',
borderRadius: window.innerWidth < 768 ? '6px' : '8px'
}
});
useEffect(() => {
const handleResize = () => {
setTheme(prev => ({
variables: {
...prev.variables,
spacingUnit: window.innerWidth < 768 ? '3px' : '4px',
fontSizeBase: window.innerWidth < 768 ? '13px' : '14px',
borderRadius: window.innerWidth < 768 ? '6px' : '8px'
}
}));
};
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return theme;
};
// Usage
function PaymentPage() {
const responsiveTheme = useResponsiveTheme();
return (
<W3PaymentWidget appearance={responsiveTheme} />
);
}Brand Integration
// Extract colors from your design system
const brandTheme: W3Appearance = {
variables: {
// Use your brand colors
primary: 'var(--brand-primary, #2563eb)',
// Map to your design system backgrounds
mainBackground: 'var(--surface-primary, #ffffff)',
innerBackground: 'var(--surface-secondary, #f8f9fa)',
cardBackground: 'var(--surface-primary, #ffffff)',
// Map to your text color system
primaryText: 'var(--text-primary, #1a1a1a)',
secondaryText: 'var(--text-secondary, #6b7280)',
descriptionText: 'var(--text-muted, #6b7280)',
amountText: 'var(--text-primary, #1a1a1a)',
subtitleText: 'var(--text-secondary, #6b7280)',
cardText: 'var(--text-primary, #1a1a1a)',
cardSecondaryText: 'var(--text-muted, #6b7280)',
usdText: 'var(--text-secondary, #6b7280)',
footerText: 'var(--text-secondary, #6b7280)',
// QR screen brand colors
qrAddressBackground: 'var(--surface-secondary, #f8f9fa)',
qrAddressText: 'var(--text-primary, #1a1a1a)',
qrInstructionsBackground: 'var(--surface-tertiary, #e5e7eb)',
qrInstructionsText: 'var(--text-secondary, #6b7280)',
qrCardBackground: 'var(--surface-primary, #ffffff)',
qrCardText: 'var(--text-primary, #1a1a1a)',
// Status colors from design system
success: 'var(--status-success, #16a34a)',
danger: 'var(--status-error, #dc2626)',
warning: 'var(--status-warning, #ca8a04)',
borderColor: 'var(--border-default, #e5e7eb)',
info: 'var(--status-info, #3b82f6)',
// Match your typography
fontFamily: 'var(--font-family, Inter, sans-serif)',
fontSizeBase: 'var(--text-sm, 14px)',
fontSizeSmall: 'var(--text-xs, 12px)',
fontSizeLarge: 'var(--text-2xl, 32px)',
fontWeightNormal: 'var(--font-normal, 400)',
// Match your spacing scale
spacingUnit: 'var(--spacing-1, 4px)',
borderRadius: 'var(--radius-md, 8px)',
buttonRadius: 'var(--radius-sm, 6px)'
}
};
<W3PaymentWidget appearance={brandTheme} />Complete W3Appearance API Reference
The W3Appearance API provides comprehensive theming control with component-based variable naming for precise styling.
Background Colors
{
// Main layout structure
mainBackground: string; // Outer container + footer background
innerBackground: string; // Inner container (amount/methods section)
cardBackground: string; // Payment method row background
// QR screen specific backgrounds
qrAddressBackground: string; // QR address section background
qrInstructionsBackground: string; // QR instructions section background
qrCardBackground: string; // QR network/token cards background
}Text Colors
{
// Main content text colors
primaryText: string; // Main text (logo, headers)
secondaryText: string; // Secondary text (descriptions, labels)
descriptionText: string; // Widget description text
amountText: string; // Payment amount display
subtitleText: string; // Section subtitles
// Payment method cards
cardText: string; // Payment method primary text
cardSecondaryText: string; // Payment method subtitle text
// Specific element colors
usdText: string; // USD conversion amounts
footerText: string; // Footer text
// QR screen text colors
qrAddressText: string; // QR address text
qrInstructionsText: string; // QR instructions text
qrCardText: string; // QR network/token cards text
}Status & Accent Colors
{
primary: string; // Brand/accent color
success: string; // Success states (green)
danger: string; // Error states (red)
warning: string; // Warning states (orange)
info: string; // Info backgrounds (blue)
borderColor: string; // Borders and dividers
}Typography
{
fontFamily: string; // Primary font stack
fontSizeBase: string; // Default text size (14px)
fontSizeSmall: string; // Small text size (12px)
fontSizeLarge: string; // Large text size (32px)
fontWeightNormal: string; // Default font weight (400)
}Layout & Spacing
{
spacingUnit: string; // Base spacing unit (4px)
borderRadius: string; // Default border radius (8px)
buttonRadius: string; // Button border radius (6px)
}Real-World Usage Examples
E-commerce Integration:
const ecommerceTheme: W3Appearance = {
variables: {
// Match your site's header/footer
mainBackground: '#ffffff',
footerText: '#6b7280',
// Match product card styling
cardBackground: '#ffffff',
cardText: '#1f2937',
borderRadius: '12px',
// Use your brand accent
primary: '#3b82f6',
amountText: '#059669', // Green for price
}
};DeFi Application:
const defiTheme: W3Appearance = {
variables: {
// Dark crypto aesthetic
mainBackground: '#0f172a',
innerBackground: '#1e293b',
cardBackground: '#334155',
// Bright accent for crypto
primary: '#00d4aa',
primaryText: '#f1f5f9',
amountText: '#00d4aa',
// Crypto-friendly fonts
fontFamily: 'JetBrains Mono, monospace',
borderRadius: '4px', // Sharp edges
}
};Banking Application:
const bankingTheme: W3Appearance = {
variables: {
// Conservative, trustworthy colors
mainBackground: '#fefefe',
primary: '#1e40af', // Deep blue
// Clear hierarchy
primaryText: '#1f2937',
secondaryText: '#6b7280',
amountText: '#1f2937',
// Professional typography
fontFamily: 'system-ui, sans-serif',
fontWeightNormal: '500',
borderRadius: '6px',
}
};Advanced CSS Customization
For specific styling needs beyond the W3Appearance API:
/* Target widget container */
[data-w3-payment-widget] {
/* Widget-level customization */
min-height: 500px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
/* Customize payment buttons */
[data-w3-payment-widget] button {
transition: all 0.2s ease;
}
[data-w3-payment-widget] button:hover {
transform: translateY(-1px);
}
/* Amount input styling */
[data-w3-payment-widget] input[type="number"] {
letter-spacing: 0.05em;
}Note: The W3Appearance API handles all standard theming needs. CSS overrides should only be used for specific animations or layout adjustments not covered by the design system.
How It Works
- Payment Initiation: User selects amount and payment method
- Secure Session: Widget calls your backend to create payment session
- Smart Routing: W3Payments optimizes vendor selection, conversions, and yield
- User Flow: User completes payment in vendor's secure interface
- Auto Processing: Auto conversions, bridging, and yield optimization happen automatically
- Completion: Widget receives result and calls your success/error handlers
The widget abstracts all complexity - multi-vendor routing, currency conversions, cross-chain bridging, and yield optimization happen seamlessly behind the scenes.
Roadmap
Current: Onramping, basic payments, MeshPay integration
Coming Soon: Offramping, auto-yield optimization, additional vendor integrations
Future: Advanced DeFi integrations, institutional-grade APIs, white-label solutions
Framework Support
This is the React implementation. Other frameworks coming soon:
@w3payments/vue- Vue 3 components@w3payments/angular- Angular components@w3payments/nextjs- Next.js integration
Full SDK and REST API also in development for non-JavaScript environments.
Development
Test the widget with Storybook:
cd packages/react
npm run storybookMake sure your backend server is running for end-to-end payment testing.
