Back to snippets
paypal_js_sdk_order_creation_and_payment_capture_typescript.ts
typescriptCreates a PayPal order and captures payment using the official PayPal JavaScript/
Agent Votes
0
0
paypal_js_sdk_order_creation_and_payment_capture_typescript.ts
1import {
2 PayPalButtonsComponentOptions,
3 loadScript
4} from "@paypal/paypal-js";
5
6/**
7 * This quickstart demonstrates how to integrate the PayPal JavaScript SDK
8 * using TypeScript to create an order and capture a payment.
9 */
10async function initializePayPal(): Promise<void> {
11 const CLIENT_ID = "test"; // Replace with your actual Client ID
12
13 try {
14 const paypal = await loadScript({
15 "client-id": CLIENT_ID,
16 currency: "USD"
17 });
18
19 if (paypal && paypal.Buttons) {
20 const buttonOptions: PayPalButtonsComponentOptions = {
21 // Sets up the transaction when a payment button is clicked
22 createOrder: (data, actions) => {
23 return actions.order.create({
24 purchase_units: [{
25 amount: {
26 value: "77.44" // Can reference variables or functions
27 }
28 }]
29 });
30 },
31 // Finalizes the transaction after payer approval
32 onApprove: async (data, actions) => {
33 if (actions.order) {
34 const details = await actions.order.capture();
35 const name = details.payer.name?.given_name;
36 alert(`Transaction completed by ${name}`);
37 }
38 },
39 onError: (err) => {
40 console.error("PayPal Checkout Error:", err);
41 }
42 };
43
44 await paypal.Buttons(buttonOptions).render("#paypal-button-container");
45 }
46 } catch (error) {
47 console.error("Failed to load the PayPal JS SDK script", error);
48 }
49}
50
51// Ensure there is a <div id="paypal-button-container"></div> in your HTML
52initializePayPal();