We are using Klarna Checkout(3rd party plugin) to handle payments for our WooCommerce platform.
When the product is added to cart, Klarna Checkout Form appears with the details needed like email and contact number.
When a user enters their email, I determine if it's a new email to give 50% discount:
our-custom.js
var j = jQuery.noConflict();
// check every second if email is filled
var check_is_email_done = setInterval(function() {
var is_email_done = j('.klarna-widget-form-user .email').text();
if(is_email_done.length > 0) {
console.log('email is filled: ' + is_email_done);
var notFound = j('.fortnox-users td').filter(function(){
return j(this).text() == is_email_done;
}).get();
var token = notFound.length;
if(token > 0) {
console.log('Old customer..');
} else {
console.log('New customer..');
// call new_customer_discount() method in functions.php
j.ajax({
type: 'GET',
url: ajaxurl,
cache: false,
data: { action: 'newcustomerdiscount'},
success: function(data) {
console.log('newcustomerdiscount' + data);
},
error: function(xhr,status,error) {
console.log('newcustomerdiscount error:'+error);
}
});
}
clearInterval(check_is_email_done);
}
},1000);
functions.php
function new_customer_discount() {
//echo "new_customer_discount123";
$my_total = wc_format_decimal(WC()->cart->total, 2);
echo 'Total: '.$my_total;
do_action('woocommerce_calculate_totals', function($cart) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
print_r($cart);
$computed_price = 0;
// Loop Through cart items
foreach ( $cart->get_cart() as $cart_item ) {
// Get the product id (or the variation id)
$product_id = $cart_item['data']->get_id();
// GET THE NEW PRICE (code to be replace by yours)
if($computed_price > 0)
$prod_price = $computed_price * .50; // 50% discount
// Updated cart item price
$cart_item['data']->set_price( $prod_price );
}
});
}
The flow of my code above is when I determine if a customer is new, I call the new_customer_discount()
method in functions.php then execute do_action with callback
Do you know how can I execute hook above in functions.php properly? Any help is greatly appreciated. Thanks