id = 'integration-agechecker';
$this->method_title = 'AgeChecker.Net';
$product_categories = get_terms('product_cat');
if (!function_exists('get_editable_roles')) {
require_once(ABSPATH . '/wp-admin/includes/user.php');
}
$roles = array();
foreach (get_editable_roles() as $role_name => $role_info) {
$roles[] = $role_name;
}
$this->init_form_fields();
$this->init_settings();
add_action('wp_head', array(
$this,
'add_script_head'
), 1);
add_action('wp_footer', array(
$this,
'add_script_footer'
), 1);
add_action('woocommerce_update_options_integration_integration-agechecker', array(
$this,
'process_admin_options'
));
add_action('woocommerce_checkout_process', array(
$this,
'validate_order'
));
add_action( 'woocommerce_new_order', array(
$this,
'add_verified_notes'
));
add_action('woocommerce_thankyou', array(
$this,
'add_script_afterpayment'
));
add_action( 'rest_api_init', array(
$this,
'establish_api'
));
$this->key = $this->get_option('key');
$this->secret = $this->get_option('secret');
$this->store_name = $this->get_option('store_name');
$this->element = $this->get_option('element');
$this->workflow_type = $this->get_option('workflow_type');
$this->excluded_categories = $this->get_option('excluded_categories');
$this->categories_mode = $this->get_option('categories_mode');
$this->excluded_groups = $this->get_option('excluded_groups');
$this->groups_mode = $this->get_option('groups_mode');
$this->excluded_shipping = $this->get_option('excluded_shipping');
$this->page = $this->get_option('page');
$this->enable_all = $this->get_option('enable_all');
$this->script_location = $this->get_option('script_location');
$this->category_apikeys = $this->get_option('category_apikeys');
$this->apikeys_list = $this->get_option('apikeys_list');
$this->client_config = wp_specialchars_decode($this->get_option('client_config'), 'double');
$this->before_script = wp_specialchars_decode($this->get_option('before_script'), 'double');
$this->tag_order = $this->get_option('tag_order');
$this->set_customer_role = $this->get_option('set_customer_role');
// Set settings to version without entity codes.
$this->settings['client_config'] = $this->client_config;
$this->settings['before_script'] = $this->before_script;
}
public function init_form_fields() {
$this->form_fields = array(
'settings_hider' => array(
'type' => 'settingshider',
'desc_tip' => false,
),
'workflow_type' => array(
'title' => 'Verification Workflow Type',
'type' => 'radio',
'description' => 'Specify where in the order process you want age verification to occur.',
'default' => 'before_payment',
'desc_tip' => false,
),
'key' => array(
'title' => 'API Key',
'type' => 'text',
'description' => 'The API key for this domain. Find it in the websites tab of your AgeChecker.Net account.',
'default' => '',
'desc_tip' => false,
),
'secret' => array(
'title' => 'Account Secret',
'type' => 'text',
'description' => 'The Account Secret for your AgeChecker account. Find it in the websites tab of your AgeChecker.Net account.',
'default' => '',
'desc_tip' => false,
),
'store_name' => array(
'title' => 'Store Name',
'type' => 'text',
'description' => 'Display name of your store in the popup.',
'default' => get_bloginfo('name'),
'desc_tip' => false,
),
'element' => array(
'title' => 'Element',
'type' => 'text',
'description' => 'Element selector to attach the popup event to when using the "Before Payment" workflow. You may need to change this if you use a custom theme/template. Please contact us if the popup is not showing when the element is clicked. The default element is the final checkout button.',
'default' => '#place_order',
'desc_tip' => false,
),
'excluded_categories' => array(
'title' => 'Exclude/Include Categories',
'type' => 'listbox',
'default' => '',
'list' => 'categories',
'desc_tip' => false,
),
'categories_mode' => array(
'type' => 'radio',
'default' => 'exclude',
'list' => 'categories',
'desc_tip' => false,
),
'excluded_groups' => array(
'title' => 'Exclude/Include Groups',
'type' => 'listbox',
'default' => '',
'list' => 'roles',
'desc_tip' => false,
),
'groups_mode' => array(
'type' => 'radio',
'default' => 'exclude',
'list' => 'roles',
'desc_tip' => false,
),
'excluded_shipping' => array(
'title' => 'Exclude Shipping Methods',
'type' => 'listbox',
'default' => '',
'list' => 'shipping_methods',
'desc_tip' => false,
),
'page' => array(
'title' => 'Page',
'type' => 'text',
'description' => 'Page to show AgeChecker.Net on.',
'default' => 'checkout',
'desc_tip' => false,
),
'enable_all' => array(
'title' => 'Enable on All Pages',
'type' => 'radio',
'description' => 'This option only effects the "Before Payment" workflow.NOTE: This should only be used if "Page" box above is not working. Try setting the page name in the "Page" input box above first before using this.',
'default' => 'dont_enable_all',
'desc_tip' => false,
),
'script_location' => array(
'title' => 'Script Location',
'type' => 'radio',
'description' => 'This option only effects the "Before Payment" workflow.Location of script in site source',
'default' => 'head',
'desc_tip' => false,
),
'category_apikeys' => array(
'title' => 'Category Specific API Keys (Advanced)',
'type' => 'apikeys_listbox',
'default' => '{}',
'desc_tip' => false,
),
'apikeys_list' => array(
'type' => 'ordered_listbox',
'default' => 'default_api_key',
'list' => 'apikeys',
'description' => 'Move API keys with the arrow buttons to set priority of the key. Keys with a higher position on the list will take priority to be used than ones below it. (E.g. If you have a product in a cart with a category specific API key with age settings set to 21+, you would most likely want this to override another product in the cart with a category specific API key with 18+ age settings) Default API Key = API key set in the "API Key" input box at the top of the settings page',
'desc_tip' => false,
),
'client_config' => array(
'title' => 'Additional Config (Advanced)',
'type' => 'textarea',
'description' => 'Other additional configuration options from our client API.',
'desc_tip' => false,
'css' => 'width: 400px'
),
'before_script' => array(
'title' => 'Before Load Script (Advanced)',
'type' => 'textarea',
'description' => 'Custom code to run before the script is loaded. Use "return" to prevent loading.',
'desc_tip' => false,
'css' => 'width: 400px'
),
'tag_order' => array(
'title' => 'Tag Orders',
'type' => 'radio',
'description' => 'This option only effects the "Before Payment" workflow. "After Payment" workflow will always add a verification status and UUID to the order fields, ignoring this setting.',
'default' => 'tag_none',
'desc_tip' => false,
),
'set_customer_role' => array(
'title' => 'Set Customer Role',
'type' => 'selectbox',
'description' => 'Add a role to a logged-in customer\'s list of user roles upon accepted verification. (Customers must be logged in to their account for the role to be added)',
'default' => 'do_not_set_role',
'list' => 'customer_role',
'desc_tip' => false,
),
);
}
public function generate_selectbox_html($key, $data) {
$field = $this->plugin_id . $this->id . '_' . $key;
$roles = array();
foreach (get_editable_roles() as $role_name => $role_info) {
$roles[] = $role_name;
}
ob_start();
?>
API key invalid! Use the 32-character domain key from the website tab in your
AgeChecker.Net account area.'
Invalid customer role.
category_apikeys === "{}") {
return $this->key;
}
$category_keys = json_decode(stripslashes($this->category_apikeys));
$priority_list = explode(",", $this->apikeys_list);
$default_index = array_search('default_api_key', $priority_list);
$api_key = null;
$priority_index = null;
foreach ($cart_items as $cart_item_key => $cart_item) {
$prod_id = isset($cart_item['product_id']) ? $cart_item['product_id'] : $cart_item['data']->id;
$cats = wp_get_post_terms($prod_id, 'product_cat');
foreach ($cats as $cat_key => $cat) {
$cat_name = $cat->name;
$cat_apikey = property_exists($category_keys, $cat_name) ? $category_keys->$cat_name : null;
// If category's api key is null, then it's using
// the default api key. Check priority before setting.
if($cat_apikey === null && ($priority_index === null || $default_index < $priority_index)) {
$priority_index = $default_index;
$api_key = $this->key;
continue;
}
// If category's api key is not null, then get priority
// index for that api key. Compare against current priority_index
// and update current priority_index if less than.
$index = 0;
foreach ($priority_list as $key) {
if($priority_index !== null && $priority_index < $index) break;
if($key == $cat_apikey) {
$priority_index = $index;
$api_key = $key;
break;
}
$index++;
}
}
}
return $api_key;
}
function print_script_beforepayment() {
if($this->workflow_type != "before_payment") return;
?>
workflow_type != "after_payment") return;
$order = new WC_Order($order_id);
?>
script_location == 'footer' || $this->is_excluded(WC()->cart->get_cart()) || (!is_page($this->page) && $this->enable_all == 'dont_enable_all')) {
return;
}
$this->print_script_beforepayment();
}
public function add_script_footer() {
if ($this->script_location == 'head' || $this->is_excluded(WC()->cart->get_cart()) || (!is_page($this->page) && $this->enable_all == 'dont_enable_all')) {
return;
}
$this->print_script_beforepayment();
}
public function add_script_afterpayment($order_id) {
$order = new WC_Order($order_id);
if ($this->is_excluded($order->get_items()) || $this->is_shipping_excluded()) {
return;
}
$this->print_script_afterpayment($order_id);
}
public function is_shipping_excluded() {
$excluded_shipping_methods = explode(",", $this->excluded_shipping);
if (!(sizeof($excluded_shipping_methods) == 1 && $excluded_shipping_methods[0] == "")) {
$all_shipping_methods = array();
foreach(WC_Shipping_Zones::get_zones() as $zone_key => $zone ) {
foreach($zone['shipping_methods'] as $method_key => $method ) {
$str = "(".$zone['zone_name'].") ".$method->title;
$str = str_replace('"', "", $str);
$str = str_replace("'", "", $str);
$str = str_replace("`", "", $str);
$str = str_replace(",", "", $str);
$all_shipping_methods[$method->instance_id] = $str;
}
}
$chosen_methods = WC()->session->get('chosen_shipping_methods');
if($chosen_methods) {
foreach ($chosen_methods as $shipping_method_key => $shipping_method) {
$title = $all_shipping_methods[substr(strstr($shipping_method, ":"), 1)];
foreach ($excluded_shipping_methods as $c) {
if (strpos($title, $c) !== false) {
return true;
}
}
}
}
}
return false;
}
public function is_excluded($cart_items) {
$current_user = wp_get_current_user();
if (!($current_user instanceof WP_User)) {
return true;
}
$roles = $current_user->roles;
$user_role = implode($roles);
$excluded = true;
$categories_excluded = strpos($this->categories_mode, "exclude");
$categories = explode(",", $this->excluded_categories);
if (!(sizeof($categories) == 1 && $categories[0] == "")) {
if($categories_excluded !== false) {
foreach ($cart_items as $cart_item_key => $cart_item) {
$prod_id = isset($cart_item['product_id']) ? $cart_item['product_id'] : $cart_item['data']->id;
$noExclude = true;
foreach ($categories as $c) {
if (has_term($c, 'product_cat', $prod_id)) {
$noExclude = false;
break;
}
}
if ($noExclude) {
$excluded = false;
}
}
}
else {
foreach ($cart_items as $cart_item_key => $cart_item) {
$prod_id = isset($cart_item['product_id']) ? $cart_item['product_id'] : $cart_item['data']->id;
$noExclude = false;
foreach ($categories as $c) {
if (has_term($c, 'product_cat', $prod_id)) {
$noExclude = true;
break;
}
}
if ($noExclude) {
$excluded = false;
}
}
}
} else {
$excluded = false;
}
$groups_excluded = strpos($this->groups_mode, "exclude");
$groups = explode(",", $this->excluded_groups);
if (!(sizeof($groups) == 1 && $groups[0] == "")) {
if($groups_excluded !== false) {
foreach ($groups as $c) {
if (strpos($user_role, $c) !== false) {
$excluded = true;
break;
}
}
} else if(!$excluded) {
$excluded = true;
foreach ($groups as $c) {
if (strpos($user_role, $c) !== false) {
$excluded = false;
break;
}
}
}
}
return $excluded;
}
public function set_verified_role($user, $order) {
// Add user role if defined in settings, and user's logged in
if($user && $this->set_customer_role != 'do_not_set_role') {
$user->add_role($this->set_customer_role);
}
}
public function get_status_wording($body) {
if(isset($body['blocked'])) {
return "Buyer Banned - This customer is currently banned from performing verifications.";
} else if(isset($body['error'])) {
return "Error - Error performing the verification. If you believe this is a mistake, please contact AgeChecker support.";
}
$status = $body['status'];
$denyReasons = array(
'invalid_id' => "The image uploaded was not a valid ID",
'info_missing' => "The name, DOB, or expiration was not visible in the image",
'info_mismatch' => "The name on the ID did not match the information submitted",
'blocked' => "The user was banned",
'fake_id' => "The ID was a fake, sample, or blocked ID",
'blank_id' => "The image uploaded was blank or corrupted",
'expired' => "The ID was expired",
'ip_blocked' => "Buyer\'s IP address was blocked",
'location_blocked' => "Buyer\'s location was blocked",
'selfie_mismatch' => "The selfie does not match the face on the ID",
'sms_failed' => "Incorrect phone validation code",
'selfie_id_missing' => "ID is missing or unclear in the selfie image",
'selfie_not_provided' => "A selfie image with matching ID was not provided",
'location_disabled' => "The customer ordered from a location that doesn\'t require age verification according to your age settings.",
'verification_disabled' => "The customer ordered from a location that doesn\'t require age verification according to your age settings.",
'both_sides_needed' => "Both sides of the ID are needed to see the required information",
);
switch($status) {
case 'accepted':
return 'Accepted - Customer successfully age verified.';
case 'denied':
$denyReason = $denyReasons[$body['reason']];
if(isset($denyReason)) {
return 'Denied - Customer failed the age verification for the following reason: '. $denyReasons[$body['reason']];
}
return 'Denied - Customer failed the age verification.';
case 'photo_id':
return 'Photo ID Required - Customer was prompted with photo ID, and has not submitted one yet. The customer is either still in the process of submitting, or closed the window without finishing the verification.';
case 'signature':
return 'Signature Required - Customer was prompted to submit a signature, and has not submitted one yet. The customer is either still in the process of submitting, or closed the window without finishing the verification.';
case 'not_created':
$reason = $body['reason'];
if($reason == 'location_blocked') {
return 'Location Blocked - The customer ordered from a location that is blocked according to your age settings.';
} else if($reason == 'verification_disabled') {
return 'Location Disabled - The customer ordered from a location that doesn\'t require age verification according to your age settings.';
}
break;
default:
return $status;
}
return $status;
}
public function update_order_verification($order_id, $body) {
$order = new WC_Order($order_id);
$uuid = $body['uuid'];
$order->update_meta_data('AgeChecker Status', $this->get_status_wording($body) );
if(isset($uuid)) {
$order->update_meta_data('AgeChecker UUID', $uuid );
}
$order->save();
$this->set_verified_role($order->get_user(), $order);
}
public function initCors($value) {
header('Access-Control-Allow-Origin: ' . esc_url_raw( site_url() ));
return $value;
}
public function establish_api() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', array($this, 'initCors'));
register_rest_route( 'agechecker-net/v1', '/verify', array(
'methods' => 'POST',
'callback' => array(
$this,
'handle_verification_v1'
),
) );
register_rest_route( 'agechecker-net/v1', '/callback', array(
'methods' => 'POST',
'callback' => array(
$this,
'handle_callback_v1'
),
) );
}
public function handle_verification_v1($req) {
if(!isset($req['key']) || !isset($req['data']) || !isset($req['orderKey'])
|| empty(wc_get_order_id_by_order_key($req['orderKey']))) {
return new WP_REST_Response(array('error' => 'Data is not valid'), 400);
}
$orderId = wc_get_order_id_by_order_key($req['orderKey']);
$url = "https://api.agechecker.net/v1/create";
$data = [
'key' => $req['key'],
'secret' => $this->secret,
'data' => $req['data'],
'require' => $req['require'],
'options' => [
"callback_url" => esc_url_raw( site_url() ) ."/wp-json/agechecker-net/v1/callback",
"metadata" => [
"orderId" => $orderId,
"callbackpost_83qfbg84" => "true"
]
]
];
if($_SERVER['REMOTE_ADDR'] != "::1" && $_SERVER['REMOTE_ADDR'] != "127.0.0.1" && $_SERVER['REMOTE_ADDR'] != "localhost") {
$data['options']['customer_ip'] = $_SERVER['REMOTE_ADDR'];
}
$fields = json_encode($data);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch,CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if ($result === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
$result = json_decode($result, true);
$this->update_order_verification($orderId, $result);
return new WP_REST_Response($result, 200);
}
public function handle_callback_v1($req) {
$sig = $req->get_header('X-AgeChecker-Signature');
if(!$sig) {
return new WP_REST_Response(array('error' => 'Unauthorized request'), 403);
}
$encoded = base64_encode(hash_hmac('sha1', $req->get_body(), $this->secret, true));
if(!hash_equals($encoded, $sig)) {
return new WP_REST_Response(array('error' => 'Unauthorized request'), 403);
}
$body = json_decode($req->get_body(), true);
$ch = curl_init();
$url = "https://api.agechecker.net/v1/status/". $body['uuid'];
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER, array('X-AgeChecker-Secret: '. $this->secret));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$verification_info = curl_exec($ch);
if ($verification_info === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
$verification_info = json_decode($verification_info, true);
$this->update_order_verification($verification_info['metadata']['orderid'], $body);
return new WP_REST_Response(array("success" => true), 200);
}
}
endif;