Introduction
Cryptocurrency payments offer lower fees, faster settlement, and global reach. From Bitcoin to stablecoins, integrating crypto payments can expand your customer base and reduce processing costs.
Key Statistics:
- Crypto payment market: $30B annually
- Transaction fees: 1-3% vs 2.5% for cards
- Settlement: Minutes vs days
- 30% of unbanked prefer crypto
Payment Types
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Cryptocurrency Payment Options โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ On-Chain (Native) โ
โ โโโ Bitcoin: Store of value, slow confirmation โ
โ โโโ Ethereum: Smart contracts, fast (with L2) โ
โ โโโ Solana: Fast, low cost โ
โ โ
โ Stablecoins (Price-Pegged) โ
โ โโโ USDC: Dollar-backed, regulated โ
โ โโโ USDT: Dollar-backed, widely used โ
โ โโโ DAI: Decentralized, crypto-collateralized โ
โ โ
โ Off-Chain (Payment Rail) โ
โ โโโ Lightning Network: Bitcoin fast payments โ
โ โโโ Arbitrum/Optimism: Ethereum L2 โ
โ โโโ Payment Channels: Instant, low cost โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Bitcoin Payment
#!/usr/bin/env python3
"""Bitcoin payment integration."""
from bitcoinrpc.authproxy import AuthServiceProxy
import qrcode
class BitcoinPayment:
"""Bitcoin payment processor."""
def __init__(self, rpc_url, rpc_user, rpc_password):
self.rpc = AuthServiceProxy(f"http://{rpc_user}:{rpc_password}@{rpc_url}")
def create_invoice(self, amount_sats, description, expiry_minutes=60):
"""Create payment invoice."""
# Create address for payment
address = self.rpc.getnewaddress()
# Store invoice
invoice = {
'address': address,
'amount_sats': amount_sats,
'description': description,
'created_at': datetime.utcnow(),
'expires_at': datetime.utcnow() + timedelta(minutes=expiry_minutes),
'status': 'pending'
}
return invoice
def check_payment(self, address):
"""Check if payment received."""
# Get transactions to address
txs = self.rpc.listtransactions(address, 10, 0, True)
if not txs:
return {'paid': False}
# Get current confirmations
latest_tx = txs[0]
confirmations = latest_tx.get('confirmations', 0)
return {
'paid': confirmations > 0,
'confirmations': confirmations,
'amount_sats': int(latest_tx['amount'] * 1e8),
'txid': latest_tx['txid']
}
def generate_qr(self, address, amount_sats):
"""Generate payment QR code."""
# BIP 21 URI
uri = f"bitcoin:{address}?amount={amount_sats/1e8}"
qr = qrcode.QRCode(version=1, box_size=10, border=5)
qr.add_data(uri)
qr.make(fit=True)
return qr.make_image(fill_color="black", back_color="white")
Ethereum/ERC-20 Payment
#!/usr/bin/env python3
"""Ethereum and ERC-20 payment."""
from web3 import Web3
from eth_abi import encode
class EthereumPayment:
"""Ethereum payment processor."""
def __init__(self, rpc_url, private_key):
self.w3 = Web3(Web3.HTTPProvider(rpc_url))
self.account = self.w3.eth.account.from_key(private_key)
def create_payment_request(self, token_address, amount, description):
"""Create payment request."""
# Generate payment address
payment_address = self.w3.eth.account.create().address
payment = {
'payment_address': payment_address,
'token_address': token_address,
'amount': amount,
'description': description,
'created_at': datetime.utcnow(),
'status': 'pending'
}
return payment
def accept_payment(self, from_address, amount, token_address=None):
"""Accept ETH or ERC-20 payment."""
if token_address is None:
# ETH payment
tx = {
'from': from_address,
'to': self.account.address,
'value': self.w3.to_wei(amount, 'ether'),
'gas': 21000,
'gasPrice': self.w3.eth.gas_price,
'nonce': self.w3.eth.get_transaction_count(from_address),
'chainId': 1
}
else:
# ERC-20 payment
# Encode transfer function
data = encode(
['address', 'uint256'],
[self.account.address, self.w3.to_wei(amount, 'ether')]
)
tx = {
'from': from_address,
'to': token_address,
'data': data,
'gas': 100000,
'gasPrice': self.w3.eth.gas_price,
'nonce': self.w3.eth.get_transaction_count(from_address),
'chainId': 1
}
# Sign and send
signed = self.w3.eth.account.sign_transaction(tx, private_key)
tx_hash = self.w3.eth.send_raw_transaction(signed.rawTransaction)
return tx_hash.hex()
Stablecoin Integration
#!/usr/bin/env python3
"""Stablecoin payment processing."""
class StablecoinPayment:
"""Process USDC, USDT, DAI payments."""
# Contract addresses (mainnet)
USDC = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
USDT = "0xdAC17F958D2ee523a2206206994597C13D831ec7"
DAI = "0x6B175474E89094C44Da98b954EesadcdEF9ce9CC"
def __init__(self, web3, private_key):
self.w3 = web3
self.account = self.w3.eth.account.from_key(private_key)
def get_payment_address(self):
"""Get unique payment address for customer."""
# Generate customer-specific address
customer_address = self.w3.eth.account.create().address
return customer_address
def verify_payment(self, token_address, amount, expected_amount):
"""Verify stablecoin payment."""
# Check balance
if token_address == self.USDC:
balance = self.get_usdc_balance(self.account.address)
elif token_address == self.USDT:
balance = self.get_usdt_balance(self.account.address)
return balance >= self.w3.to_wei(expected_amount, 6)
def get_token_balance(self, token_address, address):
"""Get ERC-20 token balance."""
# ERC-20 balanceOf function
abi = '[{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"type":"function"}]'
contract = self.w3.eth.contract(token_address, abi=abi)
balance = contract.functions.balanceOf(address).call()
return balance
def withdraw_to_fiat(self, token_address, amount, bank_account):
"""Convert crypto to fiat."""
# In production: integrate with off-ramp service (e.g., MoonPay, Wyre)
# This is a placeholder
pass
Payment Gateway Integration
#!/usr/bin/env python3
"""Unified crypto payment gateway."""
class CryptoPaymentGateway:
"""Unified payment gateway for multiple cryptocurrencies."""
def __init__(self, config):
self.btc = BitcoinPayment(config['btc'])
self.eth = EthereumPayment(config['eth'], config['eth_private_key'])
self.stablecoin = StablecoinPayment(config['eth'], config['eth_private_key'])
def create_invoice(self, amount, currency='USD', crypto='BTC'):
"""Create payment invoice."""
# Convert USD to crypto
rate = self.get_exchange_rate(currency, crypto, amount)
crypto_amount = amount / rate
if crypto == 'BTC':
return self.btc.create_payment_request(
int(crypto_amount * 1e8), # Satoshis
f"Invoice #{amount}"
)
elif crypto in ['USDC', 'USDT', 'ETH']:
return self.eth.create_payment_request(
crypto,
crypto_amount,
f"Invoice #{amount}"
)
def get_exchange_rate(self, fiat, crypto, amount):
"""Get exchange rate from price API."""
# Use CoinGecko or similar API
# Placeholder
import requests
response = requests.get(
f"https://api.coingecko.com/api/v3/simple/price",
params={
'ids': crypto.lower(),
'vs_currencies': fiat.lower()
}
)
rate = response.json()[crypto.lower()][fiat.lower()]
return rate
def confirm_payment(self, invoice):
"""Confirm payment and fulfill order."""
if 'bitcoin' in invoice:
result = self.btc.check_payment(invoice['address'])
if result['paid'] and result['confirmations'] >= 1:
return {'status': 'confirmed', 'txid': result['txid']}
return {'status': 'pending'}
Compliance
# Crypto payment compliance
compliance:
kyc:
required_for:
- "Onboarding merchants"
- "High value transactions (> $10,000)"
verification:
- "Identity documents"
- "Address verification"
- "Sanctions screening"
aml:
transaction_monitoring:
- "Wallet screening"
- "Pattern detection"
- "Suspicious activity alerts"
reporting:
- "CTR for > $10,000"
- "SAR for suspicious activity"
tax:
record_keeping:
- "Transaction history"
- "Cost basis calculation"
- "Capital gains/losses"
Comments