简体   繁体   中英

Create new product with woocommerce REST API with javascript (clientside)?

I try to create a new product in Woocommerce with its API in javascript (clientside)?

endpoint:

https://localhost/wpShop/wc-api/v2/products?consumer_key=ck_1111111111122123&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1458225139&oauth_nonce=nVq4rX&consumer_secret=cs_232332322233232&oauth_signature=kzoVx+VYSWlLbRpi3f8222222=

With a GET I get all products from Woocommerce! Perfect!

But, why can't I create a new product?

my new product:

var data = {
    product: {
      title: 'Premium Quality',
      type: 'simple',
      regular_price: '21.99',
      description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.',
      short_description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.',
      categories: [
        9,
        14
      ],
      images: [
        {
          src: 'http://www.adpic.de/data/picture/detail/Wasserflasche_74756.jpg',
          position: 0
        },
        {
          src: 'http://www.adpic.de/data/picture/detail/Wasserflasche_74756.jpg',
          position: 1
        }
      ]
    }
  };

my ajax POST request:

$.ajax({
  method: "POST",
  url: woocommerceURLcreateProduct,
  data: $.param(data)
})
  .done(function( msg ) {
    console.log( "Data Saved: " );
    console.log( msg );
  });

I get the error:

{code: "woocommerce_api_missing_callback_param", message: "Missing Parameter data"}

Source:

http://woothemes.github.io/woocommerce-rest-api-docs/v2.html?javascript#create-a-product

According to the jQuery Docs , jQuery.param(...) takes your object and serializes it into a string, typically used for transferring data via GET .

According to WooCommerce Docs , your requests should be sent as a JSON string.

Replace data: $.param(data) with data: data , jQuery's ajax allows you to pass an object as your data, and it will do all the hard work of stringifying it into a JSON string for the endpoint.

Don't forget to set your dataType to json in your ajax call, so jQuery can parse WooCommerce's JSON response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM