> ## Documentation Index
> Fetch the complete documentation index at: https://walletconnect-pay-docs-wcagent-expires-at-seconds-warning-3.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# WalletConnect Pay via WalletKit - Flutter

> Integrate WalletConnect Pay through WalletKit for a unified payment experience in your Flutter wallet.

This documentation covers integrating WalletConnect Pay through ReownWalletKit. This approach provides a unified API where Pay is automatically initialized alongside WalletKit, simplifying the integration for wallet developers.

## Sample Wallet

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

<Card title="Sample Wallet - Flutter (WalletKit)" icon="github" href="https://github.com/reown-com/reown_flutter/tree/develop/packages/reown_walletkit/example">
  A reference Flutter wallet app demonstrating WalletConnect Pay via WalletKit.
</Card>

<Tip>
  **Using AI for Integration?** If you're using an AI IDE or assistant to help with integration, you can provide it with our comprehensive [AI integration prompt](/payments/wallets/walletkit/ai-prompts/flutter) for better context and guidance.
</Tip>

## Requirements

* Flutter 3.0+
* iOS 13.0+
* Android API 23+
* ReownWalletKit

## Pre-Requisites

In order to use your WalletConnect Pay, you need to obtain a WCP ID for your project from the [WalletConnect Dashboard](https://dashboard.walletconnect.com).

### How to obtain a WCP ID

1. Navigate to the [WalletConnect Dashboard](https://dashboard.walletconnect.com).
2. Select the project that is associated with your wallet (as in, the projectId that is being used for your wallet's WalletConnect integration).

<img src="https://mintcdn.com/walletconnect-pay-docs-wcagent-expires-at-seconds-warning-3/X2LLMEzkDo-z-70t/images/app-id-1.png?fit=max&auto=format&n=X2LLMEzkDo-z-70t&q=85&s=af223a65735ad55c910b535648678b66" alt="Select the project on WalletConnect Dashboard" width="3020" height="1540" data-path="images/app-id-1.png" />

3. Click on the "Get Started" button to get a WCP ID associated with your project.
4. The Dashboard will now show the WCP ID associated with your project.
5. Click on the three dots on the right of the WCP ID and select "Copy WCP ID". You will be using this for your wallet's WalletConnect Pay integration.

<img src="https://mintcdn.com/walletconnect-pay-docs-wcagent-expires-at-seconds-warning-3/X2LLMEzkDo-z-70t/images/app-id-2.png?fit=max&auto=format&n=X2LLMEzkDo-z-70t&q=85&s=840d3de4c2aaf648b34fbbb9d66d9301" alt="Copy WCP ID from WalletConnect Dashboard" width="3020" height="1540" data-path="images/app-id-2.png" />

## Installation

Add `reown_walletkit` to your `pubspec.yaml`:

```yaml theme={null}
dependencies:
  reown_walletkit: ^1.4.0
```

Then run:

```bash theme={null}
flutter pub get
```

WalletConnectPay is automatically included as a dependency of ReownWalletKit.

<Info>
  Check the [pub.dev page](https://pub.dev/packages/reown_walletkit) for the latest version.
</Info>

## Initialization

The `WalletConnectPay` client is automatically initialized during `ReownWalletKit.init()`. No additional setup is required.

```dart theme={null}
import 'package:reown_walletkit/reown_walletkit.dart';

final walletKit = await ReownWalletKit.createInstance(
  projectId: 'YOUR_PROJECT_ID',
  metadata: PairingMetadata(
    name: 'My Wallet',
    description: 'My Wallet App',
    url: 'https://mywallet.com',
    icons: ['https://mywallet.com/icon.png'],
  ),
);
```

## Accessing the Pay Client

You can access the `WalletConnectPay` instance directly:

```dart theme={null}
final payClient = walletKit.pay;
```

## Payment Link Detection

Detect if a URI is a payment link before processing:

```dart theme={null}
if (walletKit.isPaymentLink(uri)) {
  // Handle as payment. See [Get Payment Options] section
} else {
  // Handle as regular WalletConnect pairing
  await walletKit.pair(uri: Uri.parse(uri));
}
```

## Payment Flow

The payment flow consists of five main steps:

**Detect Payment Link -> Get Options -> Get Actions -> Sign Actions -> Confirm Payment**

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Wallet
    participant WebView
    participant WalletKit as WalletKit.Pay
    participant Backend as WalletConnect Pay

    User->>Wallet: Scan QR / Open payment link
    Wallet->>WalletKit: isPaymentLink(uri)
    WalletKit-->>Wallet: true
    Wallet->>WalletKit: getPaymentOptions(request)
    WalletKit->>Backend: Fetch payment options
    Backend-->>WalletKit: Payment options + merchant info
    WalletKit-->>Wallet: PaymentOptionsResponse
    Wallet->>User: Display payment options
    
    User->>Wallet: Select payment option
    Wallet->>WalletKit: getRequiredPaymentActions(request)
    WalletKit->>Backend: Get signing actions
    Backend-->>WalletKit: Required wallet RPC actions
    WalletKit-->>Wallet: List of actions to sign
    
    Wallet->>User: Request signature(s)
    User->>Wallet: Approve & sign
    
    alt Data collection required
        Wallet->>WebView: Load collectDataAction.url in WebView
        WebView->>User: Display data collection form
        User->>WebView: Fill form & accept T&C
        WebView-->>Wallet: IC_COMPLETE message
    end
    
    Wallet->>WalletKit: confirmPayment(request)
    WalletKit->>Backend: Submit payment
    Backend-->>WalletKit: Payment status
    WalletKit-->>Wallet: ConfirmPaymentResponse
    Wallet->>User: Show result
```

<Steps>
  <Step title="Get Payment Options" titleSize="h3">
    Retrieve available payment options for a payment link:

    ```dart theme={null}
    final response = await walletKit.getPaymentOptions(
      request: GetPaymentOptionsRequest(
        paymentLink: 'https://pay.walletconnect.com/pay_123',
        accounts: ['eip155:1:0x...', 'eip155:137:0x...'], // Wallet's CAIP-10 accounts
        includePaymentInfo: true,
      ),
    );

    print('Payment ID: ${response.paymentId}');
    print('Options available: ${response.options.length}');

    if (response.info != null) {
      print('Amount: ${response.info!.amount.formatAmount()}');
      print('Merchant: ${response.info!.merchant.name}');
    }

    // Check if data collection is required
    if (response.collectData != null) {
      print('Data collection required: ${response.collectData!.fields.length} fields');
    }
    ```
  </Step>

  <Step title="Get Required Payment Actions" titleSize="h3">
    Get the required wallet actions for a selected payment option:

    ```dart theme={null}
    final actions = await walletKit.getRequiredPaymentActions(
      request: GetRequiredPaymentActionsRequest(
        optionId: 'option-id',
        paymentId: 'payment-id',
      ),
    );

    // Process each action (e.g., sign transactions)
    for (final action in actions) {
      final walletRpc = action.walletRpc;
      print('Chain ID: ${walletRpc.chainId}');
      print('Method: ${walletRpc.method}');

      // Dispatch based on walletRpc.method — see Sign Actions below
    }
    ```

    <Note>
      Payment options may include multiple actions with different RPC methods. For example, a Permit2 payment where the user lacks sufficient allowance returns two actions: an `eth_sendTransaction` to approve the token allowance, followed by an `eth_signTypedData_v4` to sign the Permit2 transfer. Your wallet must check `action.walletRpc.method` and dispatch to the appropriate handler. For full implementation guidance, see [USDT support](/payments/wallets/token-chain-support/usdt-support).
    </Note>
  </Step>

  <Step title="Collect User Data (If Required)" titleSize="h3">
    Some payments may require additional user data:

    ## WebView-Based Data Collection

    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.

    ### Recommended Flow (Per-Option)

    The recommended approach is to display all payment options upfront, then handle data collection only when the user selects an option that requires it:

    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, open `selectedOption.collectData.url` in a WebView within your wallet
    5. Optionally append a `prefill=<base64-json>` query parameter with known user data (e.g., name, date of birth, address). Use proper URL building to handle existing query parameters.
    6. Listen for JS bridge messages: `IC_COMPLETE` (success) or `IC_ERROR` (failure)
    7. On `IC_COMPLETE`, proceed to `confirmPayment()` **without** passing `collectedData` — the WebView submits data directly to the backend

    ### 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                                         |

    <Info>
      The `collectData` also includes a `schema` field — a JSON schema string describing the required fields. The `required` list in this schema tells you which fields the form expects. Wallets can use these field names as keys when building the prefill JSON object. For example, if the schema's `required` array contains `["fullName", "dob", "pobAddress"]`, you can prefill with `{"fullName": "...", "dob": "...", "pobAddress": "..."}`.
    </Info>

    <Note>
      The top-level `collectData` on the payment options response is still available for backward compatibility. However, the per-option `collectData` is the recommended approach as it provides more granular control over the flow.
    </Note>

    <Warning>
      When using the WebView approach, do **not** pass `collectedData` to `confirmPayment()`. The WebView handles data submission directly.
    </Warning>

    ```dart theme={null}
    if (response.collectData?.url != null) {
      // Use the "required" list from response.collectData.schema to determine which fields to prefill
      final prefillData = {
        'fullName': 'John Doe',
        'dob': '1990-01-15',
        'pobAddress': '123 Main St, New York, NY 10001',
      };
      final prefillJson = jsonEncode(prefillData);
      final prefillBase64 = base64Url.encode(utf8.encode(prefillJson));
      final uri = Uri.parse(response.collectData!.url);
      final webViewUrl = uri.replace(
        queryParameters: {...uri.queryParameters, 'prefill': prefillBase64},
      ).toString();

      // Show WebView and wait for IC_COMPLETE message
      showDataCollectionWebView(webViewUrl);
    }
    ```

    ### WebView Message Types

    The WebView communicates with your wallet through JavaScript bridge messages. The message payload is a JSON string with the following structure:

    | Message Type  | Payload                                      | Description                                                               |
    | ------------- | -------------------------------------------- | ------------------------------------------------------------------------- |
    | `IC_COMPLETE` | `{ "type": "IC_COMPLETE", "success": true }` | User completed the form successfully. Proceed to payment confirmation.    |
    | `IC_ERROR`    | `{ "type": "IC_ERROR", "error": "..." }`     | An error occurred. Display the error message and allow the user to retry. |

    #### Platform-Specific Bridge Names

    | Platform         | Bridge Name                                   | Handler                                                       |
    | ---------------- | --------------------------------------------- | ------------------------------------------------------------- |
    | Kotlin (Android) | `AndroidWallet`                               | `@JavascriptInterface onDataCollectionComplete(json: String)` |
    | Swift (iOS)      | `payDataCollectionComplete`                   | `WKScriptMessageHandler.didReceive(message:)`                 |
    | Flutter          | `ReactNativeWebView` (injected via JS bridge) | `JavaScriptChannel.onMessageReceived`                         |
    | React Native     | `ReactNativeWebView` (native)                 | `WebView.onMessage` prop                                      |
  </Step>

  <Step title="Confirm Payment" titleSize="h3">
    Confirm the payment with signatures and optional collected data:

    ```dart theme={null}
    final confirmResponse = await walletKit.confirmPayment(
      request: ConfirmPaymentRequest(
        paymentId: 'payment-id',
        optionId: 'option-id',
        signatures: ['0x...', '0x...'], // Signatures from wallet actions
        collectedData: [
          CollectDataFieldResult(id: 'fullName', value: 'John Doe'),
          CollectDataFieldResult(id: 'dob', value: '1990-01-01'),
        ], // Optional: if data collection was required
        maxPollMs: 60000, // Maximum polling time in milliseconds
      ),
    );

    print('Payment Status: ${confirmResponse.status}');
    print('Is Final: ${confirmResponse.isFinal}');
    ```
  </Step>
</Steps>

## WebView Implementation

When `collectData.url` is present, display the URL in a WebView using `webview_flutter` (v4.10.0+). Add dependencies:

```yaml theme={null}
dependencies:
  webview_flutter: ^4.10.0
  url_launcher: ^6.1.0
```

```dart theme={null}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:url_launcher/url_launcher.dart';

class PayDataCollectionWebView extends StatefulWidget {
  final String url;
  final VoidCallback onComplete;
  final ValueChanged<String> onError;

  const PayDataCollectionWebView({
    super.key,
    required this.url,
    required this.onComplete,
    required this.onError,
  });

  @override
  State<PayDataCollectionWebView> createState() =>
      _PayDataCollectionWebViewState();
}

class _PayDataCollectionWebViewState extends State<PayDataCollectionWebView> {
  late final WebViewController _controller;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(NavigationDelegate(
        onPageFinished: (_) => setState(() => _isLoading = false),
        onNavigationRequest: (request) {
          if (!request.url.contains('pay.walletconnect.com')) {
            launchUrl(Uri.parse(request.url),
                mode: LaunchMode.externalApplication);
            return NavigationDecision.prevent;
          }
          return NavigationDecision.navigate;
        },
      ))
      ..addJavaScriptChannel(
        'ReactNativeWebView',
        onMessageReceived: (message) {
          try {
            final data = jsonDecode(message.message) as Map<String, dynamic>;
            switch (data['type']) {
              case 'IC_COMPLETE':
                widget.onComplete();
                break;
              case 'IC_ERROR':
                widget.onError(data['error'] ?? 'Unknown error');
                break;
            }
          } catch (_) {}
        },
      )
      ..loadRequest(Uri.parse(widget.url));
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        WebViewWidget(controller: _controller),
        if (_isLoading)
          const Center(child: CircularProgressIndicator()),
      ],
    );
  }
}
```

## Complete Example

Here's a complete example of processing a payment:

```dart theme={null}
import 'package:reown_walletkit/reown_walletkit.dart';

class PaymentService {
  final ReownWalletKit walletKit;

  PaymentService(this.walletKit);

  /// Process a payment from a payment link (e.g., after scanning QR code)
  Future<void> processPayment(String paymentLink) async {
    try {
      // Step 1: Get payment options
      final accounts = await getWalletAccounts(); // Your wallet accounts
      final optionsResponse = await walletKit.getPaymentOptions(
        request: GetPaymentOptionsRequest(
          paymentLink: paymentLink,
          accounts: accounts,
          includePaymentInfo: true,
        ),
      );

      if (optionsResponse.options.isEmpty) {
        throw Exception('No payment options available');
      }

      // Step 2: Collect data via WebView if required
      if (optionsResponse.collectData?.url != null) {
        await showDataCollectionWebView(optionsResponse.collectData!.url);
      }

      // Step 3: Select payment option (or let user choose)
      PaymentOption selectedOption = optionsResponse.options.first;
      final paymentId = optionsResponse.paymentId;
      final optionId = selectedOption.id;

      // Step 4: Get required payment actions (if not already in the option)
      List<Action> actions = selectedOption.actions;
      if (actions.isEmpty) {
        actions = await walletKit.getRequiredPaymentActions(
          request: GetRequiredPaymentActionsRequest(
            optionId: optionId,
            paymentId: paymentId,
          ),
        );
      }

      // Step 5: Execute wallet actions and collect signatures
      final signatures = <String>[];
      for (final action in actions) {
        // Dispatch based on action.walletRpc.method:
        // 'eth_signTypedData_v4' -> sign EIP-712 typed data
        // 'eth_sendTransaction'  -> send transaction (e.g., token approval)
        // 'personal_sign'        -> personal message signing
        signatures.add(await signAction(action.walletRpc));
      }

      // Step 6: Confirm payment
      ConfirmPaymentResponse confirmResponse = await walletKit.confirmPayment(
        request: ConfirmPaymentRequest(
          paymentId: paymentId,
          optionId: optionId,
          signatures: signatures,
          maxPollMs: 60000, // Maximum polling time in milliseconds
        ),
      );

      // Step 7: Poll until final status (if needed)
      while (!confirmResponse.isFinal && confirmResponse.pollInMs != null) {
        await Future.delayed(Duration(milliseconds: confirmResponse.pollInMs!));
        confirmResponse = await walletKit.confirmPayment(
          request: ConfirmPaymentRequest(
            paymentId: paymentId,
            optionId: optionId,
            signatures: signatures,
            maxPollMs: 60000,
          ),
        );
      }

      // Handle final payment status
      switch (confirmResponse.status) {
        case PaymentStatus.succeeded:
          print('Payment succeeded!');
          break;
        case PaymentStatus.failed:
          throw Exception('Payment failed');
        case PaymentStatus.expired:
          throw Exception('Payment expired');
        case PaymentStatus.cancelled:
          throw Exception('Payment cancelled');
        case PaymentStatus.requires_action:
          throw Exception('Payment requires additional action');
        case PaymentStatus.processing:
          // Should not happen if isFinal is true
          break;
      }
    } catch (e) {
      print('Payment error: $e');
      rethrow;
    }
  }

  Future<List<String>> getWalletAccounts() async {
    // Return your wallet's CAIP-10 formatted accounts
    // Example: ['eip155:1:0x1234...', 'eip155:137:0x5678...']
    return [];
  }
}
```

## Direct Access

You can also access the underlying `WalletConnectPay` instance directly if needed:

```dart theme={null}
final payClient = walletKit.pay;
// Use payClient methods directly
final response = await payClient.getPaymentOptions(request: request);
```

## API Reference

### ReownWalletKit Pay Methods

| Method                                                                           | Description                                     |
| -------------------------------------------------------------------------------- | ----------------------------------------------- |
| `isPaymentLink(String uri)`                                                      | Check if URI is a payment link                  |
| `getPaymentOptions({required GetPaymentOptionsRequest request})`                 | Get available payment options                   |
| `getRequiredPaymentActions({required GetRequiredPaymentActionsRequest request})` | Get actions requiring signatures                |
| `confirmPayment({required ConfirmPaymentRequest request})`                       | Confirm and finalize payment                    |
| `pay`                                                                            | Access the underlying WalletConnectPay instance |

### Models

#### GetPaymentOptionsRequest

```dart theme={null}
GetPaymentOptionsRequest({
  required String paymentLink,
  required List<String> accounts,
  @Default(false) bool includePaymentInfo,
})
```

#### PaymentOptionsResponse

```dart theme={null}
PaymentOptionsResponse({
  required String paymentId,
  PaymentInfo? info,
  required List<PaymentOption> options,
  CollectDataAction? collectData,
  PaymentResultInfo? resultInfo,     // Transaction result details (present when payment already completed)
})
```

#### PaymentResultInfo

```dart theme={null}
class PaymentResultInfo {
  final String txId;               // Transaction ID
  final PayAmount optionAmount;    // Token amount details
}
```

#### PaymentInfo

```dart theme={null}
PaymentInfo({
  required PaymentStatus status,
  required PayAmount amount,
  required int expiresAt,
  required MerchantInfo merchant,
  BuyerInfo? buyer,
})
```

#### PaymentOption

```dart theme={null}
PaymentOption({
  required String id,
  required String account,
  required PayAmount amount,
  @JsonKey(name: 'etaS') required int etaSeconds,
  required List<Action> actions,
})
```

#### ConfirmPaymentRequest

```dart theme={null}
ConfirmPaymentRequest({
  required String paymentId,
  required String optionId,
  required List<String> signatures,
  int? maxPollMs,
})
```

#### ConfirmPaymentResponse

```dart theme={null}
ConfirmPaymentResponse({
  required PaymentStatus status,
  required bool isFinal,
  int? pollInMs,
  PaymentResultInfo? info,           // Transaction result details (present on success)
})
```

#### PaymentStatus

```dart theme={null}
enum PaymentStatus {
  requires_action,
  processing,
  succeeded,
  failed,
  expired,
  cancelled,
}
```

#### CollectDataAction

```dart theme={null}
class CollectDataAction {
  final String url;                // WebView URL for data collection
  final String? schema;            // JSON schema describing required fields
}
```

## Error Handling

The SDK throws specific exception types for different error scenarios. All errors extend the abstract `PayError` class, which itself extends `PlatformException`:

```dart theme={null}
abstract class PayError extends PlatformException {
  PayError({
    required super.code,
    required super.message,
    required super.details,
    required super.stacktrace,
  });
}
```

| Exception                 | Description                          |
| ------------------------- | ------------------------------------ |
| `PayInitializeError`      | Initialization failures              |
| `GetPaymentOptionsError`  | Errors when fetching payment options |
| `GetRequiredActionsError` | Errors when getting required actions |
| `ConfirmPaymentError`     | Errors when confirming payment       |

All errors include:

* `code`: Error code
* `message`: Error message
* `details`: Additional error details
* `stacktrace`: Stack trace

### Example Error Handling

```dart theme={null}
try {
  final response = await walletKit.getPaymentOptions(request: request);
} on GetPaymentOptionsError catch (e) {
  print('Error code: ${e.code}');
  print('Error message: ${e.message}');
} on PayError catch (e) {
  // Catch any Pay-related error
  print('Pay error: ${e.message}');
} catch (e) {
  print('Unexpected error: $e');
}
```

## Best Practices

1. **Use WalletKit Integration**: If your wallet already uses WalletKit, prefer this approach for automatic configuration

2. **Use `isPaymentLink()` for Detection**: Use the utility method instead of manual URL parsing for reliable payment link detection

3. **Account Format**: Always use CAIP-10 format for accounts: `eip155:{chainId}:{address}`

4. **Multiple Chains**: Provide accounts for all supported chains to maximize payment options

5. **Signature Order**: Maintain the same order of signatures as the actions array

6. **Error Handling**: Always handle errors gracefully and show appropriate user feedback

7. **Loading States**: Show loading indicators during API calls and signing operations

8. **Expiration**: Check `paymentInfo.expiresAt` and warn users if time is running low

9. **User Data**: Only collect data when `collectData` is present in the response and you don't already have the required user data. If you already have the required data, you can submit this without collecting from the user. You must make sure the user accepts WalletConnect Terms and Conditions and Privacy Policy before submitting user information to WalletConnect.

10. **WebView Data Collection**: When `collectData.url` is present, display the URL in a WebView using `webview_flutter` rather than building native forms. The WebView handles form rendering, validation, and T\&C acceptance.

## Examples

For a complete example implementation with UI components showing the full payment flow, see the [reown\_walletkit example](https://github.com/reown-com/reown_flutter/tree/master/packages/reown_walletkit/example/lib/walletconnect_pay).

The example demonstrates:

* Payment link detection and processing
* Payment options retrieval with UI
* Data collection for compliance (KYB/KYC)
* Payment details display
* Transaction signing and confirmation
* Payment status polling and result display
