TransX402 Docs
Integrations

JavaScript Library

Complete guide to @transx402/client — installation, configuration, paywall component, and API reference for IDRX payment integration.

Overview

@transx402/client is a browser and Node.js library for IDRX x402 payments. It wraps the standard x402 client libraries and adds IDRX-specific defaults for token/network.

For full-stack integrations (recommended), pair it with @transx402/server: the client signs; your backend calls POST /facilitate.

Settlement modeWho calls /facilitateDefault forAPI key
server (canonical)Merchant backend (@transx402/server)fetch()Server env
directBrowser / agentpay() / paywallPublishable ipk_pub_sandbox_ / ipk_pub_live_ (register allowed origins in Dashboard first)

Installation

NPM (for bundled apps)

npm install @transx402/client
# Full-stack / canonical settlement:
npm install @transx402/server

CDN (for WordPress, static sites, any HTML page)

For zero-build integrations, see the dedicated CDN Usage guide. The short version:

<script src="https://cdn.transx402.com/v1/transx402.min.js"></script>

The CDN script exposes a global TransX402 object with the same API described below. CDN / paywall flows use direct settlement.

Initialization

TransX402.create(options)

Create a TransX402 client instance:

// Sandbox (CAMP testnet on the hosted facilitator)
const client = TransX402.create({
  apiKey: 'ipk_sandbox_abc123...',
});
 
// Production (Base mainnet on the same hosted facilitator)
const client = TransX402.create({
  apiKey: 'ipk_live_xyz789...',
});

The chain (sandbox/production) is determined from your API key prefix — both use https://api.transx402.com. You don't need to set the facilitator URL manually for hosted integrations.

Configuration Options

OptionTypeDefaultDescription
apiKeystringrequiredAPI key from the TransX402 dashboard
environmentstring"local" | "camp" | "base" (XOR with facilitatorUrl)
facilitatorUrlstringCustom facilitator URL (XOR with environment)
settlementstring"server" for fetch()"server" | "direct" — who calls /facilitate
onPaymentStartfunctionCallback when payment starts
onPaymentSuccessfunctionCallback when payment succeeds
onPaymentErrorfunctionCallback when payment fails
onWalletConnectfunctionCallback when wallet connects
onApprovalRequiredfunctionOptional callback for manual requestApproval() flows

Core API

client.fetch(url, options)

Drop-in replacement for fetch(). Automatically handles 402 responses.

const response = await client.fetch('https://example.com/premium-article');
const content = await response.json();

Internal flow (settlement: "server", default for fetch()):

  1. Sends a normal fetch() request
  2. If response is 402, parses payment requirements
  3. Connects wallet (if not connected)
  4. Signs x402 payment payload (Exact EVM + Permit2 witness)
  5. Retries the original request with PAYMENT-SIGNATURE / X-PAYMENT
  6. Your merchant API settles via @transx402/serverPOST /facilitate
  7. Returns the final response

Internal flow (settlement: "direct"): 1–4 as above, then the client calls POST /facilitate itself before the retry. Used by pay() and the paywall.

client.connectWallet()

Explicitly connect a wallet. Supports:

  • MetaMask / browser extension wallets (EIP-1193)
  • WalletConnect v2
  • Coinbase Wallet
const address = await client.connectWallet();
console.log('Wallet connected:', address);

client.checkApproval() (optional)

Check if the connected wallet has approved Permit2 for IDRX.

const { approved, allowance } = await client.checkApproval();
 
if (!approved) {
  console.log('Permit2 approval needed');
}

client.requestApproval() (optional)

Manual helper to request Permit2 approval. Most integrations should rely on the standard x402 flow and sponsorship extensions instead.

const tx = await client.requestApproval();
console.log('Approval successful, tx hash:', tx);

client.pay(paymentRequirements)

Manually trigger a payment without wrapping fetch.

const result = await client.pay({
  to: '0xMerchantWallet',
  amount: '150000',    // in IDR (library converts to IDRX base units)
  currency: 'IDR',
  resource: 'https://example.com/article/123',
});
 
console.log('Payment successful:', result.txHash);

Paywall Component

A ready-made paywall overlay for content gating.

Vanilla JavaScript

TransX402.paywall({
  selector: '#premium-content',    // element to gate
  price: 5000,                      // price in IDR
  currency: 'IDR',
  merchantWallet: '0xMerchant...',
  title: 'Premium Article',
  description: 'Pay Rp 5,000 to read this article',
});

React

import { Paywall } from '@transx402/client/browser';
 
function ArticlePage() {
  return (
    <Paywall
      price={5000}
      currency="IDR"
      merchantWallet="0xMerchant..."
    >
      <PremiumContent />
    </Paywall>
  );
}

Paywall Display

The default paywall overlay includes:

  • Price display in IDR (e.g., "Rp 5,000")
  • "Pay with IDRX" button
  • Wallet connection flow (if not connected)
  • Signature confirmation step
  • Payment confirmation with transaction link
  • Customizable via CSS variables

Customization

CSS Variables

:root {
  --transx402-primary: #2563eb;
  --transx402-bg: #ffffff;
  --transx402-text: #1a1a1a;
  --transx402-radius: 12px;
  --transx402-font: 'Inter', system-ui, sans-serif;
}

Event Hooks

const client = TransX402.create({
  apiKey: 'ipk_sandbox_abc123...',
  onPaymentStart: (details) => {
    console.log('Payment started:', details);
    // Track analytics
  },
  onPaymentSuccess: (result) => {
    console.log('Payment successful:', result.txHash);
    // Unlock content
  },
  onPaymentError: (error) => {
    console.error('Payment failed:', error.message);
    // Show error message
  },
  onWalletConnect: (address) => {
    console.log('Wallet connected:', address);
    // Update UI
  },
  onApprovalRequired: () => {
    console.log('Optional manual Permit2 approval flow');
  },
});

Multi-Currency Support

The library is designed for IDRX first but supports additional tokens:

const client = TransX402.create({
  apiKey: 'ipk_live_xyz789...',
  token: 'USDC',       // override default token
  network: 'base',
});

Token configuration (addresses, decimals, methods) is fetched from the facilitator's /tokens endpoint, so adding new tokens requires no client library updates.

Bundle Size Targets

VariantTarget
Core (fetch wrapper only)< 15 KB gzipped
With paywall UI< 30 KB gzipped
With wallet connectors< 50 KB gzipped
CDN full bundle< 60 KB gzipped

Compatibility

Browser

  • Chrome 90+
  • Firefox 90+
  • Safari 15+
  • Edge 90+
  • Mobile: Chrome Android, Safari iOS

Node.js

  • Node.js 18+ (Fetch API required)
  • Can be used server-side for programmatic payments (AI agents, backends)

Full Example

Blog Article Paywall

<!DOCTYPE html>
<html>
<head>
  <title>My Blog</title>
  <script src="https://cdn.transx402.com/v1/transx402.min.js"></script>
</head>
<body>
  <h1>Crypto Investment Guide 2026</h1>
 
  <p>Here is the article preview...</p>
 
  <div id="premium-content">
    <p>This premium content will unlock after payment.</p>
    <!-- Full content here -->
  </div>
 
  <script>
    const client = TransX402.create({
      apiKey: 'ipk_sandbox_abc123...',
    });
 
    TransX402.paywall({
      selector: '#premium-content',
      price: 5000,
      currency: 'IDR',
      title: 'Premium Content',
      description: 'Pay Rp 5,000 to read the full article',
    });
  </script>
</body>
</html>

Fetch API with Error Handling

import { TransX402 } from '@transx402/client';
 
const client = TransX402.create({
  apiKey: 'ipk_live_xyz789...',
  onPaymentError: (error) => {
    if (error.code === 'insufficient_balance') {
      alert('Your IDRX balance is insufficient');
    } else if (error.code === 'user_rejected') {
      console.log('User cancelled the payment');
    }
  },
});
 
try {
  const response = await client.fetch('https://api.mysite.com/premium-data');
  const data = await response.json();
  renderContent(data);
} catch (error) {
  console.error('Failed to fetch content:', error);
}