Limit woocommerce orders by IP

喜你入骨 提交于 2021-02-04 19:31:21

问题


I need to prevent selling more than 30 items per day by IP address in woocommerce. Basically, it is protection from bots. I think logic must be something like this:

  • get IP of a customer on a purchase and store it in the order meta
  • check if there are other purchases from that IP at the past 24hr
  • if more then 30 - display an error before payment and ask to return later

*user registration is disabled

So I'm not sure where to start and how to follow to woocommerce hooks rules.

Any code examples would be highly appreciated


回答1:


WooCommerce actually stores client IP addresses in the order metadata by default. You can use the get_customer_ip_address() method on a WC_Order to access this metadata. Likewise, WooCommerce includes WC_Geolocation::get_ip_address() to get the IP of the currently connected client.

Putting these together, you can use the woocommerce_checkout_process hook to give an error if a user with the same IP tries to make too many purchases in the given time period.

Here I'm using wc_get_orders() to succinctly query for all orders with a matching IP in the last 24 hours, and cancel the transaction if there are more than 30 results.

function my_ip_checker() {
    $last_24_hours_from_ip_results = wc_get_orders(array(
        'date_created'        => '>=' . (time() - 86400), // time in seconds
        'customer_ip_address' => WC_Geolocation::get_ip_address(),
        'paginate'            => true  // adds a total field to the results
    ));
    if($last_24_hours_from_ip_results->total > 30) { 
        wc_add_notice('Too many orders in the last 24 hours. Please return later.', 'error');
    }
}
add_action('woocommerce_checkout_process', 'my_ip_checker', 10, 0);

Note that the call to wc_add_notice() with a type of 'error' will stop the transaction from going through.



来源:https://stackoverflow.com/questions/53852696/limit-woocommerce-orders-by-ip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!