Build a working Payout Drop-in withdrawal in your sandbox with this walkthrough.
Before you start, make sure you have:
- Node.js 22.x or higher (for a Node.js backend) or the .NET SDK (for a .NET backend)
- API credentials from the Unity Portal (Client ID and an inbound API token)
- Payout Drop-in enabled for your site in the Unity Portal, with payout methods configured
- At least one eligible stored payout instrument for the shopper you test with (saved card, linked PayPal account, or Apple Pay or Google Pay device token), unless you are validating empty-state behaviour
The Session API returns which funding types are allowed. Drop-in shows a method only when the session permits it and the shopper has an instrument that passes SDK filtering.
Install the latest Web SDK from the npm public registry. You'll need Node.js 22.x or higher for the frontend package install.
npm i @pxpio/web-components-sdkImport PayoutDropIn from the package root (@pxpio/web-components-sdk). Prefer a single named import over paths under /src/.
Drop-in needs a session from the PXP API. Create it on your backend so inbound credentials stay secure.
Integration uses two authorisation steps, each with its own scheme:
- Your server calls the Sessions API to get credentials the Web SDK will use.
- At this point there's no session yet, only Unity Portal merchant token credentials (client ID and inbound API token).
- The correct scheme here is
PXP-UST1. - The quickstart Node.js and .NET samples cover only this step.
- After
PayoutDropIn.initialize({ session }), the SDK calls Unity APIs such as payout Drop-in configuration, Token Vault, PayPal association, and payout submission. - Those calls use the session (
sessionIdand the signing key from the session response). - The scheme there is
PXP-WCA1. - The SDK adds this automatically. Don't implement
PXP-WCA1in your backend session-creation sample.
Store your credentials securely
Set up your API credentials as environment variables. Never hardcode them in your application.
Create the HMAC signature function
Concatenate the timestamp, request ID, request path (api/v1/sessions), and minified request body with no separators, then create an HMAC SHA256 hash using your token value. Encode the digest as uppercase hex. This signature is for the PXP-UST1 session request only.
Build the session request body
Create a request with merchant and site IDs, withdrawal amount, serviceType: "PayoutDropIn", and transactionMethod.intent values of Payout for each method you enable. Minify the body before signing.
Send the session creation request
POST to https://api-services.pxp.io/api/v1/sessions with Authorization: PXP-UST1 {tokenId}:{timestamp}:{signature}, X-Request-Id, X-Client-Id, and the minified JSON body.
Return the session data to your frontend
Return the Sessions API response as session, plus transactionData with the same merchantTransactionId, amount, and currency you used when creating the session. Only return this to the authenticated shopper who owns the withdrawal.
PayoutDropIn.initialize() doesn't take payment intents on transactionData. Intents are set on the session at creation time. The frontend must still pass matching amount, currency, and merchantTransactionId. Card visibility requires allowedFundingTypes.cards on the session response; cardSchemes alone isn't enough.
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 Drop-in session from your merchant backend.
*/
export async function createSession({
merchantId,
siteId,
amount,
currency,
customerProfileId,
}) {
const timestamp = Math.floor(Date.now() / 1000);
const requestId = crypto.randomUUID();
const merchantTransactionId = crypto.randomUUID();
// Build the request body. Use intent Payout and serviceType PayoutDropIn.
const requestBody = {
merchant: merchantId,
site: siteId,
sessionTimeout: 120,
merchantTransactionId,
amounts: {
currencyCode: currency,
transactionValue: amount,
},
transactionMethod: {
intent: {
card: 'Payout',
paypal: 'Payout',
},
},
allowTransaction: true,
serviceType: 'PayoutDropIn',
};
if (customerProfileId) {
requestBody.customerProfileId = customerProfileId;
}
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,
},
};
}Import the required dependencies
Import PayoutDropIn and the types you need from @pxpio/web-components-sdk.
Set up your React component
Create a React component that hosts Payout Drop-in and destroys the instance on unmount.
Fetch the session data from your backend
Call your authenticated backend endpoint to create the payout session and return session plus transactionData.
Initialise Payout Drop-in
Configure Drop-in with environment, session, merchant group ownerId, transaction data, and callbacks. ownerType is set to MerchantGroup automatically.
Configure the transaction data
Pass currency, amount, entryType, merchantTransactionId, and merchantTransactionDate. Don't pass payment intents here: the SDK sets payout intents internally.
Provide a shopper identifier
Implement onGetShopper with the authenticated shopper ID so Drop-in can load stored cards, wallet device tokens, and PayPal association.
Optionally validate before card-on-file submit
onBeforeSubmit and onSubmit run for Card, Apple Pay, and Google Pay only. PayPal uses onSuccess or onError alone.
Show loading when card-on-file submit starts
Use onSubmit to show progress UI for Card, Apple Pay, and Google Pay.
Handle successful submissions
Implement onSuccess, then verify the payout on your backend before updating withdrawal status. Frontend callbacks can be manipulated.
Handle payout errors
Implement onError and map ErrorCode to shopper-safe messages. See Error handling.
Mount Drop-in to the page
Call create('payout-drop-in-container') after the container exists in the DOM.
Add a container element to your page
Return JSX that includes a container div where Payout Drop-in mounts.
import {
PayoutDropIn,
type BaseSdkException,
type PayoutDropInSubmitResult,
} from '@pxpio/web-components-sdk';
import { useEffect } from 'react';
export default function PayoutPage({
shopperId,
merchantGroupId,
}: {
shopperId: string;
merchantGroupId: string;
}) {
useEffect(() => {
let disposed = false;
let instance: PayoutDropIn | undefined;
async function initialisePayoutDropIn() {
// 1. Get the session data from your backend
const { session, transactionData } = await fetch('/api/create-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
amount: 25.0,
currency: 'USD',
}),
}).then((response) => response.json());
// 2. Initialise Payout Drop-in
const payoutDropIn = PayoutDropIn.initialize({
environment: 'test',
session,
ownerId: merchantGroupId,
transactionData: {
currency: transactionData.currency,
amount: transactionData.amount,
entryType: 'Ecom',
merchantTransactionId: transactionData.merchantTransactionId,
merchantTransactionDate: () => new Date().toISOString(),
},
onGetShopper: async () => ({ id: shopperId }),
onBeforeSubmit: async (payoutMethod) => {
console.log('Payout method selected:', payoutMethod);
return true;
},
onSubmit: (payoutMethod) => {
console.log('Payout processing started:', payoutMethod);
},
onSuccess: async (result: PayoutDropInSubmitResult) => {
// CRITICAL: Do NOT mark the withdrawal complete here.
// Frontend callbacks can be manipulated. Always verify on your backend.
console.log('Payout submitted:', result.systemTransactionId, result.payoutMethod);
const verified = await fetch('/api/verify-payout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
systemTransactionId: result.systemTransactionId,
merchantTransactionId: result.merchantTransactionId,
payoutMethod: result.payoutMethod,
payouts: result.payouts,
}),
}).then((response) => response.json());
if (verified.success) {
window.location.href = `/withdrawal-confirmation?id=${verified.withdrawalId}`;
} else {
alert(
'We received your request but could not confirm it yet. Please contact support if needed.',
);
}
},
onError: (error: BaseSdkException) => {
console.error('Payout failed:', error.ErrorCode, error.message);
alert(error.message || 'Withdrawal failed. Please try again.');
},
});
// 3. Mount Drop-in to your page
await payoutDropIn.create('payout-drop-in-container');
if (disposed) {
payoutDropIn.destroy();
return;
}
instance = payoutDropIn;
}
void initialisePayoutDropIn().catch((error) => {
console.error('Could not mount Payout Drop-in', error);
});
return () => {
disposed = true;
instance?.destroy();
};
}, [shopperId, merchantGroupId]);
return (
<div>
<h1>Withdraw funds</h1>
<div id="payout-drop-in-container"></div>
</div>
);
}When a payout submission succeeds, onSuccess fires with transaction details. Always verify on your backend before marking a withdrawal complete.
Configure webhooks in the Unity Portal to receive transaction notifications on your server. Payout Drop-in uses the same merchant transaction webhook channel as other products. A successful payout looks like this:
{ "eventDate": "2025-12-16T07:37:11.1613200Z", "eventCategory": "transaction", "eventData": { "state": "Authorised", "amount": { "transaction": 100, "currencyCode": "USD" }, "transactionMethod": "Payout", "merchant": "merchant-1", "site": "site-1", "merchantTransactionDate": "2025-12-16T07:37:11.1613200Z", "merchantTransactionId": "PAYOUT_001", "systemTransactionId": "787ebfee-c0ce-497a-82c3-265d1bf19b0c", "providerTransactionId": "PAYPAL_PAYOUT_ITEM_ID", "fundingData": { "paypal": { … } } } }
See Manage webhooks for subscription and signature validation.
Create the webhook endpoint
Set up an endpoint at /webhooks/pxp to receive notifications from Unity.
Process webhook events
Loop through the events array and filter for eventCategory values of transaction.
Check payout state
Filter to the successful payout states defined for your programme. The documented success examples use Authorised. Confirm acceptable states for each method you enable.
Prevent duplicate processing
Skip events you have already handled using systemTransactionId.
Verify transaction details
Match merchantTransactionId, amount, and currency against the withdrawal you authorised.
Reconcile the withdrawal
If verification passes, update withdrawal status and mark the transaction as processed.
Respond to the webhook
Always return { state: 'Success' } to acknowledge receipt, even if processing failed.
You can also verify payouts with the Transactions API. See Implementation for the broader integration flow.
// Webhook endpoint to receive payout transaction notifications
// Configure this URL in the Unity Portal under Webhooks
app.post('/webhooks/pxp', async (req, res) => {
const events = req.body;
for (const event of events) {
if (event.eventCategory !== 'transaction') {
continue;
}
const txn = event.eventData;
// PayPal payout success uses Authorised in the merchant-webhook example.
// Confirm acceptable states for each method you enable.
if (!isSuccessfulPayoutState(txn.state)) {
continue;
}
const alreadyProcessed = await isTransactionProcessed(txn.systemTransactionId);
if (alreadyProcessed) {
continue;
}
const expectedWithdrawal = await getWithdrawalByMerchantTransactionId(
txn.merchantTransactionId,
);
// PayPal payout webhooks use amount.transaction / amount.currencyCode.
// Other methods 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' });
});
function isSuccessfulPayoutState(state) {
// Extend with successful states for each method you enable
const successfulStates = ['Authorised'];
return successfulStates.includes(state);
}That's it! You now have a working Payout Drop-in integration.
Explore these guides next:
- See Implementation for HMAC details, mount lifecycle, and method availability.
- See Configuration for initialiser options,
methodConfig, and localisation. - See Events for callbacks and ordering.
- Check Card, PayPal, Apple Pay, and Google Pay for method requirements.
- Use Testing and Troubleshooting to validate and diagnose your integration.