> ## Documentation Index
> Fetch the complete documentation index at: https://docs.crossmint.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Pay with USDC

> Buy an NFT with USDC on Base Sepolia using only REST API calls

## Introduction

In this quickstart you buy an NFT with USDC on Base Sepolia. You make four API calls: create the order, send the USDC payment, submit the transaction hash, and get the order status. You do not need a sample app or an SDK.

## Prerequisites

<Snippet file="headless-checkout-prereqs.mdx" />

### External Prerequisites

* **Payer wallet:** an EVM wallet that you control, and its private key. Use a test wallet only.
* **Testnet USDC:** a small balance of USDC on Base Sepolia. Get it from the [Circle faucet](https://faucet.circle.com/). In staging, you can also pay with USDXM, a Crossmint test token that behaves like USDC: get it from the [Crossmint faucet](https://usdc-faucet.vercel.app/) and set `payment.currency` to `usdxm`.
* **Testnet ETH:** a small balance of ETH on Base Sepolia to pay for gas. Get it from a [Base Sepolia faucet](https://www.alchemy.com/faucets/base-sepolia).

## Integration Steps

**1. Create the order**

Create an order with the recipient, the payer wallet, and the collection. Refer to the [Create Order API reference](https://docs.crossmint.com/api-reference/headless/create-order.md) for all parameters.

`POST` `https://staging.crossmint.com/api/2022-06-09/orders`

```bash cURL theme={null}
curl --request POST \
    --url https://staging.crossmint.com/api/2022-06-09/orders \
    --header 'Content-Type: application/json' \
    --header 'X-API-KEY: <your-server-api-key>' \
    --data '{
        "recipient": {
            "email": "<recipient-email>"
        },
        "payment": {
            "method": "base-sepolia",
            "currency": "usdc",
            "payerAddress": "<payer-wallet-address>"
        },
        "lineItems": [
            {
                "collectionLocator": "crossmint:<your-collection-id>"
            }
        ]
    }'
```

```javascript Node.js theme={null}
const response = await fetch("https://staging.crossmint.com/api/2022-06-09/orders", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "<your-server-api-key>",
    },
    body: JSON.stringify({
        recipient: {
            email: "<recipient-email>",
        },
        payment: {
            method: "base-sepolia",
            currency: "usdc",
            payerAddress: "<payer-wallet-address>",
        },
        lineItems: [
            {
                collectionLocator: "crossmint:<your-collection-id>",
            },
        ],
    }),
});
const { order } = await response.json();

console.log("Order ID:", order.orderId);
console.log("Serialized transaction:", order.payment.preparation.serializedTransaction);
```

```python Python theme={null}
import requests

response = requests.post(
    "https://staging.crossmint.com/api/2022-06-09/orders",
    headers={
        "Content-Type": "application/json",
        "X-API-KEY": "<your-server-api-key>",
    },
    json={
        "recipient": {
            "email": "<recipient-email>",
        },
        "payment": {
            "method": "base-sepolia",
            "currency": "usdc",
            "payerAddress": "<payer-wallet-address>",
        },
        "lineItems": [
            {
                "collectionLocator": "crossmint:<your-collection-id>",
            },
        ],
    },
)
order = response.json()["order"]

print("Order ID:", order["orderId"])
print("Serialized transaction:", order["payment"]["preparation"]["serializedTransaction"])
```

* `recipient.email`: Crossmint delivers the NFT to a wallet for this email. To deliver to a wallet that you choose, use `recipient.walletAddress` instead.
* `payment.payerAddress`: the wallet that sends the USDC.
* `lineItems[].collectionLocator`: the collection to buy from.

The order is now in the `payment` phase. Save these two values from the response for the next steps:

* `order.orderId`
* `order.payment.preparation.serializedTransaction`: the USDC transfer that the payer wallet must sign and send.

> [accordion] Example response
>
> ```json theme={null}
> {
>     "clientSecret": "_removed_",
>     "order": {
>         "orderId": "cc40e6af-f8dc-4ac2-8e26-d91a32f271cf",
>         "phase": "payment",
>         "quote": {
>             "status": "valid",
>             "totalPrice": {
>                 "amount": "1",
>                 "currency": "usdc"
>             }
>         },
>         "payment": {
>             "status": "awaiting-payment",
>             "currency": "usdc",
>             "method": "base-sepolia",
>             "preparation": {
>                 "chain": "base-sepolia",
>                 "payerAddress": "0x6C3b3225759Cbda68F96378A9F0277B4374f9F06",
>                 "serializedTransaction": "0x02f8b2..."
>             }
>         }
>     }
> }
> ```

**2. Send the USDC payment**

Sign the `serializedTransaction` with the payer wallet and send it to the payment chain. A cURL call cannot sign a transaction, so this step uses a wallet library.

> [tab] EVM
>
> ```javascript Node.js theme={null}
> import { createWalletClient, http, parseTransaction } from "viem";
> import { privateKeyToAccount } from "viem/accounts";
> import { baseSepolia } from "viem/chains";
>
> const serializedTransaction = "<serialized-transaction>";
>
> const account = privateKeyToAccount("<payer-private-key>");
> const walletClient = createWalletClient({ account, chain: baseSepolia, transport: http() });
>
> const { to, value, data } = parseTransaction(serializedTransaction);
> const txHash = await walletClient.sendTransaction({ to, value, data });
>
> console.log("Transaction hash:", txHash);
> ```
>
> ```python Python theme={null}
> import rlp
> from eth_account import Account
> from web3 import Web3
> from web3.middleware import SignAndSendRawMiddlewareBuilder
>
> serialized_transaction = "<serialized-transaction>"
>
> w3 = Web3(Web3.HTTPProvider("https://sepolia.base.org"))
> account = Account.from_key("<payer-private-key>")
> w3.middleware_onion.inject(SignAndSendRawMiddlewareBuilder.build(account), layer=0)
>
> # An EIP-1559 transaction is 0x02 followed by the RLP-encoded fields
> fields = rlp.decode(bytes.fromhex(serialized_transaction[4:]))
> to, value, data = fields[5], fields[6], fields[7]
>
> tx_hash = w3.eth.send_transaction({
>     "from": account.address,
>     "to": Web3.to_checksum_address(to),
>     "value": int.from_bytes(value, "big"),
>     "data": data,
> })
>
> print("Transaction hash:", tx_hash.to_0x_hex())
> ```

> [tab] Solana
>
> To pay on Solana devnet, create the order with `"method": "solana"`, `"currency": "usdc"`, and a Solana `payerAddress`, and fund the payer with devnet USDC from the [Circle faucet](https://faucet.circle.com/) plus SOL for fees from the [Solana faucet](https://faucet.solana.com).
>
> For Solana, `serializedTransaction` is a base58-encoded transaction.
>
> ```javascript Node.js theme={null}
> import { Connection, Keypair, Transaction, clusterApiUrl, sendAndConfirmTransaction } from "@solana/web3.js";
> import bs58 from "bs58";
>
> const serializedTransaction = "<serialized-transaction>";
>
> const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
> const payer = Keypair.fromSecretKey(bs58.decode("<payer-private-key>"));
>
> const transaction = Transaction.from(bs58.decode(serializedTransaction));
> const txHash = await sendAndConfirmTransaction(connection, transaction, [payer]);
>
> console.log("Transaction hash:", txHash);
> ```
>
> ```python Python theme={null}
> import base64
>
> import base58
> import requests
> from solders.hash import Hash
> from solders.keypair import Keypair
> from solders.transaction import Transaction
>
> RPC_URL = "https://api.devnet.solana.com"
> serialized_transaction = "<serialized-transaction>"
>
>
> def rpc(method, params):
>     body = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
>     return requests.post(RPC_URL, json=body).json()["result"]
>
>
> payer = Keypair.from_base58_string("<payer-private-key>")
> blockhash = rpc("getLatestBlockhash", [])["value"]["blockhash"]
>
> transaction = Transaction.from_bytes(base58.b58decode(serialized_transaction))
> transaction.sign([payer], Hash.from_string(blockhash))
> tx_hash = rpc("sendTransaction", [base64.b64encode(bytes(transaction)).decode(), {"encoding": "base64"}])
>
> print("Transaction hash:", tx_hash)
> ```
>
> In a browser app, the buyer signs in their own wallet, for example with the `sendTransaction` function of the [Solana wallet adapter](https://github.com/anza-xyz/wallet-adapter).

> [!WARNING]
>
> Never put a production private key in your code. In a production app, the buyer signs this transaction in their own wallet, for example with wagmi's `sendTransaction`.

**3. Submit the transaction hash**

Send the transaction hash to the [Process Payment API](https://docs.crossmint.com/api-reference/headless/process-payment.md). Crossmint also detects the payment onchain, so this step is optional, but it records the payment sooner.

`POST` `https://staging.crossmint.com/api/2022-06-09/orders/<orderId>/payment`

```bash cURL theme={null}
curl --request POST \
    --url 'https://staging.crossmint.com/api/2022-06-09/orders/<orderId>/payment' \
    --header 'Content-Type: application/json' \
    --header 'X-API-KEY: <your-server-api-key>' \
    --data '{
        "type": "crypto-tx-id",
        "txId": "<transaction-hash>"
    }'
```

```javascript Node.js theme={null}
const orderId = "<orderId>";

const response = await fetch(`https://staging.crossmint.com/api/2022-06-09/orders/${orderId}/payment`, {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "<your-server-api-key>",
    },
    body: JSON.stringify({
        type: "crypto-tx-id",
        txId: "<transaction-hash>",
    }),
});
const order = await response.json();
```

```python Python theme={null}
import requests

order_id = "<orderId>"

response = requests.post(
    f"https://staging.crossmint.com/api/2022-06-09/orders/{order_id}/payment",
    headers={
        "Content-Type": "application/json",
        "X-API-KEY": "<your-server-api-key>",
    },
    json={
        "type": "crypto-tx-id",
        "txId": "<transaction-hash>",
    },
)
order = response.json()
```

**4. Get the order status**

Call the [Get Order API](https://docs.crossmint.com/api-reference/headless/get-order.md) until `phase` is `completed`. The phase changes from `payment` to `delivery`, and then to `completed`.

`GET` `https://staging.crossmint.com/api/2022-06-09/orders/<orderId>`

```bash cURL theme={null}
curl --request GET \
    --url 'https://staging.crossmint.com/api/2022-06-09/orders/<orderId>' \
    --header 'X-API-KEY: <your-server-api-key>'
```

```javascript Node.js theme={null}
const orderId = "<orderId>";

while (true) {
    const response = await fetch(`https://staging.crossmint.com/api/2022-06-09/orders/${orderId}`, {
        headers: { "X-API-KEY": "<your-server-api-key>" },
    });
    const order = await response.json();
    console.log("Order phase:", order.phase);

    if (order.phase === "completed") {
        break;
    }
    await new Promise((resolve) => setTimeout(resolve, 3000));
}
```

```python Python theme={null}
import time

import requests

order_id = "<orderId>"

while True:
    response = requests.get(
        f"https://staging.crossmint.com/api/2022-06-09/orders/{order_id}",
        headers={"X-API-KEY": "<your-server-api-key>"},
    )
    order = response.json()
    print("Order phase:", order["phase"])

    if order["phase"] == "completed":
        break
    time.sleep(3)
```

When the order is complete, the recipient gets an email with a link to the NFT. You can also see the NFT in the [staging Crossmint wallet](https://staging.crossmint.com/user/collection): sign in with the recipient email.

## Launching in Production

<Snippet file="headless-next-steps.mdx" />

## Learn More

> [card] [Supported Currencies](https://docs.crossmint.com/checkout/headless/guides/supported-currencies.md)
>
> See the supported stablecoins by chain

> [card] [Get Order API](https://docs.crossmint.com/api-reference/headless/get-order.md)
>
> See every order field and phase

> [card] [Create Order API](https://docs.crossmint.com/api-reference/headless/create-order.md)
>
> Try the API in the playground
