How to Get Coinbase API to Authenticate and Buy Bitcoin

Hiya!

I’ve got a problem which I’ve detailed in this stackoverflow post here: https://stackoverflow.com/questions/72071522/how-to-get-coinbase-api-to-authenticate-buy-bitcoin

The main issue right now is that I can’t seem to access the ‘time endpoint’ here: docs.cloud.coinbase.com/exchange/reference/time because that page doesn’t work!

My code is compalining that the timestamp is incorrect.

Any ideas??

Hi @xccelerated99, thank you for taking an interest in trying out Coinbase APIs. For the details regarding your inquiry, we will check on this for you with our team to see how we can best assist. We will get back to you once we have more information. Keep in touch!

Hi @xccelerated99, first of all, we’d like to thank you for taking an interest in trying out the Coinbase APIs.

Now, before getting started with addressing your concerns, we’d like to clear some things out. Sign in with Coinbase and Coinbase Exchange/Pro are different services. They have different API counterparts. This means their API endpoints are different as well.

If you’d like to know more about their differences, you may choose to visit our documentation at https://docs.cloud.coinbase.com/

Now that that is out of the way, we noticed that you have a mixture of codes that are trying to do two separate things at once.

(1) From the majority of the code, we can see that you are trying to push a POST request on the /orders endpoint. This endpoint belongs to the Coinbase Exchange/Pro API. And so, if this is what you are trying to do, you would need to update the URL to the appropriate one. Since you are trying to call the Coinbase Exchange/Pro endpoint, you would need to change it to https://api.exchange.coinbase.com/

(2) However, from the URL, it would imply that you are trying to push a GET request to the SIWC endpoint /accounts. If this is the case, the rest of the code has to change especially if you are trying to push a GET request to the said endpoint.

Finally, regarding timestamps, we noticed that you don’t have the Math.floor() function on the timestamp part of your code. You may check the sample code in our documentation here.

Additionally, you may query the time endpoint of SIWC (here) and compare the timestamp you are getting from your code.

Should you need further clarifications or queries about Coinbase Cloud APIs, feel free to reply to this thread.

5 Likes

Hey! Thank you so much for this articulate and solution-oriented answer.

Regards,
AJ :sunglasses: :money_mouth_face:

2 Likes

Ok, I’ve gotten the time from the time endpoint successfully but now I’m getting an error which says “{ id: ‘invalid_token’, message: ‘The access token is invalid’ }”. This is after I perform a GET call to the ‘https://coinbase.com/api/v2/accounts’ API. What would you advise?

Hello @xccelerated99, we are so glad you are moving forward from your initial standpoint. We noticed that your stackoverflow post is already removed, and so, we would appreciate it if you can provide us the most recent code you have. You may post in this thread. Upon doing so, we will quickly work on figuring out how we can help you.

1 Like

It’s been a while! How ya doin???

This is my code:

internal class CoinbaseProService
{
    private CoinbaseProClient _coinbaseProClient { get; set; }

    public CoinbaseProService()
    {
        _coinbaseProClient = new CoinbaseProClient(new Config
        {
            ApiKey = "XXXXXXXXXXXXXXXXXXXXXX",
            Secret = "XXXXXXXXXXXXXXXXXXXXXX",
            Passphrase = "XXXXXXXXXXXXXXX",
            //Override the ApiUrl property to use Sandbox.
            ApiUrl = "https://api-public.sandbox.pro.coinbase.com"
        });
    }

    public async Task BuyBitcoin()
    {
        var order = await _coinbaseProClient.Orders.PlaceLimitOrderAsync(OrderSide.Buy, "BTC-USD", size: 2, limitPrice: 45000m);

        var x = 1;
    }
}

I’m getting a 401 Unauthorized Error although I believe I’m using the proper API credentials. I could be wrong, but I think I’m doing it the right way.

What do you think? Any suggestions??

Take care!

-Alex

Hi @xccelerated99! Welcome back to the forum. Upon investigating your code snippet, the error you are receiving seems to stem from generating a proper signature. We suggest that you check these links for reference:

If you are still receiving a 401 unauthorized error, please send your code snippet when generating a signature and be careful not to send any sensitive information. Thanks!

1 Like

Awesome!! Will do :saluting_face:

adoifusadfoiajdsofjaldskfjalsdkfjalsdjf;alsdkjf;lasdkjf;la

2 Likes

Alright… I’ve put in some work on this today but I’m still running into that pesky 401 error. It says “signature invalid” in the ‘respString’ variable. I’ve tried adapting the “CB-ACCESS-SIGN” header into a form that is acceptable, as is more or less recommended here: Proper REST signatures; however, it is not working.

Here’s my code:

public async Task BuyBitcoin()
{
    HttpResponseMessage resp = await _client.GetAsync("https://api.coinbase.com/v2/time");

    string timestamp = await resp.Content.ReadAsStringAsync();

    TimeRespJson json = JsonConvert.DeserializeObject<TimeRespJson>(timestamp);

    using (var request = new HttpRequestMessage(HttpMethod.Post, "https://api.exchange.coinbase.com/orders"))
    {
        object json2 = new { name = "John Doe", age = 33 };
        string jsonStringified = JsonConvert.SerializeObject(json2);

        var signature = json.data.epoch.ToString() + "POST" + "/orders" + jsonStringified;

        request.Headers.Add("CB-ACCESS-KEY", "XXXXXXXXXXXXXXXX");
        request.Headers.Add("CB-ACCESS-TIMESTAMP", json.data.epoch.ToString());
        request.Headers.Add("CB-ACCESS-SIGN", signature);
        request.Headers.Add("CB-ACCESS-PASSPHRASE", "XXXXXXXXXXXXXXX");
        request.Headers.Add("User-Agent", "request");

        _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //ACCEPT header


        request.Content = new StringContent(jsonStringified, Encoding.UTF8, "application/json"); //CONTENT-TYPE header

        HttpResponseMessage orderResponse = await _client.SendAsync(request);

        string respString = await orderResponse.Content.ReadAsStringAsync();

    }

Keep in mind that “_client” is an HttpClient object instance.

Hi @xccelerated99! We appreciate all the information that you provided. For your concern to be properly addressed, we may require other personal information to help us further in our investigation which may not be appropriate to post here publicly in the forum for safety reasons. With that, we suggest you to open a support ticket using the email address associated with your Coinbase account. Upon creating the ticket, kindly include the link of this forum so that the team will be aware that it’s you. Looking forward to hearing from you soon. Thank you for your patience and understanding. Have a nice day!

I have no idea how I might do this in C#:

// create the prehash string by concatenating required parts
var message = cb_access_timestamp + method + requestPath + body;

// decode the base64 secret
var key = Buffer.from(secret, ‘base64’);

// create a sha256 hmac with the secret
var hmac = crypto.createHmac(‘sha256’, key);

// sign the require message with the hmac and base64 encode the result
var cb_access_sign = hmac.update(message).digest(‘base64’);

Hi @xccelerated99! We would like to reiterate that for account safety purposes and thorough investigation, it would be best to log a support ticket using the email address associated with your Coinbase account. Additional reminder, kindly include the link of this forum so that the team will be aware that it’s you.

Thank you so much for your patience and understanding.

2 Likes

Alright. Thank you…

asdjflasjdf;lkajsd;flkajsd;flaksdf;alksjdf;lkajsd;flkjasd;lfkajsd;lfkasjd;k

1 Like