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 ASP.NET Core
Bonaventure OgetoBy Bonaventure Ogeto|Updated July 22, 2026

Build Paystack Subscriptions in ASP.NET Core

To build Paystack subscriptions in ASP.NET Core, create a plan once via the Paystack API, then initialize a transaction with the plan code to subscribe a customer. Paystack handles renewals automatically. Handle subscription.create, charge.success (with plan), and invoice.payment_failed webhooks in your WebhookController to manage subscription state in your database.

In this article

  1. 1. Create a Plan via API
  2. 2. Subscribe a Customer
  3. 3. Subscription Webhook Events
  4. 4. Cancel a Subscription
  5. 5. Learn More

Create a Plan via API

// Controllers/SubscriptionController.cs
[ApiController]
[Route("api/[controller]")]
public class SubscriptionController : ControllerBase
{
    private readonly HttpClient _paystackClient;

    public SubscriptionController(IHttpClientFactory factory)
    {
        _paystackClient = factory.CreateClient("Paystack");
    }

    [HttpPost("plans")]
    public async Task<IActionResult> CreatePlan([FromBody] CreatePlanRequest req)
    {
        var payload = new
        {
            name = req.Name,
            amount = req.AmountInKobo,
            interval = req.Interval,  // "monthly", "weekly", "annually", "daily"
            currency = req.Currency ?? "NGN"
        };

        var response = await _paystackClient.PostAsJsonAsync("plan", payload);
        var result = await response.Content.ReadFromJsonAsync<JsonElement>();

        if (!result.GetProperty("status").GetBoolean())
            return BadRequest(result.GetProperty("message").GetString());

        var data = result.GetProperty("data");
        return Ok(new
        {
            plan_code = data.GetProperty("plan_code").GetString(),
            name = data.GetProperty("name").GetString(),
            amount = data.GetProperty("amount").GetInt64()
        });
    }
}

public record CreatePlanRequest(string Name, long AmountInKobo, string Interval, string? Currency = null);

Subscribe a Customer

[HttpPost("subscribe")]
public async Task<IActionResult> Subscribe([FromBody] SubscribeRequest req)
{
    // Your plan code stored in config
    var planCode = "PLN_xxxxxxxxxxxx";

    var reference = $"sub_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}_{Guid.NewGuid():N}"[..30];

    var payload = new
    {
        email = req.Email,
        plan = planCode,
        reference = reference,
        callback_url = "https://yourapp.com/subscription/callback"
    };

    var response = await _paystackClient.PostAsJsonAsync("transaction/initialize", payload);
    var result = await response.Content.ReadFromJsonAsync<JsonElement>();

    if (!result.GetProperty("status").GetBoolean())
        return BadRequest(result.GetProperty("message").GetString());

    var data = result.GetProperty("data");
    return Ok(new
    {
        authorization_url = data.GetProperty("authorization_url").GetString(),
        access_code = data.GetProperty("access_code").GetString(),
        reference = data.GetProperty("reference").GetString()
    });
}

public record SubscribeRequest(string Email);

Get weekly developer tips

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

No spam. Unsubscribe anytime.

Subscription Webhook Events

// In WebhookController.cs ProcessEventAsync
case "subscription.create":
{
    var subCode = data.GetProperty("subscription_code").GetString();
    var emailToken = data.GetProperty("email_token").GetString();
    var customerEmail = data.GetProperty("customer").GetProperty("email").GetString();

    _logger.LogInformation("New subscription: {SubCode} for {Email}", subCode, customerEmail);
    // Activate the customer's plan in database
    // Store subCode and emailToken for future cancellation
    break;
}
case "charge.success":
{
    // Check if this is a subscription renewal
    if (data.TryGetProperty("plan", out var plan) &&
        plan.ValueKind != JsonValueKind.Null)
    {
        var subRef = data.GetProperty("reference").GetString();
        var amount = data.GetProperty("amount").GetInt64();
        _logger.LogInformation("Subscription renewal: {Ref}, {Amount}", subRef, amount / 100m);
        // Extend subscription period in database
    }
    break;
}
case "invoice.payment_failed":
{
    var subInfo = data.GetProperty("subscription");
    var subCode = subInfo.GetProperty("subscription_code").GetString();
    _logger.LogWarning("Renewal failed for subscription: {SubCode}", subCode);
    // Pause access, send payment failure email
    break;
}
case "subscription.disable":
{
    var subCode = data.GetProperty("subscription_code").GetString();
    _logger.LogInformation("Subscription cancelled: {SubCode}", subCode);
    // Deactivate plan, do not delete — keep for audit
    break;
}

Cancel a Subscription

[HttpPost("cancel")]
public async Task<IActionResult> Cancel([FromBody] CancelRequest req)
{
    var payload = new { code = req.SubscriptionCode, token = req.EmailToken };
    var response = await _paystackClient.PostAsJsonAsync("subscription/disable", payload);
    var result = await response.Content.ReadFromJsonAsync<JsonElement>();

    if (!result.GetProperty("status").GetBoolean())
        return BadRequest(result.GetProperty("message").GetString());

    return Ok(new { cancelled = true });
}

public record CancelRequest(string SubscriptionCode, string EmailToken);

Learn More

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

Sign up for the McTaba newsletter

Key Takeaways

  • ✓Create a plan once and store its plan_code. Use the plan_code when initializing subscription transactions.
  • ✓Including a plan code in transaction/initialize causes Paystack to create a subscription after payment and store the card.
  • ✓Renewals are automatic. You receive charge.success webhooks with a plan property on each successful renewal.
  • ✓Store subscription_code and email_token from the subscription.create webhook. You need both to cancel.
  • ✓Handle invoice.payment_failed to revoke or downgrade customer access when a renewal fails.
  • ✓Use CancellationToken in async actions to handle client disconnects gracefully.

Frequently Asked Questions

Does Paystack have a .NET SDK?
Paystack does not maintain an official .NET SDK. Most .NET developers call the REST API directly using IHttpClientFactory and System.Net.Http.Json, which is what this guide covers. Third-party community libraries exist on NuGet but verify their maintenance status before using.
How do I handle failed subscription renewals in ASP.NET Core?
Listen for invoice.payment_failed in your webhook controller. When received, look up the subscription by subscription_code in your database and downgrade or pause the customer access. Send them an email with a link to update their payment method. Paystack may retry automatically.
Can I use SignalR to notify users when their subscription payment succeeds?
Yes. After processing a charge.success webhook in your webhook controller, push a real-time notification to the customer using SignalR IHubContext. Inject it into your webhook controller and call Clients.User(userId).SendAsync() after confirming the payment.
How should I store subscription data in ASP.NET Core with EF Core?
Create a Subscription entity with fields for subscription_code, email_token, status, plan_code, customer_email, start_date, next_payment_date, and cancelled_at. Update these fields from webhook events. The email_token field is needed for cancellation.

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 ASP.NET Core

Wire Paystack payments into an ASP.NET Core web application. This guide covers configuring HttpClient for the Paystack API, creating payment controllers, initializing transactions, handling redirect callbacks, and verifying payments server-side.

Read more

Handle Paystack Webhooks in ASP.NET Core

A complete guide to receiving and verifying Paystack webhooks in an ASP.NET Core application. Covers reading the raw body before JSON parsing, computing the HMAC SHA512 signature in C#, routing events, and preventing double-processing.

Read more

Handling subscription.create, subscription.disable and invoice Events

A complete walkthrough of every Paystack subscription and invoice webhook event. Covers subscription.create, subscription.not_renew, subscription.disable, invoice.create, invoice.payment_failed, and invoice.update with production-ready Node.js handlers.

Read more

Paystack Subscription Not Charging

Your Paystack subscription exists but recurring charges are not happening. The subscription might be disabled, the authorization code might not be reusable, the card might have expired, the plan amount might have changed, or the subscription might be in arrears. This guide walks through every cause with a systematic debug checklist.

Read more

Paystack Card Not Supported for Recurring

When Paystack says a card is not supported for recurring charges, the card type or issuing bank blocks tokenization. This guide covers why it happens, which card types are affected, how to handle it gracefully, and alternative billing strategies.

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.