{"templateId":"markdown","sharedDataIds":{"sidebar":"sidebar-guides/sidebars.yaml"},"props":{"metadata":{"markdoc":{"tagList":["sub-heading","accordion","code-walkthrough","step","admonition"]},"type":"markdown"},"seo":{"title":"Quickstart","description":"Transform your commerce with PXP's unified platform—seamless payments, real-time insights, and global growth in one powerful integration.","lang":"en-UK","siteUrl":"https://developer.pxp.io"},"dynamicMarkdocComponents":[],"compilationErrors":[],"ast":{"$$mdtype":"Tag","name":"article","attributes":{},"children":[{"$$mdtype":"Tag","name":"Heading","attributes":{"level":1,"id":"quickstart","__idx":0},"children":["Quickstart"]},{"$$mdtype":"Tag","name":"SubHeading","attributes":{},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Follow our walkthrough to get Payout Components for Web running in minutes."]}]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["This quickstart focuses on a PayPal withdrawal for a returning customer in the test environment. Components for Web also supports Venmo payouts. See ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"#whats-next"},"children":["What's next?"]}," for the full PayPal guide set."]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"requirements","__idx":1},"children":["Requirements"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Before you start, make sure you have:"]},{"$$mdtype":"Tag","name":"ul","attributes":{"className":"code-walkthrough-list"},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Node.js 22.x or higher installed on your computer"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Your API credentials from the ",{"$$mdtype":"Tag","name":"a","attributes":{"href":"https://portal.pxp.io","target":"_blank"},"children":["Unity Portal"]}]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["A returning customer with a stored PayPal email and payer ID on your backend"]}]},{"$$mdtype":"Tag","name":"Accordion","attributes":{"title":"Where to find your credentials","defaultOpen":false},"children":[{"$$mdtype":"Tag","name":"ol","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":["In the Unity Portal, go to ",{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["Merchant setup > Merchant groups"]}," and select a merchant group."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Click the ",{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["Inbound calls"]}," tab. Your client ID is in the top right."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["Click ",{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["+ New token"]}," to create a token, then copy both the ",{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["ID"]}," and the ",{"$$mdtype":"Tag","name":"strong","attributes":{},"children":["Value"]},"."]}]}]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"install-the-sdk","__idx":2},"children":["Install the SDK"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Install the latest version of the Web SDK from the ",{"$$mdtype":"Tag","name":"a","attributes":{"href":"https://www.npmjs.com/package/@pxpio/web-components-sdk","target":"_blank"},"children":["npm public registry"]},". You'll need Node.js 22.x or higher."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"shell","header":{"controls":{"copy":{}}},"source":"npm i @pxpio/web-components-sdk\n","lang":"shell"},"children":[]},{"$$mdtype":"Tag","name":"CodeWalkthrough","attributes":{"__idx":1,"filters":{},"filesets":[{"files":[{"path":"guides/payout/components/web/_filesets/installation/create-session.js","content":["import crypto from 'node:crypto';","",{"start":2,"condition":{"steps":["credentials-setup"]},"children":["// 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';","",{"start":17,"condition":{"steps":["create-signature-function"]},"children":["/**"," * 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();","",{"start":50,"condition":{"steps":["build-request-body"]},"children":["  // 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);"]},"",{"start":72,"condition":{"steps":["generate-signature"]},"children":["  const signature = createHmacSignature(","    timestamp,","    requestId,","    REQUEST_PATH,","    requestBodyString,","    TOKEN_VALUE,","  );"]},"",{"start":82,"condition":{"steps":["send-session-request"]},"children":["  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,","  });"]},"",{"start":95,"condition":{"steps":["handle-response"]},"children":["  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,","    },","  };"]},"}",""],"metadata":{"steps":["credentials-setup","create-signature-function","build-request-body","generate-signature","send-session-request","handle-response"]},"basename":"create-session.js","language":"javascript"}],"downloadAssociatedFiles":[{"path":"guides/payout/components/web/_filesets/installation/create-session.js","content":["import crypto from 'node:crypto';","",{"start":2,"condition":{"steps":["credentials-setup"]},"children":["// 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';","",{"start":17,"condition":{"steps":["create-signature-function"]},"children":["/**"," * 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();","",{"start":50,"condition":{"steps":["build-request-body"]},"children":["  // 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);"]},"",{"start":72,"condition":{"steps":["generate-signature"]},"children":["  const signature = createHmacSignature(","    timestamp,","    requestId,","    REQUEST_PATH,","    requestBodyString,","    TOKEN_VALUE,","  );"]},"",{"start":82,"condition":{"steps":["send-session-request"]},"children":["  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,","  });"]},"",{"start":95,"condition":{"steps":["handle-response"]},"children":["  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,","    },","  };"]},"}",""],"metadata":{"steps":["credentials-setup","create-signature-function","build-request-body","generate-signature","send-session-request","handle-response"]},"basename":"create-session.js","language":"javascript"}]}],"steps":[{"id":"credentials-setup","heading":"Store your credentials securely"},{"id":"create-signature-function","heading":"Create the HMAC signature function"},{"id":"build-request-body","heading":"Build the session request body"},{"id":"generate-signature","heading":"Generate the HMAC signature"},{"id":"send-session-request","heading":"Send the session creation request"},{"id":"handle-response","heading":"Return the session data to your frontend"},{"id":"session-route","heading":"Register your backend session route"}],"inputs":{},"toggles":{}},"children":[{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"create-a-session-on-your-backend","__idx":3},"children":["Create a session on your backend"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["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."]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"credentials-setup","heading":"Store your credentials securely"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Set your token ID, token value, and client ID as the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["PXP_TOKEN_ID"]},", ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["PXP_TOKEN_VALUE"]},", and ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["PXP_CLIENT_ID"]}," environment variables. Never hardcode them in your application."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"create-signature-function","heading":"Create the HMAC signature function"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["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."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"build-request-body","heading":"Build the session request body"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Load the withdrawal by its ID on your backend, then create a request with the server-controlled merchant, site, amount, and currency. Set ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["transactionMethod.intent.paypal"]}," to ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["Payout"]},". The request body must be minified (no whitespace) for the HMAC signature."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"generate-signature","heading":"Generate the HMAC signature"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Call the signature function with your credentials and request details."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"send-session-request","heading":"Send the session creation request"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["POST to ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["https://api-services.pxp.io/api/v1/sessions"]}," (production) or ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["https://api-services.test.pxp.io/api/v1/sessions"]}," (sandbox) with your authentication headers and request body."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"handle-response","heading":"Return the session data to your frontend"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The API returns ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["sessionId"]},", ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["hmacKey"]},", ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["encryptionKey"]},", and related session fields. Return a payload that matches what your frontend expects: the session object plus the server-controlled ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["merchantTransactionId"]},", amount, and currency."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"session-route","heading":"Register your backend session route"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Register ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["/api/sessions"]}," on your existing backend. Require a withdrawal ID and idempotency key, then load the authoritative withdrawal before creating or reusing a session."]}]}]},{"$$mdtype":"Tag","name":"CodeWalkthrough","attributes":{"__idx":2,"filters":{},"filesets":[{"files":[{"path":"guides/payout/components/web/_filesets/installation/PayoutPage.tsx","content":[{"start":0,"condition":{"steps":["import-dependencies"]},"children":["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;","};","",{"start":24,"condition":{"steps":["setup-component"]},"children":["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());","",{"start":37,"condition":{"steps":["fetch-session"]},"children":["  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;","    }","",{"start":87,"condition":{"steps":["initialize-sdk"]},"children":["    const pxpSdk = PxpCheckout.initialize({","      environment: 'test',","      session: sessionData.session,","      ownerId: merchantGroupId,","      ownerType: 'MerchantGroup',",{"start":93,"condition":{"steps":["configure-transaction"]},"children":["      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(),","      },"]},{"start":105,"condition":{"steps":["configure-paypal"]},"children":["      paypalConfig: {","        payoutConfig: {","          proceedPayoutWithSdk: true,","          paypalWallet: {","            email: wallet.email,","            payerId: wallet.payerId,","          },","        },","      },"]},"    });"]},"",{"start":119,"condition":{"steps":["create-components"]},"children":["    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',",{"start":131,"condition":{"steps":["pre-payout-callback"]},"children":["      onPrePayoutSubmit: async () => ({","        isApproved: true,","      }),"]},{"start":136,"condition":{"steps":["success-callback"]},"children":["      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.');","      },"]},{"start":168,"condition":{"steps":["error-callback"]},"children":["      onError: (error) => {","        console.error('Payout failed:', error.errorCode, error.errorReason);","        setErrorMessage('Withdrawal failed. Try again.');","      },"]},"    });"]},"",{"start":177,"condition":{"steps":["mount-components"]},"children":["    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]);","",{"start":190,"condition":{"steps":["render-containers"]},"children":["  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>","  );"]},"}"]},""],"metadata":{"steps":["import-dependencies","setup-component","fetch-session","initialize-sdk","configure-transaction","configure-paypal","create-components","pre-payout-callback","success-callback","error-callback","mount-components","render-containers"]},"basename":"PayoutPage.tsx","language":"tsx"}],"downloadAssociatedFiles":[{"path":"guides/payout/components/web/_filesets/installation/PayoutPage.tsx","content":[{"start":0,"condition":{"steps":["import-dependencies"]},"children":["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;","};","",{"start":24,"condition":{"steps":["setup-component"]},"children":["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());","",{"start":37,"condition":{"steps":["fetch-session"]},"children":["  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;","    }","",{"start":87,"condition":{"steps":["initialize-sdk"]},"children":["    const pxpSdk = PxpCheckout.initialize({","      environment: 'test',","      session: sessionData.session,","      ownerId: merchantGroupId,","      ownerType: 'MerchantGroup',",{"start":93,"condition":{"steps":["configure-transaction"]},"children":["      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(),","      },"]},{"start":105,"condition":{"steps":["configure-paypal"]},"children":["      paypalConfig: {","        payoutConfig: {","          proceedPayoutWithSdk: true,","          paypalWallet: {","            email: wallet.email,","            payerId: wallet.payerId,","          },","        },","      },"]},"    });"]},"",{"start":119,"condition":{"steps":["create-components"]},"children":["    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',",{"start":131,"condition":{"steps":["pre-payout-callback"]},"children":["      onPrePayoutSubmit: async () => ({","        isApproved: true,","      }),"]},{"start":136,"condition":{"steps":["success-callback"]},"children":["      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.');","      },"]},{"start":168,"condition":{"steps":["error-callback"]},"children":["      onError: (error) => {","        console.error('Payout failed:', error.errorCode, error.errorReason);","        setErrorMessage('Withdrawal failed. Try again.');","      },"]},"    });"]},"",{"start":177,"condition":{"steps":["mount-components"]},"children":["    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]);","",{"start":190,"condition":{"steps":["render-containers"]},"children":["  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>","  );"]},"}"]},""],"metadata":{"steps":["import-dependencies","setup-component","fetch-session","initialize-sdk","configure-transaction","configure-paypal","create-components","pre-payout-callback","success-callback","error-callback","mount-components","render-containers"]},"basename":"PayoutPage.tsx","language":"tsx"},{"path":"guides/payout/components/web/_filesets/installation/package.json","content":["{","  \"name\": \"payout-components-integration\",","  \"version\": \"1.0.0\",","  \"description\": \"PXP Payout Components for Web integration example\",","  \"type\": \"module\",","  \"scripts\": {","    \"dev\": \"vite\",","    \"build\": \"vite build\"","  },","  \"dependencies\": {","    \"@pxpio/web-components-sdk\": \"latest\",","    \"react\": \"^19.2.3\",","    \"react-dom\": \"^19.2.3\"","  },","  \"devDependencies\": {","    \"@vitejs/plugin-react\": \"^4.0.0\",","    \"vite\": \"^4.0.0\"","  }","}",""],"metadata":{"steps":[]},"basename":"package.json","language":"text"}]}],"steps":[{"id":"import-dependencies","heading":"Import the required dependencies"},{"id":"setup-component","heading":"Set up your React component"},{"id":"fetch-session","heading":"Fetch the session and wallet data from your backend"},{"id":"initialize-sdk","heading":"Initialise the SDK"},{"id":"configure-transaction","heading":"Configure the transaction data"},{"id":"configure-paypal","heading":"Configure the PayPal wallet"},{"id":"create-components","heading":"Create the payout components"},{"id":"pre-payout-callback","heading":"Approve the payout before execution"},{"id":"success-callback","heading":"Handle successful payouts"},{"id":"error-callback","heading":"Handle payout errors"},{"id":"mount-components","heading":"Mount the components to the page"},{"id":"render-containers","heading":"Add container elements to your page"}],"inputs":{},"toggles":{}},"children":[{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"initialise-the-payout-components-on-your-frontend","__idx":4},"children":["Initialise the payout components on your frontend"]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"import-dependencies","heading":"Import the required dependencies"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Import ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["PxpCheckout"]}," and necessary types from the Web SDK."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"setup-component","heading":"Set up your React component"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Create a React component that hosts the withdrawal interface. Pass the authenticated withdrawal ID and merchant group ID from your application."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"fetch-session","heading":"Fetch the session and wallet data from your backend"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Call your backend to get the session data and the customer's stored PayPal email and payer ID."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"initialize-sdk","heading":"Initialise the SDK"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Configure the SDK with your environment, session data, owner details, and transaction information."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"configure-transaction","heading":"Configure the transaction data"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Specify the currency, amount, entry type, and PayPal payout intent."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"configure-paypal","heading":"Configure the PayPal wallet"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Set ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["paypalConfig.payoutConfig"]}," with ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["proceedPayoutWithSdk: true"]}," and the stored ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["paypalWallet"]}," email and payer ID for the returning customer."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"create-components","heading":"Create the payout components"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Create the amount, PayPal receiver, and submission components."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"pre-payout-callback","heading":"Approve the payout before execution"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Implement ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["onPrePayoutSubmit"]}," and return ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["{ isApproved: true }"]}," to let the SDK execute the payout. Return ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["{ isApproved: false }"]}," to cancel."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"success-callback","heading":"Handle successful payouts"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Implement ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["onPostPayout"]}," to handle the PXP response. Always verify successful payouts on your backend before marking the withdrawal complete, because frontend callbacks can be manipulated."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"error-callback","heading":"Handle payout errors"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Implement ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["onError"]}," to handle runtime failures during SDK-initiated payout execution. Configuration and wallet validation failures are thrown when you create components."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"mount-components","heading":"Mount the components to the page"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Call ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["mount()"]}," on each component with your container element IDs."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"render-containers","heading":"Add container elements to your page"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Return JSX that includes containers where the amount, receiver, and submission components mount."]}]}]},{"$$mdtype":"Tag","name":"CodeWalkthrough","attributes":{"__idx":3,"filters":{},"filesets":[{"files":[{"path":"guides/payout/components/web/_filesets/installation/webhook-handler.js","content":["export function registerPxpWebhook(","  app,","  {","    isTransactionProcessed,","    getWithdrawalByMerchantTransactionId,","    reconcileWithdrawal,","    markTransactionProcessed,","  },",") {",{"start":9,"condition":{"steps":["webhook-endpoint"]},"children":["  // 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) => {"]},{"start":14,"condition":{"steps":["process-events"]},"children":["  const events = Array.isArray(req.body) ? req.body : [];","","  for (const event of events) {","    if (event.eventCategory === 'Transaction' || event.eventCategory === 'transaction') {","      const txn = event.eventData;"]},"",{"start":22,"condition":{"steps":["check-state"]},"children":["      // PayPal payout success commonly uses Authorised. Confirm acceptable states for your flow.","      if (txn.state === 'Authorised' || txn.state === 'Captured') {"]},{"start":26,"condition":{"steps":["prevent-duplicates"]},"children":["        const alreadyProcessed = await isTransactionProcessed(txn.systemTransactionId);","        if (alreadyProcessed) {","          continue;","        }"]},"",{"start":33,"condition":{"steps":["verify-details"]},"children":["        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","        ) {"]},"",{"start":50,"condition":{"steps":["fulfill-order"]},"children":["          await reconcileWithdrawal(txn);","          await markTransactionProcessed(txn.systemTransactionId);","          console.log(`Withdrawal ${txn.merchantTransactionId} reconciled successfully`);"]},"        } else {","          console.error('Withdrawal verification failed - amount or currency mismatch');","        }","      }","    }","  }","",{"start":62,"condition":{"steps":["respond"]},"children":["  res.json({ state: 'Success' });"]},"  });","}",""],"metadata":{"steps":["webhook-endpoint","process-events","check-state","prevent-duplicates","verify-details","fulfill-order","respond"]},"basename":"webhook-handler.js","language":"javascript"}],"downloadAssociatedFiles":[{"path":"guides/payout/components/web/_filesets/installation/webhook-handler.js","content":["export function registerPxpWebhook(","  app,","  {","    isTransactionProcessed,","    getWithdrawalByMerchantTransactionId,","    reconcileWithdrawal,","    markTransactionProcessed,","  },",") {",{"start":9,"condition":{"steps":["webhook-endpoint"]},"children":["  // 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) => {"]},{"start":14,"condition":{"steps":["process-events"]},"children":["  const events = Array.isArray(req.body) ? req.body : [];","","  for (const event of events) {","    if (event.eventCategory === 'Transaction' || event.eventCategory === 'transaction') {","      const txn = event.eventData;"]},"",{"start":22,"condition":{"steps":["check-state"]},"children":["      // PayPal payout success commonly uses Authorised. Confirm acceptable states for your flow.","      if (txn.state === 'Authorised' || txn.state === 'Captured') {"]},{"start":26,"condition":{"steps":["prevent-duplicates"]},"children":["        const alreadyProcessed = await isTransactionProcessed(txn.systemTransactionId);","        if (alreadyProcessed) {","          continue;","        }"]},"",{"start":33,"condition":{"steps":["verify-details"]},"children":["        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","        ) {"]},"",{"start":50,"condition":{"steps":["fulfill-order"]},"children":["          await reconcileWithdrawal(txn);","          await markTransactionProcessed(txn.systemTransactionId);","          console.log(`Withdrawal ${txn.merchantTransactionId} reconciled successfully`);"]},"        } else {","          console.error('Withdrawal verification failed - amount or currency mismatch');","        }","      }","    }","  }","",{"start":62,"condition":{"steps":["respond"]},"children":["  res.json({ state: 'Success' });"]},"  });","}",""],"metadata":{"steps":["webhook-endpoint","process-events","check-state","prevent-duplicates","verify-details","fulfill-order","respond"]},"basename":"webhook-handler.js","language":"javascript"}]}],"steps":[{"id":"webhook-endpoint","heading":"Create the webhook endpoint"},{"id":"process-events","heading":"Process webhook events"},{"id":"check-state","heading":"Check payout state"},{"id":"prevent-duplicates","heading":"Prevent duplicate processing"},{"id":"verify-details","heading":"Verify transaction details"},{"id":"fulfill-order","heading":"Reconcile the withdrawal"},{"id":"respond","heading":"Respond to webhook"},{"id":"verification-route","heading":"Register the verification endpoint"}],"inputs":{},"toggles":{}},"children":[{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"verify-payouts","__idx":5},"children":["Verify payouts"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["When PXP returns a payout response, ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["onPostPayout"]}," receives the result. Always verify the payout on your backend before marking the withdrawal complete."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Configure webhooks in the Unity Portal to receive real-time transaction notifications on your backend."]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"webhook-endpoint","heading":"Create the webhook endpoint"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Register ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["/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 ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["registerPxpWebhook()"]},"."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"process-events","heading":"Process webhook events"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Loop through the events array and filter for Transaction events."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"check-state","heading":"Check payout state"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Verify the transaction state is an accepted success state (for example ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["Authorised"]},") before processing."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"prevent-duplicates","heading":"Prevent duplicate processing"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Skip events you've already handled by checking ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["systemTransactionId"]}," before reconciliation."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"verify-details","heading":"Verify transaction details"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Match the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["merchantTransactionId"]},", amount, and currency against your withdrawal records."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"fulfill-order","heading":"Reconcile the withdrawal"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["If verification passes, reconcile the withdrawal and mark the transaction as processed."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"respond","heading":"Respond to webhook"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["After authenticating the request, return ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["{ state: 'Success' }"]}," to acknowledge receipt. Handle reconciliation failures through your own retry and incident process rather than failing the webhook response in this sample."]}]},{"$$mdtype":"Tag","name":"CodeStep","attributes":{"id":"verification-route","heading":"Register the verification endpoint"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Register ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["/api/verify-payout"]}," on your backend. Load the authenticated customer's withdrawal and retrieve the authoritative transaction from PXP before returning a verified result."]}]},{"$$mdtype":"Tag","name":"Admonition","attributes":{"type":"info"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["You can also verify payouts using the Transactions API to query transaction status directly. See ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"/guides/payout/components/web/paypal/withdrawal-flow"},"children":["Withdrawal flow"]}," for the end-to-end returning-customer integration."]}]}]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["You now have the core fragments needed to add a PayPal payout Components integration to your application."]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"whats-next","__idx":6},"children":["What's next?"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Now that you have payout components running, here are the recommended next steps:"]},{"$$mdtype":"Tag","name":"ul","attributes":{"className":"code-walkthrough-list"},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"a","attributes":{"href":"/guides/payout/components/web/paypal/how-it-works"},"children":["How it works"]},": PayPal and Venmo payout concepts, compliance, and execution modes"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"a","attributes":{"href":"/guides/payout/components/web/paypal/onboarding"},"children":["Onboarding"]},": Connect your PayPal Business account"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"a","attributes":{"href":"/guides/payout/components/web/paypal/withdrawal-flow"},"children":["Withdrawal flow"]},": Full returning-customer integration"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"a","attributes":{"href":"/guides/payout/components/web/paypal/about-configuration"},"children":["Configuration"]},": Customise amount, receiver, and submission components"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"a","attributes":{"href":"/guides/payout/components/web/paypal/events"},"children":["Events"]},": Add callbacks for approval, success, and errors"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"a","attributes":{"href":"/guides/payout/components/web/paypal/error-handling"},"children":["Error handling"]},": Map payout error codes to customer-facing messages"]}]}]},"headings":[{"value":"Quickstart","id":"quickstart","depth":1},{"value":"Requirements","id":"requirements","depth":2},{"value":"Install the SDK","id":"install-the-sdk","depth":2},{"value":"Create a session on your backend","id":"create-a-session-on-your-backend","depth":2},{"value":"Initialise the payout components on your frontend","id":"initialise-the-payout-components-on-your-frontend","depth":2},{"value":"Verify payouts","id":"verify-payouts","depth":2},{"value":"What's next?","id":"whats-next","depth":2}],"frontmatter":{"markdown":{"toc":{"hide":true}},"footer":{"hide":true},"seo":{"title":"Quickstart"}},"lastModified":"2026-11-11T13:55:54.000Z","pagePropGetterError":{"message":"","name":""}},"slug":"/guides/payout/components/web/quickstart","userData":{"isAuthenticated":false,"teams":["anonymous"]},"isPublic":true}