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 that handles the full x402 payment flow for IDRX. It wraps the standard x402 client libraries and adds IDRX-specific logic: Permit2 approval detection, one-time approval prompts, and preconfigured token/network defaults.

The key design goal: zero friction for website owners — drop in one script tag or npm package, and IDRX payments work.

Installation

NPM (for bundled apps)

npm install @transx402/client

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.

Initialization

TransX402.create(options)

Create a TransX402 client instance:

// Sandbox (auto-routes to sandbox.transx402.com)
const client = TransX402.create({
  apiKey: 'ipk_sandbox_abc123...',
});
 
// Production (auto-routes to api.transx402.com)
const client = TransX402.create({
  apiKey: 'ipk_live_xyz789...',
});

The environment (sandbox/production) is determined automatically from the API key prefix — you don't need to set the facilitator URL manually.

Configuration Options

OptionTypeDefaultDescription
apiKeystringrequiredAPI key from the TransX402 dashboard
tokenstring'IDRX'Token symbol to use
networkstring'base'Blockchain network
onPaymentStartfunctionCallback when payment starts
onPaymentSuccessfunctionCallback when payment succeeds
onPaymentErrorfunctionCallback when payment fails
onWalletConnectfunctionCallback when wallet connects
onApprovalRequiredfunctionCallback when Permit2 approval is needed

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:

  1. Sends a normal fetch() request
  2. If response is 402, parses payment requirements
  3. Connects wallet (if not connected)
  4. Checks Permit2 approval (prompts if needed — one time only)
  5. Signs Permit2 authorization
  6. Sends signed authorization to facilitator
  7. Retries original request with payment proof
  8. Returns the final response

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()

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()

Request Permit2 approval from the user. Only needed once per wallet.

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/react';
 
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)
  • Permit2 approval step (if first time, with explanation)
  • 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('Permit2 approval required');
    // Custom approval UI
  },
});

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);
}