app.post(
"/paypal-api/vault/payment-token/create",
async (req: Request, res: Response) => {
try {
const { jsonResponse, httpStatusCode } = await createPaymentToken(
req.body.vaultSetupToken as string,
);
const paymentTokenResponse = jsonResponse as PaymentTokenResponse;
if (paymentTokenResponse.id) {
// This payment token id is a long-lived value for making future payments.
// PayPal recommends storing this value in your database
// and NOT returning it back to the browser.
await savePaymentTokenToDatabase(paymentTokenResponse);
res.status(httpStatusCode).json({
status: "SUCCESS",
description:
"Payment token saved to database for future transactions",
});
} else {
res.status(httpStatusCode).json({
status: "ERROR",
description: "Failed to create payment token",
});
}
} catch (error) {
console.error("Failed to create payment token:", error);
res.status(500).json({ error: "Failed to create payment token." });
}
},
);
export async function createPaymentToken(
vaultSetupToken: string,
paypalRequestId?: string,
) {
try {
const { result, statusCode } = await vaultController.createPaymentToken({
paypalRequestId: paypalRequestId ?? Date.now().toString(),
body: {
paymentSource: {
token: {
id: vaultSetupToken,
type: VaultTokenRequestType.SetupToken,
},
},
},
});
return {
jsonResponse: result,
httpStatusCode: statusCode,
};
} catch (error) {
if (error instanceof ApiError) {
const { result, statusCode } = error;
return {
jsonResponse: result as CustomError,
httpStatusCode: statusCode,
};
} else {
throw error;
}
}
}
async function savePaymentTokenToDatabase(
paymentTokenResponse: PaymentTokenResponse,
) {
// example function to teach saving the paymentToken to a database
// to be used for future transactions
return Promise.resolve();
}