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

# Crypto withdrawal (End-to-end)

> Support crypto withdrawals in a single Payment Widget session that handles account selection, destination address, quoting, the Travel Rule and order status.

The Payment Widget's `withdrawal` flow handles the entire crypto withdrawal in one session: the user picks the origin Uphold account, chooses the asset and network, enters the destination address, enters the amount, reviews a live quote, provides any Travel Rule information required, confirms the transaction and sees its status — all without your backend creating a quote, a Travel Rule session or the transaction.

> [!NOTE]
>
> If you need to build the amount entry and review screens yourself, see the [Select for Withdrawal](https://developer.uphold.com/developer-guides/crypto-transfers/withdrawal/via-payment-widget/select-for-withdrawal.md) guide instead. To compare all flows, see [Flows](https://developer.uphold.com/widgets/payment/flows.md).

## Prerequisites

* The user has [completed onboarding](https://developer.uphold.com/developer-guides/user-onboarding/overview.md) and has the required capabilities enabled.
* The Payment Widget is set up in your frontend. See [Installation and setup](https://developer.uphold.com/widgets/payment/installation-and-setup.md).
* `@uphold/enterprise-payment-widget-web-sdk` is on version 0.19.0 or later.

## Walkthrough

```mermaid theme={null}
sequenceDiagram
  autonumber
  participant Usr as User
  participant U as Your App
  participant B as Your Backend
  participant P as Payment Widget
  participant A as Uphold
  participant N as Blockchain Network

  Usr->>U: Start crypto withdrawal
  U->>B: Create widget session
  B->>A: Create widget session (withdrawal)
  A-->>B: { session }
  B-->>U: { session }
  U->>P: Initialize widget
  Usr->>P: Select origin account, select crypto, asset and network, enter address and amount, review quote, confirm
  opt Quote requires the Travel Rule
    P->>A: Create Travel Rule widget session
    Usr->>P: Submit Travel Rule information
    P->>A: Wait for the request for information to resolve
  end
  P->>A: Create transaction
  A-->>P: { transaction }
  A-->>B: webhook: transaction.created (processing)
  P-->>U: complete { transaction, trigger }
  A->>N: Broadcast withdrawal
  N-->>A: Confirmations reached
  A-->>B: webhook: transaction.status-changed (completed/failed)
  B-->>Usr: Notify the user
```

***

## Complete the withdrawal in the widget

The widget session takes the user from account and destination selection through the amount, quote, Travel Rule and confirmation.

### Create a widget session

Call [Create widget session](https://developer.uphold.com/rest-apis/widgets-api/payment/create-session.md) to start the `withdrawal` flow. No `data` is required — the widget gathers everything from the user. Use `options` to customize the Widget's `theme` and `layout`, as well as the flow itself. See the example [here](https://developer.uphold.com/widgets/payment/installation-and-setup.md#1-create-a-session-on-your-backend) and the [SDK reference](https://developer.uphold.com/widgets/payment/sdk-reference.md#options) for all available options.

By default, the end-to-end flows offer bank, card and crypto. To offer crypto only, set `paymentMethods` to `crypto`:

```http theme={null}
POST /widgets/payment/sessions
{
  "flow": "withdrawal",
  "options": {
    "paymentMethods": [{ "type": "crypto" }]
  }
}
```

Withdrawals can be sourced from any account. If the origin account is not in the asset being withdrawn, the balance is converted at the time of the transaction using Uphold's prevailing rate.

> [!NOTE]
>
> In the end-to-end flows, use `availableAssets` to restrict the assets the user can pick. It replaces any `assets` filter set on the `crypto` payment method.

The response contains a `session` object with a `url` field that loads the widget. Return `response.session` to your frontend as is.

```json theme={null}
{
  "session": {
    "url": "https://payment-widget.enterprise.uphold.com/?sessionToken=..."
  }
}
```

### Set up the widget

```javascript Web SDK [expandable] theme={null}
import { PaymentWidget } from '@uphold/enterprise-payment-widget-web-sdk';

const initializeWithdrawalWidget = async (session) => {
  const widget = new PaymentWidget<'withdrawal'>(session, { debug: true });

  widget.on('complete', (event) => {
    console.log('Complete', JSON.stringify(event.detail.value));
    widget.unmount();
  });

  widget.on('cancel', () => {
    console.log('Cancelled');
    widget.unmount();
  });

  widget.on('error', (event) => {
    console.error('Error', event.detail.error);
    widget.unmount();
  });

  widget.mountIframe(document.getElementById('payment-container'));
};
```

```html Without SDK [expandable] theme={null}
<div id="payment-container"></div>

<script>
  // session is `response.session` from your backend
  async function initializeWithdrawalWidget(session) {
    const container = document.getElementById('payment-container');
    const sessionOrigin = new URL(session.url).origin;

    const iframe = document.createElement('iframe');
    iframe.src = session.url;
    // camera permission enables scanning the destination address from a QR code
    iframe.setAttribute('allow', "clipboard-write 'src'; clipboard-read 'src'; payment 'src'; camera 'src';");
    iframe.style.width = '100%';
    iframe.style.height = '100%';
    iframe.style.border = 'none';

    function teardown() {
      window.removeEventListener('message', onMessage);
      iframe.remove();
    }

    function onMessage(event) {
      if (event.origin !== sessionOrigin) return;

      switch (event.data?.type) {
        case 'load':
          iframe.contentWindow.postMessage({ options: {}, type: 'init' }, sessionOrigin);
          break;
        case 'ready':
          break;
        case 'complete':
          console.log('Complete', JSON.stringify(event.data.value));
          teardown();
          break;
        case 'cancel':
          console.log('Cancelled');
          teardown();
          break;
        case 'error':
          console.error('Error', event.data.error);
          teardown();
          break;
      }
    }

    window.addEventListener('message', onMessage);
    container.appendChild(iframe);
  }
</script>
```

> [!NOTE]
>
> Both examples above are for web applications — either creating the iframe yourself or letting the SDK do it. For native apps using a WebView, see [Native apps with the Web SDK](https://developer.uphold.com/widgets/payment/installation-and-setup.md#native-apps-with-the-web-sdk) for the SDK's native-bundling pattern, or [Setup without the SDK](https://developer.uphold.com/widgets/payment/installation-and-setup.md#setup-without-the-sdk) for the no-SDK approach that loads the session `url` directly as the WebView's top-level page.

> [!NOTE]
>
> The destination address field offers a **Scan QR code** action only when the device has a camera and the Widget is allowed to use it. The Web SDK's `mountIframe()` grants `camera` from v0.19.0 onwards. Without the SDK, add `camera 'src'` to the iframe `allow` attribute, as in the example above. For the Permissions Policy, HTTPS and native WebView requirements, see [Allow camera access for QR code scanning](https://developer.uphold.com/widgets/payment/installation-and-setup.md#3-allow-camera-access-for-qr-code-scanning). When the camera is unavailable, the user types or pastes the address instead.

### Handle the complete event

The `complete` event fires when the user closes the terminal status screen. Its value is the authorization result — the transaction plus what triggered the completion, the same as for [card withdrawals](https://developer.uphold.com/developer-guides/card-transfers/withdrawal/via-payment-widget/end-to-end.md#handle-the-complete-event).

```javascript Web SDK theme={null}
widget.on('complete', (event) => {
  const { transaction, trigger } = event.detail.value;

  if (trigger.reason === 'transaction-status-changed') {
    if (transaction.status === 'completed') {
      handleWithdrawalCompleted(transaction);
    } else if (transaction.status === 'failed') {
      handleWithdrawalFailed(transaction);
    }
  } else if (trigger.reason === 'max-retries-reached') {
    // Polling timed out — the transaction is still processing
    handleWithdrawalPending(transaction);
  }

  widget.unmount();
});
```

```javascript Without SDK theme={null}
// Inside the onMessage switch from Set up the widget
case 'complete': {
  const { transaction, trigger } = event.data.value;

  if (trigger.reason === 'transaction-status-changed') {
    if (transaction.status === 'completed') {
      handleWithdrawalCompleted(transaction);
    } else if (transaction.status === 'failed') {
      handleWithdrawalFailed(transaction);
    }
  } else if (trigger.reason === 'max-retries-reached') {
    handleWithdrawalPending(transaction);
  }

  teardown();
  break;
}
```

> [!WARNING]
>
> `complete` is only emitted once the user closes the status screen. A user who abandons the widget there leaves a real transaction behind that your app never hears about. Treat webhooks as the source of truth and `complete` as a UX signal.

### Handle cancellations

The `cancel` event fires when the user closes the widget before confirming, or after the Travel Rule verification failed. No transaction exists at that point.

```javascript theme={null}
widget.on('cancel', () => {
  widget.unmount();
  // Return the user to the previous screen
});
```

### Handle errors

> [!WARNING]
>
> The Payment Widget handles most errors internally. For unrecoverable errors, the widget fires an `error` event. It is the host application's responsibility to handle these events, present an error message to the user, and unmount the widget.

The widget recovers from address validation, quote and transaction failures internally by returning the user to the relevant screen with an appropriate action — correct the address, change the amount, change the payment method, or try again. Insufficient balance is handled this way rather than as an `error` event.

The Travel Rule step is the exception: when the quote requires the [Travel Rule](https://developer.uphold.com/developer-guides/travel-rule/overview.md), the Widget collects the information itself, and if that step fails and the user closes the Widget instead of trying again, the Widget emits an `error` event.

> [!TIP]
>
> To trigger a Travel Rule requirement in sandbox, use a GB user and withdraw 30 XRP to an external address.

***

## Monitor for settlement

* Webhook events (recommended):
  * [core.transaction.created](https://developer.uphold.com/rest-apis/core-api/transactions/webhooks/transaction-created.md)
    * `status: processing` → initiated but not yet broadcast
  * [core.transaction.status-changed](https://developer.uphold.com/rest-apis/core-api/transactions/webhooks/transaction-status-changed.md)
    * `status: completed` → broadcast and confirmed
    * `status: on-hold` → transaction checks paused (e.g., pending RFIs)
    * `status: failed` → transaction failed, check `statusDetails` for more info
* Polling (fallback): [Get transaction](https://developer.uphold.com/rest-apis/core-api/transactions/get-transaction.md)

Unlike a deposit hold, a withdrawal transaction is created right away, so failures surface after creation — either when the Travel Rule payload is rejected at creation time, or when the counterparty VASP later rejects the data.

After the transaction is created, the counterparty VASP has a window to review the Travel Rule data. If the data is rejected, Uphold emits a `core.transaction.status-changed` webhook with `status: failed` and `statusDetails.reason: travel-rule-verification-failed`. Common causes are the transaction being created before the RFI was fully resolved, or the beneficiary VASP being unrecognized or invalid. Notify the user and ask them to retry with a different destination.

## Sample transaction

In a successful crypto withdrawal, the origin is the source account and the destination is a `crypto-address` node reflecting the recipient's on-chain address.

```json [expandable] theme={null} theme={null}
{
  "transaction": {
    "id": "623000c8-9bdf-4a2b-aa3d-6a6b44a7f6a0",
    "origin": {
      "amount": "0.00121023",
      "asset": "BTC",
      "rate": "0.00002629253259492961",
      "node": {
        "type": "account",
        "id": "a00507fe-628c-4f27-ae81-e1c40b2a8fb8",
        "ownerId": "e4ce04dc-67b7-4e9f-af91-482cb6f9fc4a"
      }
    },
    "destination": {
      "amount": "0.00121023",
      "asset": "BTC",
      "rate": "1",
      "node": {
        "type": "crypto-address",
        "address": "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
        "network": "bitcoin",
        "execution": {
          "mode": "onchain"
        }
      }
    },
    "fees": [],
    "status": "processing",
    "quotedAt": "2024-07-24T15:02:39Z",
    "createdAt": "2024-07-24T15:22:39Z",
    "updatedAt": "2024-07-24T15:22:39Z",
    "denomination": {
      "amount": "100.00",
      "asset": "GBP",
      "target": "origin",
      "rate": "0.00001210225938333485"
    }
  }
}
```

### Execution modes

Crypto withdrawals are executed in one of the following modes, indicated by `destination.node.execution.mode`:

> [accordion] On-chain
>
> The transaction is broadcast to the blockchain network. `destination.node.execution.mode` is `onchain`, and `destination.node.execution.transactionHash` is set once the transaction is completed.

> [accordion] Off-chain
>
> When both the sender and recipient are Uphold users, the transfer is processed within Uphold's infrastructure instead of the blockchain. This avoids network fees and is faster than on-chain processing.
>
> Each side sees the transfer from its own perspective:
>
> | | Sender | Recipient |
> | - | - | - |
> | Seen as | Withdrawal | Deposit |
> | `origin.node.type` | `account` | `crypto-address` |
> | `destination.node.type` | `crypto-address` | `account` |
>
> When both users belong to the same organization, the execution also identifies the counterpart account: `destination.node.execution.accountOwnerId` and `destination.node.execution.accountId` for the sender, and `origin.node.execution.accountOwnerId` and `origin.node.execution.accountId` for the recipient.
>
> Because funds move between Uphold accounts, the assets may differ from an on-chain transfer:
>
> * **Sender:** `destination.asset` is the asset of the recipient account associated with the address, which may differ from the one in the quote.
> * **Recipient:** `origin.asset` is the asset of the sender's account, which may differ from the network's asset or even be one the network doesn't support, such as a fiat asset.

> [accordion] Simulated
>
> Used in development environments for testing. The transaction appears processed without affecting blockchain state, although user balances are updated. `destination.node.execution.mode` is `simulated`.

## Notify the user

Display an in-app confirmation when the transaction is `completed`, and send an email if applicable.

> [!TIP]
>
> You now support end-to-end crypto withdrawals via the Payment Widget.
