Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { loadScript } from "@paypal/paypal-js";
- import SendClientInfo from './sendClientInfo.js';
- class PayPalManager {
- constructor(client_id, formContainer, paypalContainer, orderEndPoint, emailEndPoint) {
- console.log("this is paypal_manager");
- this.client_id = client_id;
- this.paypal = null;
- /*this.sendClientInfo =
- new SendClientInfo(
- ".checkoutForm",
- ".checkoutForm .contactInfo",
- ".checkoutForm .address",
- "#formAction",
- emailEndPoint,
- "div[aria-label='PayPal']",
- orderData
- );*/
- this.buttonContainer = document.querySelector(paypalContainer);
- this.orderEndPoint = orderEndPoint;
- this.emailEndPoint = emailEndPoint;
- console.log("this.paypal in the constructor: ", this.paypal);
- //console.log("this.sendClientInfo in the constructor: ", this.sendClientInfo);
- }
- // Loads the SDK script into the window
- async init() {
- console.log("init() called");
- try {
- this.paypal = await loadScript({ "client-id": this.client_id });
- console.log("PayPal SDK loaded: ", this.paypal);
- console.log("this.paypal inside init(): ", this.paypal.client_id);
- } catch (error) {
- console.error("Failed to load the PayPal JS SDK script:", error);
- throw error;
- }
- }
- // Renders the button into the specified container element
- async renderButtons(containerId = "#paypal-button-container") {
- console.log("renderButtons called");
- const orderEndPoint = this.orderEndPoint;
- const emailEndPoint = this.emailEndPoint;
- if (!this.paypal) {
- console.error("PayPal SDK is not initialized. Call init() first.");
- return;
- }
- try {
- await this.paypal.Buttons({
- style: {
- layout: 'vertical',
- color: 'gold',
- shape: 'rect',
- label: 'paypal'
- },
- // Call your server to set up the transaction
- createOrder: function(data, actions) {
- console.log("createOrder called");
- return fetch(orderEndPoint, {
- method: 'post'
- }).then(function(res) {
- return res.json();
- }).then(function(orderData) {
- return orderData.id;
- });
- },
- // Call your server to finalize the transaction
- onApprove: function(data, actions) {
- console.log("onApprove called");
- // ADD CUSTOM LOGIC FOR SENDING EMAIL HERE
- return (async () => {
- try {
- const res = await fetch(
- orderEndPoint + data.orderID + '/capture/',
- {
- method: 'post'
- });
- console.log("res result: ", res);
- const orderData = await res.json();
- console.log("orderData result: ", orderData);
- const errorDetail = Array.isArray(orderData.details) && orderData.details[0];
- console.log("errorDetail result: ", errorDetail);
- // Three cases to handle:
- // (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
- // (2) Other non-recoverable errors -> Show a failure message
- // (3) Successful transaction -> Send confirmation email and show confirmation or thank you
- // This example reads a v2/checkout/orders capture response, propagated from the server
- // You could use a different API or structure for your 'orderData'
- if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
- return actions.restart(); // Recoverable state, per:
- // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
- }
- if (errorDetail) {
- let msg = 'Sorry, your transaction could not be processed.';
- if (errorDetail.description) msg += '\n\n' + errorDetail.description;
- if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
- return alert(msg); // Show a failure message (try to avoid alerts in production environments)
- }
- // Successful capture! For demo purposes:
- console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
- const transaction = orderData.purchase_units[0].payments.captures[0];
- console.log("orderData at line 104 (paypal_manager.js): ", orderData);
- alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');
- // Replace the above to show a success message within this page, e.g.
- // const element = document.getElementById('paypal-button-container');
- // element.innerHTML = '';
- // element.innerHTML = '<h3>Thank you for your payment!</h3>';
- // Or go to another URL: actions.redirect('thank_you.html');
- /*
- const sendClientInfo = new SendClientInfo(
- this.formBody,
- this.contactInfo,
- this.address,
- "#formAction",
- emailEndPoint,
- "div[aria-label='PayPal']",
- orderData
- );
- */
- const sendClientInfo = new SendClientInfo(
- this.formContainer,
- ".checkoutForm .contactInfo",
- ".checkoutForm .address",
- "#formAction",
- emailEndPoint,
- "div[aria-label='PayPal']",
- orderData
- );
- await sendClientInfo.sendMail(sendClientInfo.postUrl, sendClientInfo.order);
- sendClientInfo.clearForm(document.querySelector(this.formContainer));
- }
- catch(error) {
- console.error("the transaction could not be processed post approval: ", error);
- throw error;
- }
- })();
- },
- // If an order is cancelled
- // TODO: sendClientInfo should not be called if an order is cancelled.
- onCancel: function(data) {
- console.log('Payment cancelled: ', data);
- },
- // If an error occurs
- // TODO: sendClientInfo should not be called if an error occurs.
- onError: function(err) {
- console.error('PayPal error: ', err);
- }
- }).render(".paymentMethods .paypalContainer");
- } catch (error) {
- console.error("Failed to render the PayPal Buttons:", error);
- throw error;
- }
- }
- }
- export default PayPalManager;
Advertisement
Add Comment
Please, Sign In to add comment