Integrate Square API in a Ruby Application
- First, ensure you have the Square API SDK for Ruby installed in your project. If not, you can add it to your Gemfile:
gem 'square'
- Run
bundle install
to ensure the gem is installed in your application.
Configure Your API Client
- Start by requiring the
square
gem and creating a client object using your Square access token:
require 'square'
# Specify the environment and obtain an access token from your Square Dashboard
client = Square::Client.new(
access_token: 'YOUR_ACCESS_TOKEN',
environment: 'sandbox' # or 'production'
)
- For security purposes, ensure that your keys are stored safely, using Rails credentials or environment variables, avoiding hardcoding directly.
Create an Order
- To process payments, you'll need to create an order. Start by defining the line items you'd like to charge:
order_body = {
order: {
location_id: 'YOUR_LOCATION_ID',
line_items: [
{
name: 'T-Shirt',
quantity: '1',
base_price_money: {
amount: 2000, # This amount is in cents, i.e., 20.00 USD
currency: 'USD'
}
}
]
}
}
# Create Order
api_response = client.orders.create_order(body: order_body)
order_id = api_response.data.order.id if api_response.success?
- Handle the response to ensure the order is created successfully, error checking is crucial for troubleshooting.
Process a Payment
- Once the order is ready, proceed to process the payment. You need a valid nonce, which you can obtain using Square's payment form or mobile SDKs:
payment_body = {
source_id: 'CARD_NONCE', # This should be replaced with the actual card nonce
idempotency_key: SecureRandom.uuid, # Ensure each key is unique
amount_money: {
amount: 2000,
currency: 'USD'
},
order_id: order_id
}
# Process Payment
payment_response = client.payments.create_payment(body: payment_body)
- Ensure proper handling for both successful payments and errors:
if payment_response.success?
puts "Payment processed, ID: #{payment_response.data.payment.id}"
else
puts "Payment failed: #{payment_response.errors}"
end
Manage Payment Results
- Store transaction details in your database for future reference and customer support inquiries.
- Ensure you're compliant with financial data regulations, securely encrypting and storing sensitive information.
Testing and Error Handling
- Test your integration thoroughly in the 'sandbox' environment before going live.
- Handle potential exceptions and build a robust error-handling mechanism to manage declined payments and API errors.
Additional Features
- Consider implementing features like storing customer's card details for quick transactions in the future, handling refunds, and integrating with your existing inventory management system to reflect purchase updates.