Code Examples

JavaScript/TypeScript

Basic Payment Creation

const response = await fetch('https://api.billmyagent.ai/api/v1/payments', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'your-api-key'
  },
  body: JSON.stringify({
    amount: '1000000000000000000',
    currency: 'ETH',
    network: 'ethereum',
    scheme: 'exact',
    payment_payload: paymentPayload,
    payment_required: paymentRequired
  })
});

const payment = await response.json();
console.log('Payment ID:', payment.id);

Payment Verification

const response = await fetch('https://api.billmyagent.ai/api/v1/verify', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Key': 'your-api-key'
  },
  body: JSON.stringify({
    payment_payload: base64EncodedPayload,
    payment_required: base64EncodedRequired
  })
});

const result = await response.json();
if (result.valid) {
  console.log('Payment is valid');
} else {
  console.log('Payment validation failed:', result.message);
}

Get Payment Status

const response = await fetch(`https://api.billmyagent.ai/api/v1/payments/${paymentId}`, {
  headers: {
    'X-API-Key': 'your-api-key'
  }
});

const payment = await response.json();
console.log('Payment status:', payment.status);
console.log('Payment amount:', payment.amount);

React Example - Simplified API

import React from 'react';
import { PaymentButton, PaymentClient } from '@billmyagent/payments-react';

function PaymentForm() {
  const client = new PaymentClient({
    apiKey: 'your-api-key',
    baseURL: 'https://api.billmyagent.ai/api/v1'
  });

  return (
    <div>
      <PaymentButton
        client={client}
        amount="1000000000000000000"
        currency="ETH"
        network="ethereum"
        scheme="exact"
        onSuccess={(payment) => {
          console.log('Payment created:', payment);
        }}
        onError={(error) => {
          console.error('Payment failed:', error);
        }}
      >
        Pay with BillMyAgent
      </PaymentButton>
    </div>
  );
}

React Example - Advanced API (Manual Payloads)

import React from 'react';
import { PaymentButton, PaymentClient } from '@billmyagent/payments-react';

function PaymentForm() {
  const client = new PaymentClient({
    apiKey: 'your-api-key',
    baseURL: 'https://api.billmyagent.ai/api/v1'
  });

  const paymentRequest = {
    amount: '1000000000000000000',
    currency: 'ETH',
    network: 'ethereum',
    scheme: 'exact',
    payment_payload: paymentPayload, // Manually generated
    payment_required: paymentRequired // Manually generated
  };

  return (
    <PaymentButton
      client={client}
      paymentRequest={paymentRequest}
      onSuccess={(payment) => console.log('Payment created:', payment)}
    >
      Pay Now
    </PaymentButton>
  );
}

Automatic 402 Handling Example

import { PaymentClient, MetaMaskAdapter } from '@billmyagent/payments-core';

// Set up wallet adapter
const walletAdapter = new MetaMaskAdapter();

// Create client with automatic 402 handling
const client = new PaymentClient({
  apiKey: 'your-api-key',
  walletAdapter, // Enable automatic 402 handling
  autoHandle402: true, // Automatically handle 402 responses
});

// When API returns 402, SDK will:
// 1. Detect 402 response
// 2. Parse payment instructions
// 3. Prompt user to sign via wallet
// 4. Submit signed payment
// 5. Wait for verification
// 6. Retry original request automatically

try {
  const result = await client.getPayment('payment-id');
  // If payment was required, it's handled automatically!
} catch (error) {
  console.error('Request failed:', error);
}

React Hook Example - usePayment

import { usePayment } from '@billmyagent/payments-react';
import { MetaMaskAdapter } from '@billmyagent/payments-core';

function PaymentComponent() {
  const walletAdapter = new MetaMaskAdapter();
  const { 
    payment, 
    loading, 
    error,
    createPayment,
    walletConnected,
    connectWallet 
  } = usePayment({
    client: paymentClient,
    walletAdapter,
    autoConnect: true,
  });

  return (
    <div>
      {!walletConnected && (
        <button onClick={connectWallet}>Connect Wallet</button>
      )}
      <button 
        onClick={() => createPayment({
          amount: '1.00',
          currency: 'USDC',
          network: 'ethereum',
          scheme: 'exact'
        })}
        disabled={loading}
      >
        {loading ? 'Processing...' : 'Create Payment'}
      </button>
      {payment && <p>Payment ID: {payment.id}</p>}
    </div>
  );
}

Node.js Example - Simplified API

const { PaymentClient } = require('@billmyagent/payments-core');

async function createPayment() {
  try {
    const client = new PaymentClient({
      apiKey: 'your-api-key',
      baseURL: 'https://api.billmyagent.ai/api/v1'
    });

    // Payment payloads are automatically generated!
    const payment = await client.createPaymentSimple({
      amount: '1000000000000000000',
      currency: 'ETH',
      network: 'ethereum',
      scheme: 'exact'
    });

    console.log('Payment created:', payment);
    return payment;
  } catch (error) {
    console.error('Error creating payment:', error.message);
    throw error;
  }
}

createPayment();

Python Example

import requests

def create_payment():
    url = 'https://api.billmyagent.ai/api/v1/payments'
    headers = {
        'Content-Type': 'application/json',
        'X-API-Key': 'your-api-key'
    }
    data = {
        'amount': '1000000000000000000',
        'currency': 'ETH',
        'network': 'ethereum',
        'scheme': 'exact',
        'payment_payload': payment_payload,
        'payment_required': payment_required
    }
    
    response = requests.post(url, json=data, headers=headers)
    response.raise_for_status()
    
    payment = response.json()
    print(f'Payment created: {payment["id"]}')
    return payment

if __name__ == '__main__':
    create_payment()

Error Handling

try {
  const response = await fetch('https://api.billmyagent.ai/api/v1/payments', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-API-Key': 'your-api-key'
    },
    body: JSON.stringify(paymentData)
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.message || 'Payment creation failed');
  }

  const payment = await response.json();
  return payment;
} catch (error) {
  console.error('Payment error:', error);
  // Handle error appropriately
}