无法获得优惠券以将折扣应用于订单。 (以编程方式创建新订单)
以下是代码:
$order = wc_create_order();
$order->add_product( get_product( $pid ), $item['quantity'] ); // pid 8 & qty 1
$order->set_address( $address_billing, 'billing' );
$order->set_address( $address_shipping, 'shipping' );
$order->add_coupon( $discount['code'], ($discount['amount']/100) ); // not pennies (use dollars amount)
$order->set_total( ($discount['amount']/100) , 'order_discount'); // not pennies (use dollar amount)
$order->set_payment_method($this);
$rate = new WC_Shipping_Rate( $response_body['shippingMethodCode'] , $ship_method_title, ($response_body['shippingCost']/100), array(), $response_body['shippingMethodCode'] );
$order->add_shipping( $rate );
$order->calculate_totals();
$return_url = $this->get_return_url( $order );
订单是在Woocommerce中创建的,一切看起来都不错,但正在应用的优惠券代码并不反映返回网址上的折扣金额感谢页面 - 而且 - 在查看Woocommerce订单时不在wp-admin中 - 并且 - 不是在发送出去的新客户订单电子邮件中....
它确实在wp-admin中显示优惠券代码,但折扣行仍显示$ 0,且总数未显示任何减去的金额。
任何人都知道这里做错了什么?现在已经在这几个星期了,似乎无法解决。
答案 0 :(得分:4)
要实现这一点,您需要以编程方式计算添加到订单的每个产品的折扣,并将其作为附加参数传递。请参阅更新示例:
$order = wc_create_order();
$product_to_add = get_product( $pid );
$sale_price = $product_to_add->get_price();
// Here we calculate the final price with the discount
$final_price = round($sale_price * ((100-$discount['amount']) / 100), 2);
// Create the price params that will be passed with add_product(), if you have taxes you will need to calculate them here too
$price_params = array( 'totals' => array( 'subtotal' => $sale_price, 'total' => $final_price ) );
$order->add_product( get_product( $pid ), $item['quantity'], $price_params ); // pid 8 & qty 1
$order->set_address( $address_billing, 'billing' );
$order->set_address( $address_shipping, 'shipping' );
$order->add_coupon( $discount['code'], ($discount['amount']/100) ); // not pennies (use dollars amount)
$order->set_total( ($discount['amount']/100) , 'order_discount'); // not pennies (use dollar amount)
$order->set_payment_method($this);
$rate = new WC_Shipping_Rate( $response_body['shippingMethodCode'] , $ship_method_title, ($response_body['shippingCost']/100), array(), $response_body['shippingMethodCode'] );
$order->add_shipping( $rate );enter code here
$order->calculate_totals();
$return_url = $this->get_return_url( $order );