Skip to content

Quickstart

Follow our walkthrough to get Payout Components for Web running in minutes.

This quickstart focuses on a PayPal withdrawal for a returning customer in the test environment. Components for Web also supports Venmo payouts. See What's next? for the full PayPal guide set.

Requirements

Before you start, make sure you have:

  • Node.js 22.x or higher installed on your computer
  • Your API credentials from the Unity Portal
  • A returning customer with a stored PayPal email and payer ID on your backend

Install the SDK

Install the latest version of the Web SDK from the npm public registry. You'll need Node.js 22.x or higher.

npm i @pxpio/web-components-sdk

Create a session on your backend

Payout Components for Web needs a session from the PXP API. This must happen on your backend using Hash-based Message Authentication Code (HMAC) authentication.

Store your credentials securely

Set your token ID, token value, and client ID as the PXP_TOKEN_ID, PXP_TOKEN_VALUE, and PXP_CLIENT_ID environment variables. Never hardcode them in your application.

Create the HMAC signature function

This function generates a secure authentication hash by combining timestamp, request ID, request path, and request body, then hashing with your token value using HMAC SHA256.

Build the session request body

Load the withdrawal by its ID on your backend, then create a request with the server-controlled merchant, site, amount, and currency. Set transactionMethod.intent.paypal to Payout. The request body must be minified (no whitespace) for the HMAC signature.

Generate the HMAC signature

Call the signature function with your credentials and request details.

Send the session creation request

POST to https://api-services.pxp.io/api/v1/sessions (production) or https://api-services.test.pxp.io/api/v1/sessions (sandbox) with your authentication headers and request body.

Return the session data to your frontend

The API returns sessionId, hmacKey, encryptionKey, and related session fields. Return a payload that matches what your frontend expects: the session object plus the server-controlled merchantTransactionId, amount, and currency.

Register your backend session route

Register /api/sessions on your existing backend. Require a withdrawal ID and idempotency key, then load the authoritative withdrawal before creating or reusing a session.

import crypto from 'node:crypto';

// Store your API credentials from the Unity Portal as environment variables.
const TOKEN_ID = process.env.PXP_TOKEN_ID;
const TOKEN_VALUE = process.env.PXP_TOKEN_VALUE;
const CLIENT_ID = process.env.PXP_CLIENT_ID;

if (!TOKEN_ID || !TOKEN_VALUE || !CLIENT_ID) {
  throw new Error(
    'Set PXP_TOKEN_ID, PXP_TOKEN_VALUE, and PXP_CLIENT_ID before starting the server.',
  );
}

const REQUEST_PATH = 'api/v1/sessions';

/**
 * Creates an HMAC signature for authenticating API requests
 */
function createHmacSignature(
  timestamp,
  requestId,
  requestPath,
  requestBody,
  tokenValue,
) {
  const stringToHash = `${timestamp}${requestId}${requestPath}${requestBody}`;
  const hmac = crypto.createHmac('sha256', tokenValue);

  hmac.update(stringToHash);

  return hmac.digest('hex').toUpperCase();
}

/**
 * Creates a payout Components session from your merchant backend.
 */
export async function createSession({
  merchantId,
  siteId,
  amount,
  currency,
}) {
  const timestamp = Math.floor(Date.now() / 1000);
  const requestId = crypto.randomUUID();
  const merchantTransactionId = crypto.randomUUID();

  // Build the request body. For PayPal Components payouts, set paypal intent to Payout.
  const requestBody = {
    merchant: merchantId,
    site: siteId,
    sessionTimeout: 120,
    merchantTransactionId,
    transactionMethod: {
      intent: {
        paypal: 'Payout',
      },
    },
    amounts: {
      currencyCode: currency,
      transactionValue: amount,
    },
    allowTransaction: true,
  };

  const requestBodyString = JSON.stringify(requestBody);

  const signature = createHmacSignature(
    timestamp,
    requestId,
    REQUEST_PATH,
    requestBodyString,
    TOKEN_VALUE,
  );

  const response = await fetch(`https://api-services.pxp.io/${REQUEST_PATH}`, {
    method: 'POST',
    headers: {
      Authorization: `PXP-UST1 ${TOKEN_ID}:${timestamp}:${signature}`,
      'X-Request-Id': requestId,
      'X-Client-Id': CLIENT_ID,
      'Content-Type': 'application/json',
    },
    body: requestBodyString,
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(
      `Session creation failed (${response.status}): ${errorText || response.statusText}`,
    );
  }

  const sessionData = await response.json();

  return {
    session: sessionData,
    transactionData: {
      merchantTransactionId,
      amount,
      currency,
    },
  };
}

Initialise the payout components on your frontend

Import the required dependencies

Import PxpCheckout and necessary types from the Web SDK.

Set up your React component

Create a React component that hosts the withdrawal interface. Pass the authenticated withdrawal ID and merchant group ID from your application.

Fetch the session and wallet data from your backend

Call your backend to get the session data and the customer's stored PayPal email and payer ID.

Initialise the SDK

Configure the SDK with your environment, session data, owner details, and transaction information.

Configure the transaction data

Specify the currency, amount, entry type, and PayPal payout intent.

Configure the PayPal wallet

Set paypalConfig.payoutConfig with proceedPayoutWithSdk: true and the stored paypalWallet email and payer ID for the returning customer.

Create the payout components

Create the amount, PayPal receiver, and submission components.

Approve the payout before execution

Implement onPrePayoutSubmit and return { isApproved: true } to let the SDK execute the payout. Return { isApproved: false } to cancel.

Handle successful payouts

Implement onPostPayout to handle the PXP response. Always verify successful payouts on your backend before marking the withdrawal complete, because frontend callbacks can be manipulated.

Handle payout errors

Implement onError to handle runtime failures during SDK-initiated payout execution. Configuration and wallet validation failures are thrown when you create components.

Mount the components to the page

Call mount() on each component with your container element IDs.

Add container elements to your page

Return JSX that includes containers where the amount, receiver, and submission components mount.

import {
  IntentType,
  PxpCheckout,
  type CurrencyType,
  type SessionData,
} from '@pxpio/web-components-sdk';
import { useEffect, useRef, useState } from 'react';

type PayoutSessionResponse = {
  session: SessionData;
  transactionData: {
    merchantTransactionId: string;
    amount: number;
    currency: string;
  };
};

type CustomerWallet = {
  email: string;
  payerId: string;
};

export default function PayoutPage({
  withdrawalId,
  merchantGroupId,
}: {
  withdrawalId: string;
  merchantGroupId: string;
}) {
  const [sessionData, setSessionData] = useState<PayoutSessionResponse | null>(null);
  const [wallet, setWallet] = useState<CustomerWallet | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const sessionRequestId = useRef(crypto.randomUUID());

  useEffect(() => {
    const controller = new AbortController();

    async function fetchSessionAndWallet() {
      const [sessionResponse, walletResponse] = await Promise.all([
        fetch('/api/sessions', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Idempotency-Key': sessionRequestId.current,
          },
          body: JSON.stringify({ withdrawalId }),
          signal: controller.signal,
        }),
        fetch('/api/customer-wallet', {
          signal: controller.signal,
        }),
      ]);

      if (!sessionResponse.ok) {
        throw new Error(`Session creation failed with status ${sessionResponse.status}.`);
      }

      if (!walletResponse.ok) {
        throw new Error(`Wallet retrieval failed with status ${walletResponse.status}.`);
      }

      setSessionData((await sessionResponse.json()) as PayoutSessionResponse);
      setWallet((await walletResponse.json()) as CustomerWallet);
    }

    fetchSessionAndWallet().catch((error: unknown) => {
      if (error instanceof DOMException && error.name === 'AbortError') {
        return;
      }

      console.error('Unable to start payout:', error);
      setErrorMessage('Unable to start withdrawal. Try again.');
    });

    return () => controller.abort();
  }, [withdrawalId]);

  useEffect(() => {
    if (!sessionData || !wallet) {
      return;
    }

    const pxpSdk = PxpCheckout.initialize({
      environment: 'test',
      session: sessionData.session,
      ownerId: merchantGroupId,
      ownerType: 'MerchantGroup',
      transactionData: {
        currency: sessionData.transactionData.currency as CurrencyType,
        amount: sessionData.transactionData.amount,
        entryType: 'Ecom',
        intent: {
          paypal: IntentType.Payout,
        },
        merchantTransactionId: sessionData.transactionData.merchantTransactionId,
        merchantTransactionDate: () => new Date().toISOString(),
      },
      paypalConfig: {
        payoutConfig: {
          proceedPayoutWithSdk: true,
          paypalWallet: {
            email: wallet.email,
            payerId: wallet.payerId,
          },
        },
      },
    });

    const amountComponent = pxpSdk.create('payout-amount', {
      label: 'Withdrawal Amount',
    });

    const receiverComponent = pxpSdk.create('paypal-payout-receiver', {
      label: 'PayPal Account',
      showMaskToggle: true,
    });

    const submitComponent = pxpSdk.create('payout-submission', {
      recipientWallet: 'Paypal',
      onPrePayoutSubmit: async () => ({
        isApproved: true,
      }),
      onPostPayout: async (result) => {
        // CRITICAL: Do NOT mark the withdrawal complete here.
        // Frontend callbacks can be manipulated. Always verify on your backend.
        const response = await fetch('/api/verify-payout', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            withdrawalId,
            systemTransactionId: result.systemTransactionId,
            merchantTransactionId: result.merchantTransactionId,
          }),
        });

        if (!response.ok) {
          setErrorMessage('Withdrawal verification is unavailable. Contact support.');
          return;
        }

        const verified = (await response.json()) as {
          success: boolean;
          withdrawalId?: string;
        };

        if (verified.success && verified.withdrawalId) {
          globalThis.location.href = `/withdrawal-confirmation?id=${verified.withdrawalId}`;
          return;
        }

        setErrorMessage('Withdrawal could not be verified. Contact support.');
      },
      onError: (error) => {
        console.error('Payout failed:', error.errorCode, error.errorReason);
        setErrorMessage('Withdrawal failed. Try again.');
      },
    });

    amountComponent.mount('payout-amount-container');
    receiverComponent.mount('payout-receiver-container');
    submitComponent.mount('payout-submit-container');

    return () => {
      amountComponent.unmount();
      receiverComponent.unmount();
      submitComponent.unmount();
    };
  }, [merchantGroupId, sessionData, wallet, withdrawalId]);

  return (
    <div>
      <h1>Withdraw funds</h1>
      {errorMessage && <p role="alert">{errorMessage}</p>}
      <div id="payout-amount-container"></div>
      <div id="payout-receiver-container"></div>
      <div id="payout-submit-container"></div>
    </div>
  );
}

Verify payouts

When PXP returns a payout response, onPostPayout receives the result. Always verify the payout on your backend before marking the withdrawal complete.

Configure webhooks in the Unity Portal to receive real-time transaction notifications on your backend.

Create the webhook endpoint

Register /webhooks/pxp to receive payout notifications from Unity. Verify the webhook signature against the raw request body before processing any event. Pass your Express-compatible application, signature verifier, and persistence functions to registerPxpWebhook().

Process webhook events

Loop through the events array and filter for Transaction events.

Check payout state

Verify the transaction state is an accepted success state (for example Authorised) before processing.

Prevent duplicate processing

Skip events you've already handled by checking systemTransactionId before reconciliation.

Verify transaction details

Match the merchantTransactionId, amount, and currency against your withdrawal records.

Reconcile the withdrawal

If verification passes, reconcile the withdrawal and mark the transaction as processed.

Respond to webhook

After authenticating the request, return { state: 'Success' } to acknowledge receipt. Handle reconciliation failures through your own retry and incident process rather than failing the webhook response in this sample.

Register the verification endpoint

Register /api/verify-payout on your backend. Load the authenticated customer's withdrawal and retrieve the authoritative transaction from PXP before returning a verified result.

You can also verify payouts using the Transactions API to query transaction status directly. See Withdrawal flow for the end-to-end returning-customer integration.

export function registerPxpWebhook(
  app,
  {
    isTransactionProcessed,
    getWithdrawalByMerchantTransactionId,
    reconcileWithdrawal,
    markTransactionProcessed,
  },
) {
  // Configure this webhook URL in the Unity Portal.
  // Verify the Unity webhook signature in middleware before this handler runs.
  app.post('/webhooks/pxp', async (req, res) => {
  const events = Array.isArray(req.body) ? req.body : [];

  for (const event of events) {
    if (event.eventCategory === 'Transaction' || event.eventCategory === 'transaction') {
      const txn = event.eventData;

      // PayPal payout success commonly uses Authorised. Confirm acceptable states for your flow.
      if (txn.state === 'Authorised' || txn.state === 'Captured') {
        const alreadyProcessed = await isTransactionProcessed(txn.systemTransactionId);
        if (alreadyProcessed) {
          continue;
        }

        const expectedWithdrawal = await getWithdrawalByMerchantTransactionId(
          txn.merchantTransactionId,
        );

        // PayPal payout webhooks may use amount.transaction / amount.currencyCode.
        // Other payloads may use amounts.transactionValue / amounts.currencyCode.
        const amount = txn.amount?.transaction ?? txn.amounts?.transactionValue;
        const currency = txn.amount?.currencyCode ?? txn.amounts?.currencyCode;

        if (
          expectedWithdrawal &&
          amount === expectedWithdrawal.amount &&
          currency === expectedWithdrawal.currency
        ) {

          await reconcileWithdrawal(txn);
          await markTransactionProcessed(txn.systemTransactionId);
          console.log(`Withdrawal ${txn.merchantTransactionId} reconciled successfully`);
        } else {
          console.error('Withdrawal verification failed - amount or currency mismatch');
        }
      }
    }
  }

  res.json({ state: 'Success' });
  });
}

You now have the core fragments needed to add a PayPal payout Components integration to your application.

What's next?

Now that you have payout components running, here are the recommended next steps:

  • How it works: PayPal and Venmo payout concepts, compliance, and execution modes
  • Onboarding: Connect your PayPal Business account
  • Withdrawal flow: Full returning-customer integration
  • Configuration: Customise amount, receiver, and submission components
  • Events: Add callbacks for approval, success, and errors
  • Error handling: Map payout error codes to customer-facing messages