Guest User

Paypal Manager Class

a guest
Aug 5th, 2026
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { loadScript } from "@paypal/paypal-js";
  2. import SendClientInfo from './sendClientInfo.js';
  3.  
  4. class PayPalManager {
  5.     constructor(client_id, formContainer, paypalContainer, orderEndPoint, emailEndPoint) {
  6.         console.log("this is paypal_manager");
  7.    
  8.         this.client_id = client_id;
  9.         this.paypal = null;
  10.         /*this.sendClientInfo =
  11.         new SendClientInfo(
  12.             ".checkoutForm",
  13.             ".checkoutForm .contactInfo",
  14.             ".checkoutForm .address",
  15.             "#formAction",
  16.             emailEndPoint,
  17.             "div[aria-label='PayPal']",
  18.             orderData
  19.         );*/
  20.         this.buttonContainer = document.querySelector(paypalContainer);
  21.         this.orderEndPoint = orderEndPoint;
  22.         this.emailEndPoint = emailEndPoint;
  23.         console.log("this.paypal in the constructor: ", this.paypal);
  24.         //console.log("this.sendClientInfo in the constructor: ", this.sendClientInfo);
  25.        
  26.     }
  27.  
  28.     // Loads the SDK script into the window
  29.     async init() {
  30.         console.log("init() called");
  31.        
  32.         try {
  33.             this.paypal = await loadScript({ "client-id": this.client_id });
  34.         console.log("PayPal SDK loaded: ", this.paypal);
  35.             console.log("this.paypal inside init(): ", this.paypal.client_id);
  36.         } catch (error) {
  37.             console.error("Failed to load the PayPal JS SDK script:", error);
  38.             throw error;
  39.         }
  40.     }
  41.  
  42.     // Renders the button into the specified container element
  43.     async renderButtons(containerId = "#paypal-button-container") {
  44.         console.log("renderButtons called");
  45.         const orderEndPoint = this.orderEndPoint;
  46.         const emailEndPoint = this.emailEndPoint;
  47.         if (!this.paypal) {
  48.             console.error("PayPal SDK is not initialized. Call init() first.");
  49.             return;
  50.         }
  51.  
  52.         try {
  53.             await this.paypal.Buttons({
  54.                 style: {
  55.                     layout: 'vertical',
  56.                     color:  'gold',
  57.                     shape:  'rect',
  58.                     label:  'paypal'
  59.                 },
  60.                
  61.                 // Call your server to set up the transaction
  62.                 createOrder: function(data, actions) {
  63.                     console.log("createOrder called");
  64.                    
  65.                    
  66.                    
  67.                     return fetch(orderEndPoint, {
  68.                         method: 'post'
  69.                     }).then(function(res) {
  70.                         return res.json();
  71.                     }).then(function(orderData) {
  72.                         return orderData.id;
  73.                     });
  74.                 },
  75.                
  76.                 // Call your server to finalize the transaction
  77.                 onApprove: function(data, actions) {
  78.                     console.log("onApprove called");
  79.                     // ADD CUSTOM LOGIC FOR SENDING EMAIL HERE
  80.                     return (async () => {
  81.                         try {
  82.                             const res = await fetch(
  83.                                 orderEndPoint + data.orderID + '/capture/',
  84.                                 {
  85.                                 method: 'post'
  86.                             });
  87.                             console.log("res result: ", res);
  88.                            
  89.                             const orderData = await res.json();
  90.                             console.log("orderData result: ", orderData);
  91.                            
  92.                             const errorDetail = Array.isArray(orderData.details) && orderData.details[0];
  93.                             console.log("errorDetail result: ", errorDetail);
  94.                            
  95.                             // Three cases to handle:
  96.                             //   (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
  97.                             //   (2) Other non-recoverable errors -> Show a failure message
  98.                             //   (3) Successful transaction -> Send confirmation email and show confirmation or thank you
  99.  
  100.                             // This example reads a v2/checkout/orders capture response, propagated from the server
  101.                             // You could use a different API or structure for your 'orderData'
  102.                            
  103.                             if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
  104.                                     return actions.restart(); // Recoverable state, per:
  105.                                     // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
  106.                             }
  107.  
  108.                             if (errorDetail) {
  109.                                 let msg = 'Sorry, your transaction could not be processed.';
  110.                                 if (errorDetail.description) msg += '\n\n' + errorDetail.description;
  111.                                 if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
  112.                                 return alert(msg); // Show a failure message (try to avoid alerts in production environments)
  113.                             }
  114.                            
  115.                             // Successful capture! For demo purposes:
  116.                             console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
  117.                             const transaction = orderData.purchase_units[0].payments.captures[0];
  118.                             console.log("orderData at line 104 (paypal_manager.js): ", orderData);
  119.                             alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
  120.  
  121.                             // Replace the above to show a success message within this page, e.g.
  122.                             // const element = document.getElementById('paypal-button-container');
  123.                             // element.innerHTML = '';
  124.                             // element.innerHTML = '<h3>Thank you for your payment!</h3>';
  125.                             // Or go to another URL:  actions.redirect('thank_you.html');
  126.                             /*
  127.                             const sendClientInfo = new SendClientInfo(
  128.                                 this.formBody,
  129.                                 this.contactInfo,
  130.                                 this.address,
  131.                                 "#formAction",
  132.                                 emailEndPoint,
  133.                                 "div[aria-label='PayPal']",
  134.                                 orderData
  135.                             );
  136.                             */
  137.                            
  138.                             const sendClientInfo = new SendClientInfo(
  139.                                 this.formContainer,
  140.                                 ".checkoutForm .contactInfo",
  141.                                 ".checkoutForm .address",
  142.                                 "#formAction",
  143.                                 emailEndPoint,
  144.                                 "div[aria-label='PayPal']",
  145.                                 orderData
  146.                             );
  147.                             await sendClientInfo.sendMail(sendClientInfo.postUrl, sendClientInfo.order);
  148.                            
  149.                             sendClientInfo.clearForm(document.querySelector(this.formContainer));
  150.                         }
  151.                         catch(error) {
  152.                             console.error("the transaction could not be processed post approval: ", error);
  153.                             throw error;
  154.                         }
  155.                        
  156.                     })();
  157.                    
  158.                 },
  159.                 // If an order is cancelled
  160.                 // TODO: sendClientInfo should not be called if an order is cancelled.
  161.                 onCancel: function(data) {
  162.                     console.log('Payment cancelled: ', data);
  163.                 },
  164.                 // If an error occurs
  165.                 // TODO: sendClientInfo should not be called if an error occurs.
  166.                 onError: function(err) {
  167.                     console.error('PayPal error: ', err);
  168.                 }
  169.             }).render(".paymentMethods .paypalContainer");
  170.         } catch (error) {
  171.             console.error("Failed to render the PayPal Buttons:", error);
  172.             throw error;
  173.         }
  174.     }
  175. }
  176.  
  177. export default PayPalManager;
Advertisement
Add Comment
Please, Sign In to add comment