Server-Side Webhook for Subscriptions: Renewal, Cancel, Refund

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
Server-Side Webhook for Subscriptions: Renewal, Cancel, Refund
Medium
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    858
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    744
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1160
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1034
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    968
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    562

Server-Side Webhook for Subscription Events (Renewal, Cancel, Refund)

Webhook from Stripe, App Store, or Google Play is an HTTP POST to your server with a JSON body about what happened to the subscription. Sounds simple. In practice, it is the most vulnerable part of a subscription system: events arrive out of order, duplicate, get lost, and some require a response within seconds or will be retried. We have implemented dozens of such integrations — here is how to make them reliable. Errors in webhook processing can lead to losing up to 30% of subscription revenue — our methodology reduces that risk to 1%.

Why Idempotency is Critical?

Stripe may send the same event multiple times — if your endpoint responded slowly or returned a 500. Processing invoice.payment_succeeded twice means extending the subscription twice in the database and sending two "thank you for payment" emails. Solution: store processed event.id:

def handle_stripe_webhook(event_id: str, event_type: str, event_data: dict):
    # Check idempotency
    if db.is_event_processed(event_id):
        return  # already processed, do nothing

    # Process
    process_event(event_type, event_data)

    # Mark as processed
    db.mark_event_processed(event_id, processed_at=datetime.utcnow())

Store processed IDs for 30 days — Stripe guarantees retries only within a few days. In our practice, a client forgot idempotency and got double charges — we had to fix the logic from scratch. Using idempotency reduces the chance of duplicates by 99%.

How to Verify Webhook Signature?

Never process a webhook without verifying its signature. An attacker could send a fake invoice.payment_succeeded event to your endpoint and gain access without payment.

import stripe
from fastapi import Request, HTTPException

STRIPE_WEBHOOK_SECRET = "whsec_..."

@app.post("/webhooks/stripe")
async def stripe_webhook(request: Request):
    payload = await request.body()
    sig_header = request.headers.get("stripe-signature")

    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, STRIPE_WEBHOOK_SECRET
        )
    except stripe.error.SignatureVerificationError as e:
        raise HTTPException(status_code=400, detail=str(e))

    # Process asynchronously — return 200 immediately
    background_tasks.add_task(process_stripe_event, event)
    return {"status": "ok"}

Important: return HTTP 200 immediately, before processing finishes. Stripe considers a webhook failed if no response is received within 30 seconds. Processing should happen in the background.

Event Map: What to Do for Each

async def process_stripe_event(event: dict):
    event_type = event['type']
    data = event['data']['object']

    match event_type:
        case 'invoice.payment_succeeded':
            # Subscription renewed — update access period
            subscription_id = data['subscription']
            period_end = data['lines']['data'][0]['period']['end']
            db.extend_subscription(
                subscription_id=subscription_id,
                access_until=datetime.fromtimestamp(period_end)
            )
            analytics.track('subscription_renewed', {'subscription_id': subscription_id})

        case 'invoice.payment_failed':
            # Handled by retry logic
            handle_payment_failure(data['subscription'], data.get('last_payment_error'))

        case 'customer.subscription.deleted':
            # Cancel: user canceled or retries exhausted
            reason = data.get('cancellation_details', {}).get('reason')
            db.deactivate_subscription(data['id'], reason=reason)
            if reason == 'payment_failed':
                notify_subscription_expired_payment(data['customer'])
            else:
                notify_subscription_cancelled(data['customer'])

        case 'customer.subscription.updated':
            # Plan change, period change, reactivation
            if data['status'] == 'active' and data.get('pause_collection') is None:
                db.reactivate_subscription_if_paused(data['id'])

        case 'charge.refunded':
            # Refund
            charge_id = data['id']
            amount_refunded = data['amount_refunded']
            reason = data.get('refund_reason')
            db.record_refund(charge_id, amount_refunded, reason)
            revoke_access_if_full_refund(data)

App Store Server Notifications (iOS)

Apple uses JWT-signed notifications version 2. Verification via Apple's public key (fetched from .well-known/apple-app-site-association or via AppleJWT library):

from appstoreconnect import AppStoreServerNotificationsClient

@app.post("/webhooks/apple")
async def apple_webhook(request: Request):
    body = await request.json()
    signed_payload = body.get("signedPayload")

    client = AppStoreServerNotificationsClient()
    try:
        notification = client.decode_notification(signed_payload)
    except Exception:
        raise HTTPException(400)

    notification_type = notification.notificationType
    subtype = notification.subtype
    transaction_info = notification.data.signedTransactionInfo

    match notification_type:
        case "DID_RENEW":
            # Subscription renewed
            extend_ios_subscription(transaction_info)
        case "EXPIRED":
            # Subscription expired (subtype: VOLUNTARY / BILLING_RETRY / PRICE_INCREASE)
            deactivate_ios_subscription(transaction_info, reason=subtype)
        case "REFUND":
            # Refund through Apple
            handle_ios_refund(transaction_info)
        case "GRACE_PERIOD_EXPIRED":
            # Grace period expired — final block
            hard_deactivate_ios_subscription(transaction_info)

Google Play Real-time Developer Notifications (Android)

Google Play sends notifications via Cloud Pub/Sub, not HTTP webhook. You need to create a Pub/Sub topic, subscription, and either poll or use push subscription:

from google.cloud import pubsub_v1
import base64

def process_pubsub_message(message: pubsub_v1.types.ReceivedMessage):
    data = json.loads(base64.b64decode(message.message.data))

    if 'subscriptionNotification' in data:
        notification = data['subscriptionNotification']
        notification_type = notification['notificationType']
        purchase_token = notification['purchaseToken']

        # Verify through Google Play Developer API
        purchase = google_play_client.purchases().subscriptions().get(
            packageName=PACKAGE_NAME,
            subscriptionId=notification['subscriptionId'],
            token=purchase_token
        ).execute()

        match notification_type:
            case 4:  # SUBSCRIPTION_PURCHASED
                activate_android_subscription(purchase_token, purchase)
            case 2:  # SUBSCRIPTION_RENEWED
                extend_android_subscription(purchase_token, purchase)
            case 3:  # SUBSCRIPTION_CANCELED
                mark_android_subscription_cancelled(purchase_token)
            case 13: # SUBSCRIPTION_EXPIRED
                deactivate_android_subscription(purchase_token)

Comparison of Webhook Handlers Across Stores

Parameter Stripe App Store Google Play
Protocol HTTP POST HTTP POST (JWT) Pub/Sub (push/pull)
Idempotency event.id signedPayload JTI messageId Pub/Sub
Response timeout 30 seconds 5 seconds 10 seconds
Retries Yes, up to 3 days Yes, up to 24 hours Yes, up to 7 days
Verification stripe-signature + secret Apple JWT key Google API verification
Typical events payment_succeeded, refund DID_RENEW, EXPIRED, REFUND SUBSCRIPTION_RENEWED, CANCELED

Common Webhook Implementation Mistakes

Mistake Consequence Solution
Missing idempotency Double subscription renewal Store event.id in Redis
No signature verification Free access for attacker Verify signature for each event
Sending 200 before processing finishes Event loss on failure Async processing in background
Blocking on EXPIRED without grace period False access revoke Use grace period
Idempotency Implementation Details

Store processed IDs in Redis with a 30-day TTL. For highly critical cases, add a database-level lock: before processing, insert event_id into processed_events table with a unique constraint. On duplicate insert, catch the exception and skip.

What's Included in Turnkey Webhook Development

  • Event schema design and endpoint creation for each store.
  • Implementation of idempotency (Redis/Postgres) and signature verification.
  • Handling of renewal, cancel, refund, upgrade/downgrade.
  • Handling edge cases: reactivation, grace period, retry payments.
  • Logging all events, error monitoring, alerts for failures.
  • Integration testing with each store's sandbox (TestFlight, internal test track).
  • Webhook API documentation and deployment instructions.
  • Post-deployment support (1 month).

Event Order: Sometimes Cancel Arrives Before Renewal

App Store peculiarity: EXPIRED can arrive seconds before DID_RENEW when a renewal succeeds at the last moment. If you blocked access due to EXPIRED, you need to restore it immediately upon DID_RENEW. The subscription state in the database should be determined not only by webhook events but also by receipt/purchase verification on Apple/Google servers. We have 5+ years of payment integration experience — we account for all nuances. Time saved on debugging such edge cases can be up to 50%.

Timeline

3–5 days. Stripe webhook with idempotency and full event set — 1.5 days. App Store Server Notifications v2 — 1 day. Google Play Pub/Sub — 1 day. Integration testing of all scenarios — 0.5–1 day. The cost is calculated individually. Contact us — we will evaluate your project and propose the optimal solution. Reach out to us for implementing a reliable webhook handler.

For a deeper understanding of webhook operation, refer to Stripe's official documentation.

Payments in Mobile Apps: In-App Purchase, StoreKit 2, Google Billing, Stripe, RevenueCat

In every monetization project, we balance App Store and Google Play policies, PCI DSS requirements, and purchase verification logic on the backend. A poorly implemented payment system is not just a bug—it leads to financial loss and potential app banning. Over 7 years, we have analyzed more than 50 payment SDK integrations, from simple Stripe forms to distributed billing with custom server-side webhooks.

In-App Purchase: Two Platforms, Two Different APIs

If your app sells digital content or subscriptions, Apple and Google require you to use their payment systems. This is non-negotiable: violating App Store rule 3.1.1 or Google Play Developer Policy results in app removal. Physical goods and offline services are a different story.

StoreKit 2 (iOS 15+)

StoreKit 2 is a complete overhaul of the original StoreKit with async/await API. Product.products(for:), product.purchase(), Transaction.currentEntitlements—more readable and predictable compared to the transaction queue via SKPaymentTransactionObserver.

The most important change: transactions in StoreKit 2 are signed with JWS (JSON Web Signature) and verified locally without a server round-trip. Transaction.verificationResult returns .verified(Transaction) or .unverified(Transaction, VerificationError). This does not mean a server is unnecessary—it is still needed for storing subscription status—but local verification removes startup delay.

StoreKit.AppTransaction verifies the actual app download from the App Store. Required for paid downloads or non-renewing purchases.

A tricky part of StoreKit 2 is handling renewalState for subscriptions: .subscribed, .expired, .inBillingRetryPeriod, .inGracePeriod, .revoked. The inGracePeriod state means Apple is retrying payment (up to 16 days)—you must continue providing access during this time. Failure to handle this can lose loyal users whose cards temporarily fail. Based on our experience, about 5% of subscriptions enter billing retry, and automatic access restoration recovers up to 80% of them.

Google Play Billing Library (v6+)

Google Billing is more complex than StoreKit in terms of scenario handling. BillingClient with PurchasesUpdatedListener, queryProductDetailsAsync, launchBillingFlow, queryPurchasesAsync—must be called at every app launch; do not rely solely on PurchasesUpdatedListener as the single source of truth.

Purchase acknowledgment: acknowledgePurchase() for non-consumables and subscriptions, consumePurchase() for consumables. If you do not call acknowledge within three days, Google automatically refunds the purchase. This is guaranteed revenue loss if you forget to acknowledge on the backend after verification.

ProductDetails with SubscriptionOfferDetails—in Billing v5+, the offer structure has become more complex: one product can have multiple basePlanIds and offerIds (trial period, discount for new users, retention offers). BillingFlowParams.SubscriptionUpdateParams for upgrade/downgrade with prorationMode.

Why Is Server-Side Verification Mandatory?

Never trust only client-side code when unlocking paid content. Client-side verification can be bypassed by modifying the app.

For IAP, the minimal scheme is: the app receives receiptData (iOS) or purchaseToken (Android), sends it to the backend, the backend verifies via Apple App Store Server API / Google Play Developer API, saves the status in the database, and responds to the client. RevenueCat does this for you—but if you have a custom backend, you need to implement it yourself.

Webhooks are more important than they seem. Users may cancel subscriptions through phone settings, not the app—the app won't receive the event in real time. Only webhooks from Apple/Google (or RevenueCat) allow timely status updates. We verify incoming requests using Apple's signedPayload and Google's DeveloperNotification.

How Does RevenueCat Simplify Integration?

Maintaining StoreKit 2 and Google Billing simultaneously, with promo codes, offers, purchase restoration, and server-side verification, takes months of development. RevenueCat handles most of this layer.

RevenueCat is not just a payment SDK. It offers:

  • A unified API for iOS and Android (and Stripe for web)
  • Server-side verification and subscription status storage
  • Webhooks for events (purchase, renewal, cancellation, billing issue)
  • Analytics for cohorts, MRR, churn
  • A/B testing of offers via Experiments

Purchases.configure(withAPIKey:) at startup, Purchases.shared.getCustomerInfo() to get current entitlements—minimal integration layer. Purchases.shared.purchase(package:) instead of directly calling StoreKit/Billing.

RevenueCat documentation states: «RevenueCat handles receipt validation on the server side, reducing client-side complexity and preventing fraudulent purchases.»

Limitations of RevenueCat: it is paid (free up to $2.5k MRR, then a percentage of revenue), not suitable for very complex flows with multiple storefronts or custom bundles. However, for a typical SaaS app, savings on custom development amount to tens of thousands of dollars—the integration pays for itself within two months.

Stripe in Mobile Apps

Stripe is used for physical goods, services, and B2B payments where IAP is not required by platform policy.

Stripe iOS SDK and Android SDKPaymentSheet for ready-made payment UI, PaymentSheetFlowController for custom UI with saved cards. Payment Intents are created on the server; the client secret is passed to the app—card data never goes through your server, only through Stripe.

Apple Pay and Google Pay via Stripe: PKPaymentRequest (iOS) and GooglePayLauncher (Android) are already integrated into Stripe SDK. Apple Pay conversion rates are 1.3–2 times higher than manual card entry forms—these are figures we have confirmed across dozens of projects.

Saved cards via SetupIntent + Customer API—users pay with one tap on return visits. Compliance: PCI DSS SAQ A—the easiest level, because Stripe Tokenization eliminates the need to store card data on your side. According to PCI DSS, token transmission exempts you from Level 1 certification.

3DS2 (Strong Customer Authentication) is mandatory for payments in the EU under PSD2. Stripe handles it automatically via PaymentIntent.confirmPayment, but you need to correctly handle the .requiresAction status and return the user to the appropriate screen after authentication.

What Is Included in the Work (Deliverables)

Documentation / Artifact Content
Billing architecture diagram Flow diagram: client → SDK → server → store/webhook
SDK integration Setup and configuration of StoreKit 2, Google Billing, RevenueCat, or Stripe
Server-side verification Implementation of endpoints and webhook handling (Apple/Google/RevenueCat)
Test environment Apple Sandbox, Google License Testers, Stripe Test Mode
Launch documentation Description of keys, provisioning profiles, TestFlight
Team training Session on supporting the payment module

Process and Timeline

We start by clarifying the business model: subscriptions, one-time purchases, consumables, freemium. The architecture depends on this. Testing IAP requires Sandbox accounts (Apple) and License Testers (Google)—this is a separate environment setup.

Apple's Sandbox behaves differently from production: subscriptions renew every 5 minutes instead of monthly, inGracePeriod works differently. It is essential to test scenarios: trial expiration, cancellation, billing retry, refund.

Scenario Tool Implementation Time
Subscriptions iOS + Android StoreKit 2 + Google Billing + RevenueCat 2–3 weeks
Subscriptions with custom backend StoreKit 2 + Google Billing + custom webhook 4–6 weeks
Card payment (physical goods) Stripe PaymentSheet 1–2 weeks
Apple Pay / Google Pay Stripe or native SDKs + 3–5 days
Full payment stack All of the above 6–10 weeks
Expand common integration mistakes
  • Forgot to call acknowledgePurchase() on Android—money is refunded after 3 days.
  • Did not handle inGracePeriod—loyal users are blocked from access.
  • Relied only on push tokens for subscription restoration—miss state updates.
  • Used production keys in TestFlight—real charges occur.

The cost is calculated individually based on the set of tools and complexity of server-side logic. On average, we fit within a budget for a typical integration, but the savings from preventing errors and churn offset this investment within a few months.

Get a consultation for your project—contact us. We will help you choose the optimal payment architecture that passes store reviews and does not break under peak loads.