Deploying Bitcart
Bitcart is a lightweight, open-source cryptocurrency payment processor designed for merchants and developers who want to accept digital payments without intermediaries. Built with Python and modern web technologies, Bitcart provides a complete solution for processing Bitcoin, Litecoin, and other cryptocurrency payments with full control over transactions and customer data. Whether you’re an online merchant, service provider, or developer building payment solutions, Bitcart enables secure, private, and decentralized payment processing.
Why Bitcart?
Bitcart stands out in the cryptocurrency payment processing landscape with its focus on control, privacy, and developer flexibility:
- Self-Hosted: Run your own payment processor—no intermediaries, no service fees, complete control
- Lightweight: Minimal resource requirements and fast deployment
- Multi-Currency Support: Accept Bitcoin, Litecoin, and other cryptocurrencies
- No Middleman: Direct transactions between you and customers
- Zero Transaction Fees: No payment processor fees or hidden charges
- Instant Notifications: Real-time payment confirmations and status updates
- Flexible Pricing: Display prices in fiat currency with automatic conversion
- Secure Wallets: Manage cryptocurrency wallets directly on your server
- REST API: Full-featured API for integrating with e-commerce platforms and custom applications
- Plugins: Built-in plugins for popular platforms (WooCommerce, Shopify integration ready)
- Payment Pages: Create and customize payment pages without coding
- Invoice Management: Generate and track invoices with payment status
- QR Code Generation: Automatic QR code creation for mobile payments
- Privacy First: No analytics tracking, customer data remains on your server
- Open Source: MIT licensed with active community support
- Merchant Dashboard: Intuitive interface for managing payments and stores
- Admin Panel: Full administrative control over accounts and settings
Bitcart is ideal for online stores, service providers, nonprofits, freelancers, developers, and organizations that want to accept cryptocurrency payments with complete autonomy. With persistent storage on Klutch.sh, your payment data and wallet configurations are always safe and accessible.
Prerequisites
Before deploying Bitcart, ensure you have:
- A Klutch.sh account
- A GitHub repository with your Bitcart deployment configuration
- Basic familiarity with Docker, Git, and cryptocurrency concepts
- A domain name (recommended for production payment processing)
- Understanding of cryptocurrency wallets and blockchain basics
- Optional: existing cryptocurrency wallets for integration
Important Considerations
Deploying Bitcart
Create a New Project
Log in to your Klutch.sh dashboard and create a new project for your Bitcart deployment.
Prepare Your Repository
Create a GitHub repository with the following structure for your Bitcart deployment:
bitcart-deploy/├─ Dockerfile├─ .env.example├─ docker-compose.local.yml├─ .gitignore└─ README.mdHere’s a Dockerfile for Bitcart:
FROM python:3.11-slim# Install required system dependenciesRUN apt-get update && apt-get install -y \curl \git \build-essential \libssl-dev \libffi-dev \&& rm -rf /var/lib/apt/lists/*# Set working directoryWORKDIR /app# Clone Bitcart repositoryRUN git clone https://github.com/bitcartcc/bitcart.git . && \git checkout main# Install Python dependenciesRUN pip install --no-cache-dir -r requirements.txt# Create necessary directoriesRUN mkdir -p /app/data \/app/logs \/app/uploads && \chmod -R 755 /app# Copy entrypoint scriptCOPY docker-entrypoint.sh /RUN chmod +x /docker-entrypoint.sh# Expose portEXPOSE 8000# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \CMD curl -f http://localhost:8000/api/health || exit 1# Run entrypointENTRYPOINT ["/docker-entrypoint.sh"]CMD ["start"]Create a
docker-entrypoint.shfile:#!/bin/bashset -e# Initialize application database if neededif [ ! -f /app/data/initialized ]; thenecho "Initializing Bitcart..."python -m bitcart.server --migratetouch /app/data/initializedfi# Set permissionschmod -R 755 /appif [ "$1" = "start" ]; then# Start the applicationpython -m uvicorn bitcart.server:app --host 0.0.0.0 --port 8000elseexec "$@"fiCreate a
.env.examplefile:Terminal window # Application ConfigurationAPP_URL=https://yourdomain.comAPP_PORT=8000APP_ENV=productionDEBUG=falseSECRET_KEY=your-secret-key-here# Database ConfigurationDATABASE_URL=sqlite:////app/data/bitcart.dbDB_DRIVER=sqlite# Admin ConfigurationADMIN_USERNAME=adminADMIN_PASSWORD=secure_password_hereADMIN_EMAIL=admin@yourdomain.com# Bitcoin ConfigurationBTC_NETWORK=mainnetBTC_LIGHTNING=trueBTC_WALLET_HOST=127.0.0.1BTC_WALLET_PORT=18332# Store ConfigurationSTORE_NAME="My Store"STORE_TIMEZONE=UTCSTORE_CURRENCY=USD# Email Configuration (for notifications)MAIL_DRIVER=smtpMAIL_HOST=smtp.gmail.comMAIL_PORT=587MAIL_USERNAME=your-email@gmail.comMAIL_PASSWORD=your-app-passwordMAIL_FROM=noreply@yourdomain.com# SecurityREQUIRE_HTTPS=trueALLOWED_HOSTS=yourdomain.com,www.yourdomain.com# FeaturesENABLE_REGISTRATION=falseENABLE_PLUGIN_STORE=trueENABLE_FIAT_CONVERSION=trueCommit and push to your GitHub repository:
Terminal window git initgit add .git commit -m "Initial Bitcart deployment"git remote add origin https://github.com/yourusername/bitcart-deploy.gitgit push -u origin mainCreate a New App
In the Klutch.sh dashboard:
- Click “Create New App”
- Select your GitHub repository containing the Dockerfile
- Choose the branch (typically
mainormaster) - Klutch.sh will automatically detect the Dockerfile in the root directory
Configure Environment Variables
Set up these essential environment variables in your Klutch.sh dashboard:
Variable Description Example APP_URLYour application domain https://payments.example.comAPP_PORTApplication port 8000APP_ENVEnvironment (production or development) productionDEBUGDebug mode (false for production) falseSECRET_KEYDjango secret key (generate secure random string) secure-random-stringDATABASE_URLDatabase connection string sqlite:////app/data/bitcart.dbADMIN_USERNAMEAdmin account username adminADMIN_PASSWORDAdmin account password (use strong password) secure_password_hereADMIN_EMAILAdmin email address admin@yourdomain.comBTC_NETWORKBitcoin network (mainnet or testnet) mainnetBTC_LIGHTNINGEnable Lightning Network support trueSTORE_NAMEYour store name My StoreSTORE_TIMEZONETimezone for store UTCSTORE_CURRENCYDefault currency USDMAIL_DRIVERMail service driver smtpMAIL_HOSTSMTP server hostname smtp.gmail.comMAIL_PORTSMTP port 587MAIL_USERNAMESMTP username your-email@gmail.comMAIL_PASSWORDSMTP password or app password app_passwordREQUIRE_HTTPSEnforce HTTPS trueENABLE_REGISTRATIONAllow user registration falseConfigure Persistent Storage
Bitcart requires persistent storage for database, wallet data, and transaction records. Add persistent volumes:
Mount Path Description Recommended Size /app/dataDatabase and wallet configuration 50GB /app/logsApplication logs 20GB /app/uploadsReceipt and invoice uploads 10GB In the Klutch.sh dashboard:
- Navigate to your app settings
- Go to the “Volumes” section
- Click “Add Volume” for each mount path
- Set mount paths and sizes as specified above
Set Network Configuration
Configure your app’s network settings:
- Select traffic type: HTTP (Bitcart uses standard web ports)
- Recommended internal port: 8000 (as specified in Dockerfile)
- Klutch.sh will automatically handle HTTPS termination via reverse proxy
- Ensure ports 80 and 443 are accessible from your domain
Configure Custom Domain
Bitcart requires a custom domain for payment processing:
- Navigate to your app’s “Domains” section in Klutch.sh
- Click “Add Custom Domain”
- Enter your domain (e.g.,
payments.yourdomain.com) - Configure DNS with a CNAME record to point to your Klutch.sh app
- Update
APP_URLenvironment variable to match your domain - Klutch.sh will automatically provision SSL certificates
Deploy Your App
- Review all settings and environment variables
- Click “Deploy”
- Klutch.sh will build the Docker image and start your Bitcart instance
- Wait for the deployment to complete (typically 5-10 minutes)
- Access your Bitcart instance at your configured domain
- Log in with your admin credentials to complete setup
Initial Setup and Configuration
After deployment completes, access your Bitcart instance to complete setup.
Accessing Bitcart Admin Panel
Navigate to your domain: https://yourdomain.com/admin/
Log in with the admin credentials you configured in environment variables.
Creating Your First Store
- Click “Create Store” in the admin dashboard
- Configure store details:
- Store name
- Description
- Logo (optional)
- Default currency
- Timezone
- Set up payment methods:
- Select cryptocurrencies to accept
- Configure wallet addresses
- Set payment confirmation requirements
- Configure email notifications
- Save and activate store
Configuring Wallets
- Navigate to “Wallets” in admin panel
- Click “Connect Wallet”
- Choose cryptocurrency:
- Bitcoin
- Litecoin
- Other supported coins
- Configure wallet:
- Paste public key/address
- Set network (mainnet/testnet)
- Configure derivation path if using HD wallet
- Test connection
- Enable wallet for payments
Creating Your First Invoice
- Go to “Invoices” section
- Click “Create Invoice”
- Set invoice details:
- Amount in fiat currency
- Customer email
- Invoice description
- Order ID (optional)
- Select accepted cryptocurrencies
- Set payment confirmation requirements
- Generate invoice
- Share invoice link with customer
Environment Variable Examples
Basic Configuration
APP_URL=https://payments.yourdomain.comAPP_PORT=8000APP_ENV=productionSECRET_KEY=your-secure-secret-keyDATABASE_URL=sqlite:////app/data/bitcart.dbADMIN_USERNAME=adminADMIN_PASSWORD=secure_passwordBTC_NETWORK=mainnetSTORE_NAME="My Store"STORE_CURRENCY=USDComplete Production Configuration
# Application SettingsAPP_URL=https://payments.yourdomain.comAPP_PORT=8000APP_ENV=productionDEBUG=falseSECRET_KEY=your-secure-secret-key-hereLOG_LEVEL=info
# Database ConfigurationDATABASE_URL=sqlite:////app/data/bitcart.dbDB_DRIVER=sqliteDB_POOL_SIZE=10
# Admin ConfigurationADMIN_USERNAME=adminADMIN_PASSWORD=secure_password_hereADMIN_EMAIL=admin@yourdomain.com
# Bitcoin ConfigurationBTC_NETWORK=mainnetBTC_LIGHTNING=trueBTC_WALLET_HOST=127.0.0.1BTC_WALLET_PORT=18332BTC_CONFIRMATIONS_REQUIRED=1
# Litecoin Configuration (if enabled)LTC_NETWORK=mainnetLTC_LIGHTNING=falseLTC_CONFIRMATIONS_REQUIRED=2
# Store ConfigurationSTORE_NAME="My Store"STORE_DESCRIPTION="Premium Products"STORE_TIMEZONE=UTCSTORE_CURRENCY=USDSTORE_THEME=modern
# Email NotificationsMAIL_DRIVER=smtpMAIL_HOST=smtp.gmail.comMAIL_PORT=587MAIL_USERNAME=your-email@gmail.comMAIL_PASSWORD=your-app-passwordMAIL_FROM=noreply@yourdomain.comMAIL_FROM_NAME="My Store"MAIL_ENCRYPTION=tls
# SecurityREQUIRE_HTTPS=trueALLOWED_HOSTS=payments.yourdomain.comCORS_ORIGINS=https://yourdomain.comSESSION_SECURE=trueSESSION_HTTP_ONLY=true
# FeaturesENABLE_REGISTRATION=falseENABLE_PLUGIN_STORE=trueENABLE_FIAT_CONVERSION=trueENABLE_EXPORT=true
# API ConfigurationAPI_RATE_LIMIT=1000API_RATE_LIMIT_PERIOD=3600
# MaintenanceAUTO_BACKUP_ENABLED=trueAUTO_BACKUP_INTERVAL=86400KEEP_BACKUP_DAYS=30Sample Code and Getting Started
Python - Creating Invoices via API
import requestsimport jsonfrom datetime import datetime, timedelta
class BitcartClient: def __init__(self, base_url, api_key=None): self.base_url = base_url self.api_url = f'{base_url}/api' self.api_key = api_key self.headers = { 'Content-Type': 'application/json' } if api_key: self.headers['Authorization'] = f'Bearer {api_key}'
def create_invoice(self, store_id, amount, currency='USD', customer_email=None, order_id=None, description=None, metadata=None): """Create a new invoice""" try: payload = { 'store_id': store_id, 'amount': amount, 'currency': currency, 'customer_email': customer_email or '', 'order_id': order_id or '', 'description': description or '', 'metadata': metadata or {} }
response = requests.post( f'{self.api_url}/invoices', headers=self.headers, json=payload ) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"Error creating invoice: {e}") return None
def get_invoice(self, invoice_id): """Retrieve invoice details""" try: response = requests.get( f'{self.api_url}/invoices/{invoice_id}', headers=self.headers ) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"Error retrieving invoice: {e}") return None
def list_invoices(self, store_id, limit=50, offset=0): """List all invoices for a store""" try: response = requests.get( f'{self.api_url}/invoices', headers=self.headers, params={ 'store_id': store_id, 'limit': limit, 'offset': offset } ) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"Error retrieving invoices: {e}") return None
def get_stores(self): """Get all available stores""" try: response = requests.get( f'{self.api_url}/stores', headers=self.headers ) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"Error retrieving stores: {e}") return None
def get_payment_methods(self, store_id): """Get enabled payment methods for store""" try: response = requests.get( f'{self.api_url}/stores/{store_id}/payment-methods', headers=self.headers ) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"Error retrieving payment methods: {e}") return None
def webhook_verify(self, payload, signature, secret): """Verify webhook signature""" import hmac import hashlib
expected_signature = hmac.new( secret.encode(), payload.encode(), hashlib.sha256 ).hexdigest()
return hmac.compare_digest(signature, expected_signature)
# Usage exampleif __name__ == "__main__": client = BitcartClient('https://payments.yourdomain.com', api_key='your-api-key')
# Get stores stores = client.get_stores() if stores and len(stores) > 0: store_id = stores[0]['id'] print(f"Using store: {store_id}")
# Get payment methods methods = client.get_payment_methods(store_id) print(f"Available payment methods: {methods}")
# Create invoice invoice = client.create_invoice( store_id=store_id, amount=99.99, currency='USD', customer_email='customer@example.com', order_id='ORDER-001', description='Premium subscription', metadata={'plan': 'pro', 'billing_cycle': 'monthly'} )
if invoice: print(f"Invoice created: {invoice}") invoice_id = invoice['id']
# Retrieve invoice invoice_details = client.get_invoice(invoice_id) print(f"Invoice details: {invoice_details}")
# List invoices invoices = client.list_invoices(store_id, limit=10) print(f"Store invoices: {invoices}")JavaScript - Payment Page Integration
const API_URL = 'https://payments.yourdomain.com/api';
class BitcartPaymentManager { constructor(storeId) { this.storeId = storeId; }
// Create invoice and show payment page async initiatePayment(amount, currency = 'USD', orderId = '') { try { const response = await fetch(`${API_URL}/invoices`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ store_id: this.storeId, amount: amount, currency: currency, order_id: orderId }) });
if (!response.ok) { throw new Error('Failed to create invoice'); }
const invoice = await response.json();
// Redirect to payment page window.location.href = `${API_URL}/invoices/${invoice.id}/pay`;
return invoice; } catch (error) { console.error('Payment initiation error:', error); throw error; } }
// Poll invoice status async pollInvoiceStatus(invoiceId, timeout = 3600000) { const startTime = Date.now(); const pollInterval = 5000; // 5 seconds
return new Promise((resolve, reject) => { const pollFunction = async () => { try { const response = await fetch(`${API_URL}/invoices/${invoiceId}`); const invoice = await response.json();
console.log(`Invoice status: ${invoice.status}`);
if (invoice.status === 'paid' || invoice.status === 'confirmed') { resolve(invoice); } else if (invoice.status === 'expired') { reject(new Error('Invoice expired')); } else if (Date.now() - startTime > timeout) { reject(new Error('Payment timeout')); } else { setTimeout(pollFunction, pollInterval); } } catch (error) { reject(error); } };
pollFunction(); }); }
// Handle webhook notifications setupWebhookListener(elementId, invoiceId) { // Use Server-Sent Events for real-time updates const eventSource = new EventSource( `${API_URL}/invoices/${invoiceId}/events` );
eventSource.onmessage = (event) => { const data = JSON.parse(event.data); const element = document.getElementById(elementId);
if (element) { switch (data.status) { case 'paid': element.innerHTML = '<div class="success">Payment received!</div>'; eventSource.close(); break; case 'expired': element.innerHTML = '<div class="error">Invoice expired</div>'; eventSource.close(); break; case 'pending': element.innerHTML = '<div class="pending">Waiting for payment...</div>'; break; case 'confirmed': element.innerHTML = '<div class="success">Payment confirmed!</div>'; eventSource.close(); break; } } };
eventSource.onerror = () => { eventSource.close(); }; }
// Create embedded payment widget createPaymentWidget(containerId, invoiceId) { const container = document.getElementById(containerId);
if (!container) { console.error('Container not found'); return; }
// Create iframe const iframe = document.createElement('iframe'); iframe.src = `${API_URL}/invoices/${invoiceId}/embedded`; iframe.width = '100%'; iframe.height = '400'; iframe.frameBorder = '0'; iframe.allow = 'payment';
container.appendChild(iframe); }}
// Usage exampleconst paymentManager = new BitcartPaymentManager('store-123');
// Button click handler for paymentdocument.getElementById('pay-button')?.addEventListener('click', async () => { try { const invoice = await paymentManager.initiatePayment(99.99, 'USD', 'ORDER-001'); console.log('Invoice created:', invoice); } catch (error) { console.error('Payment failed:', error); }});
// Monitor payment statusasync function checkPaymentStatus(invoiceId) { try { const invoice = await paymentManager.pollInvoiceStatus(invoiceId); console.log('Payment completed:', invoice); // Handle successful payment } catch (error) { console.error('Payment error:', error); // Handle payment error }}
// Display payment widgetdocument.addEventListener('DOMContentLoaded', () => { const invoiceId = new URLSearchParams(window.location.search).get('invoice_id'); if (invoiceId) { paymentManager.createPaymentWidget('payment-widget', invoiceId); }});cURL - Invoice Management
# Create an invoicecurl -X POST https://payments.yourdomain.com/api/invoices \ -H "Content-Type: application/json" \ -d '{ "store_id": "store-123", "amount": 99.99, "currency": "USD", "customer_email": "customer@example.com", "order_id": "ORDER-001", "description": "Product purchase" }'
# Get invoice statuscurl -X GET https://payments.yourdomain.com/api/invoices/{invoice_id}
# Get invoice payment addresscurl -X GET https://payments.yourdomain.com/api/invoices/{invoice_id}/payment-address
# List all invoicescurl -X GET "https://payments.yourdomain.com/api/invoices?store_id=store-123&limit=50"
# Get exchange ratescurl -X GET https://payments.yourdomain.com/api/rates
# Get store configurationcurl -X GET https://payments.yourdomain.com/api/stores/store-123Docker Compose for Local Development
For local testing before deploying to Klutch.sh:
version: '3.8'
services: bitcart: build: . container_name: bitcart-app environment: APP_URL: http://localhost:8000 APP_PORT: 8000 APP_ENV: development DEBUG: "true" SECRET_KEY: dev-secret-key DATABASE_URL: sqlite:////app/data/bitcart.db ADMIN_USERNAME: admin ADMIN_PASSWORD: admin123 ADMIN_EMAIL: admin@localhost BTC_NETWORK: testnet STORE_NAME: "Test Store" STORE_CURRENCY: USD MAIL_DRIVER: log ports: - "8000:8000" volumes: - ./:/app - ./data:/app/data - ./logs:/app/logs restart: unless-stoppedTo run locally:
docker-compose -f docker-compose.local.yml up -dAccess Bitcart at http://localhost:8000
Payment Processing Features
Invoice Management
Complete invoice lifecycle:
- Create invoices with custom amounts
- Set invoice expiration times
- Track payment status in real-time
- Generate payment QR codes
- Send invoice reminders
- Download invoice receipts
Payment Notifications
Real-time payment alerts:
- Email notifications on payment received
- Webhook notifications for system integration
- Payment status updates via API
- Transaction confirmation tracking
Multi-Cryptocurrency Support
Accept multiple digital currencies:
- Bitcoin (mainnet and testnet)
- Litecoin (mainnet and testnet)
- Extensible for additional cryptocurrencies
- Automatic exchange rate conversion
- Multi-wallet management
Wallet Management
Secure wallet operations:
- Connect multiple wallets
- Support for public key derivation
- Hardware wallet integration
- Multi-signature wallet support
- Watch-only wallet mode
Store Configuration
Store Settings
Configure your payment store:
- Navigate to “Store Settings” in admin
- Configure:
- Store name and description
- Logo and branding
- Default currency and timezone
- Email notification preferences
- Set payment policies:
- Confirmation requirements
- Invoice expiration time
- Payment redirect URLs
- Configure store theme and appearance
Payment Methods
Enable and configure accepted payment methods:
- Go to “Payment Methods”
- Select cryptocurrencies to accept
- Configure each payment method:
- Wallet address or public key
- Network (mainnet/testnet)
- Confirmation requirements
- Price conversion settings
- Test payment method connectivity
Security Best Practices
Authentication and Access Control
- Use strong admin passwords
- Disable user registration unless needed:
ENABLE_REGISTRATION=false - Implement two-factor authentication if available
- Create separate user accounts for team members
- Limit API key usage to specific stores
- Rotate API keys periodically
Cryptocurrency Security
- Never expose private keys
- Use watch-only wallets when possible
- Implement multi-signature wallets for large amounts
- Monitor wallet activity regularly
- Use hardware wallets for cold storage
- Test with testnet before mainnet deployment
Data Security
- Always use HTTPS (automatic via Klutch.sh)
- Implement proper database backups
- Secure webhook endpoints with signatures
- Monitor transaction logs for anomalies
- Implement rate limiting on APIs
- Store sensitive data encrypted
Transaction Monitoring
# Monitor transactions for suspicious activityimport requests
def check_transaction_anomalies(store_id, api_key): """Check for unusual transaction patterns""" client = BitcartClient(f'https://payments.yourdomain.com', api_key)
invoices = client.list_invoices(store_id)
# Check for rapid successive payments # Check for unusually large amounts # Check for duplicate customer payments # Alert on suspicious patterns
return invoicesBackup and Recovery
Automated Backups
Regular backup of critical data:
#!/bin/bashBACKUP_DIR="/backups"TIMESTAMP=$(date +%Y%m%d_%H%M%S)
# Backup databasecp /app/data/bitcart.db $BACKUP_DIR/bitcart_db_$TIMESTAMP.db
# Backup configurationtar -czf $BACKUP_DIR/bitcart_config_$TIMESTAMP.tar.gz /app/data
# Keep only last 30 daysfind $BACKUP_DIR -name "bitcart_*" -mtime +30 -delete
echo "Backup completed: $TIMESTAMP"Recovery Procedures
Restore from backup:
- Stop the Bitcart container
- Restore database:
cp backup.db /app/data/bitcart.db - Restore configuration:
tar -xzf backup.tar.gz - Restart the container
Performance Optimization
Database Optimization
-- Optimize database for common queriesCREATE INDEX idx_store_id ON invoices(store_id);CREATE INDEX idx_created_at ON invoices(created_at);CREATE INDEX idx_status ON invoices(status);CREATE INDEX idx_customer_email ON invoices(customer_email);Caching Configuration
Enable caching for better performance:
CACHE_ENABLED=trueCACHE_TTL=3600CACHE_BACKEND=memoryAPI Rate Limiting
Prevent abuse:
API_RATE_LIMIT=1000API_RATE_LIMIT_PERIOD=3600ENABLE_RATE_LIMITING=trueWebhook Integration
Setting Up Webhooks
- Navigate to “Webhooks” in admin panel
- Click “Add Webhook”
- Configure:
- Webhook URL (your application endpoint)
- Events to subscribe to
- Secret key for signature verification
- Test webhook delivery
Handling Webhook Events
Process webhook notifications:
from flask import Flask, requestimport hmacimport hashlib
app = Flask(__name__)WEBHOOK_SECRET = 'your-webhook-secret'
@app.route('/webhook/bitcart', methods=['POST'])def handle_bitcart_webhook(): # Verify signature signature = request.headers.get('X-Signature') payload = request.get_data(as_text=True)
expected_signature = hmac.new( WEBHOOK_SECRET.encode(), payload.encode(), hashlib.sha256 ).hexdigest()
if not hmac.compare_digest(signature, expected_signature): return {'error': 'Invalid signature'}, 401
# Process webhook data = request.json event_type = data['event']
if event_type == 'invoice.paid': handle_payment_received(data) elif event_type == 'invoice.confirmed': handle_payment_confirmed(data) elif event_type == 'invoice.expired': handle_invoice_expired(data)
return {'success': True}, 200
def handle_payment_received(data): invoice_id = data['invoice_id'] amount = data['amount'] currency = data['currency'] # Process payment in your system print(f"Payment received: {amount} {currency}")
def handle_payment_confirmed(data): invoice_id = data['invoice_id'] # Confirm order fulfillment print(f"Payment confirmed: {invoice_id}")
def handle_invoice_expired(data): invoice_id = data['invoice_id'] # Handle expired invoice print(f"Invoice expired: {invoice_id}")
if __name__ == '__main__': app.run(port=5000)Plugin Integration
WooCommerce Integration
Set up Bitcart payment gateway for WooCommerce:
- Install Bitcart WooCommerce plugin
- Configure plugin settings:
- Bitcart server URL
- Store ID
- API key
- Enable Bitcart as payment method
- Test payment checkout
Custom Integration
Integrate with custom applications:
- Use Bitcart REST API
- Create invoices programmatically
- Handle webhook notifications
- Update order status on payment
- Generate receipts and confirmations
Exchange Rate Management
Setting Prices
Configure price display:
- Set store default currency
- Prices automatically convert to cryptocurrency
- Configure exchange rate source
- Set price precision
- Handle rounding preferences
Exchange Rate Sources
# Configure exchange rate providerEXCHANGE_RATE_PROVIDER=coingeckoEXCHANGE_RATE_UPDATE_INTERVAL=300EXCHANGE_RATE_CACHE_TTL=600Troubleshooting
Common Issues and Solutions
Issue: Payments not being received
Solutions:
- Verify wallet is connected and accessible
- Check blockchain network connectivity
- Ensure correct network is selected (mainnet vs testnet)
- Verify wallet address is correct
- Check payment notification settings
Issue: Webhook notifications not sending
Troubleshooting:
- Verify webhook URL is accessible
- Check webhook signature verification
- Review webhook logs
- Test webhook manually with curl
- Verify event subscriptions
Issue: Slow invoice creation
Solutions:
- Check database performance
- Enable caching:
CACHE_ENABLED=true - Optimize database queries
- Check system resources
- Review application logs
Issue: Exchange rate conversion errors
Solutions:
- Verify exchange rate provider is accessible
- Check exchange rate source configuration
- Ensure correct currency codes
- Review conversion precision settings
Upgrading Bitcart
To update Bitcart to a newer version:
-
Update your Dockerfile:
RUN git clone https://github.com/bitcartcc/bitcart.git . && \git checkout latest-version -
Commit and push to GitHub
-
Klutch.sh will automatically rebuild
-
Always backup data before upgrading
-
Test in development first
-
Monitor logs after upgrade for issues
Additional Resources
- Bitcart Official Website - Project information and news
- Bitcart Documentation - Complete guides and reference
- Bitcart GitHub Repository - Source code
- Bitcart API Documentation - API reference
- Bitcart Blog - Tutorials and updates
- Klutch.sh Getting Started Guide
- Klutch.sh Volumes Documentation
- Klutch.sh Custom Domains Guide
Conclusion
Deploying Bitcart on Klutch.sh provides you with a complete, self-hosted cryptocurrency payment processor that maintains full control over your transactions and customer data. With support for multiple cryptocurrencies, instant payment notifications, comprehensive webhook integration, and powerful APIs, Bitcart enables merchants and developers to accept digital payments independently. Klutch.sh’s managed infrastructure ensures your payment processor is always available, secure, and performant, allowing you to focus on growing your business.
Start accepting cryptocurrency payments today by deploying Bitcart on Klutch.sh and experience the freedom of truly independent payment processing.