Hey there, fellow Ruby developer! Ready to add some payment magic to your app? Let's dive into integrating Razorpay's API using Ruby. It's easier than you might think, and I'll walk you through it step by step.
Razorpay is a powerhouse when it comes to payment gateways in India. Their API is robust, well-documented, and a joy to work with. By the end of this guide, you'll be processing payments like a pro!
Before we jump in, make sure you've got:
razorpay
gem (we'll install it in a sec)First things first, let's add the Razorpay gem to your project. Pop this into your Gemfile:
gem 'razorpay'
Then run:
bundle install
Easy peasy!
Now, let's set up those Razorpay credentials. Create an initializer file (config/initializers/razorpay.rb
) and add:
Razorpay.setup('YOUR_KEY_ID', 'YOUR_KEY_SECRET')
Pro tip: Use environment variables for those keys in production!
Time to create your first order. Here's how:
order = Razorpay::Order.create(amount: 50000, currency: 'INR', receipt: 'ORDER_ID')
This creates an order for ₹500 (amount is in paise). You'll get back an order object with all the details you need.
After a successful payment, you'll want to capture it:
payment = Razorpay::Payment.fetch(payment_id) payment.capture({ amount: payment.amount })
Remember to wrap this in a begin-rescue block to handle any hiccups!
Security first! Always verify the payment signature:
Razorpay::Utility.verify_payment_signature({ 'razorpay_order_id' => order_id, 'razorpay_payment_id' => payment_id, 'razorpay_signature' => signature })
If it's invalid, it'll raise a Razorpay::Error
.
Webhooks are your friend for real-time updates. Set up an endpoint in your app:
post '/razorpay_webhook' do # Verify the webhook signature webhook_signature = request.env['HTTP_X_RAZORPAY_SIGNATURE'] webhook_body = request.body.read begin Razorpay::Utility.verify_webhook_signature(webhook_body, webhook_signature, webhook_secret) # Process the webhook event rescue Razorpay::Error => e # Handle invalid signature end end
Oops, need to refund? No sweat:
refund = Razorpay::Refund.create(payment_id: payment_id)
Razorpay provides a test mode - use it! And don't forget to write tests:
RSpec.describe RazorpayService do it 'creates an order' do # Your test here end end
Running into issues? Check these common culprits:
And there you have it! You're now equipped to handle payments like a boss. Remember, practice makes perfect, so don't be afraid to experiment in test mode.
Happy coding, and may your transactions always be successful! 🚀💰