Skip to content

Commit

Permalink
Paypal with express checkout (#378)
Browse files Browse the repository at this point in the history
* Refactor paypal method class

* PHPCS code formating

* WIP: PayPal Express flow

* Add condition to disable paypal button when attribute is not selected

* Fix script loading if gateway is not available

* Change PayPal request parameters,
Clear PayPal session on any changes to cart,
Add nonce to AJAX request,
Fix code formatting,

* Update checkout field as per selected in PayPal popup

* Add first name last name spliting from content details

* Add logs behind condition
  • Loading branch information
SanketChodavadiya authored Jun 24, 2024
1 parent 742731c commit 5faa8c8
Show file tree
Hide file tree
Showing 9 changed files with 977 additions and 232 deletions.
16 changes: 10 additions & 6 deletions assets/js/cko-frames-integration.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,21 @@ jQuery(function () {
}

function initFrames() {
var localization;
let localization;

if ( ! document.getElementById( "public-key" ) ) {
return;
}

try {
localization = JSON.parse( document.getElementById("localization").value );
} catch ( e ) {
localization = document.getElementById("localization").value;
localization = document.getElementById("localization")?.value;
}

Frames.init({
debug: document.getElementById( "debug" ).value === "yes",
publicKey: document.getElementById("public-key").value,
debug: document.getElementById( "debug" )?.value === "yes",
publicKey: document.getElementById("public-key")?.value,
localization: localization,
schemeChoice: true,
modes: [ Frames.modes.FEATURE_FLAG_SCHEME_CHOICE ],
Expand Down Expand Up @@ -118,7 +122,7 @@ jQuery(function () {
}
}

if (document.getElementById("multiFrame").value == 1) {
if ( document.getElementById("multiFrame")?.value == 1 ) {
var logos = generateLogos();

function generateLogos() {
Expand Down Expand Up @@ -352,7 +356,7 @@ jQuery(function () {
* function to show saved card checkbox based on logged-in user
*/
function checkUserLoggedIn() {
if (document.getElementById("user-logged-in").value) {
if ( document.getElementById("user-logged-in")?.value ) {
jQuery(".cko-save-card-checkbox").show();
} else {
jQuery(".cko-save-card-checkbox").hide();
Expand Down
176 changes: 176 additions & 0 deletions assets/js/cko-paypal-express-integration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
/* global cko_paypal_vars */

jQuery( function ( $ ) {

const formSelector = 'form.cart';

const onFormChange = function ( e ) {
const form = document.querySelector( formSelector );

const addToCartButton = form ? form.querySelector('.single_add_to_cart_button') : null;

const isEnabled = ( null === addToCartButton ) || ! addToCartButton.classList.contains( 'disabled' );

const element = jQuery( cko_paypal_vars.paypal_button_selector );

if ( isEnabled ) {
jQuery(element)
.removeClass('cko-disabled')
.off('mouseup')
.find('> *')
.css('pointer-events', '');
} else {
jQuery(element)
.addClass('cko-disabled')
.on('mouseup', function(event) {
event.stopImmediatePropagation();
})
.find('> *')
.css('pointer-events', 'none');
}

};

const getAttributes = function() {
var select = $( '.variations_form' ).find( '.variations select' ),
data = {},
count = 0,
chosen = 0;

select.each( function() {
var attribute_name = $( this ).data( 'attribute_name' ) || $( this ).attr( 'name' );
var value = $( this ).val() || '';

if ( value.length > 0 ) {
chosen ++;
}

count ++;
data[ attribute_name ] = value;
});

return {
'count' : count,
'chosenCount': chosen,
'data' : data
};
};

const cko_express_add_to_cart = async function () {
var product_id = $( '.single_add_to_cart_button' ).val();

// Check if product is a variable product.
if ( $( '.single_variation_wrap' ).length ) {
product_id = $( '.single_variation_wrap' ).find( 'input[name="product_id"]' ).val();
}

var data = {
product_id: product_id,
qty: $( '.quantity .qty' ).val(),
attributes: $( '.variations_form' ).length ? getAttributes().data : [],
nonce: cko_paypal_vars.paypal_express_add_to_cart_nonce
};

return await $.ajax( {
url: cko_paypal_vars.add_to_cart_url,
type: 'POST',
async: false,
data: data
} ).done( function ( response ) {
cko_paypal_vars.debug && console.log( response );
} )
}

const cko_express_create_order_id = async function () {
let addToCartSuccess = await cko_express_add_to_cart()

// Prepare add-to-cart for express checkout.
let data = {
express_checkout: true,
add_to_cart: addToCartSuccess.result
}

cko_paypal_vars.debug && console.log( data );

// Get Order ID from below endpoint.
return fetch( cko_paypal_vars.create_order_url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: jQuery.param( data )
}).then(function (res) {
return res.json();
}).then(function (data) {
if (typeof data.success !== 'undefined') {
let messages = data.data.messages ? data.data.messages : data.data;

if ( 'string' === typeof messages || Array.isArray( messages ) ) {
showError( messages );
}
return null;
} else {
return data.order_id;
}
});
};

const paypalButton = {
init: function () {
// Initialize PayPal express button.
paypal.Buttons({ ...this.paypalButtonProps() }).render( cko_paypal_vars.paypal_button_selector );

this.updateButtonVisibility();

jQuery(document).on('change', formSelector, onFormChange );
},

paypalButtonProps: function () {
let paypalButtonProps = {
onApprove: async function (data) {
cko_paypal_vars.debug && console.log(data);

jQuery.post(cko_paypal_vars.paypal_order_session_url + "&paypal_order_id=" + data.orderID + "&woocommerce-process-checkout-nonce=" + cko_paypal_vars.woocommerce_process_checkout, function (data) {
if (typeof data.success !== 'undefined' && data.success !== true ) {
var messages = data.data.messages ? data.data.messages : data.data;

if ( 'string' === typeof messages || Array.isArray( messages ) ) {
showError( messages );
}
} else {
window.location.href = cko_paypal_vars.redirect;
}
});
},
onCancel: function (data, actions) {
cko_paypal_vars.debug && console.log(data);
jQuery('.woocommerce').unblock();
},
onError: function (err) {
cko_paypal_vars.debug && console.log(err);
jQuery('.woocommerce').unblock();
},
};

if ( cko_paypal_vars.is_cart_contains_subscription ) {
paypalButtonProps.createBillingAgreement = function( data, actions ) {
return cko_express_create_order_id();
};
} else {
paypalButtonProps.createOrder = function( data, actions ) {
return cko_express_create_order_id();
};
}

return paypalButtonProps;
},

updateButtonVisibility: function () {
if ( jQuery( cko_paypal_vars.paypal_button_selector ) ) {
jQuery( cko_paypal_vars.paypal_button_selector ).show();
}
}
}

paypalButton.init();
});
Loading

0 comments on commit 5faa8c8

Please sign in to comment.