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.
Before we jump in, make sure you've got:
First things first, let's get that gem installed:
gem install paypal-sdk-rest
Easy peasy, right?
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.
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
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
Curious about a payment? Look it up:
payment = PayPal::SDK::REST::Payment.find("PAYMENT_ID") puts payment.to_json
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" } })
For those steady streams of income:
billing_plan = PayPal::SDK::REST::Plan.new({ # Plan details here }) billing_plan.create
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
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
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
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!