Server-side webhook for subscription events renewal cancel refund

NOVASOLUTIONS.TECHNOLOGY 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 1 servicesAll 1735 services
Server-side webhook for subscription events renewal cancel refund
Medium
~3-5 business days
FAQ
Our competencies:
Development stages
Latest works
  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    756
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    624
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1052
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    947
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    862
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    445

Implementing Server Webhooks for Subscription Events (Renewal, Cancel, Refund)

A webhook from Stripe, App Store, or Google Play is an HTTP POST to your server with JSON about what happened to the subscription. Simple in theory. In practice, it's the most vulnerable part of a subscription system: events arrive in arbitrary order, duplicate, get lost, and some require a response within 5 seconds or will retry.

Idempotency: Solve First

Stripe can send an event multiple times — if your endpoint delayed or returned 500. Processing invoice.payment_succeeded twice means renewing the subscription twice, sending "Thank you for payment" twice. 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

    # 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 only retries within days.

Signature Verification: Mandatory

Never process a webhook without verifying the signature. An attacker can send a fake invoice.payment_succeeded event and get free access.

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 async — return 200 immediately
    background_tasks.add_task(process_stripe_event, event)
    return {"status": "ok"}

Important: return HTTP 200 immediately, before processing completes. Stripe considers webhook failed if no response within 30 seconds. Processing must be 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':
            # Cancellation: user cancelled 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 update, 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 v2. Verify via Apple's public key:

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":
            extend_ios_subscription(transaction_info)
        case "EXPIRED":
            deactivate_ios_subscription(transaction_info, reason=subtype)
        case "REFUND":
            handle_ios_refund(transaction_info)
        case "GRACE_PERIOD_EXPIRED":
            hard_deactivate_ios_subscription(transaction_info)

Google Play Real-time Developer Notifications (Android)

Google sends via Cloud Pub/Sub, not HTTP webhook:

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 via 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)

Event Order: Sometimes Cancel Arrives Before Renewal

App Store quirk: EXPIRED can arrive seconds before DID_RENEW on successful last-moment renewal. If you blocked access on EXPIRED, restore it on DID_RENEW. Subscription state should be determined not just by webhooks, but by verifying receipt on Apple/Google servers.

Timeline

3–5 days. Stripe webhook with idempotency and full event set — 1.5 days. App Store Notifications v2 — 1 day. Google Play Pub/Sub — 1 day. Integration testing all scenarios — 0.5–1 day. Pricing is calculated individually.