Learn about the Square Ruby SDK features.
Use the require
statement to load the Square Ruby SDK and make it available to your application:
require 'square'
To use the Square SDK, instantiate a Square::Client
object and initialize it with the appropriate environment and corresponding access token, as shown:
For testing, Square provides a Sandbox environment as shown in the following code fragment:
client = Square::Client.new( bearer_auth_credentials: BearerAuthCredentials.new( access_token: ENV['SQUARE_ACCESS_TOKEN'] ), environment: 'sandbox' )To access production resources, set the environment to
production
as shown:client = Square::Client.new( bearer_auth_credentials: BearerAuthCredentials.new( access_token: ENV['SQUARE_ACCESS_TOKEN'] ), environment: 'production' )To set a custom environment, provide a
custom_url
and set the environment tocustom
, as shown:client = Square::Client.new( bearer_auth_credentials: BearerAuthCredentials.new( access_token: ENV['SQUARE_ACCESS_TOKEN'] ), environment: 'custom', custom_url: 'https://your.customdomain.com', )
For further customizations, see Optional: Configure the Faraday client library.
The following example shows how to call a Square API:
require 'square'
client = Square::Client.new(
bearer_auth_credentials: BearerAuthCredentials.new(
access_token: ENV['SQUARE_ACCESS_TOKEN']
),
environment: 'sandbox'
)
result = client.locations.list_locations
if result.success?
result.data.locations.each do |loc|
printf("%s: %s, %s, %s\n",
loc[:id],
loc[:name],
loc[:address][:address_line_1],
loc[:address][:locality])
end
elsif result.error?
result.errors.each do |error|
warn error[:category]
warn error[:code]
warn error[:detail]
end
end
The Square::Client
object instantiates every API class and exposes them as properties. You work with an API by calling methods on an instance of an API class. Most of these methods require you to provide a hash that contains the request body.
Some API classes accept nested data (for example, address
, customer
, and order
). For these, you can embed hashes containing the data within the body
hash.
The following creates a new customer, with a nested hash for address
:
require 'securerandom'
result = client.customers.create_customer(
body: {
given_name: 'John',
family_name: 'Doe',
address: {
address_line_1: '1455 Market St',
address_line_2: 'San Francisco, CA 94103'
},
idempotency_key: SecureRandom.uuid
}
)
if result.success?
customer = result.data.customer
puts "New customer created with customer ID #{customer[:id]}"
elsif result.error?
result.errors.each do |error|
warn error[:category]
warn error[:code]
warn error[:detail]
end
end
The Square API endpoints can have path parameters, query parameters, and a request body. When you make corresponding method calls using the Square Ruby SDK, you provide the values as follows:
Request body - In the Square Ruby SDK, a request body is represented by a hash. Depending on the method being called, the parameter values are represented as scalars or as embedded hashes.
require 'securerandom' result = client.customers.create_customer( body: { given_name: "Mary", family_name: "Smith", address: { address_line_1: "1455 Market St", address_line_2: "San Francisco, CA 94103" }, idempotency_key: SecureRandom.uuid } ) if result.success? puts result.data elsif result.error? result.errors.each do |error| warn error[:category] warn error[:code] warn error[:detail] end endPath and query parameters - For example:
- The RetrieveCustomer endpoint has a
customer_id
path parameter (GET /v2/customers/{customer_id}
). - The ListCustomers endpoint has several query parameters such as
cursor
andlimit
.
You provide these as parameters to the method calls. The following example passes the
customer_id
path parameter as a parameter to theupdate_customer
method.result = client.customers.update_customer( customer_id: "GZ48C4P2CWVXV7F7K2ZH795RSG", body: { given_name: "Fred", family_name: "Jones", address: { address_line_1: "1455 Market St", address_line_2: "San Francisco, CA 94103" }, version: 0 } ) if result.success? puts result.data elsif result.error? result.errors.each do |error| warn error[:category] warn error[:code] warn error[:detail] end endFor an example of query parameters, see Pagination.
- The RetrieveCustomer endpoint has a
You can configure the number of retries and the timeout values for HTTP requests when using the Square Ruby SDK:
Retries - By default, the Square SDK doesn't retry a failed request. When your application starts, the Square SDK sets the number of retries to 0. You have the option to configure a different value when you create a client. Retries can help improve application stability by allowing applications to handle momentary failures in connecting to a service by transparently retrying a failed request.
Timeout - Timeout is the time period that a client waits for a server response. The Square SDK sets the default timeout to 60 seconds. On timeout, the SDK throws an exception. You have the option to configure a timeout value at the client level.
The following code creates a client and sets the number of retries to 2 and the timeout to 60 seconds:
client = Square::Client.new(
bearer_auth_credentials: BearerAuthCredentials.new(
access_token: ENV['SQUARE_ACCESS_TOKEN']
),
environment: 'sandbox',
max_retries: 2,
timeout: 60
Configuring a client with long timeout values and a high number of retries can cause some SDK operations to appear unresponsive. There are several considerations that apply when configuring the timeout and retries. These include:
- For network issues (decrease in network connectivity and response speed), how should the application respond? Do you want the call to fail fast, or do you want the application to retry the failed call?
- Buyer-facing applications might need to be responsive compared to a background job that can tolerate increased latency due increased timeout values and retries.
The response object contains information about both the request and the response. You can use the response object's success
and error
methods to determine whether the API call succeeded or failed:
If an API call succeeds, the response object contains the data returned from that call.
If an API call fails, the response object contains any errors that were encountered during processing.
result = client.locations.list_locations
if result.success?
puts 'Successfully called List Locations'
# Your business logic here
elsif result.error?
warn 'Failed to make the request'
result.errors.each do |error|
warn error[:category]
warn error[:code]
warn error[:detail]
# Your error-handling code here
end
end
For more information, see Square API errors.
The Square Ruby SDK client uses Faraday, a client library that handles HTTP requests and replies. Faraday is preconfigured for immediate use and is transparent to your application. In most circumstances, no Faraday changes are needed.
When you create a Square::Client
instance, the Square Ruby SDK creates a Faraday connection automatically:
require 'square'
client = Square::Client.new(
bearer_auth_credentials: BearerAuthCredentials.new(
access_token: ENV['SQUARE_ACCESS_TOKEN']
),
environment: 'sandbox'
)
Because the client uses a default configuration for Faraday, there's nothing you need to do. However, Faraday is highly customizable and the Square Ruby SDK fully supports this.
If you want to define your own Faraday configuration, you can set the optional connection
attribute for Square::Client
. To do this, use Faraday.new
to create a connection object and then assign it to a new Square::Client
instance, as shown in the following code snippet:
require 'square'
my_custom_connection = Faraday.new do |faraday|
faraday.use Faraday::HttpCache, serializer: nil
faraday.use FaradayMiddleware::FollowRedirects
faraday.use :gzip
faraday.request :multipart
faraday.request :url_encoded
faraday.ssl[:ca_file] = Certifi.where
faraday.ssl[:verify] = true
faraday.request :retry, max: 0, interval: 1,
backoff_factor: 2,
retry_statuses: [408, 413, 429, 500, 502, 503, 504, 521, 522, 524],
methods: %i[get put]
faraday.adapter Faraday.default_adapter
faraday.options[:params_encoder] = Faraday::FlatParamsEncoder
faraday.options[:timeout] = 60
end
client = Square::Client.new(
bearer_auth_credentials: BearerAuthCredentials.new(
access_token: ENV['SQUARE_ACCESS_TOKEN']
),
environment: 'sandbox',
connection: my_custom_connection
)
The configuration shown in this code snippet is similar to the SDK's default settings. You can use this as a starting point for your own customizations. For more information, see Faraday.
Faraday provides a common interface for network adapters and middleware. The Square Ruby SDK uses Net::HTTP as its default adapter, but you can use a different one if you want.
For example, suppose you already use Typhoeus instead of Net::HTTP in your project, to support multiple HTTP requests running in parallel. To switch your adapter, the first step is to install Typhoeus.
gem install typhoeus
In your code, you need to load Typhoeus itself, along with the Typhoeus adapter for Faraday.
require 'square'
require 'typhoeus'
require 'typhoeus/adapters/faraday'
You can now create a connection object, define Typhoeus as the faraday.adapter
, and assign that connection to a new Square::Client instance.
my_typhoeus_connection = Faraday.new do |faraday|
faraday.use Faraday::HttpCache, serializer: nil
faraday.use FaradayMiddleware::FollowRedirects
faraday.use :gzip
faraday.request :multipart
faraday.request :url_encoded
faraday.ssl[:ca_file] = Certifi.where
faraday.ssl[:verify] = true
faraday.request :retry, max: 0, interval: 1,
backoff_factor: 2,
retry_statuses: [408, 413, 429, 500, 502, 503, 504, 521, 522, 524],
methods: %i[get put]
faraday.adapter :typhoeus
faraday.options[:params_encoder] = Faraday::FlatParamsEncoder
faraday.options[:timeout] = 60
end
client = Square::Client.new(
bearer_auth_credentials: BearerAuthCredentials.new(
access_token: ENV['SQUARE_ACCESS_TOKEN']
),
environment: 'sandbox',
connection: my_typhoeus_connection
)