Bonaventure OgetoBy Bonaventure Ogeto|

Handle Paystack Webhooks in Flutter

Flutter cannot receive Paystack webhooks directly — webhooks are server-to-server HTTP requests. Build a webhook endpoint on your backend (Node.js, Django, etc.), verify the x-paystack-signature, process the event, and then notify your Flutter app via push notifications (FCM), WebSocket, or the Flutter app polling a status endpoint. The backend is the source of truth.

Webhooks Are Not for Mobile Apps

A Paystack webhook is an HTTP POST request from Paystack's servers to a URL you control. Mobile apps do not have a public IP address or domain. Paystack cannot reach your Flutter app directly.

The correct pattern:

  1. Your backend server receives the Paystack webhook
  2. Backend verifies the signature and processes the event
  3. Backend updates your database
  4. Backend notifies the Flutter app through one of three channels

Backend Webhook Handler

Your backend handles the webhook. Here is a Node.js example that also triggers a push notification:

// Node.js/Express webhook handler
var crypto = require('crypto');
var admin = require('firebase-admin'); // For FCM push notifications

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

  if (hash !== signature) {
    return res.status(400).json({ error: 'Invalid signature' });
  }

  res.sendStatus(200); // Respond immediately

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

  switch (event.event) {
    case 'charge.success':
      await handleChargeSuccess(event.data);
      break;
    default:
      console.log('Unhandled event:', event.event);
  }
});

async function handleChargeSuccess(data) {
  var reference = data.reference;
  var amount = data.amount / 100;
  var customerEmail = data.customer.email;

  // Update order in database
  var user = await db.users.findByEmail(customerEmail);

  // Push to Flutter app via FCM
  if (user && user.fcmToken) {
    await admin.messaging().send({
      token: user.fcmToken,
      notification: {
        title: 'Payment Confirmed',
        body: 'Your payment of NGN ' + amount + ' was successful',
      },
      data: {
        event: 'charge.success',
        reference: reference,
        amount: String(amount),
      },
    });
  }
}

Flutter: Handle Push Notification

// lib/main.dart
import 'package:firebase_messaging/firebase_messaging.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  // Handle background messages
  FirebaseMessaging.onBackgroundMessage(_handleBackgroundMessage);

  runApp(const MyApp());
}

Future<void> _handleBackgroundMessage(RemoteMessage message) async {
  print('Background message: ${message.data}');
}

// In your app widget
class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    _setupMessaging();
  }

  Future<void> _setupMessaging() async {
    // Get FCM token and send to backend
    var token = await FirebaseMessaging.instance.getToken();
    if (token != null) {
      await _sendTokenToBackend(token);
    }

    // Handle foreground messages
    FirebaseMessaging.onMessage.listen((message) {
      var event = message.data['event'];
      if (event == 'charge.success') {
        var reference = message.data['reference'];
        // Update UI, navigate to success screen
        _handlePaymentSuccess(reference);
      }
    });

    // Handle notification tap (app in background)
    FirebaseMessaging.onMessageOpenedApp.listen((message) {
      var event = message.data['event'];
      if (event == 'charge.success') {
        _navigateToOrderScreen();
      }
    });
  }

  Future<void> _sendTokenToBackend(String token) async {
    // Send FCM token to your backend so it can push to this device
    await http.post(
      Uri.parse('https://your-backend.com/api/users/fcm-token'),
      headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + userToken},
      body: jsonEncode({'fcm_token': token}),
    );
  }
}

Alternative: Polling from Flutter

If push notifications are not set up yet, polling is a simpler fallback. Poll your backend every few seconds while the user is on a payment-pending screen:

// Poll for payment status
Timer? _pollingTimer;

void _startPolling(String reference) {
  _pollingTimer = Timer.periodic(const Duration(seconds: 3), (timer) async {
    var status = await _checkPaymentStatus(reference);
    if (status == 'success') {
      timer.cancel();
      _navigateToSuccess();
    } else if (status == 'failed') {
      timer.cancel();
      _showFailure();
    }
    // Continue polling if status is 'pending'
  });
}

@override
void dispose() {
  _pollingTimer?.cancel();
  super.dispose();
}

Cancel the timer when the screen is disposed to avoid memory leaks.

Learn More

Key Takeaways

  • Paystack webhooks are sent to an HTTPS URL on your server. Flutter apps cannot receive them directly.
  • Build a webhook handler on your backend (Node.js, Django, Laravel, etc.) — not in Flutter.
  • After your backend processes a webhook, notify the Flutter app via FCM push notification, WebSocket, or polling.
  • Push notifications (Firebase Cloud Messaging) are the most reliable way to wake the Flutter app on payment events.
  • For in-app real-time updates (user is looking at the screen), use polling every 3-5 seconds or a WebSocket.
  • Always verify the webhook signature on your backend before pushing anything to the Flutter app.

Frequently Asked Questions

Can I receive Paystack webhooks directly in a Flutter app?
No. Webhooks require an HTTPS server with a public domain. Flutter apps run on mobile devices that do not have public IP addresses or domains. You must have a backend server to receive webhooks.
What is the simplest way to notify Flutter after a webhook?
Polling is the simplest. After checkout, poll your backend status endpoint every 3-5 seconds for up to 30 seconds. If payment success is recorded (from the webhook), show the success screen. Firebase Cloud Messaging (FCM) is more reliable but requires more setup.
Do I need Firebase to handle Paystack webhooks in Flutter?
No. Firebase is one option for push notifications. You can also use polling (simplest), WebSockets, or OneSignal for push notifications. The webhook itself is handled entirely on your backend regardless of which notification method you choose.
How do I test Paystack webhooks locally for Flutter development?
Use ngrok or Cloudflare Tunnel to expose your local backend server. Set the webhook URL in the Paystack dashboard to the tunnel URL. Your Flutter app connects to localhost or the tunnel URL. Webhooks arrive at your local server and you can debug locally.

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