DEV Community

Cover image for How to add payments to your Rails app with Paystack
dngst
dngst

Posted on • Edited on

How to add payments to your Rails app with Paystack

Setup

$ bundle add httparty
Enter fullscreen mode Exit fullscreen mode
# .env
PAYSTACK_SECRET_KEY="sk_test_xxx"
Enter fullscreen mode Exit fullscreen mode
# config/routes.rb
get "/checkout/callback", to: "checkouts#paystack_callback"
Enter fullscreen mode Exit fullscreen mode

Paystack service

# app/services/paystack_service.rb
class PaystackService
  include HTTParty
  base_uri "https://api.paystack.co"

  def initialize
    @headers = {
      "Authorization" => "Bearer #{ENV["PAYSTACK_SECRET_KEY"]}",
      "Content-Type" => "application/json",
      "Accept" => "application/json"
    }
  end
  # other methods
end
Enter fullscreen mode Exit fullscreen mode

Initialize the transaction

def initialize_transaction(email, amount, callback_url = nil)
  body = {
    email: email,
    amount: amount * 100,
    callback_url: callback_url
  }.compact

  self.class.post("/transaction/initialize", headers: @headers, body: body.to_json)
end
Enter fullscreen mode Exit fullscreen mode

Verify the transaction

def verify_transaction(transaction_reference)
  self.class.get("/transaction/verify/#{transaction_reference}", headers: @headers)
end
Enter fullscreen mode Exit fullscreen mode

When a transaction is initialized, the response contains a link to the Paystack payment page. A callback handles the verification of the transaction.

@paystack = PaystackService.new
Enter fullscreen mode Exit fullscreen mode
@paystack.initialize_transaction(email, amount, "#{request.base_url}/checkout/callback")
Enter fullscreen mode Exit fullscreen mode
def paystack_callback
  response = @paystack.verify_transaction(params[:reference])
  if response["status"]
    # do something
  end
end
Enter fullscreen mode Exit fullscreen mode

To test you can use ngrok.

Start it on port 3000 with your domain from https://dashboard.ngrok.com/domains

$ ngrok http --url=lorem-lorem-lorem.ngrok-free.dev 3000
Enter fullscreen mode Exit fullscreen mode

Whitelist the URL by adding it in development.rb

config.hosts << ENV["NGROK_HOST"]
Enter fullscreen mode Exit fullscreen mode
# .env
 NGROK_HOST="lorem-lorem-lorem.ngrok-free.dev"
Enter fullscreen mode Exit fullscreen mode

Start the app server and navigate to lorem-lorem-lorem.ngrok-free.dev

Docs

https://paystack.com/docs/api

Top comments (0)