|

|  How to Process Payments Using PayPal API in Ruby

How to Process Payments Using PayPal API in Ruby

October 31, 2024

Discover how to seamlessly process payments in Ruby using the PayPal API. This guide simplifies integration steps, ensuring secure and efficient transactions.

How to Process Payments Using PayPal API in Ruby

 

Configure PayPal SDK for Ruby

 

  • To start processing payments with PayPal using Ruby, you need to install the PayPal SDK. Add the `paypal-sdk-rest` gem to your `Gemfile` and run `bundle install`:
gem 'paypal-sdk-rest'

 

Initialize the PayPal SDK

 

  • Require the PayPal SDK and initialize it with your client ID and secret:
require 'paypal-sdk-rest'

PayPal::SDK::REST.set_config(
  :mode => "sandbox", # Set this to "live" for production
  :client_id => "YOUR_CLIENT_ID",
  :client_secret => "YOUR_CLIENT_SECRET"
)

 

Create a Payment Object

 

  • Create a payment object with details about the transaction, payer, and redirection URLs. This is crucial to set up the structure of the payment before approval:
payment = PayPal::SDK::REST::Payment.new({
  intent:  "sale",
  payer:  {
    payment_method:  "paypal" 
  },
  redirect_urls: {
    return_url: "http://yourwebsite.com/execute",
    cancel_url: "http://yourwebsite.com/cancel" 
  },
  transactions:  [{
    item_list: {
      items: [{
        name: "Item Name",
        sku: "item",
        price: "15.00",
        currency: "USD",
        quantity: 1 
      }]
    },
    amount: {
      total:  "15.00",
      currency:  "USD" 
    },
    description:  "This is the payment description." 
  }]
})

 

Execute a Payment

 

  • Redirect users to PayPal to approve the payment, and provide routing to handle the approval. This is where users approve the payment on the PayPal site:
if payment.create
  redirect_url = payment.links.find{|v| v.rel == "approval_url" }.href
  # Redirect the user to redirect_url for payment approval
else
  # Handle errors
  puts payment.error.inspect
end

 

Handle Payment Execution

 

  • After the payment is approved, PayPal redirects back to your application with payment details, ready for execution. Capture these details and execute the payment:
payment_id = params[:paymentId]
payer_id = params[:PayerID]

payment = PayPal::SDK::REST::Payment.find(payment_id)

if payment.execute(payer_id: payer_id)
  # Payment successfully executed
  puts "Payment complete"
else
  # Handle execution failure
  puts payment.error.inspect
end

 

Handle Errors and Notifications

 

  • During both creation and execution phases, PayPal may return errors. Use the SDK’s error handling capabilities to gracefully manage potential issues and confirm transactions:
# Sample error handling
if payment.error
  error = payment.error
  puts "Error: #{error['message']}"
end

 

Testing and Deployment

 

  • Complete thorough testing in the 'sandbox' mode to emulate real-world scenarios without processing real payments. Ensure all pathways, including errors and success, are tested.
  • Switch to 'live' mode when you're ready to go to production. Replace the sandbox client ID and secret with your live credentials.

 

Security Considerations

 

  • Securely store your client ID and secret, and avoid hardcoding them into your source files. Use environment variables or secure vaults.
  • Ensure your website or server adheres to security best practices, such as using HTTPS and validating all input sources.