Http Post request to Woocommerce API creates empty order (no data)

I post this data to Woocommerce API for creating a new order:

 orderData = {
       "payment_method": "bacs",
   "payment_method_title": "Direct Bank Transfer",
  "set_paid": true,
  "billing": {
    "first_name": "John",
    "last_name": "Doe",
    "address_1": "969 Market",
    "address_2": "",
    "city": "San Francisco",
    "state": "CA",
    "postcode": "94103",
    "country": "US",
    "email": "john.doe@example.com",
    "phone": "(555) 555-5555"
  },
  "shipping": {
    "first_name": "John",
    "last_name": "Doe",
    "address_1": "969 Market",
    "address_2": "",
    "city": "San Francisco",
    "state": "CA",
    "postcode": "94103",
    "country": "US"
  },
  "line_items": [
    {
      "product_id": 7,
      "quantity": 1
    }
  ],
  "shipping_lines": [
    {
      "method_id": "flat_rate",
      "method_title": "Flat Rate",
      "total": 7
    }
  ]
}

My http post request is like that:

his.http.post('API_URL?consumer_key=ck_&consumer_secret=cs_',
    JSON.stringify(orderData), {
      headers: { 'Content-Type': 'application/json'
    }
    }).subscribe(response => { newOrderData=response; console.log(newOrderData);});

A new order is created but the data of the body is not posted. I read about this issue on Stackoverflow and they claimed that it happens due to the lack of the header, which I include in my request.

Hi, I create my woocommerce order with this plugin: https://www.npmjs.com/package/woocommerce-api . And i can help you with that if you try using this plugin for creating order.

Hello, I actually tried to use the node.js woocommerce api, but it did not work for me. So I manually make the http get and post requests. The problem in my case was that I did not include quotes ("") in the keys like:
data {
“key” : value
} and the server responded with errors and the data was not passed to the rest api. Now the server still responds with “400” or “500” errors but the data is passed to the rest api.
In any case it would be useful to write down some examples with the node.js woocommerce api for future reference. Existing examples I met refer to past versions of ionic.

Edit: Of course the consumer key and the consumer secret must be included as headers. This also solves somehow the problem of the http post requests.

Do you know how to pass tax rates with the post request? Because all tax related fields are read-only.

500 internel error, i fix this by upgrading my php version!

Sorry i have no idea about it. I just post it with woocommerce-api. And my order was succesfully created!

Please show an example of the woocommerce api post, in case taxes are included.

let me show you:

        placeOrder() {

    let orderItems: any[] = [];
    let data: any = {};

    let paymentData: any = {};

    this.paymentMethods.forEach((element, index) => {
      if (element.method_id == this.paymentMethod) {
        paymentData = element;
      }
    });


    data = {

      //Fixed a bug here. Updated in accordance with wc/v2 API
      payment_method: paymentData.method_id,
      payment_method_title: paymentData.method_title,
      set_paid: true,

      billing: this.newOrder.billing,
      shipping: this.newOrder.shipping,
      customer_id: this.userInfo.id || '',
      line_items: orderItems
    };


    if (paymentData.method_id == "paypal") {

      this.payPal.init({
        PayPalEnvironmentProduction: "YOUR_PRODUCTION_CLIENT_ID",
        PayPalEnvironmentSandbox: "AYkkS2ObeSpaObaCqA3bybQjRNRMKOw_2vNSha7gmxESpG4l4AhEyMfYwuzrUFKSbWGhCsN-Vhtl5FOG"
      }).then(() => {
        // Environments: PayPalEnvironmentNoNetwork, PayPalEnvironmentSandbox, PayPalEnvironmentProduction
        this.payPal.prepareToRender('PayPalEnvironmentSandbox', new PayPalConfiguration({
          // Only needed if you get an "Internal Service Error" after PayPal login!
          //payPalShippingAddressOption: 2 // PayPalShippingAddressOptionPayPal
        })).then(() => {

          this.storage.get("cart").then((cart) => {

            let total = 0.00;
            cart.forEach((element, index) => {

              if(element.variation){
                orderItems.push({ product_id: element.product.id, variation_id: element.variation.id, quantity: element.qty });
                total = total + (element.variation.price * element.qty);
              } else {
                orderItems.push({ product_id: element.product.id, quantity: element.qty });
                total = total + (element.product.price * element.qty);
              }
            });

            let payment = new PayPalPayment(total.toString(), 'USD', 'Description', 'sale');
            this.payPal.renderSinglePaymentUI(payment).then((response) => {
              // Successfully paid

              alert(JSON.stringify(response));


              data.line_items = orderItems;
              //console.log(data);
              let orderData: any = {};

              orderData.order = data;

              this.WooCommerce.postAsync('orders', orderData.order).then((data) => {
                alert("Order placed successfully!");

                let response = (JSON.parse(data.body));

                this.alertCtrl.create({
                  title: "Order Placed Successfully",
                  message: "Your order has been placed successfully. Your order number is " + response.order_number,
                  buttons: [{
                    text: "OK",
                    handler: () => {
                      this.navCtrl.push('HomePage');
                    }
                  }]
                }).present();
              })

            })

          }, () => {
            // Error or render dialog closed without being successful
          });
        }, () => {
          // Error in configuration
        });
      }, () => {
        // Error in initialization, maybe PayPal isn't supported or something else
      });





    } else {

      this.storage.get("cart").then((cart) => {

        cart.forEach((element, index) => {
          if(element.variation){
            orderItems.push({ product_id: element.product.id, variation_id: element.variation.id, quantity: element.qty });
            ///total = total + (element.variation.price * element.qty);
          } else {
            orderItems.push({ product_id: element.product.id, quantity: element.qty });
            ///total = total + (element.product.price * element.qty);
          }
        });

        data.line_items = orderItems;

        let orderData: any = {};

        orderData.order = data;

        this.WooCommerce.postAsync("orders", orderData.order).then((data) => {

          let response = (JSON.parse(data.body));

          this.alertCtrl.create({
            title: "Order Placed Successfully",
            message: "Your order has been placed successfully. Your order number is " + response.order_number,
            buttons: [{
              text: "OK",
              handler: () => {
                this.navCtrl.setRoot('HomePage');
              }
            }]
          }).present();

        })

      })

    }


  }

Note that set_paid field is for the payment. if it will true, the order will go to processing. and if it will false the order will go to pending_payment. Hope it will help.

Unfortunately in the current version of ionic ‘woocommerce-api’ does not work this way and NavController is not supported, or tweaks are needed, which I am not aware of.

No it’s not. I also worked with ionic 4 and it works. Just tell me what the error you are getting. I’ll try helping you as I can. Okay!

I install the package ‘woocommerce-api’ and it appears in the package.json.
Then import it with "import * as WooApi from ‘woocommerce-api’; and make the initialization according to
https://www.npmjs.com/package/woocommerce-api . I also declare and import woocommerce-api in the app module.ts.
I get “declaration” warning regarding the woocommerce-api and 400 bad request - authentication error when I make the post request through the emulator.

Here’s a javascript file (example.js) inside the woocommerce-api module (version 1.5)

'use strict';

var WooCommerceAPI = require('./index.js'); // use require('woocommerce-api')

// Initialize the WooCommerceAPI class
var WooCommerce = new WooCommerceAPI({
  url: 'http://example.com', // Your store url (required)
  // version: 'v3', // WooCommerce API version (optional)
  // verifySsl: true, // Use `false` when need test with self-signed certificates, default is `true` (optional)
  // encoding: 'utf8', // Encode, default is 'utf8' (optional)
  consumerKey: 'ck_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', // Your API consumer key (required)
  consumerSecret: 'cs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' // Your API consumer secret (required)
});

// GET example
WooCommerce.get('customers', function(err, data, res) {
  console.log(res);
});

// POST example
// WooCommerce.post('products', {
//   product: {
//     title: 'Premium Quality',
//     type: 'simple',
//     regular_price: '21.99'
//   }
// }, function(err, data, res) {
//   console.log(res);
// });

// PUT example
// WooCommerce.put('orders/123', {
//   order: {
//     status: 'completed'
//   }
// }, function(err, data, res) {
//   console.log(res);
// });

// Delete example
// WooCommerce.delete('coupons/123', function(err, data, res) {
//   console.log(res);
// });

Woocommerce.postAsync() function does not even exist in the current version of the woocommerce-api.

The only way to place an order is like that:

const consumer_key = "ck_";
   const consumer_secret = "cs_";
   const encoded = btoa(consumer_key + ":" + consumer_secret); 

   
   this.http.post('URL', orderData, {headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': 'Basic ' + encoded}
   }).subscribe(res=> {  console.log(res); });

The order field “created _via” is automatically set to “rest_api”, while orders created with the checkout form from website have “checkout” in this field. They also have the tax values automatically set, while the order via the rest api has only the total value set (regular price). No matter what else you post inside orderData, read-only values such as total_tax, subtotal_tax. tax_lines will be empty strings.

The only solution I found so as to post the value including taxes is to include the taxes in the total value of the products. This is also impossible if you post the request to wc/v3/orders or wc/v1/orders. Only in wc/v2/orders the total and subtotal value of the products have write permissions. This way the total of all the items will equal the prices + VAT. On the other hand, if you issue an invoice, the VAT will be missing, while VAT and price are distinct when you place an order from the website checkout.
It is ridiculous not to be able to change the permissions of the fields in a rest api. I search for the fields in the database and in the woocommerce files, there is a php file “wc-class-order” or something like that, where the order fields are initialized and have setter functions, but could not locate where the hell they are set as “read-only”. Anyway, if anyone finds out how to modify the rest api fields or add new custom fields, please let us know.

Okay here is my full woocommerce app link created in ionic 4 with woocommerce-api. Hope it will help your:


And for CORS issue you can use CORS extension in your browser or you can install a plugin in your site dashboard, and there you can handle cors issue. Hope it will help your.