BTCPay Server Greenfield API Create Invoice: Complete Guide

Accepting cryptocurrency payments through the btcpay server greenfield api create invoice gives merchants full control over their payment infrastructure. Unlike hosted payment pages or third-party processors, self-hosted BTCPay Server puts you in complete command of transaction flow, customer data, and settlement timing. The Greenfield API is the modern interface that makes programmatic invoice creation straightforward and reliable.

This guide covers everything you need to know about creating invoices programmatically with the Greenfield API — from authentication to webhook handling and common pitfalls.

Why Choose Self-Hosted Crypto Payments

Most payment providers take a cut of every transaction and store your customer data on their servers. With BTCPay Server, you run your own instance and keep custody of funds directly in your customers’ wallets until they confirm on-chain. There are zero processing fees beyond standard network mining fees.

Self-hosting also means no account restrictions. Third-party processors can freeze merchant accounts overnight. Your own BTCPay Server never goes offline unless you choose to shut it down. You control the uptime, the configuration, and the customer experience.

The Greenfield API replaces the legacy REST endpoints introduced in earlier versions. It provides a cleaner JSON-based interface with better error messages, consistent authentication, and support for all major features including invoice creation, refund processing, and point-of-sale operations.

Authentication Setup

Every Greenfield API call requires authentication. The system uses API keys tied to specific accounts with defined permissions. Generate a key from your BTCPay Server admin panel under Settings → Developers → API Keys.

Key Types and Permissions

Permission Level Scope Use Case
Store Limited to a single store Creating invoices for one shop
Store + Payment Process Store plus payment method config Managing multiple currencies
Admin Full server access Multi-store setups and automation

Store-level keys are sufficient for most e-commerce integrations. When creating an invoice, include the Authorization header with your API key:

Authorization: Bearer YOUR_API_KEY

For stores using lightning network payments, additional setup may be required depending on your node configuration. Lightning invoices generated through the API follow the same authentication model as on-chain invoices.

Creating an Invoice

Invoice creation is a simple POST request to the /stores/{storeId}/invoices endpoint. The body contains all information needed to generate a payable request.

Required Fields

Field Type Description
price number Amount in the specified currency
currency string ISO 4217 currency code (USD, EUR, GBP, etc.)
requestingData boolean Whether to require buyer-provided data
fullWebhooks boolean Enable all event types in webhook notifications

Example Request

curl -X POST "https://your-btcpay-server.example.com/api/v1/stores/STORE_ID/invoices" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "price": 49.99,
    "currency": "USD",
    "buyerEmail": "[email protected]",
    "requestingData": true,
    "redirectUrl": "https://yoursite.com/success",
    "redirectAutomatically": true,
    "paymentTypes": ["Cryptocurrency"],
    "checkout": {
      "reviewEnabled": true,
      "paymentMethods": ["BTC"]
    }
  }'

The response returns an object containing the invoice ID, payment URLs, and addresses for each configured payment method. Extract checkoutUrl to redirect the buyer to the payment page, or use links.id for direct API-based status checks.

Optional Configuration

Several options refine how the invoice behaves during checkout:

  • redirectUrl — Where the buyer goes after successful payment
  • redirectAutomatically — Auto-redirect without requiring a click
  • paymentDeadline — Duration in minutes before the invoice expires (default: 20 minutes)
  • transactionSpeed — Controls network fee level: "low", "medium", or "high"
  • refundAccount — Email address for manual refunds
  • notificationEmail — Address for real-time payment alerts

Setting transactionSpeed to "high" increases miner fees and helps buyers get faster confirmation, which matters for time-sensitive purchases.

Supported Payment Methods

Greenfield API supports both on-chain and off-chain payment options depending on your store configuration.

On-Chain Cryptocurrencies

Bitcoin, Bitcoin Cash, Litecoin, Dogecoin, and other supported coins each receive their own deposit address per invoice. Addresses regenerate for every new invoice, preventing reuse and improving privacy.

Lightning Network

Lightning invoices appear alongside on-chain options when lightning is enabled on your store. They offer near-instant settlement without mining fees. The API handles BOLT11 invoice generation automatically.

Multiple Payment Method Selection

Buyers can choose their preferred cryptocurrency at checkout. Configure available payment methods in the store settings or override them per invoice through the paymentMethods array in the request body.

Webhook Integration

Reliable payment detection requires webhooks. Instead of polling the API repeatedly, configure a webhook URL in your store settings to receive automatic notifications when invoice status changes.

Webhook Events

Event Trigger
invoiceReceivedPayment Buyer sends funds to the invoice address
invoiceCompleted Payment confirmed and invoice marked complete
invoiceExpired Invoice passed its payment deadline
invoiceCreated Invoice successfully created

Each webhook payload includes the invoice object with updated status. Verify the request signature using the BTCPAY-SIG-256 header to ensure the notification came from your server and not a malicious actor.

Webhook Secret

Generate a secret key alongside your API key. Include it in the webhook registration request. BTCPay signs each payload with HMAC-SHA256 using this secret. Validate the signature on your receiving endpoint before processing any state changes.

Checking Invoice Status

After redirecting the buyer to the payment page, monitor the invoice through the API to determine when to fulfill orders.

curl "https://your-btcpay-server.example.com/api/v1/stores/STORE_ID/invoices/INVOICE_ID" \
  -H "Authorization: Bearer YOUR_API_KEY"

The status field in the response indicates current state:

  • new — Invoice created, awaiting payment
  • waitingForTransfer — Payment detected, confirming on-chain
  • processing — Transaction being processed
  • complete — Payment confirmed, order ready for fulfillment
  • expired — Payment deadline passed
  • invalid — Payment amount insufficient or address rejected

Poll at reasonable intervals. Every few seconds is unnecessary; once per minute provides good balance between responsiveness and API load.

Common Errors and Troubleshooting

401 Unauthorized

Missing or invalid API key. Double-check that the key has store-level permissions and hasn’t been revoked. Regenerate if necessary.

404 Not Found

Wrong store ID or invoice ID. Retrieve the correct store identifier from the server dashboard URL or by calling the /stores endpoint.

400 Bad Request

Malformed JSON body or missing required fields. Validate your payload against the schema before sending. Check that price is a number, not a string, and currency matches a supported ISO code.

Invoice Already Paid

If a buyer attempts to pay the same invoice twice, the second transaction will still be accepted but flagged. Track paid amounts to avoid duplicate fulfillment. Set exceptionRefund to allow partial payments when needed.

Best Practices for Production

Rate limit your API calls during peak hours. While BTCPay Server does not enforce strict rate limits, excessive polling wastes resources and slows down order processing. Rely on webhooks for status updates instead of constant polling.

Encrypt stored API keys. Never expose them in frontend code, version control, or client-side scripts. Use environment variables or a secrets manager on your backend.

Test with small amounts before going live. Create test invoices with minimal values to verify the entire flow — creation, payment detection, webhook delivery, and order fulfillment — works end to end.

Monitor your node health if running lightning payments. Lightning channel liquidity issues can prevent incoming payments from settling. Regularly check channel balances and rebalance when necessary.

Keep your BTCPay Server instance updated. Newer versions include security patches, improved API endpoints, and enhanced lightning integration. Running outdated software exposes your store to known vulnerabilities.

Leave a Reply

Your email address will not be published. Required fields are marked *