WalletConnect Pay SDK - Web/Node.js - WalletConnect Pay Docs
Sample Wallet
For a complete working example, check out our sample wallet implementation:
Sample Wallet - Web/Node.js
A reference web wallet app demonstrating WalletConnect Pay integration.
Requirements
- Node.js 16+
Installation
Install the WalletConnect Pay SDK using npm or yarn:
- npm
npm install @walletconnect/pay
- yarn
yarn add @walletconnect/pay
Architecture
The SDK uses a provider abstraction that allows different implementations:
- WasmProvider: Uses WebAssembly module for web browsers
- NativeProvider: Uses platform-specific uniffi module (for React Native environments)
The SDK auto-detects the best available provider for your environment.
Initialization
Initialize the WalletConnect Pay client with your credentials:
import { WalletConnectPay } from "@walletconnect/pay";
const client = new WalletConnectPay({
appId: "your-wcp-id",
// OR use apiKey instead:
// apiKey: "your-api-key",
});
Configuration Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
appId |
string |
No* | WCP ID for authentication |
apiKey |
string |
No* | API key for authentication |
clientId |
string |
No | Client ID for tracking |
baseUrl |
string |
No | Custom API base URL |
logger |
Logger |
No | Custom logger instance or level |
Either appId or apiKey must be provided for authentication.
Supported Networks & Tokens
WalletConnect Pay currently supports the following tokens and networks:
| Token | Network | Chain ID | CAIP-10 Format |
|---|---|---|---|
| USDC | Arbitrum | 42161 | eip155:42161:{address} |
| USDC | Base | 8453 | eip155:8453:{address} |
| USDC | Polygon | 137 | eip155:137:{address} |
| USDC | Ethereum | 1 | eip155:1:{address} |
| USDC | Optimism | 10 | eip155:10:{address} |
| USDC | Monad | 143 | eip155:143:{address} |
| USDC | Celo | 42220 | eip155:42220:{address} |
| USDC | BSC | 56 | eip155:56:{address} |
| EURC | Ethereum | 1 | eip155:1:{address} |
| EURC | Base | 8453 | eip155:8453:{address} |
| USDT0 | Arbitrum | 42161 | eip155:42161:{address} |
| PYUSD | Ethereum | 1 | eip155:1:{address} |
| PYUSD | Arbitrum | 42161 | eip155:42161:{address} |
| USDG | Ethereum | 1 | eip155:1:{address} |
| USDT | Ethereum | 1 | eip155:1:{address} |
| USDT | Polygon | 137 | eip155:137:{address} |
| USDT | BSC | 56 | eip155:56:{address} |
Include accounts for all supported networks to maximize payment options for your users.
Payment Flow
The payment flow consists of five main steps: Get Options -> Collect Data (if required) -> Get Actions -> Sign Actions -> Confirm Payment
Get Payment Options
When a user scans a payment QR code or opens a payment link, fetch available payment options:
const options = await client.getPaymentOptions({
paymentLink: "https://pay.walletconnect.com/pay_123",
accounts: [
`eip155:1:${walletAddress}`, // Ethereum Mainnet
`eip155:8453:${walletAddress}`, // Base
],
includePaymentInfo: true,
});
console.log("Payment ID:", options.paymentId);
console.log("Options:", options.options);
// Display merchant info
if (options.info) {
console.log("Merchant:", options.info.merchant.name);
console.log("Amount:", options.info.amount.display.assetSymbol, options.info.amount.value);
}
// Check which options require data collection
for (const option of options.options) {
if (option.collectData) {
console.log(`Option ${option.id} requires info capture`);
}
}
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.
Recommended Flow
The recommended approach is to display all payment options upfront, then handle data collection only when the user selects an option that requires it:
- Call
getPaymentOptionsand display all available options to the user - Show a visual indicator (e.g., "Info required" badge) on options where
option.collectDatais present - When the user selects an option, check
selectedOption.collectData - If present, load
selectedOption.collectData.urlin the embedded form - Optionally append query parameters to the form URL —
prefill(known user data),theme, andthemeVariables(appearance). See Form URL parameters below. Use proper URL building so existing query parameters are preserved. - Listen for completion messages:
IC_COMPLETE(success) orIC_ERROR(failure) - On
IC_COMPLETE, continue the flow — fetch the required actions, sign, and confirm the payment. Don’t passcollectedDatatoconfirmPayment(); the form 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 |
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. |
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:
themeswitches the form betweenlightanddarkbase color modes. Match it to your wallet’s active mode for a seamless transition.themeVariablesapplies brand-level overrides (font, font size, select colors, button border radius, and input border radius). Generate the theme in the WalletConnect Pay Dashboard, export it as a base64url string, and append it to the form URL verbatim — you don’t need to encode it at runtime.
Iframe Message Types
The iframe communicates with your wallet through postMessage events. 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. |
Get Required Actions
After the user selects a payment option, get the wallet RPC actions required to complete the payment:
const actions = await client.getRequiredPaymentActions({
paymentId: options.paymentId,
optionId: options.options[0].id,
});
// Each action contains wallet RPC data to sign
for (const action of actions) {
console.log("Chain:", action.walletRpc.chainId);
console.log("Method:", action.walletRpc.method);
console.log("Params:", action.walletRpc.params);
}
Sign Actions
Sign each action with your wallet’s signing implementation:
// Sign each action based on its RPC method
const signatures = await Promise.all(
actions.map(async (action) => {
const { chainId, method, params } = action.walletRpc;
const parsedParams = JSON.parse(params);
switch (method) {
case "eth_signTypedData_v4":
return await wallet.signTypedData(chainId, parsedParams);
case "eth_sendTransaction":
return await wallet.sendTransaction(chainId, parsedParams[0]);
case "personal_sign":
return await wallet.personalSign(chainId, parsedParams);
default:
throw new Error(`Unsupported RPC method: ${method}`);
}
})
);
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.
Confirm Payment
Submit the signatures and collected data to complete the payment:
const result = await client.confirmPayment({
paymentId: options.paymentId,
optionId: options.options[0].id,
signatures,
collectedData, // Include if collectData was present
});
if (result.status === "succeeded") {
console.log("Payment successful!");
} else if (result.status === "processing") {
console.log("Payment is processing...");
} else if (result.status === "failed") {
console.log("Payment failed");
}
Data Collection Implementation
When selectedOption.collectData.url is present, display the URL in an iframe or modal. Listen for postMessage events to handle completion: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_ERRORmessages 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=lightortheme=darkto match your wallet’s active color mode, and apply brand tokens withthemeVariablesexported from the WalletConnect Pay Dashboard.
function showDataCollectionView(url: string): Promise<void> {
// Create a modal/overlay container
const overlay = document.createElement("div");
overlay.style.cssText =
"position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);display:flex;align-items:center;justify-content:center;z-index:9999;";
const iframe = document.createElement("iframe");
iframe.src = url;
iframe.style.cssText = "width:450px;height:650px;border:none;border-radius:12px;";
overlay.appendChild(iframe);
document.body.appendChild(overlay);
return new Promise((resolve, reject) => {
function handleMessage(event: MessageEvent) {
try {
const data = typeof event.data === "string" ? JSON.parse(event.data) : event.data;
if (data.type === "IC_COMPLETE") {
cleanup();
resolve();
} else if (data.type === "IC_ERROR") {
cleanup();
reject(new Error(data.error || "Unknown error"));
}
} catch {
// Ignore non-JSON messages
}
}
function cleanup() {
window.removeEventListener("message", handleMessage);
document.body.removeChild(overlay);
}
window.addEventListener("message", handleMessage);
});
}
Complete Example
Here’s a complete implementation example:
import { WalletConnectPay, CollectDataFieldResult } from "@walletconnect/pay";
class PaymentManager {
private client: WalletConnectPay;
constructor() {
this.client = new WalletConnectPay({
appId: "your-wcp-id",
});
}
async processPayment(paymentLink: string, walletAddress: string) {
try {
// Step 1: Get payment options
const options = await this.client.getPaymentOptions({
paymentLink,
accounts: [
`eip155:1:${walletAddress}`,
`eip155:137:${walletAddress}`,
`eip155:8453:${walletAddress}`,
],
includePaymentInfo: true,
});
if (options.options.length === 0) {
throw new Error("No payment options available");
}
// Step 2: Let user select an option (simplified - use first option)
const selectedOption = options.options[0];
// Step 3: Collect data via iframe if required for selected option.
// This must happen BEFORE fetching required actions, otherwise the
// backend rejects the fetch for options that require info capture.
if (selectedOption.collectData?.url) {
// Show iframe and wait for IC_COMPLETE
await this.showDataCollectionView(selectedOption.collectData.url);
}
// Step 4: Get required actions
const actions = await this.client.getRequiredPaymentActions({
paymentId: options.paymentId,
optionId: selectedOption.id,
});
// Step 5: Sign all actions
const signatures = await Promise.all(
actions.map((action) =>
this.signAction(action, walletAddress)
)
);
// Step 6: Confirm payment
const result = await this.client.confirmPayment({
paymentId: options.paymentId,
optionId: selectedOption.id,
signatures,
});
return result;
} catch (error) {
console.error("Payment failed:", error);
throw error;
}
}
private async signAction(action: Action, walletAddress: string): Promise<string> {
const { chainId, method, params } = action.walletRpc;
const parsedParams = JSON.parse(params);
switch (method) {
case "eth_signTypedData_v4":
return await wallet.signTypedData(chainId, parsedParams);
case "eth_sendTransaction":
return await wallet.sendTransaction(chainId, parsedParams[0]);
case "personal_sign":
return await wallet.personalSign(chainId, parsedParams);
default:
throw new Error(`Unsupported RPC method: ${method}`);
}
}
}
Provider Utilities
The SDK provides utilities for checking provider availability:
import {
isProviderAvailable,
detectProviderType,
} from "@walletconnect/pay";
// Check if any provider is available
if (isProviderAvailable()) {
// SDK can be used
}
// Detect which provider type is available
const providerType = detectProviderType(); // 'native' | 'wasm' | null
API Reference
WalletConnectPayMain client for payment operations.
Constructor
new WalletConnectPay(options: WalletConnectPayOptions)
Methods
| Method | Description |
|---|---|
getPaymentOptions(params) |
Fetch available payment options |
getRequiredPaymentActions(params) |
Get signing actions for a payment option |
confirmPayment(params) |
Confirm and execute the payment |
static isAvailable() |
Check if a provider is available |
Data Types****PaymentStatus
type PaymentStatus =
| "requires_action"
| "processing"
| "succeeded"
| "failed"
| "expired";
PayProviderType
type PayProviderType = "native" | "wasm";
CollectDataFieldType
type CollectDataFieldType = "text" | "date";
Method Parameters
interface GetPaymentOptionsParams {
/** Payment link or ID */
paymentLink: string;
/** List of CAIP-10 accounts */
accounts: string[];
/** Whether to include payment info in response */
includePaymentInfo?: boolean;
}
interface GetRequiredPaymentActionsParams {
/** Payment ID */
paymentId: string;
/** Option ID */
optionId: string;
}
interface ConfirmPaymentParams {
/** Payment ID */
paymentId: string;
/** Option ID */
optionId: string;
/** Signatures from wallet RPC calls */
signatures: string[];
}
Response Types
interface PaymentOptionsResponse {
/** Payment ID extracted from the payment link */
paymentId: string;
/** Payment information (if includePaymentInfo was true) */
info?: PaymentInfo;
/** Available payment options */
options: PaymentOption[];
/** Data collection requirements (if any) */
collectData?: CollectDataAction;
/** Transaction result details (present when payment already completed) */
resultInfo?: PaymentResultInfo;
}
interface PaymentResultInfo {
/** Transaction ID */
txId: string;
/** Token amount details */
optionAmount: PayAmount;
}
interface ConfirmPaymentResponse {
/** Payment status */
status: PaymentStatus;
/** True if the payment is in a final state */
isFinal: boolean;
/** Time to poll for payment status, in milliseconds */
pollInMs?: number;
}
PaymentOption
interface PaymentOption {
/** ID of the option */
id: string;
/** The option's token and amount */
amount: PayAmount;
/** Estimated time to complete the option, in seconds */
etaS: number;
/** Actions required to complete the option */
actions: Action[];
/** Per-option data collection requirements */
collectData?: CollectDataAction;
}
Action
interface Action {
walletRpc: WalletRpcAction;
}
interface WalletRpcAction {
/** Chain ID in CAIP-2 format (e.g., "eip155:8453") */
chainId: string;
/** RPC method name (e.g., "eth_signTypedData_v4", "eth_sendTransaction") */
method: string;
/** JSON-encoded params array */
params: string;
}
Amount Types
interface PayAmount {
/** Currency unit, prefixed with either "iso4217/" or "caip19/" */
unit: string;
/** Amount value, in the currency unit's minor units */
value: string;
/** Display information for the amount */
display: AmountDisplay;
}
interface AmountDisplay {
/** Ticker/symbol of the asset */
assetSymbol: string;
/** Full name of the asset */
assetName: string;
/** Number of minor decimals of the asset */
decimals: number;
/** URL of the icon of the asset (if token) */
iconUrl?: string;
/** Name of the network of the asset (if token) */
networkName?: string;
}
Payment Info Types
interface PaymentInfo {
/** Payment status */
status: PaymentStatus;
/** Amount to be paid */
amount: PayAmount;
/** Payment expiration timestamp, in seconds since epoch */
expiresAt: number;
/** Merchant information */
merchant: MerchantInfo;
/** Buyer information (present if payment has been submitted) */
buyer?: BuyerInfo;
}
interface MerchantInfo {
/** Merchant name */
name: string;
/** Merchant icon URL */
iconUrl?: string;
}
interface BuyerInfo {
/** Account CAIP-10 */
accountCaip10: string;
/** Account provider name */
accountProviderName: string;
/** Account provider icon URL */
accountProviderIcon?: string;
}
Collect Data Types
interface CollectDataAction {
/** URL for data collection (displayed in iframe) */
url: string;
/** JSON schema describing required fields */
schema?: string;
}
Error Handling
The SDK throws typed errors for different failure scenarios:
import {
PayError,
PaymentOptionsError,
PaymentActionsError,
ConfirmPaymentError,
} from "@walletconnect/pay";
try {
const options = await client.getPaymentOptions({
paymentLink: link,
accounts,
});
} catch (error) {
if (error instanceof PaymentOptionsError) {
console.error("Failed to get options:", error.originalMessage);
} else if (error instanceof PayError) {
console.error("Pay error:", error.code, error.message);
}
}
Best Practices
- Check Provider Availability: Always check if a provider is available before using the SDK
- Account Format: Always use CAIP-10 format for accounts:
eip155:{chainId}:{address} - Multiple Chains: Provide accounts for all supported chains to maximize payment options
- Signature Order: Maintain the same order of signatures as the actions array
- Error Handling: Always handle errors gracefully and show appropriate user feedback
- Loading States: Show loading indicators during API calls and signing operations
- Expiration: Check
paymentInfo.expiresAtand warn users if time is running low - User Data: Only collect data when
collectDatais present on the selected payment option 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. - Data Collection: When
selectedOption.collectData?.urlis present, display the URL in an iframe or modal rather than building custom forms. The hosted form handles rendering, validation, and T&C acceptance. - Per-Option Data Collection: When displaying payment options, check each option’s
collectDatafield. Show a visual indicator (e.g., "Info required" badge) on options that require data collection. Only open the iframe when the user selects an option withcollectDatapresent — use the option’scollectData.urlwhich is already scoped to that option’s account.