/**
* Create an order. Error codes:
* 520 - Cannot insert order into the database.
* 521 - Cannot get order after creation.
* 522 - Cannot update order.
* 525 - Cannot create line item.
* 526 - Cannot create fee item.
* 527 - Cannot create shipping item.
* 528 - Cannot create tax item.
* 529 - Cannot create coupon item.
*
* @throws Exception
* @param $data Posted data.
* @return int|WP_ERROR
*/
public function create_order($data)
{
// Give plugins the opportunity to create an order themselves.
if ($order_id = apply_filters('woocommerce_create_order', null, $this)) {
return $order_id;
}
try {
$order_id = absint(WC()->session->get('order_awaiting_payment'));
$cart_hash = md5(json_encode(wc_clean(WC()->cart->get_cart_for_session())) . WC()->cart->total);
/**
* If there is an order pending payment, we can resume it here so
* long as it has not changed. If the order has changed, i.e.
* different items or cost, create a new order. We use a hash to
* detect changes which is based on cart items + order total.
*/
if ($order_id && ($order = wc_get_order($order_id)) && $order->has_cart_hash($cart_hash) && $order->has_status(array('pending', 'failed'))) {
// Action for 3rd parties.
do_action('woocommerce_resume_order', $order_id);
// Remove all items - we will re-add them later.
$order->remove_order_items();
} else {
$order = new WC_Order();
}
foreach ($data as $key => $value) {
if (is_callable(array($order, "set_{$key}"))) {
$order->{"set_{$key}"}($value);
}
}
$order->set_created_via('checkout');
$order->set_cart_hash($cart_hash);
$order->set_customer_id(apply_filters('woocommerce_checkout_customer_id', get_current_user_id()));
$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_customer_note(isset($data['order_comments']) ? $data['order_comments'] : '');
$order->set_payment_method($data['payment_method']);
$order->set_shipping_total(WC()->cart->shipping_total);
$order->set_discount_total(WC()->cart->get_cart_discount_total());
$order->set_discount_tax(WC()->cart->get_cart_discount_tax_total());
$order->set_cart_tax(WC()->cart->tax_total);
$order->set_shipping_tax(WC()->cart->shipping_tax_total);
$order->set_total(WC()->cart->total);
$this->create_order_line_items($order);
$this->create_order_fee_lines($order);
$this->create_order_shipping_lines($order);
$this->create_order_tax_lines($order);
$this->create_order_coupon_lines($order);
$order_id = $order->save();
// Let plugins add their own meta data.
do_action('woocommerce_checkout_update_order_meta', $order_id, $data);
return $order_id;
} catch (Exception $e) {
return new WP_Error('checkout-error', $e->getMessage());
}
}