McTaba Labs logo
Software EngineeringThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book Call

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
McTaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Our Work

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2027 McTaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Paystack for African Developers
  3. Accept Payments with Paystack in Spring Boot
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

Accept Payments with Paystack in Spring Boot

To accept Paystack payments in Spring Boot, create a PaystackService that uses RestTemplate to call the Paystack API. Build a controller with endpoints for initialization and verification. Store your secret key in application.properties and inject it with @Value.

In this article

  1. 1. Setup
  2. 2. PaystackService
  3. 3. Payment Controller
  4. 4. Production Checklist
  5. 5. Ship Payments Faster

Setup

Add your key to application.properties:

paystack.secret-key=sk_test_xxxxxxxxxxxxxxxxxxxxx

PaystackService

// src/main/java/com/example/payment/PaystackService.java
@Service
public class PaystackService {
    @Value("${paystack.secret-key}")
    private String secretKey;

    private final RestTemplate restTemplate = new RestTemplate();

    public Map<String, Object> initializeTransaction(String email, int amountKobo, String reference, String callbackUrl) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + secretKey);
        headers.setContentType(MediaType.APPLICATION_JSON);

        Map<String, Object> body = Map.of(
            "email", email,
            "amount", amountKobo,
            "reference", reference,
            "callback_url", callbackUrl
        );

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers);
        ResponseEntity<Map> response = restTemplate.postForEntity(
            "https://api.paystack.co/transaction/initialize", request, Map.class);

        return response.getBody();
    }

    public Map<String, Object> verifyTransaction(String reference) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + secretKey);

        HttpEntity<?> request = new HttpEntity<>(headers);
        ResponseEntity<Map> response = restTemplate.exchange(
            "https://api.paystack.co/transaction/verify/" + reference,
            HttpMethod.GET, request, Map.class);

        return response.getBody();
    }
}

Get weekly developer tips

Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.

No spam. Unsubscribe anytime.

Payment Controller

@RestController
@RequestMapping("/api/payment")
public class PaymentController {
    @Autowired
    private PaystackService paystackService;

    @PostMapping("/initialize")
    public ResponseEntity<?> initialize(@RequestBody Map<String, Object> payload) {
        String email = (String) payload.get("email");
        double amount = ((Number) payload.get("amount")).doubleValue();
        String reference = "order_" + UUID.randomUUID().toString().substring(0, 12);

        Map<String, Object> result = paystackService.initializeTransaction(
            email, (int)(amount * 100), reference, "http://localhost:8080/api/payment/callback");

        if (Boolean.TRUE.equals(result.get("status"))) {
            Map<String, Object> data = (Map<String, Object>) result.get("data");
            return ResponseEntity.ok(Map.of(
                "authorization_url", data.get("authorization_url"),
                "reference", data.get("reference")
            ));
        }
        return ResponseEntity.badRequest().body(Map.of("error", result.get("message")));
    }

    @GetMapping("/callback")
    public ResponseEntity<?> callback(@RequestParam String reference) {
        Map<String, Object> result = paystackService.verifyTransaction(reference);

        if (Boolean.TRUE.equals(result.get("status"))) {
            Map<String, Object> data = (Map<String, Object>) result.get("data");
            if ("success".equals(data.get("status"))) {
                // TODO: Verify amount, mark order as paid
                return ResponseEntity.ok(Map.of("success", true));
            }
        }
        return ResponseEntity.badRequest().body(Map.of("success", false));
    }
}

Production Checklist

  1. Use profiles. Spring profiles for dev/prod keys: application-dev.properties vs application-prod.properties.
  2. Set up webhooks. See Handle Paystack Webhooks in Spring Boot.
  3. HTTPS. Required for callbacks and webhooks.
  4. Validate amounts. Check against your JPA entity, not request params.

Ship Payments Faster

This guide is part of the Paystack integration guides by language and framework series.

Sign up for the McTaba newsletter

Key Takeaways

  • ✓Spring Boot RestTemplate or WebClient handles all Paystack REST API calls.
  • ✓Store your Paystack secret key in application.properties. Inject with @Value.
  • ✓Use @Service for the PaystackService and @RestController for endpoints.
  • ✓Amounts are in kobo (NGN), pesewas (GHS), or cents. Multiply by 100.
  • ✓Always verify transactions server-side after the redirect callback.
  • ✓Spring Boot dependency injection makes PaystackService easily testable.

Frequently Asked Questions

Should I use RestTemplate or WebClient?
RestTemplate is simpler and works for synchronous calls. WebClient is non-blocking and preferred for reactive applications. Both work with Paystack.
Do I need a Paystack Java library?
No. RestTemplate handles all REST API calls. The Paystack API is a standard REST API that works with any HTTP client.
How do I handle CSRF for webhooks?
If using Spring Security, disable CSRF for the webhook endpoint. Add a security configuration that permits the webhook URL without CSRF.

Learn Paystack Integration

KES 2,999

The definitive guide to building payment systems with Paystack — from your first transaction to production-grade payment infrastructure across Africa. 9 modules, 47 lessons. Free preview available.

Start Paystack Course

Not ready? Create Free Account

Keep reading

Paystack Integration Guides by Language and Framework

A complete directory of Paystack integration guides organized by programming language and framework. Each guide covers accepting payments, verifying transactions, handling webhooks, and building subscriptions in your specific stack.

Read more

Accept Payments with Paystack in Svelte and SvelteKit

Accept Paystack payments in SvelteKit using server endpoints for backend logic and Svelte components for the frontend. This guide covers initializing transactions, inline popup checkout, redirect checkout, and verification in a single full-stack SvelteKit project.

Read more

Verify Paystack Payments in Flask

Verify Paystack payments server-side in your Flask application. This guide covers calling the Paystack verify endpoint, validating amounts and currencies, building reusable verification helpers, and preventing double-granting.

Read more

Build Paystack Subscriptions in ASP.NET Core

Implement Paystack recurring billing in ASP.NET Core. This guide covers creating plans, subscribing customers through transaction initialization, handling renewal webhooks with C#, and cancelling subscriptions.

Read more

Paystack Settlement Timelines and What Engineers Should Assume

Settlement is when the money actually lands in your bank account. It does not happen at the same time as the charge. This guide explains the settlement cycle for each Paystack-supported country, how to query settlement data, and how to build your application so that settlement timing never causes bugs or confusion.

Read more

Paystack Status Page and Incident Response for Your Team

status.paystack.com tells you when Paystack is having problems, but it will not tell you what to do about it. This guide covers how to subscribe to alerts, build an internal incident response runbook for payment outages, communicate with customers during downtime, and reconcile transactions after recovery.

Read more

Explore related topics

M-Pesa & African Stack

M-Pesa Daraja API tutorials, USSD development, and WhatsApp Business API guides. The African Stack that global bootcamps do not teach.

Learn to Code in Kenya

Everything a Kenyan needs to know before writing their first line of code. Career paths, real costs, hardware requirements, and honest answers about what it takes.

Learning to Code

Roadmaps, language guides, and practical advice for learning to code and launching a programming career.

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

The African Stack: Skills for This Market

The skills that make Kenyan developers hard to replace: M-Pesa, USSD, WhatsApp, fintech, and building for the African market.

Bonaventure Ogeto

Bonaventure Ogeto

Founder, McTaba Labs

Bonaventure is the founder of McTaba Labs, a coding bootcamp in Nairobi, Kenya. He has spent years building products for the African market and mentoring the next generation of developers across the continent.