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:
- what is coinbase?
- benefits of using the coinbase commerce client
- getting to know the coinbase commerce client gem.
- creating a coinbase account
- creating a Ruby on Rails project
- conclusion
- follow me on
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.
- Access the website for the Coinbase Commerce product and click on signup.
- After being redirected to the registration page, fill in all the details and complete your registration by clicking on “Create an account”.
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”.
- 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.
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
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'
...
bundle install
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
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
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 calledapi_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
- 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 ourapi_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>
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
- After creating and configuring the initializer, we will create a controllers called CheckoutsController
rails generate controller Checkouts
- We will add 5 methods to these controllers, which are
index
,create
,show
,update
anddestroy
. 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
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>
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
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
- Let’s actually create our first checkout now. In
CheckoutsController
we will create a private method calledpermitted_params
which will be useful for validating the allowed parameters in the checkout creation request. Additionally, in thecreate
method, we will instantiate a new client and invoke the checkoutcreate
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
- 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 routehttp://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"
}
If we now go to the Coinbase checkout page, we will see that our checkout was successfully created as illustrated below.
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.
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
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.
Follow me on:
BiteCraft | Patreon
Vinicius Borges | Github
Vinicius Borges | LinkedIn
Vinicius Borges | Instagram
Top comments (0)