### Complete Example Source: https://docs.bitrefill.com/docs/quickstart-2 A full example demonstrating how to purchase a gift card. ```javascript const API_KEY = process.env.BITREFILL_API_KEY; // or use Basic auth for Business API const BASE_URL = 'https://api.bitrefill.com/v2'; async function purchaseGiftCard(productId, packageId) { const headers = { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }; // Create and pay invoice const invoiceRes = await fetch(`${BASE_URL}/invoices`, { method: 'POST', headers, body: JSON.stringify({ products: [{ product_id: productId, package_id: packageId, quantity: 1 }], payment_method: 'balance', auto_pay: true }) }); const { data: invoice } = await invoiceRes.json(); if (invoice.status !== 'complete') { throw new Error(`Invoice status: ${invoice.status}`); } // Get redemption info const orderId = invoice.orders[0].id; const orderRes = await fetch(`${BASE_URL}/orders/${orderId}`, { headers }); const { data: order } = await orderRes.json(); return order.redemption_info; } // Usage const code = await purchaseGiftCard('amazon-us', 'amazon-us<&>50'); console.log('Gift card code:', code.code); ``` -------------------------------- ### Using Test Products Source: https://docs.bitrefill.com/docs/quickstart-2 Example of creating an invoice using test products. ```javascript const response = await fetch(`${BASE_URL}/invoices`, { method: 'POST', headers, body: JSON.stringify({ products: [{ product_id: 'test-gift-card-code', value: 10, quantity: 1 }], payment_method: 'balance', auto_pay: true }) }); ``` -------------------------------- ### Get Product Details Source: https://docs.bitrefill.com/docs/quickstart-2 Fetches available denominations for a product. ```javascript const response = await fetch(`${BASE_URL}/products/amazon-us`, { headers }); const { data: product } = await response.json(); // Fixed denominations console.log(product.packages); // [{ package_id: 'amazon-us<&>25', value: 25 }, ...] // Or flexible range console.log(product.range); // { min: 1, max: 200, step: 0.01 } ``` -------------------------------- ### Get the Redemption Code Source: https://docs.bitrefill.com/docs/quickstart-2 Retrieves the order to get the gift card code and instructions. ```javascript const orderId = invoice.orders[0].id; const response = await fetch(`${BASE_URL}/orders/${orderId}`, { headers }); const { data: order } = await response.json(); console.log('Gift card code:', order.redemption_info.code); console.log('Instructions:', order.redemption_info.instructions); ``` -------------------------------- ### Complete Example Source: https://docs.bitrefill.com/docs/brgc-batches A comprehensive example demonstrating batch creation, polling for completion, and retrieving card codes, including API key setup and error handling. ```javascript const API_ID = process.env.BITREFILL_API_ID; const API_SECRET = process.env.BITREFILL_API_SECRET; const BASE_URL = 'https://api.bitrefill.com/v2'; const token = Buffer.from(`${API_ID}:${API_SECRET}`).toString('base64'); const headers = { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' }; async function createBatch(quantity, value, currency) { // Create the batch const createRes = await fetch(`${BASE_URL}/brgc-batches`, { method: 'POST', headers, body: JSON.stringify({ quantity, value, currency }) }); const batch = await createRes.json(); const batchId = batch.data.batchId; // Poll for completion while (true) { const statusRes = await fetch(`${BASE_URL}/brgc-batches/${batchId}`, { headers }); const status = await statusRes.json(); if (status.data.status === 'complete') { return status.data.cards; } if (status.data.status === 'failed') { throw new Error('Batch creation failed'); } await new Promise(r => setTimeout(r, 2000)); } } // Usage const cards = await createBatch(10, 25, 'USD'); console.log(`Created ${cards.length} gift cards`); cards.forEach(card => console.log(card.code)); ``` -------------------------------- ### Get Product Details Tool Example Source: https://docs.bitrefill.com/docs/ecommerce-mcp Example of using the `get-product-details` tool to get product information. ```javascript get-product-details(product_id="amazon_com-usa", currency="USD") ``` -------------------------------- ### eSIM Product Example Source: https://docs.bitrefill.com/docs/core-concepts An example of an eSIM product object, showing available data packages. ```json { "id": "bitrefill-esim-europe", "name": "Bitrefill eSIM Europe", "packages": [ { "package_id": "bitrefill-esim-europe<&>1GB, 7 Days", "value": "1GB, 7 Days" }, { "package_id": "bitrefill-esim-europe<&>5GB, 30 Days", "value": "5GB, 30 Days" } ] } ``` -------------------------------- ### Set Up Authentication Source: https://docs.bitrefill.com/docs/quickstart-2 Sets up API key and base URL for authentication. ```javascript const API_KEY = process.env.BITREFILL_API_KEY; const BASE_URL = 'https://api.bitrefill.com/v2'; const headers = { 'Authorization': `Bearer ${API_KEY}`, 'Content-Type': 'application/json' }; ``` -------------------------------- ### Global Config File Example Source: https://docs.bitrefill.com/docs/use-with-claude-code Example of how to configure the Bitrefill MCP server in the global config file. ```json { "mcpServers": { "bitrefill": { "type": "http", "url": "https://api.bitrefill.com/mcp" } } } ``` -------------------------------- ### Example Prompt: Show eSIM Options Source: https://docs.bitrefill.com/docs/use-with-claude-code Example of how to ask Claude to show eSIM options using Bitrefill. ```bash Show me eSIM options for traveling to Spain ``` -------------------------------- ### Create and Pay an Invoice Source: https://docs.bitrefill.com/docs/quickstart-2 Purchases a product using the account balance. ```javascript const response = await fetch(`${BASE_URL}/invoices`, { method: 'POST', headers, body: JSON.stringify({ products: [{ product_id: 'amazon-us', package_id: 'amazon-us<&>50', quantity: 1 }], payment_method: 'balance', auto_pay: true }) }); const { data: invoice } = await response.json(); console.log(`Invoice: ${invoice.id}, Status: ${invoice.status}`); ``` -------------------------------- ### Test Your Connection Source: https://docs.bitrefill.com/docs/quickstart-2 Verifies credentials by calling the ping endpoint. ```javascript const response = await fetch(`${BASE_URL}/ping`, { headers }); const data = await response.json(); console.log(data); // { meta: {...}, data: { message: 'pong' } } ``` -------------------------------- ### Complete Example Source: https://docs.bitrefill.com/docs/account-deposits A comprehensive example demonstrating how to create both fixed and flexible amount deposit invoices, and how to use the returned information. ```javascript async function depositToAccount(currency, paymentMethod, amount = null) { const body = { currency, payment_method: paymentMethod }; // Amount is optional - omit for flexible-amount deposits if (amount !== null) { body.amount = amount; } const response = await fetch(`${BASE_URL}/accounts/deposit`, { method: 'POST', headers, body: JSON.stringify(body) }); const { data: invoice } = await response.json(); return { invoiceId: invoice.id, paymentAddress: invoice.payment.address, paymentAmount: invoice.payment.price, paymentCurrency: invoice.payment.currency }; } // Usage: Fixed amount deposit const deposit = await depositToAccount('USD', 'bitcoin', 1000); console.log(`Send ${deposit.paymentAmount} ${deposit.paymentCurrency} to ${deposit.paymentAddress}`); // Usage: Flexible amount deposit const flexibleDeposit = await depositToAccount('USD', 'bitcoin'); console.log(`Flexible deposit invoice created: ${flexibleDeposit.invoiceId}`); ``` -------------------------------- ### Find a Product Source: https://docs.bitrefill.com/docs/quickstart-2 Lists available products or searches for a specific one. ```javascript // List products const products = await fetch(`${BASE_URL}/products?limit=10`, { headers }); // Search for a product const search = await fetch(`${BASE_URL}/products/search?q=amazon`, { headers }); ``` -------------------------------- ### Webhook Example Source: https://docs.bitrefill.com/docs/rate-limits Example of using webhooks for invoice creation to avoid polling. ```javascript const invoice = await createInvoice({ products: [...], webhook_url: 'https://your-server.com/webhook' }); ``` -------------------------------- ### Example Prompt: Buy Gift Card Source: https://docs.bitrefill.com/docs/use-with-claude-code Example of how to ask Claude to buy a gift card using Bitrefill. ```bash Buy a $100 Apple gift card ``` -------------------------------- ### Search Products Tool Example Source: https://docs.bitrefill.com/docs/ecommerce-mcp Example of using the `search-products` tool to find products. ```javascript search-products(query="Amazon", country="US") ``` -------------------------------- ### Complete Example Source: https://docs.bitrefill.com/docs/crypto-payments A complete example function to purchase with crypto, including products, payment method, refund address, and webhook URL. ```javascript async function purchaseWithCrypto(products, paymentMethod, refundAddress) { const response = await fetch(`${BASE_URL}/invoices`, { method: 'POST', headers, body: JSON.stringify({ products, payment_method: paymentMethod, refund_address: refundAddress, webhook_url: 'https://your-server.com/webhook' }) }); const { data: invoice } = await response.json(); return { invoiceId: invoice.id, address: invoice.payment.address, amount: invoice.payment.price, currency: invoice.payment.currency }; } // Usage const payment = await purchaseWithCrypto( [{ product_id: 'amazon-us', value: 50 }], 'bitcoin', 'bc1q...' ); console.log(`Send ${payment.amount} ${payment.currency} to ${payment.address}`); ``` -------------------------------- ### Example Prompt: Search for Gift Cards Source: https://docs.bitrefill.com/docs/use-with-claude-code Example of how to ask Claude to search for gift cards using Bitrefill. ```bash Search for Spotify gift cards in the UK ``` -------------------------------- ### Global Config File Example with API Key Source: https://docs.bitrefill.com/docs/use-with-claude-code Example of how to configure the Bitrefill MCP server with an API key in the global config file. ```json { "mcpServers": { "bitrefill": { "type": "http", "url": "https://api.bitrefill.com/mcp/YOUR_API_KEY" } } } ``` -------------------------------- ### Authentication Source: https://docs.bitrefill.com/docs/Common%20Use%20Cases Example of how to set up HTTP Basic authentication for the Business API. ```javascript const API_ID = process.env.BITREFILL_API_ID; const API_SECRET = process.env.BITREFILL_API_SECRET; const token = Buffer.from(`${API_ID}:${API_SECRET}`).toString('base64'); const headers = { 'Authorization': `Basic ${token}`, 'Content-Type': 'application/json' }; ``` -------------------------------- ### Out of stock example Source: https://docs.bitrefill.com/docs/error-codes Example of a JSON response when a product is out of stock. ```json { "error_code": "out_of_stock", "message": "Product 'amazon-us' is currently out of stock" } ``` -------------------------------- ### eSIM Top-Up Request Example Source: https://docs.bitrefill.com/docs/core-concepts An example JSON payload for topping up an existing eSIM with a data bundle. ```json { "product_id": "bitrefill-esim-europe", "value": "5GB, 30 Days", "esim_id": "4058965632381351147" } ``` -------------------------------- ### eSIM Object Example Source: https://docs.bitrefill.com/docs/core-concepts An example of an eSIM object returned after purchase, detailing its status and data bundles. ```json { "id": "4058965632381351147", "rsp_url": "...", "pin": "1234", "barcode_value": "LPA:1$தல்", "installed": false, "package_history": [ { "package_name": "1GB, 7 Days", "data_mb": 1000, "status": "active", "remaining_quantity": 500000000 } ] } ``` -------------------------------- ### Missing parameter example Source: https://docs.bitrefill.com/docs/error-codes Example of a JSON response when a required parameter is missing. ```json { "error_code": "missing_param", "message": "Missing required parameter: product_id" } ``` -------------------------------- ### Listing with Filters Source: https://docs.bitrefill.com/docs/searching-products Examples of listing products with different filters like country and type. ```javascript // All US products const response = await fetch(`${BASE_URL}/products?country=US`, { headers }); // Gift cards only const response = await fetch(`${BASE_URL}/products?type=gift_card`, { headers }); // US gift cards const response = await fetch(`${BASE_URL}/products?country=US&type=gift_card`, { headers }); ``` -------------------------------- ### Bundle Stacking Example Source: https://docs.bitrefill.com/docs/esims When you top up, new bundles are **added** alongside existing ones — they don't replace them. The device typically consumes bundles in order (oldest first). ```json { "package_history": [ { "package_name": "3GB, 30 Days", "status": "active", "remaining_quantity": 500000000 }, { "package_name": "5GB, 30 Days", "status": "active", "remaining_quantity": 5000000000 } ] } ``` -------------------------------- ### List Batches Source: https://docs.bitrefill.com/docs/brgc-batches Example of how to list existing batches with a specified limit. ```javascript const response = await fetch(`${BASE_URL}/brgc-batches?limit=20`, { headers }); const { data: batches } = await response.json(); ``` -------------------------------- ### Balance too low example Source: https://docs.bitrefill.com/docs/error-codes Example of a JSON response when the user's balance is insufficient. ```json { "error_code": "balance_too_low", "message": "Insufficient balance. Required: $50.00, Available: $25.00" } ``` -------------------------------- ### Refund Address Example Source: https://docs.bitrefill.com/docs/refunds Example of a payment object including the refund_address for crypto payments. ```javascript { products: [...], payment_method: 'bitcoin', refund_address: 'bc1q...' // Required for refunds } ``` -------------------------------- ### Update Order Example Source: https://docs.bitrefill.com/docs/ecommerce-mcp Example of using update-order to track gift card usage or manage order visibility. ```python update-order(order_id="507f1f77bcf86cd799439011", remaining_amount=25.00) ``` -------------------------------- ### Response Source: https://docs.bitrefill.com/docs/esims The order contains installation details in `redemption_info`: ```json { "redemption_info": { "barcode_format": "QRCODE", "barcode_value": "LPA:1$sm.example.com$MATCHING-ID", "instructions": "Scan this QR code in your device settings to install" } } ``` -------------------------------- ### Gift Purchase Example Source: https://docs.bitrefill.com/docs/ecommerce-mcp Example of how to include a gift object on a cart item to send a gift email. ```python buy-products( cart_items=[ { "product_id": "amazon_com-usa", "package_id": "50", "gift": { "recipient_name": "Jane", "recipient_email": "jane@example.com", "sender_name": "John", "message": "Happy birthday!", "send_date": "2026-06-01T12:00:00Z", "theme": "birthday" } } ], payment_method="balance" ) ``` -------------------------------- ### Create a Batch Source: https://docs.bitrefill.com/docs/brgc-batches Example of how to create a batch of Bitrefill Gift Cards using the API. ```javascript const response = await fetch(`${BASE_URL}/brgc-batches`, { method: 'POST', headers, body: JSON.stringify({ quantity: 10, value: 25, currency: 'USD' }) }); const { data: batch } = await response.json(); console.log(`Batch ${batch.batchId} created, status: ${batch.status}`); ``` -------------------------------- ### Packages (Fixed Values) Example Source: https://docs.bitrefill.com/docs/core-concepts Some products have fixed denominations. You must purchase one of the available values. ```json { "packages": [ { "package_id": "amazon-us<&>25", "value": 25 }, { "package_id": "amazon-us<&>50", "value": 50 }, { "package_id": "amazon-us<&>100", "value": 100 } ] } ``` -------------------------------- ### Personal API Authentication Source: https://docs.bitrefill.com/docs/api-overview Example of how to authenticate with the Personal API using a Bearer token. ```javascript const API_KEY = process.env.BITREFILL_API_KEY; const response = await fetch(`${BASE_URL}/ping`, { headers: { 'Authorization': `Bearer ${API_KEY}` } }); ``` -------------------------------- ### Creating a Crypto Invoice Source: https://docs.bitrefill.com/docs/crypto-payments Example of how to create a crypto invoice by specifying the payment method and including a refund address. ```javascript const response = await fetch(`${BASE_URL}/invoices`, { method: 'POST', headers, body: JSON.stringify({ products: [{ product_id: 'amazon-us', value: 50 }], payment_method: 'bitcoin', refund_address: 'bc1q...' }) }); const { data: invoice } = await response.json(); console.log(`Send ${invoice.payment.price} ${invoice.payment.currency}`); console.log(`To: ${invoice.payment.address}`); ``` -------------------------------- ### Respond Quickly Source: https://docs.bitrefill.com/docs/webhooks Example of responding with 200 OK immediately and queuing the processing for asynchronous execution. ```javascript app.post('/webhooks/bitrefill', (req, res) => { res.status(200).send('OK'); queue.add('process-invoice', req.body); }); ``` -------------------------------- ### Submit Prepayment Step Source: https://docs.bitrefill.com/docs/ecommerce-mcp Example of submitting a prepayment step for a product that requires it. ```json submit-prepayment-step( product_id="prepaid-visa-usa", step_number=1, form_data={ "first_name": "Alice", "last_name": "Smith" } ) ``` -------------------------------- ### Invoice Example Source: https://docs.bitrefill.com/docs/core-concepts An invoice is a payment request for one or more products. Creating an invoice is the first step in making a purchase. ```json { "id": "inv_abc123", "status": "unpaid", "payment": { "method": "bitcoin", "address": "bc1q...", "price": 0.00123456 }, "orders": [ { "id": "ord_xyz789", "status": "created" } ] } ``` -------------------------------- ### Building a Commission Dashboard Source: https://docs.bitrefill.com/docs/commissions Example of fetching data to build a commission dashboard, including overview statistics and recent commissions. ```javascript const API_ID = process.env.BITREFILL_API_ID; const API_SECRET = process.env.BITREFILL_API_SECRET; const BASE_URL = 'https://api.bitrefill.com/v2'; const token = Buffer.from(`${API_ID}:${API_SECRET}`).toString('base64'); const headers = { 'Authorization': `Basic ${token}` }; async function getDashboardData() { const response = await fetch(`${BASE_URL}/commissions`, { headers }); const { data: commissions } = await response.json(); const now = new Date(); const thisMonth = now.toISOString().slice(0, 7); const thisMonthCommissions = commissions.filter(c => c.date.startsWith(thisMonth)); return { overview: { totalCommissions: commissions.length, totalEarningsUSD: commissions.reduce((sum, c) => sum + c.amount_usd, 0), thisMonthEarningsUSD: thisMonthCommissions.reduce((sum, c) => sum + c.amount_usd, 0), thisMonthCount: thisMonthCommissions.length }, recentCommissions: commissions.slice(0, 10) }; } ``` -------------------------------- ### Order Response Example Source: https://docs.bitrefill.com/docs/phone-topups Phone top-ups don't return redemption codes. ```json { "data": { "id": "ord_xyz789", "status": "delivered", "product": { "id": "at-t-usa", "name": "AT&T", "value": 25 }, "phone_number": "+15551234567" } } ``` -------------------------------- ### Buy Products Source: https://docs.bitrefill.com/docs/ecommerce-mcp Example of creating an invoice using the buy-products endpoint with cart items. ```json buy-products( cart_items=[ { "product_id": "amazon_com-usa", "package_id": "50" } ], payment_method="bitcoin", return_payment_link=true ) ``` -------------------------------- ### Product Example Source: https://docs.bitrefill.com/docs/core-concepts Represents something you can purchase — a gift card brand, mobile operator, or eSIM plan. ```json { "id": "amazon-us", "name": "Amazon US", "type": "gift_card", "country": "US", "currency": "USD" } ``` -------------------------------- ### Lightning Payments Source: https://docs.bitrefill.com/docs/crypto-payments Example for creating an invoice specifically for Lightning payments. ```javascript const response = await fetch(`${BASE_URL}/invoices`, { method: 'POST', headers, body: JSON.stringify({ products: [{ product_id: 'amazon-us', value: 50 }], payment_method: 'lightning' }) }); const { data: invoice } = await response.json(); // invoice.payment.address contains the BOLT11 invoice ``` -------------------------------- ### Create Invoice with Webhook URL Source: https://docs.bitrefill.com/docs/webhooks Example of how to include the `webhook_url` when creating an invoice using the fetch API. ```javascript const response = await fetch(`${BASE_URL}/invoices`, { method: 'POST', headers, body: JSON.stringify({ products: [{ product_id: 'amazon-us', value: 50 }], payment_method: 'balance', webhook_url: 'https://your-server.com/webhooks/bitrefill', auto_pay: true }) }); ``` -------------------------------- ### Order Example Source: https://docs.bitrefill.com/docs/core-concepts An order represents a single product purchase within an invoice. When an invoice is paid, each order is processed and delivered individually. ```json { "id": "ord_xyz789", "status": "delivered", "product": { "id": "amazon-us", "name": "Amazon US", "value": 50 }, "redemption_info": { "code": "ABCD-EFGH-IJKL", "link": "https://redeem.amazon.com/" } } ``` -------------------------------- ### Ranges (Flexible Values) Example Source: https://docs.bitrefill.com/docs/core-concepts Other products accept any value within a range. ```json { "range": { "min": 10, "max": 200, "step": 1 } } ``` -------------------------------- ### Check Batch Status Source: https://docs.bitrefill.com/docs/brgc-batches Example of how to check the status of a created batch and retrieve gift card codes upon completion. ```javascript const response = await fetch(`${BASE_URL}/brgc-batches/${batchId}`, { headers }); const { data: batch } = await response.json(); if (batch.status === 'complete') { console.log(`${batch.cards.length} cards ready`); batch.cards.forEach(card => console.log(card.code)); } ``` -------------------------------- ### Implement Webhook Endpoint Source: https://docs.bitrefill.com/docs/webhooks Example Express.js server code for handling incoming webhook POST requests from Bitrefill. ```javascript const express = require('express'); const app = express(); app.use(express.json()); app.post('/webhooks/bitrefill', async (req, res) => { const invoice = req.body; // Respond immediately res.status(200).send('OK'); // Process asynchronously processInvoice(invoice); }); async function processInvoice(invoice) { console.log(`Invoice ${invoice.id} status: ${invoice.status}`); for (const order of invoice.orders) { if (order.status === 'delivered') { const orderDetails = await fetchOrder(order.id); await deliverToUser(orderDetails); } else { await handleFailedOrder(order); } } } ``` -------------------------------- ### Multiple Products per Invoice Example Source: https://docs.bitrefill.com/docs/core-concepts An invoice can contain multiple products. Each product becomes a separate order within the invoice. ```json { "products": [ { "product_id": "amazon-us", "value": 50 }, { "product_id": "spotify-us", "package_id": "spotify-us<&>10" }, { "product_id": "steam-us", "value": 25, "quantity": 2 } ] } ``` -------------------------------- ### Purchasing Gift Cards Source: https://docs.bitrefill.com/docs/gift-cards Examples of how to purchase gift cards using the invoice endpoint, demonstrating both package_id and value methods. ```javascript // Using package_id (fixed value) const response = await fetch(`${BASE_URL}/invoices`, { method: 'POST', headers, body: JSON.stringify({ products: [{ product_id: 'amazon-us', package_id: 'amazon-us<&>50', quantity: 1 }], payment_method: 'balance', auto_pay: true }) }); ``` ```javascript // Using value (flexible range) const response = await fetch(`${BASE_URL}/invoices`, { method: 'POST', headers, body: JSON.stringify({ products: [{ product_id: 'amazon-us', value: 75.50, quantity: 1 }], payment_method: 'balance', auto_pay: true }) }); ``` -------------------------------- ### Get Invoice By ID Source: https://docs.bitrefill.com/docs/ecommerce-mcp Example of polling the get-invoice-by-id endpoint to check payment status. ```json get-invoice-by-id(invoice_id="6654a2ea-0df7-4f44-bc72-c1c6ad8b7b34") ``` -------------------------------- ### Order/Delivery error example Source: https://docs.bitrefill.com/docs/error-codes Example of an order object with an error status. ```json { "id": "ord_xyz789", "status": "failed", "error": "Provider temporarily unavailable" } ``` -------------------------------- ### Search products by keyword Source: https://docs.bitrefill.com/docs/searching-products Demonstrates how to search for products using a keyword query parameter. ```javascript const response = await fetch(`${BASE_URL}/products/search?q=amazon`, { headers }); const { data: products } = await response.json(); products.forEach(p => console.log(`${p.id}: ${p.name} (${p.country})`)); // amazon-us: Amazon.com (US) // amazon-uk: Amazon.co.uk (GB) ``` -------------------------------- ### Browsing Products Source: https://docs.bitrefill.com/docs/Products This code snippet demonstrates how to fetch a list of products using the Bitrefill API and log their details to the console. It also includes a placeholder for handling pagination. ```javascript const response = await fetch(`${BASE_URL}/products?limit=50`, { headers }); const { data: products, meta } = await response.json(); products.forEach(p => console.log(`${p.id}: ${p.name} (${p.type})`)); // Pagination if (meta._next) { // Fetch next page } ``` -------------------------------- ### Bitrefill MCP Server URL for SSE Source: https://docs.bitrefill.com/docs/use-with-claude-chat Alternative server URL to use if experiencing connection issues after authorization, by appending /sse. ```text https://api.bitrefill.com/mcp/sse ``` -------------------------------- ### Launch Claude Code Source: https://docs.bitrefill.com/docs/use-with-claude-code Command to launch the Claude Code CLI. ```bash claude ``` -------------------------------- ### Rate limit headers Source: https://docs.bitrefill.com/docs/error-codes Example of response headers indicating rate limits. ```text X-RateLimit-Limit: 60 X-RateLimit-Remaining: 0 X-RateLimit-Reset: 1704067200 ``` -------------------------------- ### Fetch All Products Source: https://docs.bitrefill.com/docs/integration-flow Fetches the full product catalog by paginating through the API. ```javascript async function fetchAllProducts() { const products = []; let url = `${BASE_URL}/products?limit=50`; while (url) { const response = await fetch(url, { headers }); const data = await response.json(); products.push(...data.data); url = data.meta._next || null; } return products; } ``` -------------------------------- ### Bitrefill MCP Server URL with API Key Source: https://docs.bitrefill.com/docs/use-with-claude-chat Alternative server URL to use when setting up with an API key instead of OAuth. ```text https://api.bitrefill.com/mcp/YOUR_API_KEY ``` -------------------------------- ### List Configured MCP Servers Source: https://docs.bitrefill.com/docs/use-with-claude-code Command to list all configured MCP servers. ```bash claude mcp list ``` -------------------------------- ### Handle Partial Failures Source: https://docs.bitrefill.com/docs/brgc-batches Code snippet demonstrating how to check for and handle partial failures in batch creation, identifying successful and failed cards. ```javascript if (batch.status === 'partial') { const successfulCards = batch.cards.filter(c => c.status === 'active'); const failedCount = batch.quantity - successfulCards.length; console.log(`${failedCount} cards failed to create`); } ``` -------------------------------- ### Handle Retries (Idempotency) Source: https://docs.bitrefill.com/docs/webhooks Example of an idempotent `processInvoice` function that checks for existing processed invoices before proceeding. ```javascript async function processInvoice(invoice) { const existing = await db.invoices.findOne({ id: invoice.id }); if (existing) { console.log(`Invoice ${invoice.id} already processed`); return; } await handleInvoice(invoice); await db.invoices.insertOne({ id: invoice.id, processedAt: new Date() }); } ``` -------------------------------- ### Create Invoice Source: https://docs.bitrefill.com/docs/integration-flow Creates an invoice for a purchase, specifying products, payment method, and webhook URL. ```javascript const response = await fetch(`${BASE_URL}/invoices`, { method: 'POST', headers, body: JSON.stringify({ products: [{ product_id: 'amazon-us', package_id: 'amazon-us<&>50', quantity: 1 }], payment_method: 'balance', webhook_url: 'https://your-server.com/bitrefill-webhook', auto_pay: false }) }); ``` -------------------------------- ### MCP Config File Source: https://docs.bitrefill.com/docs/use-with-cursor Create or edit `.cursor/mcp.json` in your project root to configure the Bitrefill MCP server. ```json { "mcpServers": { "bitrefill": { "url": "https://api.bitrefill.com/mcp" } } } ``` -------------------------------- ### Handle Partial Failures Source: https://docs.bitrefill.com/docs/webhooks Example of handling different order statuses within an invoice, including 'delivered', 'failed', and 'refunded'. ```javascript for (const order of invoice.orders) { switch (order.status) { case 'delivered': await deliverToUser(order); break; case 'failed': await refundUser(order); await notifySupport(order); break; case 'refunded': await updateUserBalance(order); break; } } ``` -------------------------------- ### Auto-Approve Read-Only Tools Source: https://docs.bitrefill.com/docs/use-with-cursor Configure auto-approval for read-only MCP tools to streamline workflows. ```json { "mcpServers": { "bitrefill": { "url": "https://api.bitrefill.com/mcp", "autoApprove": [ "search-products", "get-product-details", "list-invoices", "get-invoice-by-id" ] } } } ``` -------------------------------- ### Creating a Deposit Source: https://docs.bitrefill.com/docs/account-deposits Creates a deposit invoice for the specified amount and currency, using a given payment method. ```javascript const response = await fetch(`${BASE_URL}/accounts/deposit`, { method: 'POST', headers, body: JSON.stringify({ amount: 1000, currency: 'USD', payment_method: 'bitcoin' }) }); const { data: invoice } = await response.json(); console.log(`Send ${invoice.payment.price} ${invoice.payment.currency}`); console.log(`To: ${invoice.payment.address}`); ``` -------------------------------- ### API Key Authentication Source: https://docs.bitrefill.com/docs/use-with-cursor Configure the Bitrefill MCP server using an API key directly in the URL. ```json { "mcpServers": { "bitrefill": { "url": "https://api.bitrefill.com/mcp/YOUR_API_KEY" } } } ``` -------------------------------- ### Add Server with API Key Source: https://docs.bitrefill.com/docs/use-with-claude-code Command to add the Bitrefill MCP server using an API key. ```bash claude mcp add --transport http bitrefill https://api.bitrefill.com/mcp/YOUR_API_KEY --scope user ``` -------------------------------- ### Safe API Call Function Source: https://docs.bitrefill.com/docs/error-codes An example of a JavaScript function that safely calls an API, handles known error codes, and logs unknown errors and network errors. ```javascript async function safeApiCall(url, options) { try { const response = await fetch(url, options); const data = await response.json(); if (!response.ok) { // Handle known errors switch (data.error_code) { case 'balance_too_low': return { success: false, error: 'insufficient_balance' }; case 'out_of_stock': return { success: false, error: 'unavailable' }; case 'not_found': return { success: false, error: 'product_not_found' }; default: // Log unknown errors console.error('Unknown error:', data); return { success: false, error: 'unknown', details: data }; } } return { success: true, data: data.data }; } catch (networkError) { // Handle network errors console.error('Network error:', networkError); return { success: false, error: 'network_error' }; } } ``` -------------------------------- ### Error Handling Usage Source: https://docs.bitrefill.com/docs/References Example of how to use the apiRequest function and handle specific API errors using a switch statement based on the error code. ```javascript // Usage try { const invoice = await apiRequest('/invoices', { method: 'POST', ... }); } catch (error) { switch (error.code) { case 'balance_too_low': console.log('Need to add balance'); break; case 'out_of_stock': console.log('Product unavailable'); break; default: console.log(`Error: ${error.message}`); } } ``` -------------------------------- ### Listing Commissions Source: https://docs.bitrefill.com/docs/commissions Fetch and display a list of commissions. ```javascript const response = await fetch(`${BASE_URL}/commissions`, { headers }); const { data: commissions } = await response.json(); commissions.forEach(c => { console.log(`${c.id}: $${c.amount_usd} from ${c.order.product.name}`); }); ```