Docs/React SDK

React SDK

v1.0.0

React components and hooks for seamless Web3 Pay integration in your React applications.

Installation

bash
-green-400">npm install @web3pay/react

The React SDK includes the core SDK as a dependency.

Provider Setup

Wrap your app with the Web3PayProvider to enable SDK access throughout your component tree:

tsx
400">import { Web3PayProvider } 400">from 400">'@web3pay/react';

400">function App() {
  400">return (
    <Web3PayProvider
      apiKey=400">"wp3_live_pk_your_publishable_key"
      environment=400">"live"  500">// or 400">"test"
    >
      <YourApp />
    </Web3PayProvider>
  );
}

OnrampButton Component

A pre-built button that handles the entire onramp flow:

tsx
400">import { OnrampButton } 400">from 400">&#039;@web3pay/react&#039;;

400">function BuyCryptoSection({ userWallet }: { userWallet: string }) {
  400">return (
    <OnrampButton
      walletAddress={userWallet}
      cryptoCurrency=400">"ETH"
      fiatAmount={100}
      fiatCurrency=400">"USD"
      onSuccess={(session) => {
        console.log(400">&#039;Purchase complete!&#039;, session);
        500">// Update your UI, show success message, etc.
      }}
      onError={(error) => {
        console.error(400">&#039;Purchase failed:&#039;, error);
        500">// Show error message to user
      }}
      onClose={() => {
        console.log(400">&#039;User closed the widget&#039;);
      }}
    >
      Buy ETH
    </OnrampButton>
  );
}

Props

walletAddressstringrequired
Destination wallet for the crypto
cryptoCurrencystringrequired
Cryptocurrency to purchase (ETH, USDC, etc.)
fiatAmountnumber
Pre-filled amount in fiat (dollars, not cents)
fiatCurrencystring
Fiat currency code. Default: 'USD'
onSuccessfunction
Callback when transaction completes
onErrorfunction
Callback when transaction fails
onClosefunction
Callback when widget is closed
theme'light' | 'dark'
Widget theme. Default: 'light'
classNamestring
Additional CSS classes for the button
disabledboolean
Disable the button

useOnramp Hook

For more control, use the useOnramp hook to build custom UI:

tsx
400">import { useOnramp } 400">from 400">&#039;@web3pay/react&#039;;
400">import { useState } 400">from 400">&#039;react&#039;;

400">function CustomBuyForm() {
  400">const { createSession, openWidget, loading, error } = useOnramp();
  400">const [amount, setAmount] = useState(100);

  400">const handleSubmit = 400">async (e: React.FormEvent) => {
    e.preventDefault();

    400">try {
      400">const session = 400">await createSession({
        walletAddress: 400">&#039;0x742d35Cc6634C0532925a3b844Bc9e7595f5fB&#039;,
        cryptoCurrency: 400">&#039;ETH&#039;,
        fiatAmount: amount * 100, 500">// Convert to cents
        fiatCurrency: 400">&#039;USD&#039;
      });

      500">// Option 1: Open the widget
      openWidget(session.client_secret);

      500">// Option 2: Redirect to hosted checkout
      500">// window.location.href = session.redirect_url;
    } 400">catch (err) {
      console.error(400">&#039;Failed to create session:&#039;, err);
    }
  };

  400">return (
    <form onSubmit={handleSubmit}>
      <input
        400">type=400">"number"
        value={amount}
        onChange={(e) => setAmount(Number(e.target.value))}
        min={10}
        max={10000}
      />
      <button 400">type=400">"submit" disabled={loading}>
        {loading ? 400">&#039;Processing...&#039; : 400">&#039;Buy ETH&#039;}
      </button>
      {error && <p className=400">"error">{error.message}</p>}
    </form>
  );
}

Hook Return Value

createSessionfunction
Creates a new onramp session
openWidgetfunction
Opens the payment widget with a client secret
closeWidgetfunction
Programmatically closes the widget
loadingboolean
True while session is being created
errorError | null
Error from last operation

useWeb3Pay Hook

Access the underlying SDK client directly:

tsx
400">import { useWeb3Pay } 400">from 400">&#039;@web3pay/react&#039;;

400">function TransactionHistory() {
  400">const { client } = useWeb3Pay();
  400">const [transactions, setTransactions] = useState([]);

  useEffect(() => {
    400">async 400">function fetchTransactions() {
      400">const result = 400">await client.getTransactions({
        limit: 10,
        status: 400">&#039;completed&#039;
      });
      setTransactions(result.transactions);
    }
    fetchTransactions();
  }, [client]);

  400">return (
    <ul>
      {transactions.map(tx => (
        <li key={tx.id}>
          {tx.crypto_amount} {tx.crypto_currency} - {tx.status}
        </li>
      ))}
    </ul>
  );
}

Event Handling

Listen for widget events using the useOnrampEvents hook:

tsx
400">import { useOnrampEvents } 400">from 400">&#039;@web3pay/react&#039;;

400">function BuyButton({ walletAddress }: { walletAddress: string }) {
  400">const { createSession, openWidget } = useOnramp();

  500">// Set up event listeners
  useOnrampEvents({
    onSuccess: (data) => {
      console.log(400">&#039;Transaction successful:&#039;, data.tx_hash);
      showNotification(400">&#039;Crypto purchased successfully!&#039;);
    },
    onError: (error) => {
      console.error(400">&#039;Transaction failed:&#039;, error);
      showNotification(400">&#039;Purchase failed. Please 400">try again.&#039;);
    },
    onClose: () => {
      console.log(400">&#039;Widget closed&#039;);
    }
  });

  400">const handleClick = 400">async () => {
    400">const session = 400">await createSession({
      walletAddress,
      cryptoCurrency: 400">&#039;ETH&#039;,
      fiatAmount: 10000,
      fiatCurrency: 400">&#039;USD&#039;
    });
    openWidget(session.client_secret);
  };

  400">return <button onClick={handleClick}>Buy ETH</button>;
}

Styling

Customize the OnrampButton appearance:

tsx
500">// Using className
<OnrampButton
  className=400">"bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg"
  walletAddress={wallet}
  cryptoCurrency=400">"ETH"
  fiatAmount={100}
>
  Purchase ETH
</OnrampButton>

500">// Using inline styles
<OnrampButton
  style={{
    backgroundColor: 400">&#039;#6366f1&#039;,
    color: 400">&#039;white&#039;,
    padding: 400">&#039;12px 24px&#039;,
    borderRadius: 400">&#039;8px&#039;
  }}
  walletAddress={wallet}
  cryptoCurrency=400">"ETH"
  fiatAmount={100}
>
  Purchase ETH
</OnrampButton>

Complete Example

tsx
1500">// app/layout.tsx
2400">import { Web3PayProvider } 400">from 400">&#039;@web3pay/react&#039;;
3 
4400">export 400">default 400">function RootLayout({ children }) {
5 400">return (
6 <html>
7 <body>
8 <Web3PayProvider
9 apiKey={process.env.NEXT_PUBLIC_WEB3PAY_KEY!}
10 environment=400">"live"
11 >
12 {children}
13 </Web3PayProvider>
14 </body>
15 </html>
16 );
17}
18 
19500">// components/BuyCrypto.tsx
20400">import { OnrampButton } 400">from 400">&#039;@web3pay/react&#039;;
21400">import { useWallet } 400">from 400">&#039;@/hooks/useWallet&#039;;
22400">import { toast } 400">from 400">&#039;sonner&#039;;
23 
24400">export 400">function BuyCrypto() {
25 400">const { address, isConnected } = useWallet();
26 
27 400">if (!isConnected) {
28 400">return <button onClick={connect}>Connect Wallet</button>;
29 }
30 
31 400">return (
32 <div className=400">"space-y-4">
33 <h2>Buy Crypto</h2>
34 <p>Purchase ETH directly to your wallet</p>
35 
36 <OnrampButton
37 walletAddress={address}
38 cryptoCurrency=400">"ETH"
39 fiatAmount={100}
40 fiatCurrency=400">"USD"
41 theme=400">"dark"
42 className=400">"w-full py-3 bg-gradient-to-r 400">from-blue-600 to-purple-600"
43 onSuccess={(data) => {
44 toast.success(400">&#039;Purchase complete!&#039;);
45 console.log(400">&#039;TX Hash:&#039;, data.tx_hash);
46 }}
47 onError={(error) => {
48 toast.error(error.message);
49 }}
50 >
51 Buy $100 of ETH
52 </OnrampButton>
53 </div>
54 );
55}
Back to home
Was this page helpful?