# Checkout

Checkout offers a more tailored experience for when you require a user to transfer funds to your app. It is ideal
for use cases where a user is purchasing an item and may not be experienced with crypto/wallets.

Flow:
1. Summary of the transfer
2. Optional [ramps](https://moss.megaeth.com/developers/concepts/ramps) flow if they require funds
3. Confirmation

You can tailor the experience by adding line items and a checkout reference.

```ts title="Pure JS"
import { mega } from '@megaeth-labs/wallet-sdk';

// Checkout takes its own config, so it works without initialise.
const result = await mega.checkout({
    config: { network: 'mainnet' },
    amountUSD: '9.99',
    destination: '0xFD8D73c93385271d06138FA0Ff6E9c639C3Bd8b0',
    reference: 'A-2481',
});

if (result.status === 'approved') {
    console.log('Paid in transaction', result.hash);
}
```

```tsx title="React"
import { useCheckout } from '@megaeth-labs/wallet-sdk-react';

// Config comes from the surrounding MegaProvider.
export default function PayButton() {
    const { mutate: checkout, isPending, data } = useCheckout();

    return (
        <>
            <button onClick={() => checkout({ amountUSD: '9.99' })} disabled={isPending}>
                Pay $9.99
            </button>
            {data?.status === 'approved' && <p>Paid: {data.hash}</p>}
        </>
    );
}
```

```tsx title="Wagmi"
import type { MegaWalletProvider } from '@megaeth-labs/wallet-wagmi-connector';
import { useMutation } from '@tanstack/react-query';
import { useAccount } from 'wagmi';

export default function PayButton() {
    const { connector } = useAccount();

    const { mutate: checkout, isPending, data } = useMutation({
        mutationFn: async () => {
            const provider = (await connector?.getProvider()) as MegaWalletProvider;
            return provider.checkout({ amountUSD: '9.99' });
        },
    });

    return (
        <>
            <button onClick={() => checkout()} disabled={!connector || isPending}>
                Pay $9.99
            </button>
            {data?.status === 'approved' && <p>Paid: {data.hash}</p>}
        </>
    );
}
```

```ts
interface CheckoutRequest {
    amountUSD: string;
    destination?: `0x${string}`;
    tokenAddress?: `0x${string}` | 'native';
    reference?: string;
    lineItems?: { amountUSD: string; label: string }[];
    config?: Config; // Pure JS only
}

interface CheckoutResult {
    status: 'approved' | 'cancelled' | 'error';
    error?: string;
    address?: `0x${string}`;
    hash?: `0x${string}`;
    tokenAmount?: string;
    usdAmount?: string;
    destination?: `0x${string}`;
}
```

## Confirming a Purchase
The response from the checkout method contains the `hash` of the transaction which you can confirm on chain using
your own techniques and requirements.

We also offer an endpoint which can be called from your server with the result object to confirm the purchase:

```ts
async function confirmCheckout(result) {
    const response = await fetch(
        'https://wallet-api.megaeth.com/v1/activity/verify-checkout?network=mainnet',
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                address: result.address,
                hash: result.hash,
                tokenAmount: result.tokenAmount,
                usdAmount: result.usdAmount,
                destination: result.destination,
            }),
        },
    );

    return response.ok; // 200 => verified, 4xx => rejected
}
```

The endpoint re-reads the transaction on chain and only returns `200` when all of these pass:

- The transaction exists and succeeded
- It landed in the last 30 seconds
- It moved exactly `tokenAmount`
- The hash hasn't been verified before, so the same result can't be used for two orders

The endpoint confirms the transaction matches the result you send, not your order, so check that `destination` is
your address and the amount is what you charged before calling it.

Anything else returns `400` with the reason: `Transaction not found`, `Transaction was not successful`,
`Transaction is too old to verify`, `Transaction does not match the checkout details` or
`Transaction has already been verified`. Use `?network=testnet` for testnet payments.
