DEV Community

Cover image for Coinbase Commerce Client: Easily Integrate Cryptocurrency Payments in Ruby on Rails
Vinicius Borges
Vinicius Borges

Posted on

Coinbase Commerce Client: Easily Integrate Cryptocurrency Payments in Ruby on Rails

Coinbase Commerce Client Gem

The Coinbase Commerce Client is a gem that facilitates the integration of payments in Bitcoin, Ethereum, and other cryptocurrencies into Ruby on Rails applications using the Coinbase Commerce system . Coinbase supports various cryptocurrencies, such as Bitcoin, Ethereum, and Litecoin among others, and is easy to integrate into Ruby on Rails applications. It also offers support for webhooks and custom events, in addition to extensive documentation and tutorials.


Session Index:


But after all, what is Coinbase?

Coinbase: much more than a brokerage, a gateway to the future of finance. Founded in 2012, Coinbase has established itself as the most reliable entry point to the cryptocurrency universe, allowing millions of people around the world to explore this new and exciting market.

Investing in Cryptocurrencies with Security and Simplicity:

  • Easy Buy and Sell: Bitcoin, Ethereum, Litecoin, and over 150 cryptocurrencies with credit card, debit card, and bank transfer.

  • Secure Custody: Offline storage and advanced security measures for your digital assets.

  • Learn and Earn: Tutorials, articles, and videos for you to delve into the world of cryptocurrencies and earn rewards.

  • Coinbase Pro: Advanced platform for experienced traders with detailed charts, stop-loss orders, and margin trading.

  • Coinbase Wallet: Independent digital wallet for iOS and Android

Coinbase Commerce: Accept Cryptocurrencies in Your Business!

Create a Coinbase Commerce account and accept cryptocurrency payments in your online business. A fast, secure, and economical way to expand your payment options and reach new customers.


Benefits of using the Coinbase Commerce Client.

  • Save time and money on development costs: The gem offers an easy and quick way to integrate cryptocurrency payments into your Rails application, reducing development time and cost.

  • Increase the security of your payments: Coinbase Commerce uses high-level security measures to protect your payments against fraud and theft.

  • Enhance the user experience for your customers: Cryptocurrency payments are fast, secure, and convenient for your customers.


Getting to Know the Coinbase Commerce Client Gem.

The Coinbase Commerce Client gem is a tool developed to facilitate the integration of cryptocurrency payments, such as Bitcoin and Ethereum, into Ruby on Rails applications. Inspired by the official Coinbase gem, which was discontinued, this new gem aims to fill that gap and continue to offer support and functionalities for developers who rely on this integration.

Supporting Ruby versions 2.3 to 3.3.0, the gem provides a simple and effective way to handle cryptocurrency payments, allowing developers to create checkouts, manage charges and events, as well as securely validate webhook signatures.

With comprehensive documentation and clear usage examples, the Coinbase Commerce Client gem stands out for its ease of implementation and the ability to efficiently handle common API errors.

Furthermore, the community is encouraged to contribute to its continuous improvement, making it a versatile and reliable tool for integrating cryptocurrency payments into Ruby on Rails applications.


Creating a Coinbase Account and Generating Your API Token.

I apologize in advance, but since I’m from Brazil, some of the images below have their texts in Portuguese, but I made sure to add arrows and circles to illustrate what each part refers to.

Coinbase Commerce Client

  • After being redirected to the registration page, fill in all the details and complete your registration by clicking on “Create an account”.

Coinbase Commerce Client

Once you complete the registration and all the account activation steps, you will be redirected to the main dashboard where you should click on your avatar icon and then click on “settings”.

Coinbase Commerce Client

  • After entering the settings menu, navigate to the “Security” tab and you will see a screen that shows the API keys if any were created previously, and in the upper right corner, you will see a button to add a new key called “New API Key”, click on it and a new API key will be generated, save it, we will use it later.

Coinbase Commerce Client

With this, we have the Coinbase Commerce properly configured, now let’s see a little about our gem.


Creating a Ruby on Rails Project.

Now let’s create a Rails API project to then install, configure, and learn how to use the Coinbase Commerce Client gem.

For this project, we will cover the basic concepts of integration, where we will see how to create, list, edit, and delete checkouts, but there is much more, such as configuration, listing, and use of events as well as webhook configuration, all these details are documented on the gem’s GitHub page.

  • Create a Ruby on Rails API project with the name you want, but for educational purposes, I will create it as “coinbase_connect” with the code below
rails new coinbase_connect --api
Enter fullscreen mode Exit fullscreen mode

Installing the Coinbase Commerce Client gem

  • After creating our project, we need to add our gem to the Gemfile, as shown below, and run the bundle install command to install our dependency.
#Gemfile
...
gem 'coinbase_commerce_client', '~> 0.4.2'
...
Enter fullscreen mode Exit fullscreen mode
bundle install
Enter fullscreen mode Exit fullscreen mode

Configuring the API Key in Rails Credentials

  • Now, we need to take the API Key, which we configured in the section about creating a coinbase account and securely store it. By default, I will add it in the Rails credentials, as it turns all sensitive data into secure data thanks to its encryption. Type the code below, and a configuration file in YAML format will be displayed where we will put our api key inside the coinbase key.
EDITOR="nano" rails credentials:edit
Enter fullscreen mode Exit fullscreen mode

After typing the command above, we will see a structure similar to the one illustrated below.

# aws:
#   access_key_id: 123
#   secret_access_key: 345

# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: 09e529504e581b655ac2e8b82592da34168bdef2cf51963b4309c4348997d0d4f3b2962e4be1df8g484c8cacf8168debf867107e4s526d7cfbcbe53339813e58
Enter fullscreen mode Exit fullscreen mode

A secret_key_base is a secret key used to encrypt sensitive data, such as cookies and session tokens, in Ruby on Rails applications. This key is essential to ensure the security and integrity of the data transmitted and stored by the application.

  • That said, below it, we will create a field called coinbase and within this field’s block, we will add a key called api_key containing the coinbase key as its value.
# aws:
#   access_key_id: 123
#   secret_access_key: 345

# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: 09e529504e581b655ac2e8b82592da34168bdef2cf51963b4309c4348997d0d4f3b2962e4be1df8g484c8cacf8168debf867107e4s526d7cfbcbe53339813e58
coinbase:
  api_key: 512347814-512scg4-2147-6667-uy8b622dd722
Enter fullscreen mode Exit fullscreen mode
  • To validate if everything is working as it should, let’s go to our terminal, open the rails console through the command rais c and print our api_key . If your result was similar to mine, then it is perfectly configured.
# ❯ rails c
irb(main):001> Rails.application.credentials.coinbase[:api_key]
=> "512347814-512scg4-2147-6667-uy8b622dd722"
irb(main):002>
Enter fullscreen mode Exit fullscreen mode

Configuring the Rails Project

  • Now let’s create an initializer called coinbase_commerce_client.rb which will be responsible for loading our API Key, which we configured in the Rails credentials, into the gem’s settings.
#config/initializers/coinbase_commerce_client.rb
CoinbaseCommerceClient.configure do |config|
    config.api_key = Rails.application.credentials.coinbase[:api_key]
end
Enter fullscreen mode Exit fullscreen mode
  • After creating and configuring the initializer, we will create a controllers called CheckoutsController
rails generate controller Checkouts
Enter fullscreen mode Exit fullscreen mode
  • We will add 5 methods to these controllers, which are index, create, show, update and destroy. Below is how your controllers should look.
#app/controllers/checkouts_controller.rb
class CheckoutsController < ApplicationController
  def index
  end

  def show
  end

  def create
  end

  def update
  end

  def destroy
  end
end
Enter fullscreen mode Exit fullscreen mode

Using the Checkout

First, let’s focus on the checkout, but before anything else, I think it’s important to inform about the possibilities using this gem.

We can:

  • list all checkouts
  • create a new checkout
  • search for a checkout through its ID
  • update some information of a checkout
  • paginate several checkouts
  • delete a checkout

Through a simple API, you just need to instantiate a new client and use its methods to do absolutely everything you want, as shown in the example below.

client = CoinbaseCommerceClient::Client.new

#charges
client.charge.list
client.charge.auto_paging
client.charge.create <payload>
charge = client.charge.retrieve <id>
charge.resolve
charge.cancel

#checkout
client.checkout.list
client.checkout.auto_paging
client.checkout.create <payload>
checkout = client.checkout.retrieve <id>
checkout.refresh
checkout.save
checkout.modify <payload>
checkout.delete

#events
client.event.list
client.event.auto_paging
event = client.event.retrieve <id>
Enter fullscreen mode Exit fullscreen mode

Creating a Checkout

  • First of all, let’s define the routes for our Checkout, just go to the file config/routes.rb delete anything that is there, and leave it as below.
Rails.application.routes.draw do
  resources :checkouts
end
Enter fullscreen mode Exit fullscreen mode

this will create the standard routes of the RESTful architecture pointing to our previously created methods, to validate if the routes were created successfully, just type the command below in your terminal to list the created routes

❯ rails routes |grep checkouts

checkouts GET     /checkouts(.:format)             checkouts#index
POST              /checkouts(.:format)             checkouts#create
checkout GET      /checkouts/:id(.:format)         checkouts#show
PATCH             /checkouts/:id(.:format)         checkouts#update
PUT               /checkouts/:id(.:format)         checkouts#update
DELETE            /checkouts/:id(.:format)         checkouts#destroy
Enter fullscreen mode Exit fullscreen mode
  • Let’s actually create our first checkout now. In CheckoutsController we will create a private method called permitted_params which will be useful for validating the allowed parameters in the checkout creation request. Additionally, in the create method, we will instantiate a new client and invoke the checkout create method from within the client, passing an expected payload for checkout creation.

I will not go into details about what each field of the payload is, considering that the gem’s documentation already points to the official Coinbase documentation, where you can calmly analyze what each field of the payload is and how to use it.

#app/controllers/checkouts_controller.rb
class CheckoutsController < ApplicationController
  ...
    def create
        client = CoinbaseCommerceClient::Client.new
        checkout = client.checkout.create(permitted_params)
        render json: checkout
    rescue => e
        render json: { error: e.message }, status: :unprocessable_entity
    end
  ...
    private

    def permitted_params
        params.require(:checkout).permit(
            :name,
            :description,
            :pricing_type,
            local_price: [:amount, :currency],
            requested_info: []
        )
    end
end
Enter fullscreen mode Exit fullscreen mode
  • Let’s run the project with the command rails s . Now, with your favorite API Client software, in my case, I will use Insomnia, we will create a post request to the route http://localhost:3000/checkouts with the json body shown below, you should have a response similar to mine.
#POST http://localhost:3000/checkout
{
 "checkout": {
  "name": "The Sovereign Individual",
    "description": "Mastering the Transition to the Information Age",
    "pricing_type": "fixed_price",
    "local_price": {
        "amount": "1.00",
        "currency": "USD"
    },
    "requested_info": ["name", "email"]
 }
}

# output/response
{
   "id": "cf3abc0e-e718-4932-a5f4-46657786584",
   "brand_color": "#122332",
   "brand_logo_url": "",
   "coinbase_managed_merchant": false,
   "description": "Mastering the Transition to the Information Age",
   "local_price": {
      "amount": "1.00",
      "currency": "USD"
   },
   "name": "The Sovereign Individual",
   "organization_name": "",
   "pricing_type": "fixed_price",
   "requested_info": [
      "name",
      "email"
   ],
   "resource": "checkout"
}
Enter fullscreen mode Exit fullscreen mode

If we now go to the Coinbase checkout page, we will see that our checkout was successfully created as illustrated below.

Coinbase Commerce Client

Clicking on the generated checkout, we can see that it has a direct sharing link to make the checkout payment, as well as an area where a code is displayed that can be easily added to a frontend application where it is redirected to the checkout.

Coinbase Commerce Client

Displaying, Editing, Updating, and Deleting a Checkout

From now on, there’s not much secret, we will just create a private helper method called set_checkout which will be useful in all other requests, as it will return a valid checkout from an id, below contains the complete CheckoutsController class.

class CheckoutsController < ApplicationController
    before_action :set_checkout, only: [:show, :update, :destroy]

    def index
        client = CoinbaseCommerceClient::Client.new
        checkouts = client.checkout.list
        render json: checkouts
    end

    def create
        client = CoinbaseCommerceClient::Client.new
        checkout = client.checkout.create(permitted_params)
        render json: checkout
    end

    def update
        @checkout.modify(params[:id], permitted_params)
        render json: checkout
    end

    def show
        render json: @checkout
    end

    def destroy
        @checkout.delete
        head :no_content
    end

    private

    def permitted_params
        params.require(:checkout).permit(
            :name,
            :description,
            :pricing_type,
            local_price: [:amount, :currency],
            requested_info: []
        )
    end

    def set_checkout
        client = CoinbaseCommerceClient::Client.new
        @checkout = client.checkout.retrieve(params[:id])
    rescue => e
        render json: { error: e.message }, status: :not_found
    end
end
Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, integrating cryptocurrency payments into your Ruby on Rails application using the Coinbase Commerce Client can significantly enhance your business’s payment options, offering security, efficiency, and a broader reach to customers interested in digital currencies. I hope this guide empowers you to explore the exciting possibilities within the world of cryptocurrencies.

Coinbase Commerce Client


Follow me on:

BiteCraft | Patreon
Vinicius Borges | Github
Vinicius Borges | LinkedIn
Vinicius Borges | Instagram

Top comments (0)