Giter VIP home page Giter VIP logo

wc-api-java's Introduction

WooCommerce API Java Wrapper

Build Status

Java wrapper for WooCommerce REST API. The library supports the latest versions of WooCommerce REST API only with the OAuth 1.0a authentication over the HTTP protocol.

Setup

wc-api-java is available on maven central:

    <dependency>
        <groupId>com.icoderman</groupId>
        <artifactId>wc-api-java</artifactId>
        <version>1.4</version>
    </dependency>

Usage

    public static void main(String[] args) {
        // Setup client
        OAuthConfig config = new OAuthConfig("http://woocommerce.com", "consumerKey", "consumerSecret");
        WooCommerce wooCommerce = new WooCommerceAPI(config, ApiVersionType.V3);

        // Prepare object for request
        Map<String, Object> productInfo = new HashMap<>();
        productInfo.put("name", "Premium Quality");
        productInfo.put("type", "simple");
        productInfo.put("regular_price", "21.99");
        productInfo.put("description", "Pellentesque habitant morbi tristique senectus et netus");

        // Make request and retrieve result
        Map product = wooCommerce.create(EndpointBaseType.PRODUCTS.getValue(), productInfo);

        System.out.println(product.get("id"));

        // Get all with request parameters
        Map<String, String> params = new HashMap<>();
        params.put("per_page","100");
        params.put("offset","0");
        List products = wooCommerce.getAll(EndpointBaseType.PRODUCTS.getValue(), params);

        System.out.println(products.size());
    }

wc-api-java's People

Contributors

cofis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wc-api-java's Issues

I've got the JsonParseException

Hello I think that the code has some issue I don't know why it doesn't work I followed the step in the instruction but it returned a JsonParseException ( I've tried the key with NodeJS library and it works normally )


Exception in thread "main" java.lang.RuntimeException: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: (org.apache.http.conn.EofSensorInputStream); line: 1, column: 2]
	at com.icoderman.woocommerce.DefaultHttpClient.getEntityAndReleaseConnection(DefaultHttpClient.java:129)
	at com.icoderman.woocommerce.DefaultHttpClient.getAll(DefaultHttpClient.java:49)
	at com.icoderman.woocommerce.WooCommerceAPI.getAll(WooCommerceAPI.java:44)
	at com.mycompany.woocommerce_laoitdev.Main.main(Main.java:44)
Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
 at [Source: (org.apache.http.conn.EofSensorInputStream); line: 1, column: 2]
	at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1804)
	at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:663)
	at com.fasterxml.jackson.core.base.ParserMinimalBase._reportUnexpectedChar(ParserMinimalBase.java:561)
	at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2624)
	at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:826)
	at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:723)
	at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4129)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3988)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3058)
	at com.icoderman.woocommerce.DefaultHttpClient.getEntityAndReleaseConnection(DefaultHttpClient.java:123)
	... 3 more
------------------------------------------------------------------------
BUILD FAILURE
------------------------------------------------------------------------
Total time: 2.627s
Finished at: Fri Mar 30 10:35:42 ICT 2018
Final Memory: 8M/309M
------------------------------------------------------------------------
Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec (default-cli) on project woocommerce_laoitdev: Command execution failed. Process exited with an error: 1 (Exit value: 1) -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

Invalid signature - provided signature does not match

Hello

Testing the library locally, i went to woo settings and created the api keys manually and run the very simple test

final String siteUrl  = "http://wp496.wp.me/";
final String username = "ck_87a7fd079cafc0a23032612c6b739ca34cdc4fc4";
final String password = "cs_402939f008f55fae91b88cbd256d6e8c21a52858";

OAuthConfig config = new OAuthConfig(siteUrl, username, password);

WooCommerce wooCommerce = new WooCommerceAPI(config, ApiVersionType.V2);

i get this error:

{code=woocommerce_rest_authentication_error, message=Invalid signature - provided signature does not match., data={status=401}}

Any clue why such error?

  • woocommerce version 3.5.4
  • wordpress version: 5.0.3

Thanks

401 invalid signature when GET parameters contain unicode characters or SPACE

If the parameters contain unicode characters (like Vietnamese chars) or space then it will result 401 invalid signature. For example: http://duylv.anhphuongisc.vn/wp-json/wc/v2/products/categories?search=sản phẩm

or even: http://duylv.anhphuongisc.vn/wp-json/wc/v2/products/categories?search=san pham

I tried the same URL in Postman with OAuth 1.0 and it works.

I have a question and an improvement.

the search for more than 100 products and more news, for an api brings only 100 in 100 data.
this way it becomes more viable.

class WoocommercApi:

`
@OverRide
@SuppressWarnings("all")
public List getAll(String endpointBase) {
Integer OAUTH_PAGE = 1;
String privado = "private" , publico="publish",
concluido="completed",pendente="pending", cancelado="cancelled",aguardando ="on-hold"

		List listaFinal = new ArrayList<>();
		if(endpointBase.equals("products")){
	                listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, publico);
	                listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, privado);
		}else if(endpointBase.equals("orders")){
			listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, concluido);
			listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, cancelado);
			listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, pendente);
			listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, aguardando);
		}
		
        return  listaFinal;  // RETORN LIST
        
    }

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List allProduct(List listaFinal,String endpointBase, Integer OAUTH_PAGE,String status ) {
		
		List urlAll = client.getAll(metGetAll(endpointBase, OAUTH_PAGE, status)) ;
	        listaFinal.addAll(urlAll);
	    	 while(urlAll !=null) {
        		OAUTH_PAGE ++;
        		try{
        			urlAll = client.getAll(metGetAll(endpointBase, OAUTH_PAGE,status));
        			listaFinal.addAll(urlAll);
        			
        			if(urlAll!=null && urlAll.size() == 0){
        				urlAll = null;
        				break;
        			}
        		}catch(Exception e){
        			break;
        		}
        	}
	     	 
	     	 return  listaFinal;
	}
	public String metGetAll(String endpointBase, Integer OAUTH_PER_PAGE, String status) { 
		String url = String.format(API_URL_FORMAT, config.getUrl(), endpointBase);
        String signature = OauthSignature.getAsQueryStringAll(config, url, HttpMethod.GET, OAUTH_PER_PAGE, status);
        String securedUrl = String.format(URL_SECURED_FORMAT, url, signature);
        return securedUrl;
	}
	`

AND
CLASS OauthSignature:

 `public static Map<String, String> getAsMapAll(OauthConfig config, String endpoint, HttpMethod httpMethod, Integer paginas, String status) {
        if (config == null || endpoint == null || httpMethod == null) {
            return Collections.emptyMap();
        }
        String porPaginas ="100";     //page
        Map<String,String> params = new HashMap<>();
        params.put(OauthHeader.OAUTH_CONSUMER_KEY.getValue(), config.getConsumerKey());
        params.put(OauthHeader.OAUTH_CONSUMER_SECRET.getValue(), config.getConsumerSecret());
        params.put(OauthHeader.OAUTH_TIMESTAMP.getValue(), String.valueOf(System.currentTimeMillis() / 1000L));
        params.put(OauthHeader.OAUTH_NONCE.getValue(), UUID.randomUUID().toString());
        params.put(OauthHeader.OAUTH_SIGNATURE_METHOD.getValue(), SIGNATURE_METHOD_HMAC_SHA256);
        params.put(OauthHeader.OAUTH_PER_PAGE.getValue(), porPaginas);
        params.put(OauthHeader.OAUTH_PAGE.getValue(), paginas.toString());
        params.put(OauthHeader.OAUTH_STATUS.getValue(), status); // paramenter
        

        // WooCommerce specified param
        if (HttpMethod.DELETE.equals(httpMethod)) {
            params.put(DELETE_PARAM_FORCE, Boolean.TRUE.toString());
        }
        String oAuthSignature = generateOAuthSignature(config.getConsumerSecret(), endpoint, httpMethod, params);
        params.put(OauthHeader.OAUTH_SIGNATURE.getValue(), oAuthSignature);
        return params;
    }
    
    public static String getAsQueryStringAll(OauthConfig config, String endpoint, HttpMethod httpMethod, Integer pags, String status) {
        if (config == null || endpoint == null || httpMethod == null) {
            return "";
        }
        Map<String, String> oauthParameters = getAsMapAll(config, endpoint, httpMethod, pags, status);
        String encodedSignature = oauthParameters.get(OauthHeader.OAUTH_SIGNATURE.getValue())
                .replace(SpecialSymbol.PLUS.getPlain(), SpecialSymbol.PLUS.getEncoded());
        oauthParameters.put(OauthHeader.OAUTH_SIGNATURE.getValue(), encodedSignature);
        return mapToString(oauthParameters, SpecialSymbol.EQUAL.getPlain(), SpecialSymbol.AMP.getPlain());
    }`

Here I look for order and PRODUCTS

I accept improvements on the lists to be searched

Use with Android app?

Hey,
I've been trying to use this with my Android app but I get this compile time error: Return code 1 for dex process. Is this library not compatible with Android? Thanks for the help!

Not able to get orders between dates

Hi,

I wanted to get woo-commerce orders between 2 dates. I tried before and after params but it is throwing the below error. please help me .
Code :
WooCommerce wooCommerce = new WooCommerceAPI(config, ApiVersionType.V3);

		// Get all with request parameters
		Map<String, String> params = new HashMap<>();

// params.put("per_page", "1");
params.put("after", "2021-03-01T00:00:00");
params.put("before", "2021-02-16T23:59:59");

		List<Map<String, Object>> orders = wooCommerce.getAll(EndpointBaseType.ORDERS.getValue(), params);

Error
java.lang.RuntimeException: Can't parse retrieved object: {code=woocommerce_rest_authentication_error, message=Invalid signature - provided signature does not match., data={status=401}}

Creating Orders

i'm struggling at creating a new order, i pass every single data that the documentation tell us to, but it can't create. Every time i try to send the JSON, the fields i put info they're just empty, and i don't know what can i do to make it work.

thats my code:
``public static void main(String[] args) throws JSONException {
// Setup client

OAuthConfig config = new OAuthConfig("https://theoriginal-linkishere.com.br",
        "chave ck",
        "chave cs");    //  on original code this infos are correctly set

WooCommerce wooCommerce;
wooCommerce = new WooCommerceAPI(config, ApiVersionType.V3);



//Dizendo os campos e dando os valores

Map <String, Object> orderInfo = new HashMap<>();
orderInfo.put("payment_method", "bacs");
orderInfo.put("payment_method_title", "Direct Bank Transfer");
orderInfo.put("first_name", "Joe");
orderInfo.put("last_name", "Doe");
orderInfo.put("address_1", "969 Market");
orderInfo.put("address_2", "");
orderInfo.put("city", "San Francisco");
orderInfo.put("state", "CA");
orderInfo.put("postcode", "94103");
orderInfo.put("country", "US");
orderInfo.put("email", "[email protected]");
orderInfo.put("phone", "(555) 555-5555");
orderInfo.put("first_name", "Joe");
orderInfo.put("last_name", "Doe");
orderInfo.put("address_1", "969 Market");
orderInfo.put( "address_2", "");
orderInfo.put("city", "San Francisco");
orderInfo.put("state", "CA");
orderInfo.put("postcode", "94103");
orderInfo.put("country", "US");

//mapeando os pedidos
Map order = wooCommerce.create(EndpointBaseType.ORDERS.getValue(),orderInfo);


System.out.println(order.get("id"));


Map <String,String> params = new HashMap<>();
params.put("per_page", "100");
params.put("offset", "0");
List products = wooCommerce.getAll(EndpointBaseType.ORDERS.getValue(), params);

System.out.println(products.size());

}``

and it's returning this:

{ "id": 3104, "parent_id": 0, "status": "pending", "currency": "BRL", "version": "5.9.0", "prices_include_tax": false, "date_created": "2021-12-27T14:12:53", "date_modified": "2021-12-27T14:12:53", "discount_total": "0.00", "discount_tax": "0.00", "shipping_total": "0.00", "shipping_tax": "0.00", "cart_tax": "0.00", "total": "0.00", "total_tax": "0.00", "customer_id": 0, "order_key": "wc_order_ufiuvHMWQacPl", "billing": { "first_name": "", "last_name": "", "company": "", "address_1": "", "address_2": "", "city": "", "state": "", "postcode": "", "country": "", "email": "", "phone": "" }, "shipping": { "first_name": "", "last_name": "", "company": "", "address_1": "", "address_2": "", "city": "", "state": "", "postcode": "", "country": "", "phone": "" }, "payment_method": "bacs", "payment_method_title": "Direct Bank Transfer", "transaction_id": "", "customer_ip_address": "", "customer_user_agent": "", "created_via": "rest-api", "customer_note": "", "date_completed": null, "date_paid": null, "cart_hash": "", "number": "3104", "meta_data": [], "line_items": [], "tax_lines": [], "shipping_lines": [], "fee_lines": [], "coupon_lines": [], "refunds": [], "date_created_gmt": "2021-12-27T14:12:53", "date_modified_gmt": "2021-12-27T14:12:53", "date_completed_gmt": null, "date_paid_gmt": null, "currency_symbol": "R$", "_links": { "self": [ { "href": "https://catalogo.rfldesigner.com.br/wp-json/wc/v3/orders/3104" } ], "collection": [ { "href": "https://catalogo.rfldesigner.com.br/wp-json/wc/v3/orders" } ] } }

That's the issue. If you know any exemple of what could i do to make it work using Java, please let me know.

Suppor for product variations

Hi, icoderman,
I have another issue with dealing with product variations.
In the case of an update, you have to call the api with two params:

/products/:product_id/variations/:variation_id

The current update() method requires one id parameter, and uses this to assign the last String.format placeholder.
You think there is a way to handle this without modifying current WooCommerce interface?

Regards

wc-api/v3 not working via wc-api-java

woocommerce version: 3.3.3
wordpress version 4.9.4
wc-api-java version 1.2
I tried to work with wc-api/v1 and wc-api/v2 via postman and they are not works. Only wc-api/v3 works fine with my site. But when I tried to use java library wc-api-java 1.2 (https://github.com/icoderman/wc-api-java):

OAuthConfig config = new OAuthConfig(
        "http://URL",
        "ck_XXX",
        "cs_XXX"
);
WooCommerce wooCommerce = new WooCommerceAPI(config, ApiVersionType.V2);

// Prepare object for request
Map<String, Object> productInfo = new HashMap<String, Object>();
productInfo.put("name", "Premium Quality");
productInfo.put("type", "simple");
productInfo.put("regular_price", "21.99");
productInfo.put("description", "This field contains description info.");

//Make request and retrieve result
Map product = wooCommerce.create(EndpointBaseType.PRODUCTS.getValue(), productInfo);

System.out.println(product.get("id"));

// Get all with request parameters
Map<String, String> params = new HashMap<String, String>();
params.put("per_page","100");
params.put("offset","0");
List products = wooCommerce.getAll(EndpointBaseType.PRODUCTS.getValue(), params);

System.out.println(products.size());

Got an exception:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/client/methods/HttpRequestBase
    at com.icoderman.woocommerce.WooCommerceAPI.<init>(WooCommerceAPI.java:21)
    at Main.main(Main.java:21)
Caused by: java.lang.ClassNotFoundException: org.apache.http.client.methods.HttpRequestBase
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Where is no way to use wc-api/v3?

update method is not working in product case

Map<String, Object> productInfo = new HashMap<>();
        productInfo.put("id", t1.getId());
        productInfo.put("name", p1.getName());
        productInfo.put("regular_price", String.valueOf(price1));
        //image
        productInfo.put("sku",p1.getBarcode());
        productInfo.put("description", p1.getDescription());
        Map product=   wooCommerce.update(EndpointBaseType.PRODUCTS.getValue(),t1.getId(), productInfo);
        System.out.println(product.get("id"));

it is not working while everything in debugger is showing fine. if I sue the above same code for creating product just by changing the value from update to create and removing id from map.

the error which is being recived on post man is following

Request processing failed; nested exception is java.lang.RuntimeException:
		org.apache.http.NoHttpResponseException: appropriative-holde.000webhostapp.com:443 failed to respond</p>
	<p><b>Description</b> The server encountered an unexpected condition that prevented it from fulfilling the request.
<p><b>Root Cause</b></p>
	<pre>java.lang.RuntimeException: org.apache.http.NoHttpResponseException: appropriative-holde.000webhostapp.com:443 failed to respond
	com.icoderman.woocommerce.DefaultHttpClient.getEntityAndReleaseConnection(DefaultHttpClient.java:129)
	com.icoderman.woocommerce.DefaultHttpClient.postEntity(DefaultHttpClient.java:100)
	com.icoderman.woocommerce.DefaultHttpClient.put(DefaultHttpClient.java:76)
	com.icoderman.woocommerce.WooCommerceAPI.update(WooCommerceAPI.java:51)
	com.bmis.app.controller.WoocommerceController.updateWooProduct(WoocommerceController.java:179)
	com.bmis.app.controller.WoocommerceController.checkEitherToCreateOrUpdateProduct(WoocommerceController.java:150)
	com.bmis.app.controller.WoocommerceController.run(WoocommerceController.java:187)
	com.bmis.app.controller.WoocommerceController.getAllSettings(WoocommerceController.java:70)

woocommerce get products gets only first 100.

Dear Coder,

Firstly, I would like to thank you for providing such useful library. I have been developing a microservice-based application and using your library multiple times.

When I use the code below:

    Map<String, String> params = new HashMap<>();
    params.put("per_page", "100");
    params.put("offset", "0");
    List<Map<String, Object>> productsMap = wooCommerce.getAll(EndpointBaseType.PRODUCTS.getValue(), params);

Can you please help me to get all the products as Map<String, Object> because I will need to collect all the data from stores.

Thank you very much in advance.

Best regards,

Yilmaz.

get product > 100

	Object resultado = wooCommerce.getAll(EndpointBaseType.PRODUCTS.getValue(), integracao.getUrl());

     	@Override
	@SuppressWarnings("all")
    public List getAll(String endpointBase, String urlHost) {
		Integer OAUTH_PAGE = 1;
		String privado  = "private" ,  publico="publish", concluido ="completed",pendente="pending", cancelado="cancelled",aguardando ="on-hold" ;
		
		List listaFinal = new ArrayList<>();
		if(endpointBase.equals("products")){
	                listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, publico,urlHost);
	                listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, privado,urlHost);
		}else if(endpointBase.equals("orders")){
			listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, concluido, urlHost);
			listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, cancelado);
			listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, pendente);
			listaFinal = allProduct(listaFinal, endpointBase, OAUTH_PAGE, aguardando);
		}else{
			client.getAll(metGetAll(endpointBase, OAUTH_PAGE,publico),urlHost);
		}
		
        return  listaFinal;
        
    }

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List allProduct(List listaFinal,String endpointBase, Integer OAUTH_PAGE,String status , String urlHost) {
		List urlAll = client.getAll(metGetAll(endpointBase, OAUTH_PAGE, status),urlHost) ;
	        listaFinal.addAll(urlAll);
	    	 while(urlAll !=null) {
        		OAUTH_PAGE ++;
        		try{
        			urlAll = client.getAll(metGetAll(endpointBase, OAUTH_PAGE,status),urlHost);

        			if(urlAll!=null && urlAll.size() == 0){
						urlAll = null;
						break;

        			}
					listaFinal.addAll(urlAll);
        		}catch(Exception e){
        			try{
						urlAll = client.getAll(metGetAll(endpointBase, OAUTH_PAGE,status),urlHost);

						if(urlAll!=null && urlAll.size() == 0){
							urlAll = null;
							break;

						}
						listaFinal.addAll(urlAll);
					}catch(Exception e2){
        				e2.printStackTrace();
					}
        		}
        	}

	     	 return  listaFinal;
	}
	public String metGetAll(String endpointBase, Integer OAUTH_PER_PAGE, String status ) { 
		String url = String.format(API_URL_FORMAT, config.getUrl(), endpointBase);
                String signature = OauthSignature.getAsQueryStringAll(config, url, HttpMethod.GET, OAUTH_PER_PAGE, status);
                String securedUrl = String.format(URL_SECURED_FORMAT, url, signature);
        return securedUrl;
	}

I accept improvement suggestion, because I work with 6000 products and I need to update them daily.

Send image

Im new with java sorry, but how i send images to wp?

Map<String, Object> productInfo = new HashMap();
productInfo.put("name", "Premium Quality");
productInfo.put("type", "simple");
productInfo.put("regular_price", "21.99");
productInfo.put("description", "Pellentesque habitant morbi tristique senectus et netus");
productInfo.put("images", "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");

NOT OBJECT
{code=rest_invalid_param, message= status 400

Thanks

http request failed using Oauth 1.0

I'm having difficulty getting into my products, because the url error http 401, oh consumer_key is correct and the secret is also the only way I can get the data and passing the "cafearabesco.com/wp-json/wc/v2/products?consume_key=ajsajs77kajsak....&consume_secret=njnjnjnjn2n3j23nj2.." but this way it is not safe and on the server in production of the ssl error.

http://uploaddeimagens.com.br/imagens/postman_12-png

http://uploaddeimagens.com.br/imagens/postman-jpg

'java.lang.RuntimeException: Can't parse retrieved object: {code=woocommerce_rest_authentication_error, message =Invalid signature - provided signature does not match., data={status=401}}'

I haven't touched oAuth1.0a before, I used the correct secret key and secret in the apiGetAllProductsTest method in the test unit, and the request returns: 'java.lang.RuntimeException: Can't parse retrieved object: {code=woocommerce_rest_authentication_error, message =Invalid signature - provided signature does not match., data={status=401}}'
I don't know what it is, please give me some advice.

Is this save for production due to http?

I would like to access a WordPress website in from an Azure Spring app. Due to the http protocol and the older oauth1 standard, is this something to use for a company? Or is the http wrapped in https from azure anyway? I am confused. I would like to have a save connection between the WooCommerce website and my Java application.

Update of order line_items

Hi icoderman,
can you please give me an example of how I can update line_items of an order?

params.put("line_items", p); Map response = wooCommerce.update(EndpointBaseType.ORDERS.getValue(), orderId, params);

I only get the message:
{code=rest_invalid_param, message=Ungültige(r) Parameter: line_items, data={status=400, params={line_items=line_items[0] ist nicht vom Typ object.}}}

It works with Postman, when I use raw (Json) and this structure:
{"line_items": [{...}]}

Support for product variations

Hi,
I downloaded this lib in order to work with a WooCommerce site. In this case, we are using variations functionality, so I added a little bit of extra logic. This is what I've done:

EndpointBaseType.java

Added this line:
PRODUCTS_VARIATIONS("products/:product_id/variations"),

WooCommerceAPI.java

Added this function at the end of the class:

private String processEndpointBase(String epb, Map<String, Object> object) {
String retval = epb;
if (retval.equals("products/:product_id/variations")) {
if (object.get("product_id")!=null) {
retval = retval.replace(":product_id", object.get("product_id").toString());
}
}
return(retval);
}

Modified this functions:

@OverRide
public Map create(String endpointBase, Map<String, Object> object) {
String url = String.format(API_URL_FORMAT, config.getUrl(), apiVersion, processEndpointBase(endpointBase, object));
return client.post(url, OAuthSignature.getAsMap(config, url, HttpMethod.POST), object);
}

@Override
public Map update(String endpointBase, int id, Map<String, Object> object) {
    String url = String.format(API_URL_ONE_ENTITY_FORMAT, config.getUrl(), apiVersion, processEndpointBase(endpointBase, object), id);
    return client.put(url, OAuthSignature.getAsMap(config, url, HttpMethod.PUT), object);
}

I tell you about this because it might be a starting point to add this functionality, and if it is necesary I can add some code.

This is my first time contributing to an existing project so I don't really know how.

Regards,

Apply coupon compatibly v3

Hi @icoderman,

first of all, thanks for your job. Really appreciate it!
As from the title i'm trying to apply coupon in an order but seems compatible only with version V3.
In fact if I apply coupon, the order will filled with coupon information but the price still remains the same.
I've read about work-around, trying to change the total price of the order and pushing it, but also this is unreachable for me.
Any suggestion?

Emiliano

Cannot pass object as perm to map.

while creating a product we make a map. which works fine for simple attributes, but is not working for object type attributes.

dimensions.setLength("1");
        dimensions.setWidth("1");
        dimensions.setHeight("1");
        Gson gson = new Gson();
        String json = gson.toJson(dimensions);

        productInfo.put("dimensions",json);

on printing, it shows JSON has the object of dimensions
{"length":"1","width":"1","height":"1"}

help me fast plz

unable to update product using update method

I am trying to update product prices but i got "HttpResponseProxy{HTTP/1.1 400 Bad Request [Date: Sat, 06 Jun 2020 21:40:45 GMT" HttpResponse and got result from mapper.readValue is "{errors=[{code=woocommerce_api_missing_product_data, message=No product data specified to edit product}]}", below are the values which i trying to update-

          Map<String, Object> params = new HashMap<>();
       params.put("price", "151.00");
       params.put("regular_price", "200.51");
      
        Map products = wooCommerce.update(EndpointBaseType.PRODUCTS.getValue(), 41064 , params);

Receiving an HTTP 406 Not Acceptable

I just started using this library an am having a problem. I have a valid WooCommerce account and created REST API credentials, but when I try to run the sample code I experienced the same error that was reported in Issue #7.

However, I dove a little bit deeper and saw what was actually being returned from the API. I get this:

HttpResponseProxy{HTTP/1.1 406 Not Acceptable [Server: nginx, Date: Tue, 12 Sep 2023 19:02:09 GMT, Content-Type: text/html, Content-Length: 156, Connection: keep-alive, X-Cache: miss, X-Rq: yyz3 ] ResponseEntityProxy{[Content-Type: text/html,Content-Length: 156,Chunked: false]}}

Not sure how this could be happeneing. I did verify that the supporting libraries seemed okay and I'm pretty sure I entered my credentials correctly.

Any ideas on what could be happening or how to get more info? Is it possible that the API changed?

Passing categories and attributes

Hi,
I'm having trouble with product creation. I can't figure out how to pass the categories and the attributes, it keeps showing "rest_invalid_param" error code with message "categories[0] not of type object".
I first thought it should be an object array, but it didn't work. I also tried with a map, but there is no way to make it work.
Could you please give me an example of how should I do it?

Update Store Purchase in Online Woocommerce Store.

Hi sir,

Here is my scenarios. I have store application developed in .NET framewok, I would like to have a webservice to update woocommerce store when a store sales sysnchronise with woocommerce store. Can you please help me , how to use update method to implement aobe scenario.

thanks in advance

Logfactory bug

im using gradle on Android studio

And it Always get a notfound error for logfactory

401 invalid signature when doing a GET with "after" or "before" as parameter

The error occurs when trying to retrieve all orders from the api, passing "after" or "before" as parameter. The following code reproduces the error:

        Map<String, String> param = new HashMap<>();
        param.put("after", "2019-08-08T00:00:00");

        OAuthConfig config = new OAuthConfig(url, consumerKey, consumerSecret);
        WooCommerce api = new WooCommerceAPI(config, ApiVersionType.V2);

        List orders = api.getAll(EndpointBaseType.ORDERS.getValue(), param);

The stack trace:

java.lang.RuntimeException: Can't parse retrieved object: {code=woocommerce_rest_authentication_error, message=Assinatura inválida - a assinatura fornecida não corresponde., data={status=401}}

	at com.icoderman.woocommerce.DefaultHttpClient.getEntityAndReleaseConnection(DefaultHttpClient.java:127)
	at com.icoderman.woocommerce.DefaultHttpClient.getAll(DefaultHttpClient.java:49)
	at com.icoderman.woocommerce.WooCommerceAPI.getAll(WooCommerceAPI.java:44)
	at br.com.xxxxxxxxxx.SeoxApplicationTests.apiCall(SeoxApplicationTests.java:57)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
	at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
	at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
	at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
	at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

New Release

Hello Oleksandr,
Thanks for all your work on this.
I was wondering if you would be doing a release (to maven central) to include the changes you have made.
Also, will you be able to add V3("v3") to the ApiVersionType enum?

Many thanks,
Daniel

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.