## WalletConnect Pay SDK

The WalletConnect Pay SDK allows wallet users to pay merchants using their crypto assets. The SDK handles payment option discovery, permit signing coordination, and payment confirmation while leveraging your wallet’s existing signing infrastructure.

## Sample Wallet

For a complete working example, check out our sample wallet implementation:

[**Sample Wallet - Kotlin**  
A reference Android wallet app demonstrating WalletConnect Pay integration.](https://github.com/reown-com/reown-kotlin/tree/develop/sample/wallet)

## Requirements

- **Min SDK**: 23 (Android 6.0)
- **Target SDK**: 36
- **JVM Target**: 11

## Installation

Add the WalletConnect Pay SDK to your project’s `build.gradle.kts` file:

```
dependencies {
    implementation("com.walletconnect:pay:1.0.0")
}
```

The version shown above may not be the latest. Check the [GitHub releases](https://github.com/reown-com/reown-kotlin/releases) for the most recent version.

**JNA Dependency Configuration** If you encounter JNA-related errors (e.g., `UnsatisfiedLinkError` or class loading issues), explicitly configure the JNA dependency:

```
implementation("com.walletconnect:pay:1.0.0") {
    exclude(group = "net.java.dev.jna", module = "jna")
}
implementation("net.java.dev.jna:jna:5.17.0@aar")
```

## Initialization

Initialize the SDK in your `Application` class or before any payment operations:

```
import com.walletconnect.pay.Pay
import com.walletconnect.pay.WalletConnectPay

WalletConnectPay.initialize(
    Pay.SdkConfig(
        apiKey = "your-api-key",        // Your WalletConnect Pay API key (optional)
        appId = "your-wcp-id",             // Your WCP ID (optional)
        packageName = "com.your.app"    // Your app's package name
    )
)
```

### Configuration Parameters

| Parameter | Type | Required | Description |
| --- | --- | --- | --- |
| `apiKey` | `String` | No* | Your WalletConnect Pay API key |
| `appId` | `String` | No* | Your WCP ID |
| `packageName` | `String` | Yes | Your application’s package name |

*Either `apiKey` or `appId` is required for authentication.

The SDK will throw `IllegalStateException` if already initialized. Call `initialize()` only once.

## Supported Networks & Tokens

WalletConnect Pay currently supports the following tokens and networks:

| Token | Network | Chain ID | CAIP-2 Format |
| --- | --- | --- | --- |
| USDC | Arbitrum | 42161 | `eip155:42161` |
| USDC | Base | 8453 | `eip155:8453` |
| USDC | Polygon | 137 | `eip155:137` |
| USDC | Ethereum | 1 | `eip155:1` |
| USDC | Optimism | 10 | `eip155:10` |
| USDC | Monad | 143 | `eip155:143` |
| USDC | Celo | 42220 | `eip155:42220` |
| USDC | BSC | 56 | `eip155:56` |
| EURC | Ethereum | 1 | `eip155:1` |
| EURC | Base | 8453 | `eip155:8453` |
| USDT0 | Arbitrum | 42161 | `eip155:42161` |
| PYUSD | Ethereum | 1 | `eip155:1` |
| PYUSD | Arbitrum | 42161 | `eip155:42161` |
| USDG | Ethereum | 1 | `eip155:1` |
| USDT | Ethereum | 1 | `eip155:1` |
| USDT | Polygon | 137 | `eip155:137` |
| USDT | BSC | 56 | `eip155:56` |

All account addresses must be provided in CAIP-10 format: `eip155:<chainId>:<address>`.

## Payment Flow

The payment flow consists of five main steps: **Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment**

### Initialize the SDK

```
import com.walletconnect.pay.Pay
import com.walletconnect.pay.WalletConnectPay

// In your Application class or before payment operations
WalletConnectPay.initialize(
    Pay.SdkConfig(
        appId = "your-wcp-id",            // Your WCP ID
        packageName = "com.your.app"
    )
)

// Check if initialized
if (WalletConnectPay.isInitialized) {
    // SDK ready for use
}
```

### Get Payment Options

When a user scans a payment QR code or opens a payment link, fetch available payment options:

```
val result = WalletConnectPay.getPaymentOptions(
    paymentLink = "https://pay.walletconnect.com/pay_xxx",
    accounts = listOf(
        "eip155:1:0xYourAddress",      // Ethereum
        "eip155:8453:0xYourAddress",   // Base
        "eip155:10:0xYourAddress"      // Optimism
    )
)

result.onSuccess { response ->
    // Payment metadata
    val paymentId = response.paymentId
    val paymentInfo = response.info  // Merchant info, amount, expiry

// Available payment options
    val options = response.options
    options.forEach { option ->
        println("Option: \\${option.id}")
        println("Amount: \\${option.amount.value} \\${option.amount.unit}")
        println("Account: \\${option.account}")
        println("Estimated transactions: \\${option.estimatedTxs}")
        println("Requires IC: \\${option.collectData != null}")
    }
}.onFailure { error ->
    handleError(error)
}
```

### Collect User Data (If Required)

After the user selects an option, check for `collectData` on it. If present, collect the data **before** fetching the required actions.

## Embedded Data Collection Form

When a payment requires user information (e.g., for Travel Rule compliance), the SDK returns a `collectData` field on individual payment options. Each option may independently require data collection — some options may require it while others don’t. The form is loaded from `selectedOption.collectData.url` and embedded in your wallet (a WebView on mobile, an iframe on web). It handles field rendering, validation, Terms & Conditions and Privacy Policy acceptance, and submits data directly to the backend. Collect this data **before** fetching the required actions.

### Recommended Flow

1. Call `getPaymentOptions` and display all available options to the user
2. Show a visual indicator (e.g., “Info required” badge) on options where `option.collectData` is present
3. When the user selects an option, check `selectedOption.collectData`
4. If present, load `selectedOption.collectData.url` in the embedded form
5. Optionally append query parameters to the form URL — `prefill` (known user data), `theme`, and `themeVariables` (appearance). See [Form URL parameters](https://docs.walletconnect.com/payments/wallets/standalone/kotlin#form-url-parameters) below. Use proper URL building so existing query parameters are preserved.
6. Listen for completion messages: `IC_COMPLETE` (success) or `IC_ERROR` (failure)
7. On `IC_COMPLETE`, continue the flow — fetch the required actions, sign, and confirm the payment.

### Decision Matrix

| Response `collectData` | `option.collectData` | Behavior |
| --- | --- | --- |
| present | present | Option requires IC — use `option.collectData.url` |
| present | `null` | Option does NOT require IC (others might) — skip IC for this option |
| `null` | `null` | No IC needed for any option |

### Form URL parameters

The form URL accepts the following optional query parameters. Append them to `selectedOption.collectData.url` before loading it, preserving any existing query parameters.

| Parameter | Format | Description |
| --- | --- | --- |
| `prefill` | base64url-encoded JSON | Pre-populates known user fields so the user doesn’t re-enter them. Keys must match the `required` fields from `collectData.schema` (e.g. `fullName`, `dob`, `pobAddress`). |
| `theme` | `light` or `dark` | Sets the form’s base color mode. |
| `themeVariables` | base64url-encoded JSON | Overrides design tokens to match your brand — font, font size, select colors, button border radius, and input border radius. Generate and export this value from the [WalletConnect Pay Dashboard](https://dashboard.walletconnect.com/). |

`collectData.schema` is a JSON schema **string** — parse it and read its `required` array to discover the field keys for `prefill`. For example, a `required` array of `['fullName', 'dob', 'pobAddress']` maps to a prefill object of `{'fullName': '...', 'dob': '...', 'pobAddress': '...'}`.

### Customizing the form appearance

`theme` and `themeVariables` are optional and independent — pass either, both, or neither:

- **`theme`** switches the form between `light` and `dark` base color modes. Match it to your wallet’s active mode for a seamless transition.
- **`themeVariables`** applies brand-level overrides (font, font size, select colors, button border radius, and input border radius). Generate the theme in the [WalletConnect Pay Dashboard](https://dashboard.walletconnect.com/), export it as a base64url string, and append it to the form URL verbatim — you don’t need to encode it at runtime.

### Get Required Actions

After the user selects a payment option (and any required data collection has completed), get the wallet RPC actions needed to complete the payment:

```
val actionsResult = WalletConnectPay.getRequiredPaymentActions(
    paymentId = paymentId,
    optionId = selectedOption.id
)

actionsResult.onSuccess { actions ->
    actions.forEach { action ->
        when (action) {
            is Pay.RequiredAction.WalletRpc -> {
                val rpcAction = action.action
                // rpcAction.chainId - e.g., "eip155:8453"
                // rpcAction.method - e.g., "eth_signTypedData_v4" or "personal_sign"
                // rpcAction.params - JSON string with signing parameters
            }
        }
    }
}.onFailure { error ->
    handleError(error)
}
```

### Sign Actions

Sign each action using your wallet’s signing implementation:

```
val signatures = actions.map { action ->
    when (action) {
        is Pay.RequiredAction.WalletRpc -> {
            val rpc = action.action
            when (rpc.method) {
                "eth_signTypedData_v4" -> wallet.signTypedData(rpc.chainId, rpc.params)
                "personal_sign" -> wallet.personalSign(rpc.chainId, rpc.params)
                "eth_sendTransaction" -> wallet.sendTransaction(rpc.chainId, rpc.params)
                else -> throw UnsupportedOperationException("Unsupported method: \\${rpc.method}")
            }
        }
    }
}
```

### Confirm Payment

Submit the signatures to complete the payment:

```
val confirmResult = WalletConnectPay.confirmPayment(
    paymentId = paymentId,
    optionId = selectedOption.id,
    signatures = signatures
)

confirmResult.onSuccess { response ->
    when (response.status) {
        Pay.PaymentStatus.SUCCEEDED -> {
            // Payment completed successfully
        }
        Pay.PaymentStatus.PROCESSING -> {
            // Payment is being processed
            // The SDK automatically polls until final status
        }
        Pay.PaymentStatus.FAILED -> {
            // Payment failed
        }
        Pay.PaymentStatus.EXPIRED -> {
            // Payment expired
        }
        Pay.PaymentStatus.REQUIRES_ACTION -> {
            // Additional action required
        }
        Pay.PaymentStatus.CANCELLED -> {
            // Payment cancelled by user
        }
    }
}.onFailure { error ->
    handleError(error)
}
```

## Data Collection Implementation

When `selectedOption.collectData.url` is present, display the URL in a WebView. The WebView handles form rendering, validation, and T&C acceptance.

### Data Collection Best Practices

- **Display prominently**: Show the form full-screen or as a prominent modal so users can interact with it easily
- **Loading indicator**: Show a loading indicator while the form loads
- **Handle errors**: Listen for `IC_ERROR` messages and display a user-facing error message with an option to retry
- **External links**: Open Terms & Conditions and Privacy Policy links in the system browser rather than navigating within the form
- **Domain restriction**: Only allow navigation to WalletConnect pay domains and HTTPS URLs
- **Back navigation**: Handle back/dismiss gracefully — confirm cancellation with the user before closing the form mid-flow
- **Keyboard behavior**: Test that the soft keyboard appears and behaves correctly when users tap on form inputs
- **Theme to match your brand**: Pass `theme=light` or `theme=dark` to match your wallet’s active color mode, and apply brand tokens with `themeVariables` exported from the [WalletConnect Pay Dashboard](https://dashboard.walletconnect.com/).

## Complete Example

Here’s a complete implementation example using a ViewModel:

```
import com.walletconnect.pay.Pay
import com.walletconnect.pay.WalletConnectPay
import kotlinx.coroutines.launch

class PaymentViewModel : ViewModel() {

fun initializeSdk() {
            WalletConnectPay.initialize(
                Pay.SdkConfig(
                    appId = "your-wcp-id",            // Your WCP ID
                    packageName = "com.your.app"
                )
            )
        }

fun processPayment(paymentLink: String, walletAddress: String) {
        viewModelScope.launch {
            // Step 1: Get payment options
            val optionsResult = WalletConnectPay.getPaymentOptions(
                paymentLink = paymentLink,
                accounts = listOf(
                    "eip155:1:$walletAddress",
                    "eip155:8453:$walletAddress",
                    "eip155:10:$walletAddress"
                )
            )

optionsResult.onSuccess { response ->
                val paymentId = response.paymentId
                val selectedOption = response.options.first()

// Step 2: Collect data if required for selected option (via WebView).
                // IC must happen BEFORE fetching the required actions — the WebView
                // submits the data directly to the backend.
                selectedOption.collectData?.url?.let { webViewUrl ->
                    // Show WebView and wait for IC_COMPLETE
                    showDataCollectionWebView(webViewUrl)
                    return@launch // Resume after WebView completes
                }

// Step 3: Get required actions
                val actionsResult = WalletConnectPay.getRequiredPaymentActions(
                    paymentId = paymentId,
                    optionId = selectedOption.id
                )

actionsResult.onSuccess { actions ->
                    // Step 4: Sign actions
                    val signatures = signActions(actions)

// Step 5: Confirm payment
                    val confirmResult = WalletConnectPay.confirmPayment(
                        paymentId = paymentId,
                        optionId = selectedOption.id,
                        signatures = signatures
                    )

confirmResult.onSuccess { confirmation ->
                        handlePaymentStatus(confirmation.status)
                    }.onFailure { error ->
                        handleError(error)
                    }
                }.onFailure { error ->
                    handleError(error)
                }
            }.onFailure { error ->
                handleError(error)
            }
        }
    }

private suspend fun signActions(actions: List<Pay.RequiredAction>): List<String> {
        return actions.map { action ->
            when (action) {
                is Pay.RequiredAction.WalletRpc -> {
                    // Implement signing logic using your wallet
                    signWithWallet(action.action)
                }
            }
        }
    }

private fun handlePaymentStatus(status: Pay.PaymentStatus) {
        when (status) {
            Pay.PaymentStatus.SUCCEEDED -> showSuccess()
            Pay.PaymentStatus.PROCESSING -> showProcessing()
            Pay.PaymentStatus.FAILED -> showFailure()
            Pay.PaymentStatus.EXPIRED -> showExpired()
            Pay.PaymentStatus.REQUIRES_ACTION -> { /* Handle additional actions */ }
            Pay.PaymentStatus.CANCELLED -> showCancelled()
        }
    }
}
```

## API Reference

**WalletConnectPay** Main entry point for the Pay SDK (singleton object).

### Properties

| Property | Type | Description |
| --- | --- | --- |
| `isInitialized` | `Boolean` | Whether the SDK has been initialized |

### Methods

| Method | Description |
| --- | --- | --- |
| `initialize(config: Pay.SdkConfig)` | Initialize the SDK |
| `getPaymentOptions(paymentLink, accounts)` | Get available payment options |
| `getRequiredPaymentActions(paymentId, optionId)` | Get actions requiring signatures |
| `confirmPayment(paymentId, optionId, signatures)` | Confirm and finalize payment |

## Error Handling

The SDK provides typed errors for different failure scenarios:

**GetPaymentOptionsError**

| Error | Description |
| --- | --- |
| `InvalidPaymentLink` | Invalid payment link format |
| `PaymentExpired` | Payment has expired |
| `PaymentNotFound` | Payment ID doesn’t exist |
| `InvalidRequest` | Invalid request parameters |
| `InvalidAccount` | Invalid account format |
| `ComplianceFailed` | Compliance check failed |
| `Http` | Network error |
| `InternalError` | Server error |

**Example Error Handling**

```
val result = WalletConnectPay.getPaymentOptions(paymentLink, accounts)

result.onFailure { error ->
    when (error) {
        is Pay.GetPaymentOptionsError.InvalidPaymentLink -> {
            showError("Invalid payment link")
        }
        is Pay.GetPaymentOptionsError.PaymentExpired -> {
            showError("Payment has expired")
        }
        is Pay.GetPaymentOptionsError.PaymentNotFound -> {
            showError("Payment not found")
        }
        is Pay.GetPaymentOptionsError.InvalidAccount -> {
            showError("Invalid account address")
        }
        is Pay.GetPaymentOptionsError.ComplianceFailed -> {
            showError("Compliance check failed")
        }
        is Pay.GetPaymentOptionsError.Http -> {
            showError("Network error: \\${error.message}")
        }
        else -> {
            showError("An error occurred: \\${error.message}")
        }
    }
}
```
