Last active
January 8, 2018 16:18
-
-
Save NiklasHogefjord/07e60a4f08799c3cfdb0870fb5481f71 to your computer and use it in GitHub Desktop.
Code example on how to only accept purchases from people over 18 years of age with Klarna Checkout and WooCommerce
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 | |
/** | |
* WooCommerce - Klarna payment gateway | |
* Only accept purchases from customer over 18 years of age. | |
**/ | |
// 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 ) { | |
$create['options']['national_identification_number_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 abouve the KCO checkout if the customer is under 18 years. | |
add_action('klarna_before_kco_checkout', 'my_klarna_before_kco_checkout' ); | |
function my_klarna_before_kco_checkout() { | |
if ( isset( $_GET['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
https://gist.github.com/mattiasghodsian/a84d98d4f89eb57234d9a28e01b16865