使用Rest API将优惠券应用于WooCommerce订单

问题描述

在woocommerce中,我们可以使用优惠券功能(固定金额,百分比金额...)为任何订单添加折扣。

我尝试了以下代码:

function ocost_check_coupon(WP_REST_Request $request){
    $coupon_code = $request->get_param('coupon');
    $order_id = $request->get_param('order_id');
    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
    $order = wc_get_order($order_id);
    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();
        }
    }
    if ($order->save()) {
        $results = array();
        $results = array(
        'status' => 'true','message' => 'done and apply coupon to order',);  
        return $results; 
    } else{
        return array(
            'status' => 'error','message' => 'error to complete coupon function'
            );
    }
}

但是似乎没有应用任何优惠券。 我只是在订单中添加了代码:如果在wp-admin中找不到此优惠券,如何在应用优惠券之前进行检查?

任何帮助将不胜感激。

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...