Back

Step by Step Guide to Building a PayPal API Integration in Ruby

Aug 2, 20245 minute read

Introduction

Hey there, fellow Ruby developer! Ready to add some payment magic to your app? Let's dive into integrating PayPal's API using the paypal-sdk-rest package. It's easier than you might think, and I'll walk you through it step by step.

Prerequisites

Before we jump in, make sure you've got:

  • A Ruby environment set up (I know you've got this!)
  • A PayPal developer account with API credentials (if you don't have one, it's quick to set up)

Installation

First things first, let's get that gem installed:

gem install paypal-sdk-rest

Easy peasy, right?

Configuration

Now, let's tell the SDK who you are:

require 'paypal-sdk-rest' PayPal::SDK.configure do |config| config.mode = "sandbox" # "live" for production config.client_id = "YOUR_CLIENT_ID" config.client_secret = "YOUR_CLIENT_SECRET" end

Pro tip: Keep those credentials safe! Use environment variables in production.

Basic API Operations

Creating a Payment

Let's make it rain:

payment = PayPal::SDK::REST::Payment.new({ intent: "sale", payer: { payment_method: "paypal" }, transactions: [{ amount: { total: "10.00", currency: "USD" } }], redirect_urls: { return_url: "http://localhost:3000/payment/execute", cancel_url: "http://localhost:3000/payment/cancel" } }) if payment.create puts "Payment created, ID: #{payment.id}" else puts payment.error end

Executing a Payment

After the user approves, seal the deal:

payment = PayPal::SDK::REST::Payment.find("PAYMENT_ID") if payment.execute(payer_id: "PAYER_ID") puts "Payment executed successfully" else puts payment.error end

Retrieving Payment Details

Curious about a payment? Look it up:

payment = PayPal::SDK::REST::Payment.find("PAYMENT_ID") puts payment.to_json

Advanced Features

Handling Refunds

Oops, need to give money back? No sweat:

sale = PayPal::SDK::REST::Sale.find("SALE_ID") refund = sale.refund({ amount: { total: "10.00", currency: "USD" } })

Recurring Payments / Subscriptions

For those steady streams of income:

billing_plan = PayPal::SDK::REST::Plan.new({ # Plan details here }) billing_plan.create

Handling Webhooks

Stay in the loop with webhooks:

webhook = PayPal::SDK::REST::Webhook.new({ url: "https://example.com/paypal/webhook", event_types: [ { name: "PAYMENT.SALE.COMPLETED" }, { name: "PAYMENT.SALE.REFUNDED" } ] }) webhook.create

Error Handling and Logging

Always be prepared:

begin # Your PayPal operation here rescue PayPal::SDK::Core::Exceptions::ConnectionError => e Rails.logger.error "PayPal API connection error: #{e.message}" rescue PayPal::SDK::Core::Exceptions::ServerError => e Rails.logger.error "PayPal server error: #{e.message}" end

Testing

Use PayPal's sandbox for testing. It's like a playground, but for payments!

For unit tests, mock the API responses. Here's a quick example using RSpec:

RSpec.describe PaymentService do it "creates a payment" do allow(PayPal::SDK::REST::Payment).to receive(:new).and_return(double(create: true, id: "FAKE_ID")) # Your test here end end

Best Practices

  • Always use HTTPS
  • Never store raw API credentials in your code
  • Validate all input before sending it to PayPal
  • Use PayPal's IPNs (Instant Payment Notifications) for real-time updates

Conclusion

And there you have it! You're now equipped to handle payments like a pro. Remember, the PayPal API docs are your friend for more advanced use cases. Happy coding, and may your conversions be high and your chargebacks low!