Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 13 · Lesson 125 · 7 min read

Stripe Payments and Subscriptions in .NET

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: Creating a Checkout Session, Handling Webhooks and Deriving Entitlements
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Integrate a payment provider without handling card data, model the subscription lifecycle, treat webhooks as the source of truth with signature verification and idempotency, derive entitlements from subscription state, and reconcile against the provider.

Concept Explanation

The safest way to handle payment card data is not to handle it. Card numbers that pass through your servers, even briefly, bring your system into the scope of the Payment Card Industry Data Security Standard, with heavy audit requirements. Payment providers such as Stripe offer hosted pages and embedded fields that send the card directly to the provider, and your servers only ever see a token or a reference. Using a hosted checkout page or the provider's embedded elements keeps you in the simplest compliance category, and Day 136 covers PCI scope in more detail. The rule for your React and .NET code is that no card number, expiry, or security code ever appears in your request bodies, logs, or database.

The flow has a subtle trap. After the customer pays, the browser is redirected back to your site with a success message, but that redirect is not proof of payment: the user may close the tab before it, may arrive there without paying by editing the URL, or the payment may complete later or fail after an apparent success. The source of truth is the provider's webhook events, such as a completed checkout session, a successful invoice payment, or a failed one. Your webhook endpoint must verify the signature using the raw request body and the signing secret, reject old timestamps, deduplicate by event id because delivery is at least once, and tolerate events arriving out of order. Fetch current state from the provider when an event's ordering matters, and process the event with the inbox pattern from Day 122.

Subscriptions have a lifecycle. Typical states are trialing, active, past due when a renewal payment fails and the provider is retrying, unpaid or canceled when it gives up, and paused. Your application should store a minimal mirror of the subscription: the provider's customer and subscription identifiers, the price or plan, the status, and the period end. Access to features, the entitlement, should be derived from that mirrored status and the plan, in one place, not scattered through the code. Decide what past due means for the user: usually a grace period with a clear message and a link to update the payment method. Handle upgrades and downgrades with proration as the provider computes it, and taxes through the provider's tax service where available, since tax rules are a specialty of their own.

Several rules protect money and trust. Never accept a price, amount, or plan from the client; the server maps a plan name from an allowlist to the provider's price id and creates the checkout session, since a client-supplied amount is an invitation to pay one cent. Store money as integer minor units with a currency code. Use idempotency keys on every request that creates something at the provider so a retry cannot charge twice. Use restricted API keys with only the permissions the integration needs, keep secret keys in Key Vault, and use the provider's test mode and test clocks in your pipeline. In the European Economic Area, strong customer authentication rules mean some payments require the customer to complete an extra step, so your flow must handle a state that needs customer action. Finally, run a reconciliation job that compares your mirrored state with the provider's, since webhooks can be missed, and alert on differences.

ConcernApproachWhy
Card dataHosted checkout or embedded elements, tokens onlyKeeps card numbers off your servers
Proof of paymentSigned webhook events, not the browser redirectThe redirect can be faked or never arrive
Duplicate and reordered eventsInbox by event id, fetch current state when neededDelivery is at least once, not ordered
Plans and pricesServer-side allowlist mapped to provider price idsClients must not choose amounts
Feature accessEntitlement derived from mirrored subscription statusOne place decides, easy to test
DriftScheduled reconciliation with the providerMissed webhooks and manual changes

Worked Example: Creating a Checkout Session, Handling Webhooks and Deriving Entitlements

The endpoint creates a session from an allowlisted plan. The webhook handler verifies, deduplicates and updates the mirror, and the entitlement function reads it.

C#
// Create a checkout session: the plan comes from a server-side allowlist. The client only names a plan.
static readonly IReadOnlyDictionary<string, string> PriceIds = new Dictionary<string, string>
{
    ["pro-monthly"] = "price_1Pro...",       // configuration in practice, not hard-coded
    ["pro-yearly"]  = "price_1ProYear...",
};

app.MapPost("/api/billing/checkout", async (CheckoutRequest req, ClaimsPrincipal user, AppDb db, IStripeClient stripe, CancellationToken ct) =>
{
    if (!PriceIds.TryGetValue(req.Plan, out var priceId)) return Results.ValidationProblem(new Dictionary<string, string[]> { ["plan"] = ["Unknown plan."] });
    var account = await db.Accounts.SingleAsync(a => a.OwnerId == user.GetUserId(), ct);

    var service = new Stripe.Checkout.SessionService(stripe);
    var session = await service.CreateAsync(new Stripe.Checkout.SessionCreateOptions
    {
        Mode = "subscription",
        Customer = account.StripeCustomerId,
        ClientReferenceId = account.Id.ToString(),                                   // links the event back to our account
        LineItems = [new() { Price = priceId, Quantity = 1 }],
        SuccessUrl = "https://app.example.com/billing/return?session={CHECKOUT_SESSION_ID}",
        CancelUrl  = "https://app.example.com/billing",
    }, new Stripe.RequestOptions { IdempotencyKey = $"checkout:{account.Id}:{req.Plan}:{req.ClientRequestId}" }, ct);

    return Results.Ok(new { url = session.Url });                                    // React redirects the browser to this URL
}).RequireAuthorization();
C#
// Webhook: verify the signature over the RAW body, deduplicate, and update the mirror.
app.MapPost("/webhooks/stripe", async (HttpRequest request, AppDb db, IOptions<StripeOptions> opt, CancellationToken ct) =>
{
    var json = await new StreamReader(request.Body).ReadToEndAsync(ct);               // must be the exact bytes Stripe signed
    Event stripeEvent;
    try { stripeEvent = EventUtility.ConstructEvent(json, request.Headers["Stripe-Signature"], opt.Value.WebhookSecret); }   // also checks the timestamp tolerance
    catch (StripeException) { return Results.BadRequest(); }

    if (await db.ProcessedEvents.AnyAsync(e => e.EventId == stripeEvent.Id, ct)) return Results.Ok();   // duplicate delivery

    switch (stripeEvent.Data.Object)
    {
        case Subscription sub:
            var acct = await db.Accounts.SingleAsync(a => a.StripeCustomerId == sub.CustomerId, ct);
            acct.SubscriptionId = sub.Id;
            acct.PlanPriceId    = sub.Items.Data[0].Price.Id;
            acct.SubscriptionStatus = sub.Status;                                     // trialing, active, past_due, canceled, ...
            acct.CurrentPeriodEnd   = sub.Items.Data[0].CurrentPeriodEnd;
            break;
        case Invoice { Status: "paid" } inv: /* record payment for the ledger, send receipt via notifications */ break;
    }
    db.ProcessedEvents.Add(new ProcessedEvent(stripeEvent.Id, DateTimeOffset.UtcNow));
    await db.SaveChangesAsync(ct);
    return Results.Ok();                                                              // quickly: heavy work is queued, not done here
}).AllowAnonymous();                                                                  // authenticated by the signature, not by a cookie
Code
// Entitlements are derived in one place from the mirrored state.
public static Entitlements For(Account a, DateTimeOffset now) => a.SubscriptionStatus switch
{
    "active" or "trialing"                                   => Plans.Features(a.PlanPriceId),
    "past_due" when a.CurrentPeriodEnd.AddDays(7) > now      => Plans.Features(a.PlanPriceId).WithBanner("Update your payment method"),   // grace period
    _                                                        => Plans.Free,
};

// Reconciliation: a scheduled job compares our mirror with the provider and alerts on differences.
await foreach (var sub in stripe.Subscriptions.ListAutoPagingAsync(new SubscriptionListOptions { Status = "all" }, cancellationToken: ct))
    if (mirror.TryGetValue(sub.Id, out var ours) && ours.Status != sub.Status) log.LogWarning("Billing drift for {SubscriptionId}", sub.Id);

The webhook endpoint returns quickly and is not behind cookie authentication because Stripe cannot log in. It is protected by the signature, which is why the raw body and the secret must be handled with care.

The React app sends only a plan name. The server maps it to a price id from an allowlist and creates a hosted checkout session, so card data never touches your systems. Verified, deduplicated webhook events update a mirrored subscription status from which entitlements are derived.
The React app sends only a plan name. The server maps it to a price id from an allowlist and creates a hosted checkout session, so card data never touches your systems. Verified, deduplicated webhook events update a mirrored subscription status from which entitlements are derived.

Real-World Examples

  • In the 2013 breach of Target's systems, attackers installed malware on point-of-sale terminals and took data for about 40 million payment cards, and the incident contributed to significant costs and leadership changes. It remains a central example for why card data should stay out of application systems, and why the Payment Card Industry standards focus on minimizing where such data exists.
  • Stripe's documentation states that webhook events may be delivered more than once, may arrive out of order, and should be verified with the signature header, and it recommends handling them idempotently and fetching the current state when order matters. Teams that treated the checkout redirect as proof of payment have been affected by customers who received access without paying or paid without receiving access, which is why webhooks are the source of truth.
Key TakeawaysKeep card data off your own systems entirely with hosted checkout or embedded payment elements, and choose plans and amounts on the server. Treat verified, deduplicated webhooks as the source of truth for payment and subscription state. Mirror minimal subscription data, derive entitlements in one place, use idempotency keys and restricted keys, and reconcile with the provider regularly.

Review Questions & Answers

The user can close the tab before it or reach the URL without paying, and some payments complete or fail later. Only signed events from the provider reliably say what happened, so entitlements should change when a verified event arrives.

The signature is computed over the exact bytes the provider sent, and parsing and re-serializing the JSON can change them. Verifying the raw body ensures the event was not altered and really came from the provider.

A client can send any value it likes, so an amount or price id supplied by the browser could be altered to pay less. The server maps a plan name from an allowlist to the provider's price identifier.

Webhooks can be missed, delayed, or made irrelevant by manual changes in the provider dashboard, leaving your mirror out of date. A scheduled comparison detects drift so it can be corrected and investigated.