Skip to main content

Overview

This guide shows you how to implement x402 payments using Dynamic’s wallet infrastructure. We’ll use the x402 fetch library in our examples, but you can also use axios or other HTTP libraries with x402. Dynamic provides multiple wallet options that work seamlessly with the x402 payment protocol, from embedded MPC wallets to external wallet integrations.

Prerequisites

Before implementing x402 with Dynamic, ensure you have:
  • A Dynamic project set up with your API keys
  • Basic understanding of HTTP status codes and request/response patterns
  • Familiarity with Dynamic’s wallet SDKs
  • x402 fetch library installed (or axios/other HTTP library)

Installation

Install the x402 libraries. These libraries add simple request middleware to wrap your HTTP calls with x402 payment handling.
npm install x402-fetch
# or
npm install x402-axios
The x402 libraries are the official packages from Coinbase Developer Platform. You can also use other HTTP libraries with x402, but the official packages provide the best integration experience.

Implementation Options

Client-Side Implementation (React SDK)

For client-side applications, use Dynamic’s React SDK:
import { useDynamicContext } from '@dynamic-labs/sdk-react-core';
import { isEthereumWallet } from '@dynamic-labs/ethereum';
import { wrapFetchWithPayment, decodeXPaymentResponse } from 'x402-fetch';

const { primaryWallet } = useDynamicContext();

const x402PaymentUrl = 'https://example.com/x402-payment';

// Universal x402 payment handler
async function handleX402Payment(url, options = {}) {
  try {    
    if (isEthereumWallet(primaryWallet)) {
      // Get wallet client for Ethereum wallets
      const walletClient = await primaryWallet.getWalletClient();

      // Wrap fetch with x402 payment handling
      const fetchWithPayment = wrapFetchWithPayment(fetch, walletClient);

      // Make the request - x402 will handle payment automatically
      const response = await fetchWithPayment(url, options);

      // Optional: Decode payment response for debugging
      const paymentResponse = decodeXPaymentResponse(
        response.headers.get("x-payment-response")
      );
      if (paymentResponse) {
        console.log('Payment details:', paymentResponse);
      }
      
      return response;
    }
  } catch (error) {
    console.error('Payment failed:', error);
    throw error;
  }
}

// Make the request using the x402 payment handler
const response = await handleX402Payment(x402PaymentUrl);
I