function wc_place_orders($request) {
global $woocommerce;
$order_data = array(
'status' => 'processing',
'customer_id' => $request['user_id'],
'created_via' => "Created From Andriod App",
);
$address = array(
'first_name' => $request['first_name'],
'last_name' => $request['last_name'],
'company' => '',
'email' => $request['email'],
'phone' => $request['phone'],
'address_1' => $request['address_1'],
'address_2' => $request['address_2'],
'city' => $request['city'],
'state' => $request['state'],
'postcode' => $request['postcode'],
'country' => $request['country'],
);
// Now we create the order
$order = wc_create_order($order_data);
$order_id = $order->get_id();
$subtotal = $order->get_subtotal();
//Display Cart Items
$saved_cart_meta = get_user_meta($request['user_id'], '_woocommerce_persistent_cart_' . get_current_blog_id(), true);
foreach ($saved_cart_meta['cart'] as $key => $value) {
$product = wc_get_product($value['product_id']);
$total_tx[] = $value['line_tax'];
$order->add_product($product, $value['quantity'], ["tax_class" => 'hoogtarief']);
}
$TotalTx = array_sum($total_tx);
$IncTaxSubtotal = $order->get_subtotal() + $TotalTx;
$order->set_address($address, 'billing');
$order->set_created_via($order_data['created_via']);
// Set payment gateway
$payment_gateways = WC()->payment_gateways->payment_gateways();
$order->set_payment_method($payment_gateways[$request['payment']]);
//Shipping Fees (Only order above 25)
if($IncTaxSubtotal < 25){
if( !$request['free_shipping'] == 'true' ){
$shipping_taxes = WC_Tax::calc_shipping_tax($request['shipping_value'], 1.24);
$order->add_shipping(new WC_Shipping_Rate('flat_rate_shipping', $request['shipping_method_title'], $request['shipping_value'], $shipping_taxes, 'flat_rate'));
}
}
//Coupon Code
$order->apply_coupon($request['coupon_code']);
$item = new WC_Order_Item_Fee();
$item2 = new WC_Order_Item_Tax(array('rate_id' => 4, 'tax_total' => 10, 'shipping_tax_total' => 50));
$item2->set_rate(4);
$item2->set_order_id($order_id);
$item2->save();
$order->add_item($item2);
if( $request['free_shipping'] == 'true' ){
$item->set_total( $TotalTx );
} elseif($IncTaxSubtotal < 25){
$item->set_name( 'Hoogtarief' );
$item->set_total( $TotalTx + $request['shipping_tax'] );
} else {
$item->set_total( $TotalTx );
}
$item->save();
$order->add_item( $item );
$order->calculate_totals( $has_taxes );
$order->save();
$OrderDetails = wc_get_order( $order_id );
//$order->update_status("pending", 'Created With Android App', TRUE);
return new WP_REST_Response($OrderDetails);
}
Creating Endpoints
add_action('rest_api_init', function () {
register_rest_route('wp/v2', '/place_orders', array(
'methods' => 'POST',
'callback' => 'wc_place_orders', //Function name
));
});
