通过IP限制woocommerce订单 [英] Limit woocommerce orders by IP

查看:66
本文介绍了通过IP限制woocommerce订单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在woocommerce中,我需要防止每天通过IP地址销售超过30件商品.基本上,它是对机器人的保护.我认为逻辑必须是这样的:

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:

  • 获取购买商品的客户IP,并将其存储在订单元中
  • 检查在过去24小时内是否还从该IP购买了其他商品
  • 如果超过30,则在付款前显示错误并要求稍后退回

*用户注册已禁用

因此,我不确定从哪里开始以及如何遵循woocommerce钩子规则.

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

任何代码示例都将受到高度赞赏

Any code examples would be highly appreciated

推荐答案

默认情况下,WooCommerce实际上将客户端IP地址存储在订单元数据中.您可以在 WC_Order 上使用 get_customer_ip_address()方法来访问此元数据.同样,WooCommerce包含 WC_Geolocation :: get_ip_address()来获取当前连接的客户端的IP.

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.

将这些内容放在一起,如果具有相同IP的用户尝试在给定的时间段内进行过多的购买,则可以使用 woocommerce_checkout_process 钩给出错误消息.

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.

这里我使用的是 wc_get_orders() 简要查询最近24小时内具有匹配IP的所有订单,如果结果超过30个,则取消交易.

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);

请注意,对类型为'error' wc_add_notice()的调用将阻止事务处理.

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

这篇关于通过IP限制woocommerce订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆