Last active
April 28, 2023 08:39
-
-
Save mattiasghodsian/a84d98d4f89eb57234d9a28e01b16865 to your computer and use it in GitHub Desktop.
Update code snippet of wc-kco-validate-customer-age.php to only accept purchases from people over 18 years
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Title: WooCommerce - Klarna payment gateway (Modded) | |
* Author Niklas Hogefjord | |
* Editor: Mattias Ghodsian | |
* Description: Only accept purchases from customer over 18 years of age. | |
* Source: https://gist.github.com/NiklasHogefjord/07e60a4f08799c3cfdb0870fb5481f71 | |
* Klarna: https://developers.klarna.com/en/se/kco-v2/checkout-api | |
* Donate a cup of coffee: https://www.buymeacoffee.com/mattiasghodsian | |
**/ | |
/** | |
* Edit the order data sent to Klarna to make 'Date of birth' a mandatory field in the KCO iframe | |
*/ | |
add_filter('kco_create_order', 'my_kco_create_order'); | |
function my_kco_create_order( $create ) { | |
// not sure wtf this is. | |
$create['options']['national_identification_number_mandatory'] = true; | |
// enable KCO pno checkout page | |
$create['options']['date_of_birth_mandatory'] = true; | |
return $create; | |
} | |
/** | |
* Validate the customers age on the validate callback from Klarna (happens right before the purchase is finalized). | |
* The 'Check items stock and valid shipping method during checkout' setting needs to be checked in the KCO settings for this to work. | |
* The store needs to have SSL/https enabled for the validate callback to work. | |
*/ | |
add_action('kco_validate_checkout', 'my_kco_validate_checkout' ); | |
function my_kco_validate_checkout( $data ) { | |
// $data is the returned order data sent from Klarna | |
$birthday = new DateTime($data['customer']['date_of_birth']); | |
$now = new DateTime(); | |
$age = $now->diff($birthday); | |
if( $age -> y < 18 ) { | |
header( 'Location: ' . wc_get_checkout_url() . '?under_age' ); | |
exit(); | |
} | |
} | |
/** | |
* Display an error notice above the KCO checkout if the customer is under 18 years. | |
*/ | |
add_action('klarna_before_kco_checkout', 'my_klarna_before_kco_checkout' ); | |
/* | |
* add KCO error to normal woocommerce checkout | |
*/ | |
add_action('woocommerce_before_checkout_form', 'my_klarna_before_kco_checkout' ); | |
function my_klarna_before_kco_checkout() { | |
if ( isset( $_REQUEST['under_age'] ) ) { | |
echo '<div class="woocommerce-error">'; | |
_e( 'You need to be over 18 years to make a purchase.', 'woocommerce-gateway-klarna' ); | |
echo '</div>'; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment