以编程方式将优惠券应用于 WooCommerce3 中的订单

Applying programmatically a coupon to an Order in WooCommerce3

我正在开发一个直接创建订单(没有购物车)并应用优惠券的插件。在 woo API 的 3.0 版中,函数 add_coupon() 已被弃用,取而代之的是您添加到订单中的 WC_Order_Item_Coupon 对象。

创建优惠券

$coupon = new WC_Order_Item_Coupon();
$coupon->set_props(array('code' => $coupon, 'discount' => $discount_total, 
'discount_tax' => 0));
$coupon->save();

这是成功的。我可以通过调用 $coupon->get_discount().

来验证

然后我将优惠券添加到订单并重新计算总数:

$order->add_item($item);
$order->calculate_totals($discount_total);
$order->save(); 

登录 wp-admin 我可以看到带有优惠券代码的订单。但是,优惠券对订单项或总计没有影响。

是否误解了 api v3.0 打算如何处理优惠券?

好的,所以我玩了一会儿,看起来在 V3 中的东西更手动一些。

WC_Order_Item_Coupon 项目添加到求购订单中就可以做到这一点。它将优惠券对象添加到订单对象。不进行任何计算,产品线项目保持不变。您必须手动遍历产品项目并通过计算行项目总计和小计自行应用优惠券。 calculate_totals() 然后按预期进行。

// Create the coupon
global $woocommerce;
$coupon = new WC_Coupon($coupon_code);

// Get the coupon discount amount (My coupon is a fixed value off)
$discount_total = $coupon->get_amount();

// Loop through products and apply the coupon discount
foreach($order->get_items() as $order_item){
    $product_id = $order_item->get_product_id();

    if($this->coupon_applies_to_product($coupon, $product_id)){
        $total = $order_item->get_total();
        $order_item->set_subtotal($total);
        $order_item->set_total($total - $discount_total);
        $order_item->save();
    }
}
$order->save();

我编写了一个辅助函数来确保优惠券适用于相关产品coupon_applies_to_product()。完全不需要,因为我完全在代码中创建订单。但我在其他地方使用它,所以添加了它。

// Add the coupon to the order
$item = new WC_Order_Item_Coupon();
$item->set_props(array('code' => $coupon_code, 'discount' => $discount_total, 'discount_tax' => 0));
$order->add_item($item);
$order->save();

您现在可以在 wp-admin 中获得格式良好的订单,其中的订单项显示特定折扣 + 优惠券代码等。

使用WC_Abstract_Order::apply_coupon怎么样?

/**
 * Apply a coupon to the order and recalculate totals.
 *
 * @since 3.2.0
 * @param string|WC_Coupon $raw_coupon Coupon code or object.
 * @return true|WP_Error True if applied, error if not.
 */
public function apply_coupon( $raw_coupon )

这是我的代码。

$user = wp_get_current_user();

$order = new WC_Order();
$order->set_status('completed');
$order->set_customer_id($user->ID);
$order->add_product($product , 1); // This is an existing SIMPLE product
$order->set_currency( get_woocommerce_currency() );
$order->set_prices_include_tax( 'yes' === get_option( 'woocommerce_prices_include_tax' ) );
$order->set_customer_ip_address( WC_Geolocation::get_ip_address() );
$order->set_customer_user_agent( wc_get_user_agent() );
$order->set_address([
    'first_name' => $user->first_name,
    'email'      => $user->user_email,
], 'billing' );
// $order->calculate_totals();  // You don't need this

$order->apply_coupon($coupon_code);

$order->save();