Skip to content

christwinn/woocommerce-api-client-java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

375 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

WooCommerce API Client for Java

A fluent java client interface to the WooCommerce REST Api

A fully implemented lightweight, deceptively simple, fluent Java client library for the WooCommerce REST API v3.

Built for Java developers who need to quickly integrate their applications with the WooCommerce e-commerce platform.

The samples shown are the same as https://woocommerce.github.io/woocommerce-rest-api-docs/ but using this WooCommerce API Java Client

Installation

<dependency>
    <groupId>uk.co.twinn.api</groupId>
    <artifactId>woocommerce-api-client</artifactId>
    <version>3.1.3.1</version>
</dependency>

Note: We use a 4 point versioning system: (Semantic Versioning 2.0.0 + 1) W.X.Y.Z
W: The Upstream API version that is being targeted - simpler to ensure the correct client API X: MAJOR version when we make incompatible API changes
Y: MINOR version when we add functionality in a backward compatible manner
Z: PATCH version when we make backward compatible bug fixes

Optionals or Reactions

This API implements the upstream API in an 1 for 1, action for action methodology. Using generics we also simplify the codebase funnelling the code through a few pipelines while enabling simple enforcement of the upstream API interface.

Using builder class methodology we have a simple to read and simple to use basis for generating our API calls.

Two choices of usage. Either Optionals or Reactions

Optionals

private void demo() {
    
    List<Product> products = Products.listing().setSku("67020401")
            .getListed()
            .orElseThrow(
                () -> new ResponseException("list failure")
            );

    for (Product product : products) {

        Product pa = Products.read(product.getId())
                .getRead()
                .orElseThrow(
                    () -> new ResponseException("no matching product could be found")
                );

        System.out.println("======" + pa.getSku() + "======");

    }
    
}

Reactions

Rather than force you to error catch everywhere we error catch for you, leaving you with a simple call to isSuccess() to verify that a successful call was made, and of course if not then we have the error in plain speak getError().getMessage(). If it is a success we have our successful object inside getResult();

From a user point of view, all you need is the classes under api (Plurals) and then we have a few response types, these contain the returned object types (Singular type, or list of Singlular).

Newton's Third Law of Motion: "For every action, there is an equal and opposite reaction"

An overview of how to get the responses, more specific details are under "Code Samples"
/** Generic system setup **/

/** Following the simple methodology: Reaction<SingularType> = PluralType.action.getResponse(); 
 *  More specific examples are provided under the 'PluralType' sections further down.
 *
 * Builder patterns can also be accessed via WooCommerce.PluralType.create()/read()/etc for extra simplicity.
 *   e.g. WooCommerce.Products.read(123).getResponse();
 *
 **/

/**Create**/
Created<SingularType> created = PluralType.create(anyMandatoryValues).setX("...").getResponse();
Created<SingularType> created = PluralType.create(aSingularPOJOWeCreatedEarlier).getResponse();

/**Read**/
Read<SingularType> read = PluralType.read(123).getResponse();

/**Update**/
Updated<SingularType> updated = PluralType.update(123).setX("...").getResponse();
Updated<SingularType> updated = PluralType.update(aSingularPOJOWeCreatedEarlier).getResponse();

/**Delete**/
Deleted<SingularType> deleted = PluralType.delete(123, true).getResponse();

/**List All**/
Listed<SingularType> listed = PluralType.listing().getResponse();

/** Batch [Create, Update, Delete]**/
Batched<SingularType> batched = PluralType.batch()
        .addCreator(PluralType.create().setX("..."))   //creator
        .addCreator(aSingularPOJOWeCreatedEarlier)     //Single POJO of SingularType
        .addCreator(ListOfPOJOsWeCreatedEarlier)       //List<POJO> of SingularType
        .addUpdater(PluralType.update().setX("..."))
        .addUpdater(aSingularPOJOWeCreatedEarlier)
        .addUpdater(ListOfPOJOsWeCreatedEarlier)
        .addDeleter(PluralType.delete(123, true))
        .addDeleter(aSingularPOJOWeCreatedEarlier)
        .addDeleter(ListOfPOJOsWeCreatedEarlier)
        .getResponse();

Processing Responses

Always good to know what to do with the results...
private void processResults() {

/** The left hand always contains
    .isSuccess() -> did it work;

    Created, Read, Updated, Deleted will contain a single SingularType in .getResult(),
    i.e SingularType result = [created, read, updated, deleted].getResult(); 
 **/
    Read<Product> readProduct = Products.read(123).getResponse();

    if (readProduct.isSuccess()) {
        //do something with the result.
        Product p = readProduct.getResult();
        System.out.println(p.getSku());
        System.out.println(p.getDescription());
        /* p.get...*/
        System.out.println(p.toJson());
    } else {
        System.out.println(readProduct.getError().getMessage());
    }

/** 
    Listed will contain a list of SingularType in .getResult(), 
        i.e List<SingularType> result = listed.getResult();
        Really this is "search" with no parameters and only limited results are returned [default 10], 
            you need to increment the offset to retrieve all the result)
*/
    Listed<Continent> continents = Data.listAllContinents().getResponse();
    
    if (continents.isSuccss()) {
        for (Continent continent : continents.getResult()) { //continents.getResult() is a List<Continent>
            System.out.println(continent.getName());
            System.out.println(continent.toJson());
            for(Country country : continent.getCountries()){
                System.out.println(country.getName());
                System.out.println(country.getCode()); 
                /* country.get... */
            }
        }
    } else {
        System.out.println(readProduct.getError().getMessage());
    }

/*
    Batched will contain a list of SingularType in .getResult() under the requested action.
        i.e.
            List<SingularType> created = batched.getResult().getCreated();
            List<SingularType> updated = batched.getResult().getUpdated();
            List<SingularType> deleted = batched.getResult().getDeleted();

        Warning! While the action of batch() may be a success,
                 you should loop the lists to check that each record
                 actually succeeded and the API did not reject that request.
        
        Note: WooCommerce limits you to 100 objects per batch, having run experiments this is a very hopeful limit.
            You could experience PHP running out of memory, isSuccess() will be false and an error message 500 will be returned in the .getError().getMessage(), try smaller batch sizes.
*/

Batched<Customer> batched = Customers.batch()
        .addCreator(Customers.create(customer))
        .addUpdater(Customers.update(2).setFirstName("Fred"))
        .addDeleter(Customers.delete(3, true))
        .getResponse();

if (batched.isSuccess()){

    System.out.println("The request was a success BUT cycle the records to check that they are!");
    /** batched.getResult() is Batched<Customer> containing we elements: 
    *  getCreated() which is a List<Customer> relating to all the customers we just tried to create
    *  getUpdated() which is a List<Customer> relating to all the customers we just tried to update
    *  getDeleted() which is a List<Customer> relating to all the customers we just tried to delete
    */
    
    for(Customer bc :batched.getResult().getCreated()){
        if(!bc.hasError()){
            System.out.println(bc.getEmail()); /* bc.get... */
            System.out.println(bc.toString());
        }else{
            System.out.println("CREATE FAIL:"+bc.getError().getMessage());
        }
    }

    for(Customer bc :batched.getResult().getUpdated()){
        if(!bc.hasError()){
            System.out.println(bc.getEmail()); /* bc.get... */
            System.out.println(bc.toString());
        }else{
            System.out.println("UPDATE FAIL:"+bc.getError().getMessage());
        }
    }

    for(Customer bc :batched.getResult().getDeleted()){
        if(!bc.hasError()){
            System.out.println(bc.getEmail()); /* bc.get... */
            System.out.println(bc.toString());
        }else{
            System.out.println("DELETE FAIL:"+bc.getError().getMessage());
        }
    }
}else{
    System.out.println(batched.getError().getMessage());
}

/**
 getResult.getLinks() -> 
 HAL - Hypertext Application Language 
 <a href="https://stateless.group/hal_specification.html">https://stateless.group/hal_specification.html</a>
 **/

}

Code Samples

Authentication

It is assumed you have obtained the relevant credentials as per https://woocommerce.github.io/woocommerce-rest-api-docs/#rest-api-keys

Expand for example methods to Authenticate when using the WooCommerce API
private void authentication(){

    /** The simplest method is to place a file under ~/woocommerce-api/config.json 
    {
       "website": "example.com",
       "api": "/wp-json/wc/v3",
       "key": "myverysecretkeythatIgotfrommywoocommerceinstallation",
       "secret": "myverysecretsecretthatIgotfrommywoocommerceinstallation"
    }
    **/

    /**Alternatively we can...*/
    Message message = Authentication.https()
        .setWebsite("example.com")
        .setApiPath("/wp-json/wc/v3")
        .setKey("myverysecretkeythatIgotfrommywoocommerceinstallation")
        .setSecret("myverysecretsecretthatIgotfrommywoocommerceinstallation")
        .getResponse();

    /*Or*/
    
    Authentication.ConfigFile(System.getProperty("user.home") + "/.woocommerce-api/config.json").getResponse();
    
    /** Please note we have not implemented "Authentication over HTTP". We should not be retrieving customer detail's unencrypted **/
}

Coupons

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#coupons

Expand for example code to Create, Read, Update, Delete, Batch and get listed Coupons using the WooCommerce API
private void coupons() {
    /** Create **/
    Created<Coupon> created = Coupons.create()
                        .setCode("10off")
                        .setDiscountType("percent")
                        .setAmount(new BigDecimal(10))
                        .setIndividualUse(true)
                        .setExcludeSaleItems(true)
                        .setMinimumAmount(new BigDecimal(100.00))
                        .getResponse();
    /**Read**/
    Read<Coupon> read = Coupons.read(719).getResponse();

    /**Update**/
    Updated<Coupon> updated = Coupons.update(719)
                        .setAmount(new BigDecimal(15))
                        .getResponse();
    /**Delete**/
    Deleted<Coupon> deleted = Coupons.delete(719, true).getResponse();

    /**List All**/
    Listed<Coupon> listed = Coupons.listing().getResponse();

    /** Batch [Create, Update, Delete]**/
    Batched<Coupon> batched = Coupons.batch()
                        .addCreator(
                            Coupons.create()
                                .setCode("20off")
                                .setDiscountType("percent")
                                .setAmount(new BigDecimal(20))
                                .setIndividualUse(true)
                                .setExcludeSaleItems(true)
                                .setMinimumAmount(new BigDecimal(100.00))
                        )
                        .addCreator(
                            Coupons.create()
                                .setCode("30off")
                                .setDiscountType("percent")
                                .setAmount(new BigDecimal(30))
                                .setIndividualUse(true)
                                .setExcludeSaleItems(true)
                                .setMinimumAmount(new BigDecimal(400.00))
                        )
                        .addUpdater(
                            Coupons.update(719)
                                .setMinimumAmount(new BigDecimal(50))
                        )
                        .addDeleter(
                            Coupons.delete(720, true)
                        )
                        .getResponse();
}

Customers

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#customers

Expand for example code to Create, Read, Update, Delete, Batch and get listed Customers using the WooCommerce API
private void customers() {
    /** Create **/
    Created<Customer> created = Customers.create()
                        .setEmail("john.doe@example.co")
                        .setFirstName("John")
                        .setLastName("Doe")
                        .setUsername("john.doe")
                        .setPassword("shh")
                        .setBilling(new Billing()
                            .firstName("John")
                            .lastName("Doe")
                            .company("")
                            .address1("969 Market Street")
                            .address2("")
                            .city("San Fancisco")
                            .state("CA")
                            .postcode("94103")
                            .email("john.doe@example.com")
                            .phone("(555) 555-5555")
                        ).setShipping(new Shipping()
                            .firstName("John")
                            .lastName("Doe")
                            .company("")
                            .address1("969 Market")
                            .address2("")
                            .city("San Francisco")
                            .state("CA")
                            .postcode("94103")
                            .country("US")
                        )
                        .getResponse();
    /**Read (id of customer)**/
    Read<Customer> read = Customers.read(25).getResponse();

    /**Update**/
    Updated<Customer> updated = Customers.update(25)
                        .setFirstName("James")
                        .setShipping(
                            new Shipping().firstName("James")
                        )
                        .getResponse();
    /**Delete**/
    Deleted<Customer> deleted = Customers.delete(25, true).getResponse();

    /**List All**/
    Listed<Customer> listed = Customers.listing().getResponse();

    /**Search**/
    Listed<Customer> listed = Customers.listing().setEmail("john.doe@example.com").getResponse();

    /** Batch [Create, Update, Delete]**/
    Batched<Customer> batched = Customers.batch()
                        .addCreator(
                            Customers.create()
                                .setEmail("jane.doe@example.com")
                                .setFirstName("Jane")
                                .setLastName("Doe")
                                .setUsername("jane.doe")
                                .setBilling(new Billing()
                                    .firstName("Jane")
                                    .lastName("Doe")
                                    .company("")
                                    .address1("969 Market Street")
                                    .address2("")
                                    .city("San Fancisco")
                                    .state("CA")
                                    .postcode("94103")
                                    .email("jane.doe@example.com")
                                    .phone("(555) 555-5555")
                                )
                                .setShipping(new Shipping()
                                    .firstName("John")
                                    .lastName("Doe")
                                    .company("")
                                    .address1("969 Market")
                                    .address2("")
                                    .city("San Francisco")
                                    .state("CA")
                                    .postcode("94103")
                                    .country("US")
                                )
                        )
                        .addCreator(
                            Customers.create()
                                .setEmail("joao.silva2@example.com")
                                .setFirstName("Joao")
                                .setLastName("Silva")
                                .setUsername("joao.silva")
                                .setBilling(new Billing()
                                    .firstName("Joao")
                                    .lastName("Silva")
                                    .company("")
                                    .address1("Av. Brasil, 43")
                                    .address2("")
                                    .city("Rio de Janeiro")
                                    .state("RJ")
                                    .postcode("12345-000")
                                    .country("BR")
                                    .email("joao.silva2@example.com")
                                    .phone("(555) 555-5555")
                                )
                                .setShipping(new Shipping()
                                    .firstName("Joao")
                                    .lastName("Silva")
                                    .company("")
                                    .address1("Av. Brasil, 43")
                                    .address2("")
                                    .city("Rio de Janeiro")
                                    .state("RJ")
                                    .postcode("12345-000")
                                    .country("BR")
                                )
                        )
                        .addUpdater(
                            Customers.update(26)
                                .setBilling(
                                    new Billing()
                                    .phone("(11) 1111-1111")
                                )
                        )
                        .addDeleter(
                            Customers.delete(21, true)
                        )
                        .getResponse();
}

Orders

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#orders

Expand for example code to for Orders using the WooCommerce API
private void orders(){  
    
    /** Create **/
    Created<Order> creator = Orders.create()
            .setPaymentMethod("bacs")
            .setPaymentMethodTitle("Direct Bank Transfer")
            .setPaid(true)
            .setBilling(new Billing()
                    .firstName("John")
                    .lastName("Doe")
                    .company("")
                    .address1("969 Market Street")
                    .address2("")
                    .city("San Fancisco")
                    .state("CA")
                    .postcode("94103")
                    .email("john.doe@example.com")
                    .phone("(555) 555-5555")
            )
            .setShipping(new Shipping()
                    .firstName("John")
                    .lastName("Doe")
                    .company("")
                    .address1("969 Market")
                    .address2("")
                    .city("San Francisco")
                    .state("CA")
                    .postcode("94103")
                    .country("US")
            )
            .setLineItems(
                    Arrays.asList(
                            new OrderLineItem().productId(93).quantity(2),
                            new OrderLineItem().productId(22).variationId(23).quantity(2)
                    )
            )
            .setShippingLines(
                    Stream.of(
                        new OrderShippingLine().methodId("flat_rate")
                            .methodTitle("Flat Rate")
                            .total(new BigDecimal(10))
                    ).collect(Collectors.toList())
            ).getResponse();

    /** Read **/
    Read<Order> read = Orders.read(123).getResponse();
    
    /** Update **/
    Updated<Order> updater = Orders.update(123).setStatus("completed").getResponse();

    /** Delete**/
    Deleted<Order> deleted = Orders.delete(123, true).getResponse();

    /** List All **/
    Listed<Order> listed = Orders.listing().getResponse();

    /** Batch Update of orders */
    Batched<Order> batched = Orders.batch()
            .addCreator(
                    Orders.create()
                            .setPaymentMethod("bacs")
                            .setPaymentMethodTitle("Direct Bank Transfer")
                            .setPaid(true)
                            .setBilling(new Billing()
                                    .firstName("John")
                                    .lastName("Doe")
                                    .company("")
                                    .address1("969 Market Street")
                                    .address2("")
                                    .city("San Fancisco")
                                    .state("CA")
                                    .postcode("94103")
                                    .email("john.doe@example.com")
                                    .phone("(555) 555-5555")
                            )
                            .setShipping(new Shipping()
                                    .firstName("John")
                                    .lastName("Doe")
                                    .company("")
                                    .address1("969 Market")
                                    .address2("")
                                    .city("San Francisco")
                                    .state("CA")
                                    .postcode("94103")
                                    .country("US")
                            )
                            .setLineItems(
                                    Arrays.asList(
                                            new OrderLineItem().productId(93).quantity(2),
                                            new OrderLineItem().productId(22).variationId(23).quantity(2)
                                    )
                            )
                            .setShippingLines(
                                    Stream.of(
                                            new OrderShippingLine().methodId("flat_rate")
                                                    .methodTitle("Flat Rate")
                                                    .total(new BigDecimal(10))
                                    ).collect(Collectors.toList())
                            )
            )
            .addCreator(
                    Orders.create(anOrderWeMadeEarlier)
            )
            .addUpdater(
                    Orders.update(727)
                            .setStatus("completed")

            )
            .addDeleter(
                    Orders.delete(723, true)
            )
            .getResponse();
    
}

Order Actions

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#order-actions

Expand for example code for Order Actions using the WooCommerce API
private void orderActions(int customerId) {
    
    /** Send Email **/
    Created<Message> created = OrderActions.sendEmail(customerId).getResponse();
    
}    

Order Notes

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#order-notes

Expand for example code for Order Notes using the WooCommerce API
private void orderNotes(int orderId, int noteId){

    Created<OrderNote> created = OrderNotes.create(orderId).setNote("Hello World").getResponse();
    
    Read<OrderNote> read = OrderNotes.read(orderId, noteId).getResponse();

    Listed<OrderNote> list = OrderNotes.listing(orderId).getResponse();
    
    Deleted<OrderNote> deleted = OrderNotes.delete(orderId, noteId, true).getResponse();
    
}    

Order Refunds

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#order-refunds

Expand for example code for Order Refunds using the WooCommerce API
private void create(
    int orderId, 
    List <OrderRefundLineItem> lineItems,
    List <OrderShippingLine> shippingLines,
    List <OrderFeeLine> feeLines
){
    Created<OrderRefund> created = OrderRefunds.create(orderId)
            .setAmount(9.99)
            .setReason("Damaged")
            .setRefundedBy(2) /*id of user*/
            .setLineItems(lineItems)
            .setShippingLines(shippingLines)
            .setFeeLines(feeLines)
            .setApiRefund(true)
            .setApiRestock(false) //do not put back into stock
            .getResponse();
}

private void read(int orderId, int refundId){
    
    Read<OrderRefund> read = OrderRefunds.read(orderId, refundId).getResponse();

}

private void delete(int orderId, int refundId){

    Deleted<OrderRefund> deleted = OrderRefunds.delete(orderId, refundId, true).getResponse();
    
}

private void listing(int orderId){

    Listed<OrderRefund> list = OrderRefunds.listing(orderId).getResponse();

}

Products

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#products

Expand for example code for Products using the WooCommerce API
private void products() {

    /*Create*/
    Created<Product> created = Products.create()
            .setName("Premium Quality")
            .setType("simple")
            .setRegularPrice(new BigDecimal(21.99))
            .setDescription("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.")
            .setShortDescription("Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.")
            .setCategories(
                    Arrays.asList(
                            new ProductCategoriesItem().id(9),
                            new ProductCategoriesItem().id(14)
                    )
            )
            .setImage("http://mysite/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg")
            .getResponse();

    Read<Product> read = Products.read(123).getResponse();

    Updated<Product> updated = Products.update(123).setRegularPrice(new BigDecimal(9.99)).getResponse();

    Duplicated<Product> duplicated = Products.duplicate(123).getResponse();

    Deleted<Product> deleted = Products.delete(123, true).getResponse();

    Listed<Product> list = Products.listing().getResponse();

    Batched<Product> batched = Products.batch()
            .addCreator(
                    Products.create()
                            .setName("New Premium Quality 2")
                            .setType("simple")
                            .setRegularPrice(new BigDecimal(42.99))
                            .setDescription("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.")
                            .setShortDescription("Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.")
                            .setCategories(
                                    Arrays.asList(
                                            new ProductCategoriesItem().id(9),
                                            new ProductCategoriesItem().id(14)
                                    )
                            )
                            .setImage("http://mysite/woocommerce/wp-content/uploads/sites/56/2013/06/T_2_back.jpg")
            )
            .addUpdater(
                    Products.update(234).setMenuOrder(2).setName("Modified Title")
            )
            .addDeleter(
                    Products.delete(235, false)
            )
            .getResponse();

    /*Not in the API Convenience method to "list Products in a Category" in a category, will list up to 250 products*/
    Listed<Product> children = Products.listProductsInCategory(1).getResponse();

}    

Product Variations

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#product-variations

Expand for example code for Product Variations using the WooCommerce API
private void productVariations(){
    //todo
}    

Product Brands

Ref: Not documented on the REST API

Expand for example code for Product Brands using the WooCommerce API
private void productBrands(){

    Created<ProductBrand> created = ProductBrands.create("Brand 1").getResponse();

    Read<ProductBrand> read = ProductBrands.read(1).getResponse();

    Updated<ProductBrand> update = ProductBrands.update(productCategory).getResponse();

    Updated<ProductBrand> update = ProductBrands.update(1).setName("Super").getResponse();

    Deleted<ProductCBrand> delete = ProductBrands.delete(1, true).getResponse();

    Batched<ProductBrand> batched = ProductBrands.batch()
            .addCreator(
                    ProductBrands.create("Brand A")
            )
            .addUpdater(
                    ProductBrands.update(2, "Amazing")
            )
            .addDeleter(
                    ProductBrands.delete(1, false)
            )
            .getResponse();

    Listed<ProductBrand> search = ProductBrands.listing()
            .setSearch("new")
            .setHideEmpty(true)
            /** .... **/
            .getResponse();
}    

Product Attributes

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#product-attributes

Expand for example code for Product Attributes using the WooCommerce API
private void productAttributes(){
    //documentation todo
}        

Product Attribute Terms

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#product-attribute-terms

Expand for example code for Product Attribute Terms using the WooCommerce API
private void productAttributeTerms(){
    //documentation todo
}    

Product Categories

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#product-categories

Expand for example code for Product Categories using the WooCommerce API
private void productCategories() {

    Created<ProductCategory> created = ProductCategories.create("Category 1").getResponse();

    Read<ProductCategory> read = ProductCategories.read(1).getResponse();

    Updated<ProductCategory> update = ProductCategories.update(productCategory).getResponse();

    Updated<ProductCategory> update = ProductCategories.update(1).setName("My New Name").getResponse();

    Deleted<ProductCategory> delete = ProductCategories.delete(1, true).getResponse();

    Batched<ProductCategory> batched = ProductCategories.batch()
            .addCreator(
                    ProductCategories.create("Category A")
            )
            .addUpdater(
                    ProductCategories.update(2, "Category 2")
            )
            .addDeleter(
                    ProductCategories.delete(1, false)
            )
            .getResponse();

    Listed<ProductCategory> search = ProductCategories.listing()
            .setSearch("new")
            .setHideEmpty(true)
            /** .... **/
            .getResponse();

    /*Not in the API Convenience method to "list Child Categories" in a category, will list up to 250 children*/
    Listed<ProductCategory> children = ProductCategories.listChildCategories(1).getResponse();

}    

Product Custom Fields

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#product-custom-fields

Expand for example code for Product Custom Fields using the WooCommerce API
private void productCustomFields(){
    //documentation todo
}    

Product Shipping Classes

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#product-shipping-classes

Expand for example code for Product Shipping Classes using the WooCommerce API
private void productShippingClasses(){
    //documentation todo
}    

Product Tags

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#product-tags

Expand for example code for Product Tags using the WooCommerce API
private void productTags(){
    //documentation todo
}    

Product Reviews

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#product-reviews

Expand for example code for Product Reviews using the WooCommerce API
private void productReviews(){
    //documentation todo
}    

Reports

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#reports

Expand for example code to retrieve the Reports using the WooCommerce API
private void reports() {

    /*List All reports*/
    Listed<ReportListItem> list = Reports.listAll().getResponse();
    System.out.println(list.getResult().toJson());

    /*Retrieve sales report*/
    Listed<ReportSalesSummary> sales = Reports.salesSummary().getResponse();
    
    /*Retrieve top sellers report*/
    Listed<ReportTopSellersItem> topSellers = Reports.topSellers().getResponse();

    /*Retrieve coupons totals*/
    Listed<ReportOrderTotalSummary> coupons = Reports.couponsTotals().getResponse();

    /*Retrieve customers totals*/
    Listed<ReportOrderTotalSummary> customers = Reports.customersTotals().getResponse();

    /*Retrieve orders totals*/
    Listed<ReportOrderTotalSummary> orders = Reports.ordersTotals().getResponse();

    /*Retrieve products totals*/
    Listed<ReportOrderTotalSummary> products = Reports.productsTotals().getResponse();

    /*Retrieve reviews totals*/
    Listed<ReportOrderTotalSummary> reviews = Reports.reviewsTotals().getResponse();

}

Refunds

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#refunds

Expand for example code for Refunds using the WooCommerce API
private void refunds(){
    //documentation todo
}    

Tax Rates

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#tax-rates

Expand for example code for Tax Rates using the WooCommerce API
import java.math.BigDecimal;

private void taxRates() {
    
    Created<TaxRate> created = TaxRates.create().setName("Standard VAT").setRate(new BigDecimal(20.0)).getResponse();

    Created<TaxRate> created = TaxRates.create(new TaxRate().name("Zero VAT").rate(new BigDecimal(0.0))).getResponse();

    Read<TaxRate> read = TaxRates.read(1).getResponse();

    Updated<TaxRate> updated = TaxRates.update(2).setName("Std VAT").setRate(new BigDecimal(19.99)).getResponse();

    Updated<TaxRate> updated = TaxRates.update(new TaxRate().id(1).name("Std VAT").rate(new BigDecimal(15.0))).getResponse();

    Deleted<TaxRate> deleted = TaxRates.delete(1, true).getResponse();

    Listed<TaxRate> listed = TaxRates.listing().getResponse();
    
    Batched<TaxRate> batched = TaxRates.batch()
            .addCreator(new TaxRate().name("Fuels Tax").rate(new BigDecimal(5.0)))
            .addUpdater(TaxRates.update(2).setName("Standard VAT"))
            .addDeleter(TaxRates.delete(9, true))
            .getResponse();
    
}    

Tax Classes

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#tax-classes

Expand for example code for Tax Classes using the WooCommerce API
private void taxClasses(){
}    

Webhooks

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#webhooks

Expand for example code for Webhooks using the WooCommerce API
private void webhooks() {

    Created<Webhook> created = Webhooks.create("order.updated", "http://requestb.in/1g0sxmo1")
            .setName("Order Updat!")
            .getResponse();

    Read<Webhook> read = Webhooks.read(2).getResponse();

    Listed<Webhook> listed = Webhooks.listing().getResponse();

    Updated<Webhook> updated = Webhooks.update(2).setName("Order Updated").getResponse();

    Deleted<Webhook> deleted = Webhooks.delete(2, true).getResponse();

    BatchResult<Webhook> batched = Webhooks.batch()
            .addCreator(
                    Webhooks.create("coupon.created", "http://requestb.in/1g0sxmo1")
                        .setName("Coupon created")
            )
            .addCreator(
                    Webhooks.create("customer.deleted", "http://requestb.in/1g0sxmo1")
                        .setName("Customer deleted")
            )
            .addDeleter(
                    Webhooks.delete(143, true)
            )
            .getResponse();

}    

Settings

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#settings

Expand for example code to list Settings using the WooCommerce API
private void settings() {

    /**List All**/
    Listed<Setting> listing = Settings.listing().getResponse();
    for (Setting s : listing.getResult()){
        System.out.println(s.toJson().replace("},{", "},\n{"));
    }
}

SettingOptions

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#setting-option-properties

Expand for example code to read/ update Settings using the WooCommerce API
private void settingOptions() {

    /** Read a specific option**/
    Read<SettingOption> read = SettingOptions
            .read("general", "woocommerce_allowed_countries")
            .getResponse();
    System.out.println(read.getResult().toJson());

    /**List All**/
    Listed<SettingOption> listingOption = SettingOptions
            .listing("general")
            .getResponse();
    for (SettingOption s : listingOption.getResult()){
        System.out.println(s.toJson().replace("},{", "},\n{"));
    }

    /**Update**/
    Update<SettingOption> updated = SettingOptions
        .update("general", "woocommerce_allowed_countries")
        .setValue("all_except")
        .getResponse();

    /*Batch*/
    Batched<SettingOption> batched = SettingOptions.batch("general")
        .addUpdater(
            WooCommerce.SettingOptions()
                .update("ignoredInBatch", "woocommerce_allowed_countries")
                .setValue("all_except")
        )
        .getResponse();

}

Payment Gateways

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#payment-gateways

Expand for example code to list and update Payment Gateways using the WooCommerce API
private void paymentGateways() {

    /*Read*/
    Read<PaymentGateway> gateway = PaymentGateways.read("woocommerce_payments").getResponse();
    System.out.println(gateway.getResult().toJson()); 

    /**List All**/
    Listed<PaymentGateway> gateways = PaymentGateways.listing().getResponse();
    for (PaymentGateway s : gateways.getResult()){
        System.out.println(s.toJson()); 
    }

    /*Update*/
    Updated<PaymentGateway> update = PaymentGateways.update("woocommerce_payments")
                .setEnable(true).getResponse();
}

Shipping Zones

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#shipping-zones

Expand for example code for Shipping Zones using the WooCommerce API
private void shippingZones() {

    Created<ShippingZone> created = ShippingZones.create("Brazil").getResponse();
    
    Read<ShippingZone> read = ShippingZones.read(5).getResponse();

    Listed<ShippingZone> zones = ShippingZones.listing().getResponse();

    for (ShippingZone zone : zones.getResult()) {
        System.out.println(zone.toJson());
    }

    Updated<ShippingZone> updated = ShippingZones.update(1).setOrder(2).getResponse();

    Deleted<ShippingZone> deleted = ShippingZones.delete(1, true).getResponse();

}    

Shipping Zone Locations

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#shipping-zone-locations

Expand for example code for Shipping Zone Locations using the WooCommerce API
private void shippingZoneLocations() {

    Listed<ShippingZoneLocation> listed = ShippingZoneLocations.listing(1).getResponse();

    UpdatedList<ShippingZoneLocation> shipZones = ShippingZoneLocations.update(1)
            .setZoneLocation("BR:SP", "state")
            .setZoneLocation("BR:RJ", "state").getResponse();

    for (ShippingZoneLocation zoned : shipZones.getResult()) {
        System.out.println(zoned.toString());
    }

}    

Shipping Zone Methods

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#shipping-zone-methods

Expand for example code for Shipping Zone Methods using the WooCommerce API
private void shippingZoneMethods() {

    Created<ShippingZoneMethod> create = ShippingZoneMethods.create(2, "flat_rate").getResponse();

    Read<ShippingZoneMethod> zoneMethod = ShippingZoneMethods.read(2, 4).getResponse();
    System.out.println(zoneMethod.getResult().toJson());

    Listed<ShippingZoneMethod> list = ShippingZoneMethods.listing(1).getResponse();
    for (ShippingZoneMethod zoneMethod : list.getResult()) {
        System.out.println(zoneMethod.toJson());
    }

    Updated<ShippingZoneMethod> zoneUpdated = ShippingZoneMethods
            .update(2, 4)
            .setEnabled(false)
            .setSetting("cost", "10")
            .getResponse();

    Deleted<ShippingZoneMethod> zoneMethodDeleted = ShippingZoneMethods.delete(2, 4).getResponse();

}    

System Status

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#system-status

Expand for example code for System Status using the WooCommerce API
private void systemStatus(){

    Read<SystemState> status = SystemStatus.read().getResponse();
    
}    

System Status Tools

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#system-status-tools

Expand for example code for System Status Tools using the WooCommerce API
private void systemStatusTools(){

    Listed<SystemStatusTool> systemStatusToolListed = SystemStatusTools.listing().getResponse();
    for (SystemStatusTool systemStatusTool : systemStatusToolListed.getResult()){
        System.out.println(systemStatusTool.toJson());
    }

    Read<SystemStatusTool> readTool = WooCommerce. SystemStatusTools.read("clear_transients").getResponse();

    Ran<SystemStatusTool> ranTool = SystemStatusTools.run("clear_transients").setConfirm(true).getResponse();
    
}

Data

Ref: https://woocommerce.github.io/woocommerce-rest-api-docs/#data

Expand for example code for Data using the WooCommerce API
private void data(){

    Listed<Continent> continents = WooCommerce.Data.listAllContinents().getResponse();
    for (Continent continent : continents.getResult()){
        System.out.println(continent.toJson());
    }

    Read<Continent> continent = WooCommerce.Data.readContinent("eu").getResponse();
    System.out.println(continent.getResult().toJson());

    Listed<Country> countries = WooCommerce.Data.listAllCountries().getResponse();
    for (Country country : countries.getResult()){
        System.out.println(country.toJson());
    }

    Read<Country> country = WooCommerce.Data.readCountry("gb").getResponse();
    System.out.println(country.getResult().toJson());

    Listed<Currency> currencies = WooCommerce.Data.listAllCurrencies().getResponse();
    for (Currency continent : currencies.getResult()){
        System.out.println(continent.toJson());
    }

    Read<Currency> currency = WooCommerce.Data.readCurrency("gbp").getResponse();
    System.out.println(currency.getResult().toJson());
}    

WooCommerce API Client for Java

License: MIT Java Version

A lightweight Java client library for WooCommerce REST API integration. Built for Java developers who need to integrate their applications with WooCommerce e-commerce platform.

This API client provides a type-safe Java interface for WooCommerce REST API v3, enabling seamless management of:

  • WooCommerce
  • Customer data and orders
  • E-commerce operations via REST API

✨ Why choose this client?

  • πŸ’‘ Type-Safe Java API - fully typed interfaces for WooCommerce REST endpoints
  • πŸ›‘οΈ Basic authentication - secure WooCommerce API access
  • πŸ“š Clear documentation - comprehensive examples for Java integration
  • πŸš€ Wide Java support - compatible with Java 8 and newer

πŸ“¦ Version information

  • Current version: See installation at the top
  • Supported WooCommerce API version: v3
  • Java compatibility: Java 8+

πŸ”“ License

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files, to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the software.

The only requirement is to preserve the original author attribution in the source code and documentation.

πŸ”— Get involved

  • ✨ Check our GitHub Issues for latest updates
  • πŸ’‘ Have suggestions? Open an Issue or contribute to the project
  • 🌟 Star this repository if you find it helpful!

πŸ“Š Project statistics

  • πŸ”„ Regular updates and improvements
  • πŸ‘₯ Open for community contributions

πŸ” Keywords

woocommerce java client, woocommerce rest api java, java woocommerce integration, woocommerce api v3 java, e-commerce java integration, woocommerce java library, java rest api client woocommerce, woocommerce api client library for java

About

The WooCommerce REST API Client for Java provides easy access to the features of the WooCommerce platform's API version 3 using Java

Resources

License

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages