DEV Community

Anna lilith
Anna lilith

Posted on

How to Accept Bitcoin Payments in Your Python Application

How to Accept Bitcoin Payments in Your Python Application

Bitcoin is no longer just a speculative asset—today it’s being adopted as a legitimate payment method by e‑commerce sites, SaaS providers, and even brick‑and‑mortar stores. If you’re a Python developer looking to add support for accept bitcoin payments python, you’re in the right place. This guide walks you through the entire workflow—from choosing the right API to handling real‑time payment notifications—and ends with a link to production‑ready libraries you can drop into your codebase.


1. Why Bitcoin?

Before diving into code, let’s recap why developers care about Bitcoin integration:

Feature Impact Example
Borderless Sends instantly anywhere An EU client pays an American vendor
Low Clearing Time Minutes (vs. days for wire transfers) Immediate order fulfillment
No Intermediaries No bank fees Save 2‑3 % on every transaction
Decentralized No single point of failure Self‑hosted or API‑based solutions

If you’re already shipping a digital good or a subscription service, adding Bitcoin can unlock a new customer segment and reduce currency conversion costs.


2. Core Concepts You Need to Know

Term What It Means Why It Matters
Private Key Holds the cryptographic authority over a wallet You must keep it secret, otherwise you lose the funds
Address Human‑readable representation of a public key What the customer uses to send money
UTXO (Unspent Transaction Output) The base units you can spend Determines how you split or combine payments
Fee Cost for miners to process your transaction Roughly 10‑30 satoshis per byte in the network
RPC Remote Procedure Call interface to a full node Full control, but resource‑heavy

For a production‑ready approach you usually don’t run your own node; instead, you harness a payment processor or a public node provider.


3. Choosing a Payment Processor

Processor Key Strength Python SDK Pricing Ideal Use Case
BlockCypher Simple REST API, free tier blockcypher $0.001 * tx Small to medium e‑commerce
Coinbase Commerce Direct wallet integration, invoicing coinbase-commerce $X / TX Standard storefronts
BitPay Commercial support, multi‑currency bitpay-python (community) Custom Enterprise platforms
BTCPay Server Self‑hosted, no fees btcpayclient Free + hosting High‑volume, privacy‑centric

Select a processor based on cost, required features, and whether you prefer a hosted or self‑managed solution. For beginners, BlockCypher or Coinbase Commerce often provide the quickest route to production.


4. Quickstart with BlockCypher

Below is a minimal example that demonstrates how to create a Bitcoin address, build a transaction, and broadcast it. Remember this is meant for learning; never hard‑code your private key on a public server.

pip install blockcypher
Enter fullscreen mode Exit fullscreen mode
import os
from blockcypher import get_new_address, create_transaction, estimate_tx_fee
from dotenv import load_dotenv

load_dotenv()          # Load environment variables

# 1️⃣   Create a new BTC V2 address
address_info = get_new_address('btc_v2', account=os.getenv('BLOCKCYPHER_ACCOUNT'))
print(f"New address: {address_info['address']}")

# 2️⃣   Estimate fee (0.0001 BTC in USD ≈ 10000 satoshis)
fee_sats = estimate_tx_fee(1, 1) * 1000
print(f"Estimated fee: {fee_sats} satoshi")

# 3️⃣   Prepare raw transaction
# This assumes you already have UTXOs in the wallet.
# In production you’d pull UTXOs via `list_unspent()`.
inputs = [{'output': 'abcd1234...:0', 'value': 200000}]  # 0.002 BTC
outputs = [{'address': address_info['address'], 'value': 100000}]  # 0.001 BTC
tx = create_transaction(
    inputs=inputs,
    outputs=outputs,
    coin_symbol='btc',
    additional='comment',
    fee=fee_sats
)
print(f"Raw TX: {tx}")

# 4️⃣   Broadcast transaction
broad = tx.broadcast()
print("Tx broadcasted:", broad)
Enter fullscreen mode Exit fullscreen mode

Tip: For real‑time payment processing, you’ll not just generate a raw transaction—you’ll accept money from a customer’s wallet and monitor the network for the UTXO that appears.


5. Handling Incoming Payments: Webhooks

Most processors expose an HTTP webhook that fires whenever a payment arrives. Below is an example using Coinbase Commerce and Flask.

pip install flask coinbase-commerce
Enter fullscreen mode Exit fullscreen mode

python
from flask import Flask, request, jsonify
from coinbase_commerce.client import Client
from coinbase_commerce.api_resources.event import Event
from dotenv import load_dotenv

load_dotenv()
app = Flask(__name__)

client = Client(api_key=os.getenv('COINBASE_API_KEY'), bearer_token=os.getenv('COINBASE_BEARER_TOKEN'))

@app.route('/coinbase/webhook', methods=['POST'])
def coinbase_webhook():
    payload = request.get_json()

---

## Get the Production-Ready Version

Don't want to build it yourself? We have production-ready versions of these tools at [https://reply-continues-exams-confidential.trycloudflare.com](https://reply-continues-exams-confidential.trycloudflare.com).

**What you get:**
- Complete, tested Python code
- Documentation and setup guides
- Instant delivery after crypto payment
- Free updates

[Browse the collection →](https://reply-continues-exams-confidential.trycloudflare.com)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)