Java- Buy Unauthorized

I am trying to place a buy order for my java application with coinbase advanced, and I have only gotten 401 errors. My code works for other endpoints, but it does not seem to ever return anything other than 401 for orders. I hope its something stupid that I did, and someone could tell me how to fix it.

Here is my code:

import java.net.;
import java.io.
;
import java.security.;
import javax.crypto.
;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;

public class CoinbaseAPI {
private static final String API_KEY = “”;
private static final String API_SECRET = “”;

public static void main(String[] args) throws Exception {
    String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
    String method = "POST";
    String path = "/api/v3/brokerage/orders";
    String body = "{ \"client_order_id\": \"BUY.0.23i653i356\", \"product_id\": \"BTC-USD\", \"side\": \"BUY\", \"order_configuration\": { \"market_market_ioc\": { \"quote_size\": \"10.00\" } } }";

    String message = timestamp + method + path + body;
    String signature = getSignature(message, API_SECRET);

    URL url = new URL("https://api.coinbase.com" + path);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod(method);
    con.setRequestProperty("CB-ACCESS-KEY", API_KEY);
    con.setRequestProperty("CB-ACCESS-SIGN", signature);
    con.setRequestProperty("CB-ACCESS-TIMESTAMP", timestamp);
    con.setRequestProperty("Content-Type", "application/json");
    con.setDoOutput(true);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer content = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        content.append(inputLine);
    }
    in.close();
    con.disconnect();

    System.out.println(content.toString());
}

private static String getSignature(String message, String secret) throws Exception {
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
    sha256_HMAC.init(secret_key);
    return Hex.encodeHexString(sha256_HMAC.doFinal(message.getBytes()));
}

}

Check API key settings!? Maybe you have not enabled needed permissions and/or accounts…

I double checked the permissions, and they all seem to be in order.

Oh, you are not POST-ing your body, are you? Your example code only uses body to generate signature…

1 Like

That worked. Thank you so much.