Skip to content

React Native ​

Use the SDK in React Native apps (Expo or bare). The client, modules, events, and React hooks are the same as on web - you only pass a platform adapter when creating the client.

Supported features ​

FeatureReact Native
Client, session, payment methods, eventsSupported
Exchange PaySupported
Cash AppSupported
Locales, formatters, React provider and hooksSupported
WalletsNot supported
CoinbaseSupported (system auth session)
Wallet verificationNot supported

Requirements ​

  • React Native >= 0.76
  • Metro with package exports enabled - the default since React Native 0.79 / Expo SDK 53. On older setups set config.resolver.unstable_enablePackageExports = true in metro.config.js
  • react >= 18 if you use the React hooks

Install ​

bash
npx expo install @swapped/connect-sdk react-native-get-random-values react-native-url-polyfill

In a bare React Native app, use npm install with the same packages.

Import both polyfills at the very top of your entry file, before anything that imports the SDK:

ts
// index.ts
import 'react-native-get-random-values'
import 'react-native-url-polyfill/auto'

import { registerRootComponent } from 'expo'
import App from './App'

registerRootComponent(App)

Create the client ​

Pass platform: createReactNativePlatform() to createSwappedConnectClient:

ts
import { createSwappedConnectClient } from '@swapped/connect-sdk'
import { createReactNativePlatform } from '@swapped/connect-sdk/react-native'

const client = createSwappedConnectClient({
  sessionId: 'your-session-id',
  environment: 'staging', // omit or 'production' for live
  platform: createReactNativePlatform(),
})

await client.loadSession()

Create the session on your backend, as on web - see Creating a session. Never ship your secret key in the app.

Omitting modules enables Exchange Pay and Cash App. Coinbase is included automatically when you configure a system auth session on the platform adapter (see Coinbase).

Language ​

When the session does not set a language, the SDK uses the device locale. To pass the user's full list of preferred languages, use getLocales:

ts
import { getLocales } from 'expo-localization'

createReactNativePlatform({
  getLocales: () => getLocales().map(locale => locale.languageTag),
})

React ​

Wrap your screens with the same providers as on web:

tsx
import { createSwappedConnectClient } from '@swapped/connect-sdk'
import { createReactNativePlatform } from '@swapped/connect-sdk/react-native'
import {
  ExchangePayContextProvider,
  SwappedConnectProvider,
} from '@swapped/connect-sdk/react'

const client = createSwappedConnectClient({
  sessionId: 'your-session-id',
  platform: createReactNativePlatform(),
})
void client.loadSession()

export function App() {
  return (
    <SwappedConnectProvider client={client}>
      <ExchangePayContextProvider>
        <ExchangePayFlow />
      </ExchangePayContextProvider>
    </SwappedConnectProvider>
  )
}

The examples in the React track use DOM elements - swap them for View, Text, Pressable, and TextInput. Hook usage is identical.

Exchange Pay checkout ​

Follow the regular Exchange Pay flow - Core / React. To send the user to the exchange app, call openCheckout:

tsx
import { Pressable, Text } from 'react-native'
import {
  useExchangePayOrder,
  useSwappedConnectClient,
} from '@swapped/connect-sdk/react'

function OpenCheckoutButton() {
  const client = useSwappedConnectClient()
  const { order } = useExchangePayOrder()

  if (!order) return null

  return (
    <Pressable onPress={() => void client.exchangePay.openCheckout(order)}>
      <Text>Pay in app</Text>
    </Pressable>
  )
}

openCheckout tries the exchange-app link first and falls back to the web checkout link when the app is not installed. It rejects when the order has no checkout link or neither link can be opened. Show the QR code in that case, or when the user pays from another device:

  • order.checkout.qr with type: 'url' - encode value with a QR library such as react-native-qrcode-svg
  • order.checkout.qr with type: 'image' - render value as the uri of an <Image>

When the user comes back from the exchange app, order status updates automatically - no extra handling needed.

Cash App checkout ​

Follow the regular Cash App flow - Core / React, with screens wrapped in CashAppProvider. To open Cash App, call openCheckout:

tsx
import { Pressable, Text } from 'react-native'
import {
  useCashAppOrder,
  useSwappedConnectClient,
} from '@swapped/connect-sdk/react'

function OpenCashAppButton() {
  const client = useSwappedConnectClient()
  const { order } = useCashAppOrder()

  if (!order) return null

  return (
    <Pressable onPress={() => void client.cashApp.openCheckout(order)}>
      <Text>Pay with Cash App</Text>
    </Pressable>
  )
}

To pay with BTC Lightning instead, show order.invoice as a QR code, or open a Lightning wallet with Linking.openURL('lightning:' + order.invoice).

Coinbase ​

The full Coinbase flow runs on React Native with the same client.coinbase methods and React hooks as on web: connect, balances, funding tokens, network and amount, withdraw, 2FA, and the result screen. Only login is different. Instead of a popup and the hidden /gateway iframe, the SDK opens the system auth session.

Coinbase login ​

Coinbase on React Native uses the system auth session (ASWebAuthenticationSession on iOS, Chrome Custom Tabs on Android). connect() opens the Coinbase login there and returns to your app through authRedirectUrl once the user authorizes.

App setup ​

  1. Add a custom URL scheme in app.json (or app.config.js), for example "scheme": "myapp".
  2. Install expo-web-browser and expo-linking (npx expo install expo-web-browser expo-linking).
  3. Call WebBrowser.maybeCompleteAuthSession() once at startup (before your root component).
  4. Use a development build (npx expo run:ios / run:android) so the custom scheme works. Expo Go is not enough for OAuth return URLs tied to your app id.

Persist integration tokens with a secure store. The SDK storage adapter is synchronous; wrap expo-secure-store with an in-memory cache if you hydrate keys at startup.

ts
import * as WebBrowser from 'expo-web-browser'
import * as Linking from 'expo-linking'
import { createReactNativePlatform } from '@swapped/connect-sdk/react-native'

const authRedirectUrl = Linking.createURL('oauth/coinbase')

const platform = createReactNativePlatform({
  storage: yourSecureStorageAdapter,
  authRedirectUrl,
  openAuthSession: async (url, redirectUrl) => {
    const result = await WebBrowser.openAuthSessionAsync(url, redirectUrl)
    if (result.type === 'success' && result.url) {
      return { type: 'success', url: result.url }
    }
    return { type: 'cancel' }
  },
})

const client = createSwappedConnectClient({
  sessionId: 'your-session-id',
  platform,
  modules: ['coinbase', 'exchangePay', 'cashApp'],
})

Withdraw flow ​

Follow the regular Coinbase flow - Core / React, with the React example as the step-by-step walkthrough. Wrap the screen in CoinbaseProvider and derive the step from connection and withdrawal state, exactly as on web:

tsx
import { Pressable, Text } from 'react-native'
import {
  CoinbaseProvider,
  useCoinbaseConnection,
  useCoinbaseWithdrawal,
} from '@swapped/connect-sdk/react'

function CoinbaseFlow() {
  const { isConnected, isConnecting, isPopupOpen, connect } =
    useCoinbaseConnection()
  const withdrawal = useCoinbaseWithdrawal()

  const step = withdrawal.result
    ? 'done'
    : withdrawal.requires2fa ||
        withdrawal.isConfirming ||
        withdrawal.status === 'confirming'
      ? 'twofa'
      : isConnected
        ? 'form'
        : 'login'

  if (step === 'login') {
    return (
      <Pressable
        disabled={isConnecting || isPopupOpen}
        onPress={() => void connect().catch(() => undefined)}
      >
        <Text>
          {isPopupOpen ? 'Finish login in the browser…' : 'Log in with Coinbase'}
        </Text>
      </Pressable>
    )
  }
  if (step === 'form') return <WithdrawForm />
  if (step === 'twofa') return <TwoFactorStep />
  return <SuccessStep result={withdrawal.result!} />
}

export function CoinbaseScreen() {
  return (
    <CoinbaseProvider>
      <CoinbaseFlow />
    </CoinbaseProvider>
  )
}

WithdrawForm, TwoFactorStep, and SuccessStep use the same hooks as the React example (useCoinbaseBalances, useCoinbaseToken, useCoinbaseNetwork, useCoinbaseAmount, useCoinbaseFundingTokens, useCoinbaseWithdrawalCooldown, …) with View, Text, TextInput, and Pressable in place of DOM elements. A few web patterns need a native equivalent:

  • Amount inputs - use TextInput with keyboardType="decimal-pad" and onChangeText for setAmount / setAmountFiat.

  • 2FA code - TextInput with autoComplete="one-time-code". Codes are 6-7 characters, so do not limit the input to 6 digits.

  • Amount adjustment - startWithdrawal accepts an onAmountAdjusted callback that returns a promise. Resolve it from a Modal to let the user confirm or cancel the lower amount:

    tsx
    await startWithdrawal(undefined, {
      onAmountAdjusted: adjustment =>
        new Promise<boolean>(resolve => {
          // Show a Modal with adjustment.formatted.adjustedAmount;
          // call resolve(true) on confirm, resolve(false) on cancel.
          showAdjustmentModal(adjustment, resolve)
        }),
    })
  • Funding token priority - useCoinbaseFundingTokens().reorder(fromIndex, toIndex) takes indexes into selected. Up / down buttons are enough; a drag-and-drop list library is optional.

  • Restart - after a completed withdrawal, call restartSession() (or useRestartSession) before starting another payment, as on web.

Differences from web ​

TopicWebReact Native
LoginOAuth popup plus the hidden /gateway iframeSystem auth session from openAuthSession
isPopupOpen / oauth:popupOpenChangedPopup is openAuth session is open
User closes loginOAUTH_POPUP_CLOSEDconnect() resolves false, no error - offer retry
Login redirect fails (error, missing token)OAUTH_POPUP_*connect() resolves false and oauth:error fires (useOnOAuthError)
Content-Security-Policy, WALLET_GATEWAY_NOT_READYAppliesDoes not apply - no iframe
Token storageBrowser storageThe storage adapter passed to createReactNativePlatform

Everything after login - balances, networks, limits, funding tokens, cooldown, 2FA, summary, events, and errors - behaves the same as on web.

Errors ​

CodeWhenWhat to do
REACT_NATIVE_PLATFORM_REQUIREDClient created without platformPass platform: createReactNativePlatform()
REACT_NATIVE_POLYFILL_MISSINGPolyfills are not importedImport them at the top of your entry file - see Install
MODULE_NOT_SUPPORTED_ON_PLATFORMmodules lists wallets, or coinbase without auth sessionRemove wallets; configure openAuthSession and authRedirectUrl for Coinbase
CHECKOUT_URL_MISSINGopenCheckout on an order without a checkout linkShow the QR code

Other errors are the same as on web - see Client, Exchange Pay, Cash App, and Coinbase.