我有一个部署在 firebase 云功能上的 webhook,并成功监听了 squareup 终端 api 的响应。现在的问题是我想在我的反应前端中听到同样的声音。因为我只能查看firebase云函数日志中的数据。请建议一种在我的反应应用程序中实时收听的方法,这里是代码
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();
}
});