JSFiddle - React, Tailwind, and code Playground

by Lucas Bittar Magnani

JavaScript

// payment-controller.js

/*
 * Controller method triggered as user selects to pay with PayPal
 */
function payWithPayPal() {

  var token = commonsService.extractParam('token');

  if (token) {
    var url = paypal.checkout.urlPrefix + token;
    paypal.checkout.initXO();
    paypal.checkout.restartFlow(url);
  } else {
    $rs.startSpin();
    paymentService.payWithPayPal($s.event.id, 'payment', $s.summary.total, function (response) {
      callbackPayPal(response)
    });
  }
}

/*
 * Callback method that checks if token was retrived successfully.
 * If so, calls mini-browser's method. First PayPal's flow ends here 
 * and waits for user's interaction with mini-browser to proceed the purchase
 */
function callbackPayPal (response) {
  console.log(response);
  $rs.stopSpin();
  if (response.status) {
    var url = paypal.checkout.urlPrefix + response.token;
    paypal.checkout.initXO();
    paypal.checkout.startFlow(url);
  } else {
    $s.requestingUpdate = false;
    notificationService.error(response.message);
    paypal.checkout.closeFlow();
  }
}

// payment-service.js

var paymentService = [

	/*
   * Initializes PayPal
   */
  function initPayPal() {

    if(!payPalInitialized) {
      paypal.checkout.setup("38QDZQ8BET5H8", {
        environment: 'sandbox',
        button: ['paypalMethod']
      });

      payPalInitialized = true;
    }
  }

	return {

    /**
     * Call IR's API to retrieve PayPal's token
     */
    payWithPayPal : function(eventId, urlSufix, value, callback) {

      $rs.totalValue = value;
      initPayPal();

      var currentPath = window.location.protocol + '//' + window.location.host + window.location.pathname,
          returnUrl = currentPath + '?id=' + eventId + '#!/' + urlSufix + '?paypal=1',
          cancelUrl = currentPath + '?id=' + eventId + '#!/' + urlSufix + '?paypal=0';

      function process(response, status) {
        var object = parsePayPal(response, status);
        callback(object);
      }

     ...