E-commerce Integration

Complete examples for integrating BSV payments into e-commerce platforms, including shopping carts, checkout flows, and payment verification.

Overview

Integrating BSV into e-commerce systems enables fast, low-cost payments with immediate settlement. This guide covers payment request generation, checkout integration, payment verification, inventory management, and customer order fulfillment. These patterns work with any e-commerce platform or custom solution.

Related SDK Components:

Payment Request Generator

import { PrivateKey, Script } from '@bsv/sdk'

/**
 * Payment Request Generator
 *
 * Generate payment requests for e-commerce checkout
 */
class PaymentRequestGenerator {
  private merchantAddress: string

  constructor(merchantKey: PrivateKey) {
    this.merchantAddress = merchantKey.toPublicKey().toAddress()
  }

  /**
   * Generate payment request for cart
   */
  generatePaymentRequest(params: {
    cartId: string
    items: CartItem[]
    customerId?: string
    customerEmail?: string
  }): PaymentRequest {
    try {
      // Calculate totals
      const subtotal = params.items.reduce((sum, item) => sum + (item.price * item.quantity), 0)
      const tax = Math.floor(subtotal * 0.08) // 8% tax
      const shipping = this.calculateShipping(params.items)
      const total = subtotal + tax + shipping

      const request: PaymentRequest = {
        requestId: this.generateRequestId(),
        cartId: params.cartId,
        merchantAddress: this.merchantAddress,
        amount: total,
        currency: 'satoshis',
        items: params.items,
        breakdown: {
          subtotal,
          tax,
          shipping,
          total
        },
        customerId: params.customerId,
        customerEmail: params.customerEmail,
        createdAt: Date.now(),
        expiresAt: Date.now() + 30 * 60 * 1000, // 30 minutes
        status: 'pending'
      }

      console.log('Payment request generated')
      console.log('Request ID:', request.requestId)
      console.log('Amount:', request.amount, 'satoshis')

      return request
    } catch (error) {
      throw new Error(`Payment request generation failed: ${error.message}`)
    }
  }

  /**
   * Generate payment URI (BIP-21 style)
   */
  generatePaymentURI(request: PaymentRequest): string {
    const uri = `bitcoin:${request.merchantAddress}?` +
      `amount=${request.amount / 100000000}&` + // Convert to BSV
      `label=${encodeURIComponent('E-commerce Payment')}&` +
      `message=${encodeURIComponent(`Order ${request.requestId}`)}`

    return uri
  }

  /**
   * Generate QR code data
   */
  generateQRCodeData(request: PaymentRequest): string {
    return this.generatePaymentURI(request)
  }

  /**
   * Calculate shipping cost
   */
  private calculateShipping(items: CartItem[]): number {
    const totalWeight = items.reduce((sum, item) => sum + (item.weight || 0) * item.quantity, 0)

    if (totalWeight === 0) return 0
    if (totalWeight < 1000) return 5000 // 5000 sats for < 1kg
    if (totalWeight < 5000) return 10000 // 10000 sats for < 5kg
    return 20000 // 20000 sats for > 5kg
  }

  /**
   * Generate unique request ID
   */
  private generateRequestId(): string {
    return `PAY-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
  }
}

interface CartItem {
  itemId: string
  name: string
  price: number
  quantity: number
  weight?: number // grams
}

interface PaymentRequest {
  requestId: string
  cartId: string
  merchantAddress: string
  amount: number
  currency: string
  items: CartItem[]
  breakdown: {
    subtotal: number
    tax: number
    shipping: number
    total: number
  }
  customerId?: string
  customerEmail?: string
  createdAt: number
  expiresAt: number
  status: 'pending' | 'paid' | 'expired'
}

/**
 * Usage Example
 */
function paymentRequestExample() {
  const merchantKey = PrivateKey.fromRandom()
  const generator = new PaymentRequestGenerator(merchantKey)

  const request = generator.generatePaymentRequest({
    cartId: 'CART-123',
    items: [
      { itemId: 'ITEM-001', name: 'T-Shirt', price: 25000, quantity: 2, weight: 200 },
      { itemId: 'ITEM-002', name: 'Mug', price: 15000, quantity: 1, weight: 300 }
    ],
    customerEmail: '[email protected]'
  })

  console.log('Payment request:', request)

  // Generate payment URI
  const uri = generator.generatePaymentURI(request)
  console.log('Payment URI:', uri)

  // Generate QR code data
  const qrData = generator.generateQRCodeData(request)
  console.log('QR code data:', qrData)
}

Checkout Integration

Order Management System

See Also

SDK Components:

Learning Paths:

Last updated