itsource

WooCommerce 3에서 주문에 프로그래밍 방식으로 쿠폰 적용하기

mycopycode 2023. 10. 4. 21:51
반응형

WooCommerce 3에서 주문에 프로그래밍 방식으로 쿠폰 적용하기

저는 직접 주문을 생성하고(카트 없음) 쿠폰을 적용하는 플러그인을 개발하고 있습니다.woo API 버전 3.0에서 functionadd_coupon()A에 유리하게 감가상각되었습니다.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에서 우리가 쿠폰을 어떻게 처리할 것인지 오해한 적이 있습니까?

사용해보는건 어떨까요.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();

네, 그래서 조금 더 놀았는데 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에서 특정 할인 + 쿠폰 코드 등이 표시된 줄 항목과 함께 잘 포맷된 주문을 받으실 수 있습니다.

언급URL : https://stackoverflow.com/questions/48188567/applying-programmatically-a-coupon-to-an-order-in-woocommerce3

반응형