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. Handle Paystack Webhooks in Spring Boot
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 20, 2026

Handle Paystack Webhooks in Spring Boot

To handle Paystack webhooks in Spring Boot, create a controller that reads the raw body with @RequestBody String, computes an HMAC SHA-512 hash using javax.crypto.Mac, compares it to the X-Paystack-Signature header, and processes the event asynchronously. Return ResponseEntity.ok().

In this article

  1. 1. Security Configuration
  2. 2. Webhook Controller
  3. 3. Testing
  4. 4. Ship Payments Faster

Security Configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.ignoringRequestMatchers("/webhooks/**"))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/webhooks/**").permitAll()
                .anyRequest().authenticated()
            );
        return http.build();
    }
}

Webhook Controller

@RestController
@RequestMapping("/webhooks")
public class WebhookController {
    @Value("${paystack.secret-key}")
    private String secretKey;

    @Autowired
    private PaystackService paystackService;

    @PostMapping("/paystack")
    public ResponseEntity<String> handleWebhook(
            @RequestBody String body,
            @RequestHeader("X-Paystack-Signature") String signature) {

        if (!verifySignature(body, signature)) {
            return ResponseEntity.badRequest().body("Invalid signature");
        }

        // Parse and process
        ObjectMapper mapper = new ObjectMapper();
        try {
            JsonNode event = mapper.readTree(body);
            String eventType = event.get("event").asText();
            JsonNode data = event.get("data");

            processEvent(eventType, data);
        } catch (Exception e) {
            // Log error but still return 200
        }

        return ResponseEntity.ok("OK");
    }

    private boolean verifySignature(String body, String signature) {
        try {
            Mac mac = Mac.getInstance("HmacSHA512");
            SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA512");
            mac.init(keySpec);
            byte[] hash = mac.doFinal(body.getBytes());

            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            return MessageDigest.isEqual(
                hexString.toString().getBytes(),
                signature.getBytes()
            );
        } catch (Exception e) {
            return false;
        }
    }

    private void processEvent(String eventType, JsonNode data) {
        if ("charge.success".equals(eventType)) {
            String reference = data.get("reference").asText();
            paystackService.verifyAndFulfill(reference);
        }
    }
}

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Testing

@Test
public void testValidWebhook() throws Exception {
    String payload = "{\"event\":\"charge.success\",\"data\":{\"reference\":\"test\"}}";
    Mac mac = Mac.getInstance("HmacSHA512");
    SecretKeySpec keySpec = new SecretKeySpec("sk_test_xxx".getBytes(), "HmacSHA512");
    mac.init(keySpec);
    String signature = Hex.encodeHexString(mac.doFinal(payload.getBytes()));

    mockMvc.perform(post("/webhooks/paystack")
        .content(payload)
        .contentType(MediaType.APPLICATION_JSON)
        .header("X-Paystack-Signature", signature))
        .andExpect(status().isOk());
}

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

  • ✓Use @RequestBody String to get the raw body for HMAC computation.
  • ✓javax.crypto.Mac with HmacSHA512 handles the signature computation.
  • ✓Disable CSRF for the webhook endpoint in your SecurityFilterChain.
  • ✓Use @Async for non-blocking event processing after returning 200.
  • ✓Make handlers idempotent. Paystack retries failed deliveries.
  • ✓Spring Security configuration must permit the webhook URL without authentication.

Frequently Asked Questions

Why does my webhook return 403?
Your Spring Security configuration is probably blocking the webhook URL or CSRF is enabled. Add the webhook path to CSRF ignore list and permit it without authentication.
Should I use @Async for webhook processing?
Yes. @Async lets you return 200 immediately and process in a separate thread. Make sure to enable @EnableAsync on your configuration class.
Can I use Spring Events for webhook processing?
Yes. Publish an ApplicationEvent from the controller and handle it with an @EventListener. This decouples the webhook receipt from processing.

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

How Paystack Accept Payments Actually Works Under the Hood

Most tutorials show you the API call and skip to "payment successful." This guide traces what actually happens between your server, Paystack, the card networks, the issuing bank, and the acquiring bank. Every step, every handshake, every place things can fail.

Read more

Paystack Invalid Key: Every Cause and Fix

The Paystack "Invalid key" error means the API key you sent does not match any active key on your Paystack account. This guide covers every cause and the exact fix for each one.

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.