Bonaventure OgetoBy Bonaventure Ogeto|

Handle Paystack Webhooks in iOS with Swift

iOS apps cannot receive Paystack webhooks directly. Build a backend webhook endpoint, verify the signature, and update your database. Send payment events to the iOS app via APNs push notifications using Firebase Cloud Messaging or the Apple Push Notification service directly. In iOS, handle push notifications in AppDelegate or UNUserNotificationCenter and update your app state accordingly.

Architecture: Backend Receives, iOS Displays

The payment notification flow for iOS:

  1. Paystack fires a webhook to your backend
  2. Backend verifies the signature and processes the event
  3. Backend updates the database (order marked paid)
  4. Backend sends an APNs push notification via FCM or directly
  5. iOS receives the push, updates the UI

Your iOS app never makes outbound connections to Paystack. It only talks to your backend.

Backend: Webhook + APNs Push

// Node.js backend with Firebase Admin SDK (FCM to iOS)
var crypto = require('crypto');
var admin = require('firebase-admin');

app.post('/api/webhooks/paystack',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    var sig = req.headers['x-paystack-signature'];
    var hash = crypto
      .createHmac('sha512', process.env.PAYSTACK_SECRET_KEY)
      .update(req.body)
      .digest('hex');

    if (hash !== sig) return res.status(400).send('Invalid signature');
    res.sendStatus(200);

    var event = JSON.parse(req.body.toString());

    if (event.event === 'charge.success') {
      var email = event.data.customer.email;
      var reference = event.data.reference;
      var amount = event.data.amount / 100;

      await db.orders.markAsPaid(reference);

      var user = await db.users.findByEmail(email);
      if (user?.iosApnsToken) {
        // Send via FCM (which delivers to APNs for iOS)
        await admin.messaging().send({
          token: user.iosFcmToken,
          apns: {
            payload: {
              aps: {
                alert: {
                  title: 'Payment Confirmed',
                  body: 'NGN ' + amount + ' received'
                },
                sound: 'default',
                badge: 1
              }
            }
          },
          data: {
            event: 'charge.success',
            reference: reference,
            amount: String(amount)
          }
        });
      }
    }
  }
);

iOS: Push Notification Setup

// AppDelegate.swift
import UIKit
import UserNotifications
import FirebaseCore
import FirebaseMessaging

@main
class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate,
                   UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FirebaseApp.configure()

        UNUserNotificationCenter.current().delegate = self
        Messaging.messaging().delegate = self

        UNUserNotificationCenter.current().requestAuthorization(
            options: [.alert, .badge, .sound]
        ) { granted, error in
            if granted {
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            }
        }
        return true
    }

    // FCM token received — send to your backend
    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        guard let token = fcmToken else { return }
        sendTokenToBackend(token: token)
    }

    // Notification received while app is in foreground
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let userInfo = notification.request.content.userInfo
        handlePaystackEvent(userInfo: userInfo)
        completionHandler([.banner, .sound])
    }

    // Notification tapped (app in background or closed)
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        handlePaystackEvent(userInfo: userInfo)
        completionHandler()
    }

    private func handlePaystackEvent(userInfo: [AnyHashable: Any]) {
        guard let event = userInfo["event"] as? String,
              let reference = userInfo["reference"] as? String else { return }

        if event == "charge.success" {
            // Post notification so any listening View can update
            NotificationCenter.default.post(
                name: Notification.Name("PaystackPaymentConfirmed"),
                object: nil,
                userInfo: ["reference": reference]
            )
        }
    }

    private func sendTokenToBackend(token: String) {
        // POST token to your backend API
    }
}

Learn More

Key Takeaways

  • iOS apps do not have public HTTPS endpoints. Paystack webhooks cannot reach them directly.
  • Build the webhook handler on your backend. iOS app is only a consumer of payment events.
  • Use APNs (via Firebase Cloud Messaging or directly) to push payment events to the iOS app.
  • Implement UNUserNotificationCenterDelegate to handle notifications in the foreground and background.
  • Request notification permissions using UNUserNotificationCenter.requestAuthorization early in the app lifecycle.
  • For in-app real-time updates, use polling or a WebSocket while the user is on a payment-waiting screen.

Frequently Asked Questions

Do I need Firebase to send push notifications for Paystack events on iOS?
No. You can send directly via APNs using libraries like node-apn or go-apns2. Firebase Cloud Messaging is convenient because it handles the APNs certificate management and token refresh. For most apps, FCM is the easier path.
What is the difference between device token and FCM token in iOS?
The device token is the raw APNs token from iOS. The FCM token is a Firebase registration token that Firebase maps to the APNs token internally. When using Firebase, use the FCM token. Firebase handles token refresh and delivery to APNs for you.
Can I receive Paystack events in a SwiftUI app via push notifications?
Yes. Use @UIApplicationDelegateAdaptor in your SwiftUI app to connect AppDelegate with push notification handling. Post a NotificationCenter notification from AppDelegate when a payment event arrives, and observe it in your SwiftUI views with .onReceive.
What if the user denies notification permissions on iOS?
Fall back to polling. After checkout, start polling your backend status endpoint every few seconds on the payment-pending screen. If the user denies permissions, do not ask again immediately — guide them to Settings if they want to enable notifications later.

Ready to build real-world apps?

Join the McTaba Labs full-stack marathon (4 months full-time · 6 months part-time). Learn M-Pesa, USSD, and WhatsApp engineering while shipping 8 production apps.

Apply to the McTaba Marathon