Skip to content

Instantly share code, notes, and snippets.

@goranefbl
Created August 21, 2025 22:59
Show Gist options
  • Save goranefbl/ac5f5f66f09a59d990bb913e33b6db7d to your computer and use it in GitHub Desktop.
Save goranefbl/ac5f5f66f09a59d990bb913e33b6db7d to your computer and use it in GitHub Desktop.
class-wpgens-raf-checkout.php
<?php
/**
* Hook into checkout
*
* @since 2.0.0
*/
if (!defined('ABSPATH')) {
exit;
}
class WPGens_RAF_Checkout
{
/**
* Constructor.
*
*/
public function __construct()
{
// Save RAF ID in Order Meta after Order is Complete
add_action('woocommerce_checkout_update_order_meta', array($this, 'maybe_save_raf_id_classic'), 10, 2);
add_action('woocommerce_store_api_checkout_update_order_meta', array($this, 'maybe_save_raf_id'), 10, 1);
//Remove Cookie after checkout if Setting is set
add_action('woocommerce_thankyou', array($this, 'remove_cookie_after'));
// Hide auto applied coupon codes from showing.
add_filter('woocommerce_cart_totals_coupon_label', array($this, 'hide_coupon_code'), 10, 2);
// Auto apply RAF Coupons on cart for referrals. Also apply on checkout if cart is skipped.
add_action('woocommerce_before_cart', array($this, 'apply_matched_coupons')); // woocommerce_before_checkout_form
add_action('woocommerce_before_checkout_form', array($this, 'apply_matched_coupons')); // woocommerce_before_checkout_form
add_action('woocommerce_ajax_added_to_cart', array($this, 'apply_matched_coupons')); //woocomerce ajax add to cart but wc_print_notices is problem.
add_action('woocommerce_checkout_update_order_review', array($this, 'checkout_form_check'));
add_filter('woocommerce_get_shop_coupon_data', array($this, 'add_referral_via_coupon_field'), 10, 2);
add_action('woocommerce_applied_coupon', array($this, 'add_referral_apply_coupon_referral_code'), 10, 2);
add_action('woocommerce_removed_coupon', array($this, 'wc_removed_coupon'), 10, 1);
// Block-based checkout hooks
add_action('woocommerce_store_api_cart_errors', array($this, 'validate_block_checkout_coupons'), 10, 1);
add_action('woocommerce_applied_coupon', array($this, 'validate_and_remove_coupon'), 10, 1);
}
/**
* Before version 3, settings field were saved as "yes", after new react admin its "1".
*/
public function settings_field_active($field)
{
$value = get_option($field);
if ($value === "yes" || $value === "1") {
return true;
}
return false;
}
public function wc_removed_coupon($coupon)
{
$guest_coupon_code = get_option('gens_raf_guest_coupon_code');
if ($coupon === $guest_coupon_code || substr($coupon, 0, 3) === "ref") {
// unset($_COOKIE['gens_raf']);
// setcookie('gens_raf', '', time() - 3600, '/');
}
}
public function add_referral_apply_coupon_referral_code($coupon_code)
{
$guest_coupon_code = get_option('gens_raf_guest_coupon_code');
if ($coupon_code !== $guest_coupon_code && $this->settings_field_active('gens_raf_guest_enable') && substr($coupon_code, 0, 3) === "ref") {
$user_id = $this->get_id_from_referral_code($coupon_code);
if ($user_id) {
$time = 1;
if (get_current_user_id() != $user_id) {
if (get_option('gens_raf_cookie_time') != '') {
$time = intval(get_option('gens_raf_cookie_time'));
}
do_action('new_raf_data', 'coupon_applied', array('user' => get_current_user_id(), 'referral' => $user_id, 'type' => 'code'));
setcookie('gens_raf', $coupon_code, time() + 60 * 60 * 24 * $time, '/');
}
}
}
}
public function add_referral_via_coupon_field($data, $coupon_code)
{
if (substr($coupon_code, 0, 3) != "ref") {
return $data;
}
$user_id = $this->get_id_from_referral_code($coupon_code);
$guest_coupon_code = $this->get_guest_coupon_code($user_id);
if (!$this->settings_field_active('gens_raf_referral_codes') || is_admin() || (isset(WC()->cart) && WC()->cart->has_discount($guest_coupon_code))) {
return $data;
}
$is_banned_user = $this->is_banned_user_code($user_id);
if ($is_banned_user) {
return $data;
}
if ($user_id) {
// For guest referrals, user_id is the referral code string, not a numeric user ID
// For registered users, user_id is numeric. Only check self-referral for registered users.
$should_process = true;
if (is_numeric($user_id)) {
// Registered user - check if they're trying to use their own code
$should_process = (get_current_user_id() != $user_id);
}
// For guest codes (string), always process since there's no user account to compare
if ($should_process) {
$args = array(
'posts_per_page' => 1,
'post_type' => 'shop_coupon',
'post_status' => 'publish',
'title' => $guest_coupon_code,
'fields' => 'ids'
);
// Use get_posts to fetch the coupon
$coupon_posts = get_posts($args);
if (empty($coupon_posts)) {
return $data;
}
$coupon_id = $coupon_posts[0];
$discount_type = get_post_meta($coupon_id, "discount_type", true);
$amount = get_post_meta($coupon_id, "coupon_amount", true);
$product_ids = get_post_meta($coupon_id, "product_ids", true);
$exclude_product_ids = get_post_meta($coupon_id, "exclude_product_ids", true);
$exclude_product_categories = get_post_meta($coupon_id, "exclude_product_categories", true);
$product_categories = get_post_meta($coupon_id, "product_categories", true);
$minimum_amount = get_post_meta($coupon_id, "minimum_amount", true);
$individual_use = get_post_meta($coupon_id, "individual_use", true);
$exclude_sale_items = get_post_meta($coupon_id, "exclude_sale_items", true);
$free_shipping = get_post_meta($coupon_id, "free_shipping", true);
$data = array(
'discount_type' => $discount_type,
'amount' => $amount,
'free_shipping' => $free_shipping,
'minimum_amount' => $minimum_amount,
'individual_use' => $individual_use === "yes" ? true : false,
'exclude_sale_items' => $exclude_sale_items === "yes" ? true : false,
'product_ids' => array_map('intval', (array) explode(',', $product_ids)),
'excluded_product_ids' => array_map('intval', (array) explode(',', $exclude_product_ids)),
'product_categories' => array_map('intval', (array) $product_categories),
'excluded_product_categories' => array_map('intval', (array) $exclude_product_categories),
'id' => true
);
// Add filter for coupon data
$data = apply_filters('gens_raf_coupon_data', $data, $coupon_id, $user_id, $coupon_code);
}
}
return $data;
}
public function maybe_save_raf_id_classic($order_id, $posted_data)
{
$order = wc_get_order($order_id);
if ($order) {
$this->maybe_save_raf_id($order);
}
}
/**
* Save RAF(User) ID in Order Meta after Order is Complete
* woocommerce_checkout_update_order_meta hook
*
* @since 2.0.0
* @return string
*/
public function maybe_save_raf_id($order)
{
//1. Check cookie & get referrer or exit
$referrer_id = $this->check_referrer_cookie();
if (!$referrer_id) {
return;
}
//2. Check filter & is plugin active
$disable = apply_filters('gens_raf_disable', $this->settings_field_active('gens_raf_disable'), $order->get_id(), $referrer_id);
if ($disable) {
return;
}
// 3. Check for self-referral before saving any data
$user_email = $order->get_billing_email();
$is_self_referral = false;
// Check for logged-in user self-referral
if (get_current_user_id() === $referrer_id || $user_email === $referrer_id) {
$is_self_referral = true;
}
// Check for guest self-referral
if (!$is_self_referral && is_string($referrer_id) && strpos($referrer_id, 'ref') === 0) {
$db = new WPGens_RAF_DB();
$guest_referral = $db->get_guest_referral_by_code($referrer_id);
if ($guest_referral && $guest_referral['email'] === $user_email) {
$is_self_referral = true;
}
}
// If self-referral detected, remove cookie and exit without saving referral data
if ($is_self_referral) {
if (isset($_COOKIE['gens_raf'])) {
unset($_COOKIE['gens_raf']);
setcookie('gens_raf', '', time() - 3600, '/');
}
return;
}
// 4. Save referral id and then work on security.
if (filter_var($referrer_id, FILTER_VALIDATE_EMAIL)) {
$rafID = $referrer_id;
} elseif (is_string($referrer_id) && strpos($referrer_id, 'ref') === 0) {
// Guest referral code - store directly
$rafID = $referrer_id;
} else {
$rafID = get_user_meta($referrer_id, "gens_referral_id", true);
}
$raf_info = $this->security_check($order->get_id(), $referrer_id);
// Only log user_referred if user is a guest (not registered) or if registration rewards are disabled
// This prevents duplicate user_referred events for users who register and then make a purchase
$current_user_id = get_current_user_id();
if ($current_user_id === 0 || !get_option('gens_raf_generate_for_registration')) {
do_action('new_raf_data', 'user_referred', array('user' => $current_user_id === 0 ? $order->get_billing_email() : $current_user_id, 'referrer' => $referrer_id));
}
do_action('new_raf_data', 'new_order', array_merge(array('user' => $current_user_id, 'referral' => $referrer_id, 'order' => $order->get_id()), $raf_info));
$order->update_meta_data('_raf_meta', $raf_info); // will be depricated
$order->update_meta_data('_wpgens_raf_meta', $raf_info);
$order->update_meta_data('_raf_id', esc_attr($rafID)); // will be depricated
$order->update_meta_data('_wpgens_raf_id', esc_attr($rafID));
$order->save();
}
public function security_check($order_id, $referrer_id)
{
$minimum_amount = apply_filters('gens_raf_minimum_order_amount', get_option('gens_raf_min_ref_order'), $order_id);
$nth_coupon = intval(get_option('gens_raf_nth_coupon'));
$fraud_email_address = get_option('gens_raf_fraud_email_address');
$is_banned_user = $this->is_banned_user_code($referrer_id);
// Prevent user from checkout as a guest using his email
$order = wc_get_order($order_id);
$aelia_order_total = $order->get_meta('_order_total_base_currency', true);
$order_total = $order->get_total();
$user_email = (defined('WC_VERSION') && version_compare(WC_VERSION, '2.7', '<')) ? $order->billing_email : $order->get_billing_email();
$user_address = (defined('WC_VERSION') && version_compare(WC_VERSION, '2.7', '<')) ? $order->billing_address_1 : $order->get_billing_address_1();
$num_referrals = intval(get_user_meta($referrer_id, "gens_num_friends", true)) + 1;
// Check if user exists with this email already in the system?
$order_statuses = $this->get_fraud_order_statuses();
$email_exists = wc_get_orders(array(
'limit' => 1,
'customer' => $user_email,
'status' => $order_statuses,
'exclude' => array($order_id)
));
$customer_ip_address = $order->get_customer_ip_address();
$ip_address_exists = $this->orders_exist_from_ip($customer_ip_address, $order_id);
$customer_phone = (defined('WC_VERSION') && version_compare(WC_VERSION, '2.7', '<')) ? $order->billing_phone : $order->get_billing_phone();
$phone_exists = $this->orders_exist_from_phone($customer_phone, $order_id);
$custom_msg = "";
$raf_info['custom_msg'] = apply_filters('gens_raf_custom_message', $custom_msg);
if (!empty($email_exists) && !$this->settings_field_active('gens_raf_allow_existing')) {
$raf_info = array("info" => __("Potential Fraud Detected. Referred customer has previous orders with " . $user_email . " address. Check plugin fraud settings to change this.", "gens-raf"), "generate" => "false", "increase_referrals" => "false", "email_notify" => "true");
} else if ($ip_address_exists) {
$raf_info = array("info" => __("Potential Fraud Detected. Referred customer has previous orders with " . $customer_ip_address . " ip address. Check plugin fraud settings to change this.", "gens-raf"), "generate" => "false", "increase_referrals" => "false", "email_notify" => "true");
} else if ($phone_exists) {
$raf_info = array("info" => __("Potential Fraud Detected. Referred customer has previous orders with " . $customer_phone . " phone number. Check plugin fraud settings to change this.", "gens-raf"), "generate" => "false", "increase_referrals" => "false", "email_notify" => "true");
} else if ($this->user_has_orders() && !$this->settings_field_active('gens_raf_allow_existing')) {
$raf_info = array("info" => __("This is not a new customer, and settings are set to disable coupons for existing customers.", "gens-raf"), "generate" => "false", "increase_referrals" => "false", "email_notify" => "false");
} else if (($user_address == get_user_meta($referrer_id, "billing_address_1", true)) && $user_address != '' && !$this->settings_field_active('gens_raf_fraud_disable_street')) {
$raf_info = array("info" => __("Potential Fraud Detected. Referer and referre have the same billing address. Investigate.", "gens-raf"), "generate" => "false", "increase_referrals" => "false", "email_notify" => "true");
} else if ($minimum_amount && (($aelia_order_total === '' && $minimum_amount > $order_total) || ($aelia_order_total !== '' && $minimum_amount > $aelia_order_total))) {
$raf_info = array("info" => __("Order minimum amount of " . $minimum_amount . " has not been met.", "gens-raf"), "generate" => "false", "increase_referrals" => "false", "email_notify" => "false");
} else if (!empty($nth_coupon) && ($nth_coupon !== 1) && ($num_referrals % $nth_coupon != 0)) {
$raf_info = array("info" => __("Coupons wont be generated due to nth coupon option.", "gens-raf"), "generate" => "false", "increase_referrals" => "true", "email_notify" => "false");
} else if ($is_banned_user) {
$raf_info = array("info" => __("Coupons wont be generated as advocate has been blacklisted.", "gens-raf"), "generate" => "false", "increase_referrals" => "false", "email_notify" => "false");
} else {
$raf_info = array("info" => "Referral is fine. Coupon will be generated on the order complete.", "generate" => "true", "increase_referrals" => "true", "email_notify" => "false");
}
// Notify admin of potential fraud detection.
if ($raf_info['email_notify'] == 'true') {
if (!$fraud_email_address) {
$fraud_email_address = get_option('admin_email');
}
$subject = 'Refer a friend - Potential fraud detected for a new referral';
$body = $raf_info['info'] . ' Order: ' . get_admin_url(null, 'post.php?post=' . $order_id . '&action=edit');
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($fraud_email_address, $subject, $body, $headers);
}
return apply_filters("gens_raf_order_info", $raf_info, $order, $referrer_id);
}
protected function orders_exist_from_ip($ip_address, $current_order_id = null)
{
$order_statuses = $this->get_fraud_order_statuses();
$args = array(
'limit' => 1,
'customer_ip_address' => $ip_address,
'status' => $order_statuses,
'exclude' => array($current_order_id)
);
$orders = wc_get_orders($args);
return count($orders) > 0 && !$this->settings_field_active('gens_raf_fraud_disable_ip') && !$this->settings_field_active('gens_raf_allow_existing');
}
protected function orders_exist_from_phone($phone_number, $current_order_id = null)
{
// Don't check for fraud if phone number is empty
if (empty($phone_number)) {
return false;
}
$order_statuses = $this->get_fraud_order_statuses();
$args = array(
'limit' => 1,
'billing_phone' => $phone_number,
'status' => $order_statuses,
'exclude' => array($current_order_id)
);
$orders = wc_get_orders($args);
return count($orders) > 0 && !$this->settings_field_active('gens_raf_fraud_disable_phone') && !$this->settings_field_active('gens_raf_allow_existing');
}
/**
* Returning number of orders customer has.
*
* @since 2.0.0
*/
public function user_has_orders($user_email = false)
{
$user_id = get_current_user_id();
if ($user_id == 0) {
if ($user_email !== false && $user_email != '') {
$status_list = apply_filters('wpgens_user_has_orders_status_list', array('wc-processing', 'wc-completed'));
$email_exists = wc_get_orders(array(
'limit' => 1,
'customer' => $user_email,
'status' => $status_list
));
return count($email_exists);
}
return 0;
}
$customer_orders = wc_get_orders(array(
'numberposts' => 5,
'customer_id' => $user_id,
'status' => array('wc-completed'),
));
return count($customer_orders);
}
public function check_referrer_cookie()
{
// First check cookie
if (isset($_COOKIE["gens_raf"])) {
$user_id = $this->get_id_from_referral_code($_COOKIE["gens_raf"]);
if ($user_id) {
return $user_id;
}
}
// Then check if referral was applied through coupon.
if (!empty(WC()->cart->applied_coupons)) {
$coupons = WC()->cart->applied_coupons;
foreach ($coupons as $coupon) {
if (substr($coupon, 0, 3) === "ref") {
$user_id = $this->get_id_from_referral_code($coupon);
if ($user_id) {
return $user_id;
}
}
}
}
// Legacy: check for old email-based cookies (for backward compatibility only)
if (isset($_COOKIE["gens_raf"]) && filter_var($_COOKIE["gens_raf"], FILTER_VALIDATE_EMAIL)) {
// Try to convert to new system if possible
$db = new WPGens_RAF_DB();
$guest_referral = $db->get_guest_referral_by_email($_COOKIE["gens_raf"]);
if ($guest_referral) {
return $guest_referral['referral_code'];
}
// Fallback to email for unmigrated cases
return $_COOKIE["gens_raf"];
}
// Nothing? Return false.
return false;
}
/**
* Remove Cookie after checkout if Setting is set
* woocommerce_thankyou hook
*
* @since 1.0.0
*/
public function remove_cookie_after($order_id)
{
if (isset($_COOKIE['gens_raf']) && $this->settings_field_active('gens_raf_cookie_remove')) {
unset($_COOKIE['gens_raf']);
setcookie('gens_raf', '', time() - 3600, '/');
}
}
public function hide_coupon_code($text, $coupon)
{
$guest_coupon_code = get_option('gens_raf_guest_coupon_code');
$user_special_discounts = get_option('gens_raf_user_specific_discounts');
if (method_exists($coupon, "get_code")) { // Support for older version of WooCommerce
$coupon_code = $coupon->get_code();
} else {
$coupon_code = $coupon->code; // Direct property access in older Woo versions
}
$coupon_code = strtolower($coupon_code);
// Check if the coupon code matches the guest coupon code
if ($coupon_code == strtolower($guest_coupon_code)) {
return apply_filters("gens_raf_coupon_applied", __('Coupon Applied!', 'gens-raf'));
}
// Check against user-specific discount coupon codes
if (!empty($user_special_discounts)) {
foreach ($user_special_discounts as $user_discount) {
if (isset($user_discount['friendCoupon']) && $coupon_code == strtolower($user_discount['friendCoupon'])) {
return apply_filters("gens_raf_coupon_applied", __('Coupon Applied!', 'gens-raf'));
}
}
}
// Return the original text if no matches found
return $text;
}
/**
* Auto apply coupons at the cart page for referred person, if chosen.
*
* @since 1.1.0
*/
public function apply_matched_coupons($product_id = null)
{
// DO NOT Display notice on woocommerce_ajax_added_to_cart hook
$display_notices = is_null($product_id);
$guest_coupon_msg = get_option('gens_raf_guest_coupon_msg');
$allow_guests = $this->settings_field_active('gens_raf_allow_guests');
$referrer_id = $this->check_referrer_cookie();
if (!$referrer_id || get_current_user_id() === $referrer_id) {
return false;
}
if ($this->is_banned_user_code($referrer_id)) {
return false;
}
if (filter_var($referrer_id, FILTER_VALIDATE_EMAIL)) {
// Legacy: Email-based guest referral
if (!$allow_guests) {
return;
}
if (get_option('gens_raf_hide_no_orders') === "1") {
$customer_orders = wc_get_orders(array(
'numberposts' => 1,
'billing_email' => $referrer_id,
'status' => array('wc-processing', 'wc-completed'),
));
if (count($customer_orders) < 1) {
return false;
}
}
} elseif (is_string($referrer_id) && strpos($referrer_id, 'ref') === 0) {
// New: Guest referral code system
if (!$allow_guests) {
return;
}
// Get guest referral info from database
$db = new WPGens_RAF_DB();
$guest_referral = $db->get_guest_referral_by_code($referrer_id);
if (!$guest_referral) {
return false;
}
if (get_option('gens_raf_hide_no_orders') === "1") {
$customer_orders = wc_get_orders(array(
'numberposts' => 1,
'billing_email' => $guest_referral['email'],
'status' => array('wc-processing', 'wc-completed'),
));
if (count($customer_orders) < 1) {
return false;
}
}
// Use name from guest referral or default
$user_name = !empty($guest_referral['name']) ? $guest_referral['name'] : __("Your friend", "gens-raf");
$guest_coupon_msg = str_replace('{{name}}', $user_name, $guest_coupon_msg);
} else {
// Numeric user ID - registered user
$user_info = get_userdata($referrer_id);
if (!$user_info) {
return false;
}
$user_name = ($user_info->first_name != '') ? $user_info->first_name . ' ' . $user_info->last_name : __("Your friend", "gens-raf");
$guest_coupon_msg = str_replace('{{name}}', $user_name, $guest_coupon_msg);
}
$guest_coupon_code = $this->get_guest_coupon_code($referrer_id);
do_action('gens_raf_auto_apply_coupon', $referrer_id);
if (!empty(WC()->cart->applied_coupons) || empty($guest_coupon_code) || $this->settings_field_active('gens_raf_disable') || WC()->cart->cart_contents_count < 1 || !$this->settings_field_active('gens_raf_guest_enable') || ($this->user_has_orders() >= 1 && !$this->settings_field_active('gens_raf_allow_existing'))) {
return false;
}
do_action('new_raf_data', 'coupon_applied', array('user' => get_current_user_id(), 'referral' => $referrer_id, 'type' => 'link'));
if (WC()->cart->add_discount($guest_coupon_code) && $display_notices) {
wc_add_notice($guest_coupon_msg);
wc_print_notices();
}
}
/**
* Remove coupon if user wants to abuse it by adding it as a guest then logging in at the checkout.
*
* @since 1.1.0
*/
public function checkout_form_check($post_data)
{
$user_id = 0;
$email_exists = false;
parse_str($post_data, $data);
$referrer_id = $this->check_referrer_cookie();
if (!$referrer_id) {
return false;
}
$guest_coupon_code = $this->get_guest_coupon_code($referrer_id);
$advocate_address = get_user_meta($referrer_id, "billing_address_1", true);
if (isset($data['billing_email']) && $data['billing_email'] != "") {
// This email already exists? Remove coupon.
$email_exists = wc_get_orders(array(
'numberposts' => 1,
'billing_email' => $data['billing_email'],
'status' => array('wc-processing', 'wc-completed'),
));
// This phone already exists? Remove coupon.
$phone_exists = false;
// Check phone from form data (for guests or new phone numbers)
if (isset($data['billing_phone']) && $data['billing_phone']) {
$phone_exists = $this->orders_exist_from_phone($data['billing_phone']);
}
// Also check saved phone for logged-in users (if not already checked from form)
if (!$phone_exists) {
$current_user_id = get_current_user_id();
if ($current_user_id) {
$saved_phone = get_user_meta($current_user_id, 'billing_phone', true);
if ($saved_phone) {
$phone_exists = $this->orders_exist_from_phone($saved_phone);
}
}
}
// In case referral is using his own coupon code.
$user = get_user_by('email', $data['billing_email']);
if ($user) {
$raf_code = get_user_meta($user->ID, 'gens_referral_id', true);
if (!empty($raf_code) && WC()->cart->has_discount($raf_code)) {
WC()->cart->remove_coupon($raf_code);
}
}
}
do_action('gens_raf_checkout_check', $guest_coupon_code, $referrer_id);
// Determine conditions for removing the coupon
$is_guest_and_matches_cookie = isset($_COOKIE["gens_raf_guest"]) && $data['billing_email'] === $_COOKIE["gens_raf_guest"];
$is_self_referral = $user_id === $referrer_id;
// Check for new guest referral self-referral (same email used to generate and checkout)
$is_guest_self_referral = false;
if (isset($_COOKIE["gens_raf"]) && is_string($_COOKIE["gens_raf"]) && strpos($_COOKIE["gens_raf"], 'ref') === 0) {
$db = new WPGens_RAF_DB();
$guest_referral = $db->get_guest_referral_by_code($_COOKIE["gens_raf"]);
if ($guest_referral && $guest_referral['email'] === $data['billing_email']) {
$is_guest_self_referral = true;
}
}
$user_has_previous_orders = $this->user_has_orders($data['billing_email']) > 0;
$email_has_previous_orders = !empty($email_exists);
$same_billing_address = ($advocate_address === $data['billing_address_1'] && $advocate_address !== '');
$allow_existing_customers = $this->settings_field_active('gens_raf_allow_existing');
$is_existing_customer_disallowed = (
($user_has_previous_orders || $email_has_previous_orders || $same_billing_address || $phone_exists)
&& !$allow_existing_customers
);
$should_remove_coupon = $is_guest_and_matches_cookie || $is_self_referral || $is_guest_self_referral || $is_existing_customer_disallowed;
$current_ip = WC_Geolocation::get_ip_address();
$ip_causes_removal = $this->orders_exist_from_ip($current_ip);
if ($ip_causes_removal) {
$should_remove_coupon = true;
}
$should_remove_coupon = apply_filters('gens_raf_should_remove_coupon', $should_remove_coupon, $guest_coupon_code, $referrer_id);
$coupon_removal_message = apply_filters('gens_raf_coupon_removal_message', __('The coupon has been removed from your cart. You are an existing customer and are not entitled to a referral discount.', 'gens-raf'));
if ($should_remove_coupon) {
if (WC()->cart->has_discount($guest_coupon_code)) {
WC()->cart->remove_coupon($guest_coupon_code);
wc_add_notice($coupon_removal_message, 'error');
}
if (isset($_COOKIE["gens_raf"]) && !empty($_COOKIE["gens_raf"]) && WC()->cart->has_discount($_COOKIE["gens_raf"])) {
WC()->cart->remove_coupon($_COOKIE["gens_raf"]);
wc_add_notice($coupon_removal_message, 'error');
}
}
// Because we cant remove multiple coupons during applying of them....
if (WC()->cart->has_discount() && count(WC()->cart->get_applied_coupons()) > 1) {
$coupons = WC()->cart->get_applied_coupons();
$i = 0;
foreach ($coupons as $coupon) {
if (substr($coupon, 0, 3) === "ref" || $coupon == $guest_coupon_code) {
$i++;
}
if ($i > 1) {
WC()->cart->remove_coupon($coupon);
}
}
}
}
public function get_id_from_referral_code($referral_code)
{
global $wpdb, $wpgens_raf;
// First check registered users' referral codes
$results = $wpdb->get_results($wpdb->prepare("SELECT user_id FROM $wpdb->usermeta WHERE meta_key='gens_referral_id' AND meta_value = %s", $referral_code));
if (!empty($results)) {
return (int)$results[0]->user_id;
}
// Then check our guest referrals table
$db = new WPGens_RAF_DB();
$guest_referral = $db->get_guest_referral_by_code($referral_code);
if ($guest_referral) {
// For guest referrals, we return the referral code directly as the identifier
return $referral_code;
}
return false;
}
public function is_banned_user_code($user_id_or_email)
{
$email_ban_list = get_option('gens_raf_fraud_ban_list');
$banned_emails = array_map('trim', explode(',', $email_ban_list));
if (!empty($banned_emails)) {
if (filter_var($user_id_or_email, FILTER_VALIDATE_EMAIL)) {
if (in_array($user_id_or_email, $banned_emails)) {
return true;
}
} elseif (is_string($user_id_or_email) && strpos($user_id_or_email, 'ref') === 0) {
// Guest referral code - get email from guest table
$db = new WPGens_RAF_DB();
$guest_referral = $db->get_guest_referral_by_code($user_id_or_email);
if ($guest_referral && in_array($guest_referral['email'], $banned_emails)) {
return true;
}
} else {
// Numeric user ID - get user data
$user_info = get_userdata($user_id_or_email);
if ($user_info && in_array($user_info->user_email, $banned_emails)) {
return true;
}
}
}
return false;
}
public function get_guest_coupon_code($user_id_or_email)
{
$guest_coupon_code = get_option('gens_raf_guest_coupon_code');
$user_special_discounts = get_option('gens_raf_user_specific_discounts');
if (empty($user_special_discounts)) {
return $guest_coupon_code;
}
$email_to_check = filter_var($user_id_or_email, FILTER_VALIDATE_EMAIL) ? $user_id_or_email : null;
if (!$email_to_check) {
$user_info = get_userdata($user_id_or_email);
if ($user_info) {
$email_to_check = $user_info->user_email;
}
}
// Process only if we have an email to check
foreach ($user_special_discounts as $user_discount) {
if ($email_to_check === $user_discount['email']) {
return $user_discount['friendCoupon'];
}
}
// Return guest code
return $guest_coupon_code;
}
public function get_fraud_order_statuses()
{
$all_statuses = wc_get_order_statuses();
unset($all_statuses['wc-failed']); // Remove 'failed' status
$statuses = apply_filters('gens_raf_fraud_order_status', array_keys($all_statuses));
return $statuses;
}
/**
* Validate coupons for block-based checkout
*
* @param WP_Error $errors
*/
public function validate_block_checkout_coupons($errors)
{
$referrer_id = $this->check_referrer_cookie();
if (!$referrer_id) {
return;
}
$guest_coupon_code = $this->get_guest_coupon_code($referrer_id);
$advocate_address = get_user_meta($referrer_id, "billing_address_1", true);
// Get customer data from cart
$user_id = get_current_user_id();
$user_email = $user_id ? get_userdata($user_id)->user_email : '';
$user_address = $user_id ? get_user_meta($user_id, 'billing_address_1', true) : '';
// Check if user exists with this email ONLY if we have an email (i.e., user is logged in)
$email_exists = false;
if (! empty($user_email)) {
$email_exists = wc_get_orders(array(
'numberposts' => 1,
'billing_email' => $user_email,
'status' => array('wc-processing', 'wc-completed'),
));
}
// Check if phone exists
$phone_exists = false;
if ($user_id) {
$phone = get_user_meta($user_id, 'billing_phone', true);
if ($phone) {
$phone_exists = $this->orders_exist_from_phone($phone);
}
}
// Check if referral is using their own coupon code
if ($user_id) {
$raf_code = get_user_meta($user_id, 'gens_referral_id', true);
if (!empty($raf_code) && WC()->cart->has_discount($raf_code)) {
WC()->cart->remove_coupon($raf_code);
$errors->add('raf_error', __('You cannot use your own referral code.', 'gens-raf'));
}
}
do_action('gens_raf_checkout_check', $guest_coupon_code, $referrer_id);
// Determine conditions for removing the coupon
$is_guest_and_matches_cookie = isset($_COOKIE["gens_raf_guest"]) && $user_email === $_COOKIE["gens_raf_guest"];
$is_self_referral = $user_id === $referrer_id;
// Check for new guest referral self-referral (same email used to generate and checkout)
$is_guest_self_referral = false;
if (isset($_COOKIE["gens_raf"]) && is_string($_COOKIE["gens_raf"]) && strpos($_COOKIE["gens_raf"], 'ref') === 0) {
$db = new WPGens_RAF_DB();
$guest_referral = $db->get_guest_referral_by_code($_COOKIE["gens_raf"]);
if ($guest_referral && (!empty($user_email) ? $guest_referral['email'] === $user_email : $guest_referral['email'] === $data['billing_email'])) {
$is_guest_self_referral = true;
}
}
$user_has_previous_orders = $this->user_has_orders($user_email) > 0;
$email_has_previous_orders = !empty($email_exists);
$same_billing_address = ($advocate_address === $user_address && $advocate_address !== '');
$allow_existing_customers = $this->settings_field_active('gens_raf_allow_existing');
$is_existing_customer_disallowed = (
($user_has_previous_orders || $email_has_previous_orders || $same_billing_address || $phone_exists)
&& !$allow_existing_customers
);
$should_remove_coupon = $is_guest_and_matches_cookie || $is_self_referral || $is_guest_self_referral || $is_existing_customer_disallowed;
$current_ip = WC_Geolocation::get_ip_address();
$ip_causes_removal = $this->orders_exist_from_ip($current_ip);
if ($ip_causes_removal) {
$should_remove_coupon = true;
}
$should_remove_coupon = apply_filters('gens_raf_should_remove_coupon', $should_remove_coupon, $guest_coupon_code, $referrer_id);
// Set appropriate removal message based on reason
if ($is_guest_self_referral || $is_guest_and_matches_cookie) {
$coupon_removal_message = apply_filters('gens_raf_self_referral_message', __('You cannot use your own referral code to get a discount.', 'gens-raf'));
} else {
$coupon_removal_message = apply_filters('gens_raf_coupon_removal_message', __('The coupon has been removed from your cart. You are an existing customer and are not entitled to a referral discount.', 'gens-raf'));
}
if ($should_remove_coupon) {
if (WC()->cart->has_discount($guest_coupon_code)) {
WC()->cart->remove_coupon($guest_coupon_code);
$errors->add('raf_error', $coupon_removal_message);
}
if (isset($_COOKIE["gens_raf"]) && !empty($_COOKIE["gens_raf"]) && WC()->cart->has_discount($_COOKIE["gens_raf"])) {
WC()->cart->remove_coupon($_COOKIE["gens_raf"]);
$errors->add('raf_error', $coupon_removal_message);
}
}
}
/**
* Validate and potentially remove coupon when it's being applied
*
* @param string $coupon_code
*/
public function validate_and_remove_coupon($coupon_code)
{
$referrer_id = $this->check_referrer_cookie();
if (!$referrer_id) {
return;
}
$guest_coupon_code = $this->get_guest_coupon_code($referrer_id);
// Only validate RAF-related coupons
if ($coupon_code !== $guest_coupon_code && substr($coupon_code, 0, 3) !== "ref") {
return;
}
// Get current user data
$user_id = get_current_user_id();
$user_email = $user_id ? get_userdata($user_id)->user_email : '';
$user_address = $user_id ? get_user_meta($user_id, 'billing_address_1', true) : '';
$advocate_address = get_user_meta($referrer_id, "billing_address_1", true);
// Check if user exists with this email ONLY if we have an email (i.e., user is logged in)
$email_exists = false;
if (! empty($user_email)) {
$email_exists = wc_get_orders(array(
'numberposts' => 1,
'billing_email' => $user_email,
'status' => array('wc-processing', 'wc-completed'),
));
}
// Check if phone exists
$phone_exists = false;
if ($user_id) {
$phone = get_user_meta($user_id, 'billing_phone', true);
if ($phone) {
$phone_exists = $this->orders_exist_from_phone($phone);
}
}
// Determine conditions for removing the coupon
$is_guest_and_matches_cookie = isset($_COOKIE["gens_raf_guest"]) && $user_email === $_COOKIE["gens_raf_guest"];
$is_self_referral = $user_id === $referrer_id;
// Check for new guest referral self-referral (same email used to generate and checkout)
$is_guest_self_referral = false;
if (isset($_COOKIE["gens_raf"]) && is_string($_COOKIE["gens_raf"]) && strpos($_COOKIE["gens_raf"], 'ref') === 0) {
$db = new WPGens_RAF_DB();
$guest_referral = $db->get_guest_referral_by_code($_COOKIE["gens_raf"]);
if ($guest_referral && (!empty($user_email) ? $guest_referral['email'] === $user_email : $guest_referral['email'] === $data['billing_email'])) {
$is_guest_self_referral = true;
}
}
$user_has_previous_orders = $this->user_has_orders($user_email) > 0;
$email_has_previous_orders = !empty($email_exists);
$same_billing_address = ($advocate_address === $user_address && $advocate_address !== '');
$allow_existing_customers = $this->settings_field_active('gens_raf_allow_existing');
$is_existing_customer_disallowed = (
($user_has_previous_orders || $email_has_previous_orders || $same_billing_address || $phone_exists)
&& !$allow_existing_customers
);
$should_remove_coupon = $is_guest_and_matches_cookie || $is_self_referral || $is_guest_self_referral || $is_existing_customer_disallowed;
$current_ip = WC_Geolocation::get_ip_address();
$ip_causes_removal = $this->orders_exist_from_ip($current_ip);
if ($ip_causes_removal) {
$should_remove_coupon = true;
}
$should_remove_coupon = apply_filters('gens_raf_should_remove_coupon', $should_remove_coupon, $guest_coupon_code, $referrer_id);
// Set appropriate removal message based on reason
if ($is_guest_self_referral || $is_guest_and_matches_cookie) {
$coupon_removal_message = apply_filters('gens_raf_self_referral_message', __('You cannot use your own referral code to get a discount.', 'gens-raf'));
} else {
$coupon_removal_message = apply_filters('gens_raf_coupon_removal_message', __('The coupon has been removed from your cart. You are an existing customer and are not entitled to a referral discount.', 'gens-raf'));
}
if ($should_remove_coupon) {
WC()->cart->remove_coupon($coupon_code);
wc_add_notice($coupon_removal_message, 'error');
}
}
}
$wpgens_raf_checkout = new WPGens_RAF_Checkout();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment