Skip to main content

createCoinbaseOnrampOrder

Creates a Coinbase onramp order for purchasing cryptocurrency with fiat. This returns a payment link URL that you can display in an iframe within your app, providing an embedded purchase experience. This function is typically used with addCoinbaseOnrampOrderEventListener to track the order status in real-time.

Usage

import {
  createCoinbaseOnrampOrder,
  addCoinbaseOnrampOrderEventListener,
} from "@dynamic-labs-sdk/client";

// Create the order
const order = await createCoinbaseOnrampOrder({
  agreementAcceptedAt: new Date(),
  destinationAddress: "0x1234...",
  destinationNetwork: "base",
  paymentCurrency: "USD",
  paymentMethod: "GUEST_CHECKOUT_APPLE_PAY",
  purchaseAmount: "100",
  purchaseCurrency: "USDC",
  isSandbox: true, // Use true for testing
});

// Display the payment link in an iframe
const iframe = document.createElement("iframe");
iframe.src = order.paymentLink.url;
document.body.appendChild(iframe);

// Listen for order events
const removeListener = addCoinbaseOnrampOrderEventListener({
  listener: (event) => {
    console.log("Event:", event.eventName, event.data);
  },
});

Parameters

ParameterTypeDescription
agreementAcceptedAtDateTimestamp when user accepted Coinbase’s terms.
destinationAddressstringThe wallet address to receive the crypto.
destinationNetworkstringThe network for the purchase (e.g., base, ethereum).
paymentCurrencystringThe fiat currency (e.g., USD, EUR).
paymentMethodstringThe payment method. Currently only GUEST_CHECKOUT_APPLE_PAY is supported.
purchaseAmountstringThe amount of crypto to purchase.
purchaseCurrencystringThe crypto to purchase (e.g., USDC, ETH).
isSandboxboolean (optional)Set to true for testing without real transactions.
clientDynamicClient (optional)The Dynamic client instance. Only required when using multiple clients.

Returns

Promise<CoinbaseOnrampOrderResponse> - A promise that resolves to the created order, including:
type CoinbaseOnrampOrderResponse = {
  order: {
    orderId: string;
    status: string;
    destinationAddress: string;
    destinationNetwork: string;
    purchaseAmount: string;
    purchaseCurrency: string;
    paymentCurrency: string;
    paymentTotal: string;
    fees: Array<{ type: string; amount: string; currency: string }>;
    // ... and more
  };
  paymentLink?: {
    url: string; // Display this in an iframe
    paymentLinkType: string;
  };
};

Prerequisites

This function requires the user to have verified email and phone number. Use getMissingVerificationForCoinbaseOnrampOrder to check verification status before creating an order.

Complete Example

Here’s a full implementation showing how to create an order, display it in an iframe, and handle events:
import { useState, useRef, useEffect } from "react";
import {
  createCoinbaseOnrampOrder,
  addCoinbaseOnrampOrderEventListener,
  getMissingVerificationForCoinbaseOnrampOrder,
} from "@dynamic-labs-sdk/client";

const CoinbaseOnrampWidget = ({ walletAddress }) => {
  const [paymentUrl, setPaymentUrl] = useState(null);
  const [status, setStatus] = useState("idle");
  const removeListenerRef = useRef(null);

  const handleCreateOrder = async () => {
    // Check verification requirements first
    const missing = getMissingVerificationForCoinbaseOnrampOrder({
      paymentMethod: "GUEST_CHECKOUT_APPLE_PAY",
    });

    if (missing.length > 0) {
      alert("Please verify your email and phone number first");
      return;
    }

    setStatus("creating");

    try {
      const order = await createCoinbaseOnrampOrder({
        agreementAcceptedAt: new Date(),
        destinationAddress: walletAddress,
        destinationNetwork: "base",
        paymentCurrency: "USD",
        paymentMethod: "GUEST_CHECKOUT_APPLE_PAY",
        purchaseAmount: "100",
        purchaseCurrency: "USDC",
        isSandbox: true,
      });

      if (order.paymentLink?.url) {
        setPaymentUrl(order.paymentLink.url);
        setStatus("pending");

        // Start listening for events
        removeListenerRef.current = addCoinbaseOnrampOrderEventListener({
          listener: (event) => {
            switch (event.eventName) {
              case "onramp_api.cancel":
                setStatus("cancelled");
                setPaymentUrl(null);
                break;
              case "onramp_api.commit_success":
                setStatus("processing");
                break;
              case "onramp_api.commit_error":
                setStatus("error");
                console.error("Payment error:", event.data.errorMessage);
                break;
              case "onramp_api.polling_success":
                setStatus("completed");
                setPaymentUrl(null);
                break;
              case "onramp_api.polling_failed":
                setStatus("error");
                console.error("Transaction failed:", event.data.errorMessage);
                break;
            }
          },
        });
      }
    } catch (error) {
      setStatus("error");
      console.error("Failed to create order:", error);
    }
  };

  // Cleanup listener on unmount
  useEffect(() => {
    return () => {
      removeListenerRef.current?.();
    };
  }, []);

  if (paymentUrl) {
    return (
      <iframe
        src={paymentUrl}
        width="100%"
        height="500px"
        allow="payment"
        title="Coinbase Payment"
      />
    );
  }

  return (
    <div>
      <p>Status: {status}</p>
      <button onClick={handleCreateOrder} disabled={status === "creating"}>
        {status === "creating" ? "Creating order..." : "Buy Crypto"}
      </button>
    </div>
  );
};