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

Build Paystack Subscriptions in Spring Boot

To build Paystack subscriptions in Spring Boot, create a plan, initialize a transaction with the plan code, handle subscription webhooks to update a JPA entity, use @PreAuthorize for subscription-gated endpoints, and provide cancellation via the Paystack API.

In this article

  1. 1. Subscription Entity
  2. 2. Subscribe Endpoint
  3. 3. Webhook Handlers
  4. 4. Subscription Security
  5. 5. Ship Payments Faster

Subscription Entity

@Entity
@Table(name = "subscriptions")
public class Subscription {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @OneToOne
    @JoinColumn(name = "user_id")
    private User user;

    @Column(unique = true)
    private String subscriptionCode;
    private String planCode;
    private String emailToken;
    private String status; // active, past_due, cancelled
    private LocalDateTime nextPaymentDate;

    // Getters and setters
}

Subscribe Endpoint

@PostMapping("/subscribe")
public ResponseEntity<?> subscribe(@RequestBody Map<String, String> payload) {
    String planCode = payload.get("plan_code");
    String email = getCurrentUser().getEmail();

    Map<String, Object> body = Map.of("email", email, "plan", planCode);
    // Call Paystack initialize with plan parameter
    // Return authorization_url
}

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Webhook Handlers

private void handleSubscriptionCreate(JsonNode data) {
    String email = data.get("customer").get("email").asText();
    User user = userRepository.findByEmail(email);
    if (user == null) return;

    Subscription sub = subscriptionRepository.findByUser(user);
    if (sub == null) {
        sub = new Subscription();
        sub.setUser(user);
    }
    sub.setSubscriptionCode(data.get("subscription_code").asText());
    sub.setPlanCode(data.get("plan").get("plan_code").asText());
    sub.setEmailToken(data.has("email_token") ? data.get("email_token").asText() : "");
    sub.setStatus("active");
    subscriptionRepository.save(sub);
}

Subscription Security

@PreAuthorize("@subscriptionChecker.hasActive(authentication)")
@GetMapping("/premium")
public ResponseEntity<?> premiumContent() {
    return ResponseEntity.ok(Map.of("content", "Premium data"));
}

@Component("subscriptionChecker")
public class SubscriptionChecker {
    @Autowired private SubscriptionRepository subscriptionRepository;

    public boolean hasActive(Authentication auth) {
        User user = (User) auth.getPrincipal();
        Subscription sub = subscriptionRepository.findByUser(user);
        return sub != null && "active".equals(sub.getStatus());
    }
}

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

  • ✓Paystack handles recurring billing. Create plans and subscribe customers.
  • ✓Use a JPA @Entity for subscription tracking with status, subscriptionCode, and emailToken.
  • ✓Webhook events drive state changes. Handle subscription.create and invoice.payment_failed.
  • ✓Spring Security @PreAuthorize checks subscription status on premium endpoints.
  • ✓Store emailToken from the webhook for cancellation.
  • ✓Use @Async for webhook processing to return 200 quickly.

Frequently Asked Questions

Can I use Spring Security for subscription access control?
Yes. Use @PreAuthorize with a custom SpEL expression that checks the subscription status. This is clean and integrates with Spring Security.
How do I handle plan upgrades?
Cancel the current subscription and create a new one. Paystack does not support direct plan changes.
What if a renewal fails?
Handle the invoice.payment_failed webhook and update the status to past_due. Notify the customer to update their payment method.

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

Initialize Transaction vs Charge API: Which Paystack Endpoint to Use

Paystack gives you two ways to collect payments: Initialize Transaction and the Charge API. One gives you a hosted checkout in minutes. The other gives you full control but demands more code. This guide walks through both with code examples and a decision matrix so you pick the right one.

Read more

Paystack 401 Unauthorized on /transaction/initialize

Getting a 401 Unauthorized when calling Paystack /transaction/initialize means your request is not authenticated. This guide walks through 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.