reactjsfirebasegoogle-cloud-functionsreal-timesquare

Listen webhook response in react frontend app in real time


I have a webhook which is deployed on firebase cloud function and successfully listening response from squareup terminal api. Now the thing is i want to listen the same in my react front end. Because i can only view the data in firebase cloud function logs. Pleae suggest a way to listen in real time in my react app here is the code

const functions = require('firebase-functions');
const crypto = require('crypto');
const admin = require('firebase-admin');
const { WebhooksHelper } = require('square');

// The URL where event notifications are sent.
const NOTIFICATION_URL = 'https://us-central1-demo.cloudfunctions.net/webhook';

// The signature key defined for the subscription.
const SIGNATURE_KEY = 'my-signatre-key';

// Function to verify webhook signature
function isFromSquare(signature, body) {
    return WebhooksHelper.isValidWebhookEventSignature(
        body,
        signature,
        SIGNATURE_KEY,
        NOTIFICATION_URL
    )
}

// Cloud Function to handle incoming webhook requests
exports.webhookHandler = functions.https.onRequest(async (req, res) => {
    if (req.method !== 'POST') {
        return res.status(405).end('Method Not Allowed');
    }

    const body = req.rawBody.toString('utf-8');
    const signature = req.headers['x-square-hmacsha256-signature'];

    const isValidSignature = isFromSquare(signature, body)

    if (isValidSignature) {
        try {
            console.log("Webhook response saved to Firestore:", body);
            return res.status(200).json({ message: 'Request successful', data: body });
      } catch (error) {
          console.error('Error saving webhook response:', error);
          return res.status(500).end();
      }
    } else {
        // Signature is invalid. Return 403 Forbidden.
        console.error('Invalid webhook signature');
        return res.status(403).end();
    }
});

Solution

  • i want to listen the same in my react front end

    One way to do that would be to have your Cloud Function write the response from Stripe to Firestore (or the Realtime Database) and then have your React app listen to that.