Overview

In this article, we will explore how to dynamically create a checkout session using the Coinbase Commerce API in a JavaScript application. We will utilize Axios for making HTTP requests and troubleshoot common issues related to authentication headers.

Prerequisites

Before we begin, ensure you have the following:

  • A valid API key from Coinbase Commerce.
  • Axios installed in your project. You can add it via npm:
    npm install axios

Making a Checkout Request

To create a checkout, you need to send a POST request to the Coinbase Commerce API endpoint. Below is an example of how to do this using Axios:

Example Request Using Curl

Here’s how a successful request looks using Curl:

curl https://api.commerce.coinbase.com/checkouts \
     -X POST \
     -H 'Content-Type: application/json' \
     -H 'X-CC-Api-Key: <Your API Key>' \
     -H 'X-CC-Version: 2018-03-22' \
     -d '{
         "name": "The Sovereign Individual",
         "description": "Mastering the Transition to the Information Age",
         "local_price": {
             "amount": "100.00",
             "currency": "USD"
         },
         "pricing_type": "fixed_price",
         "requested_info": ["email"]
     }'

Axios Implementation

Here’s how to implement the same request in JavaScript using Axios:

let amount = 10;
try {
    const options = {
        headers: {
            'Content-Type': 'application/json',
            'X-CC-Api-Key': '<Your API Key>',
            'X-CC-Version': '2018-03-22'
        }
    };

    const data = {
        name: `US$${amount} Credit Refill`,
        description: 'Credit refill',
        local_price: {
            amount: amount,
            currency: 'USD'
        },
        pricing_type: 'fixed_price'
    };

    const response = await axios.post('https://api.commerce.coinbase.com/checkouts', data, options);
    console.log(response.data);
} catch (error) {
    console.error('Error:', error.response ? error.response.data : error.message);
}

Common Issues

If you encounter a 401 Unauthorized error, it typically indicates an issue with the authentication headers. Here are some troubleshooting steps:

  • Check API Key: Ensure that you are using the correct API key and that it has the necessary permissions.
  • Header Case Sensitivity: Ensure that the header names are correctly cased. For example, use X-CC-Api-Key instead of x-api-key.
  • Network Issues: Verify that your network allows outbound requests to the Coinbase Commerce API.

By following these guidelines, you should be able to successfully create a checkout session using the Coinbase Commerce API with Axios.