Overview
useX402 hook from @coinbase/cdp-hooks, you can integrate x402 payments into your embedded wallet application, allowing users to seamlessly pay for API access and services with their embedded wallets.
This guide demonstrates how to use the useX402 hook to enable your users to make micropayments for paid APIs and services without complex payment flows or intermediaries.
How it works
When your application makes a request to an x402-protected resource:- The server responds with
402 Payment Requiredstatus including payment details - The
useX402hook automatically:- Extracts the payment information from the response
- Creates and signs a payment transaction using the user’s embedded wallet
- Includes the payment proof in a retry request
- The server validates the payment and returns the requested resource
Prerequisites
Before integrating x402 payments, ensure you have:- Completed the Embedded Wallets Quickstart
- Installed the required packages:
The
x402-fetch package must be installed separately as it provides the underlying payment protocol implementation.Usage
TheuseX402 hook provides a fetchWithPayment function that works like the standard fetch API but automatically handles x402 payment flows:
useX402 hook, see here.
Compatibility
Accounts
TheuseX402 hook works with Smart Accounts, EOAs and Solana accounts.
Frameworks
TheuseX402 hook works in React and React Native. If you need support in other frameworks or vanilla JavaScript, you can use the fetchWithX402 action from @coinbase/cdp-core:
- x402 Protocol Overview: Learn more about the x402 payment protocol
- x402 Quickstart for Buyers: Comprehensive guide for consuming x402 APIs
- x402 Bazaar: Discover x402-compatible APIs and services
- Smart Accounts: Enable gas-free payments with Smart Accounts
- React Hooks Reference: Explore all available CDP hooks