Setup
$ bundle add httparty
# .env
PAYSTACK_SECRET_KEY="sk_test_xxx"
# config/routes.rb
get "/checkout/callback", to: "checkouts#paystack_callback"
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
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
Verify the transaction
def verify_transaction(transaction_reference)
self.class.get("/transaction/verify/#{transaction_reference}", headers: @headers)
end
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
@paystack.initialize_transaction(email, amount, "#{request.base_url}/checkout/callback")
def paystack_callback
response = @paystack.verify_transaction(params[:reference])
if response["status"]
# do something
end
end
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
Whitelist the URL by adding it in development.rb
config.hosts << ENV["NGROK_HOST"]
# .env
NGROK_HOST="lorem-lorem-lorem.ngrok-free.dev"
Start the app server and navigate to lorem-lorem-lorem.ngrok-free.dev
Top comments (0)