Home / eCommerce / ACFW – Fraud prevention on one-time coupons
Duplicate Snippet

Embed Snippet on Your Site

ACFW – Fraud prevention on one-time coupons

Code Preview
php
<?php
  add_action( 'woocommerce_checkout_process', function() {
      $coupon_code   = 'your_coupon_code';
      $billing_phone = wc_clean( wp_unslash( $_POST['billing_phone'] ?? '' ) );
      $billing_addr1 = strtolower( wc_clean( wp_unslash( $_POST['billing_address_1'] ?? '' ) ) );
      if ( ! WC()->cart ) {
          return;
      }
      $applied = array_map( 'wc_format_coupon_code', WC()->cart->get_applied_coupons() );
      if ( ! in_array( wc_format_coupon_code( $coupon_code ), $applied, true ) ) {
          return;
      }
      global $wpdb;
      $order_ids = $wpdb->get_col( $wpdb->prepare(
          "SELECT order_id FROM {$wpdb->prefix}woocommerce_order_items
           WHERE order_item_type = 'coupon'
           AND order_item_name = %s",
          wc_format_coupon_code( $coupon_code )
      ) );
      if ( empty( $order_ids ) ) {
          return;
      }
      foreach ( $order_ids as $order_id ) {
          $order = wc_get_order( absint( $order_id ) );
          if ( ! $order ) {
              continue;
          }
          $phone_match = ! empty( $billing_phone ) && $order->get_billing_phone() === $billing_phone;
          $addr1_match = ! empty( $billing_addr1 ) && strtolower( $order->get_billing_address_1() ) === $billing_addr1;
          if ( $phone_match || $addr1_match ) {
              wc_add_notice(
                  __( 'This coupon has already been used. It is only available to new customers.', 'woocommerce' ),
                  'error'
              );
              return;
          }
      }
  } );

Comments

Add a Comment