Why don't I get client.postMessage on the client? - javascript

I have this code in my service worker:
messaging.onBackgroundMessage(function (payload) {
console.log("onBackgroundMessage email and contact_link:");
console.log(payload.data.email,payload.data.contact_link);
self.clients.matchAll().then(clients => {
clients.forEach(client => client.postMessage({
msg: "This is a message from the SW",
email: payload.data.email,
contact_link: payload.data.contact_link
}));
})
});
I have this code on the client:
navigator.serviceWorker.addEventListener('message', payload => {
console.log("Message from ServiceWorker");
console.log(payload.data.msg, payload.data.email, payload.data.contact_link);
});
I get the data properly on the console from the service worker, however the client's console says all the data is undefined.
Why is that, what am I doing wrong?

I still do not know why it does not work, but I used this code on the server:
const channel = new BroadcastChannel('sw-messages');
channel.postMessage(payload.data);
And this code on the client instead:
const channel = new BroadcastChannel('sw-messages');
channel.addEventListener('message', event => {
console.log('Received:', event.data);
});
It works well.

Related

Stripe Webhook error 400 with netlify functions

I have set up payments with stripe using Netlify function by following this article https://www.netlify.com/blog/2020/04/22/automate-order-fulfillment-w/stripe-webhooks-netlify-functions/ and in my Stripe dashboard I get error saying that:
Webhook Error: No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe? https://github.com/stripe/stripe-node#webhook-signing
Now I am not sure if the user gets confirmation email, Sendgrid does not show any activity, however it has not shown any when I was testing this flow previously, and although I received confirmation email. Unfortunately back then I pressed resend by my webhook activity details in Stripe dashboard, and I am not sure if I should be resending those or do they go through. Would anyone be able to tell me what is wrong with my code?
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const sgMail = require("#sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
exports.handler = async ({ body, headers }) => {
try {
const stripeEvent = stripe.webhooks.constructEvent(
body,
headers["stripe-signature"],
process.env.STRIPE_WEBHOOK_SECRET
);
if (stripeEvent.type === "charge.succeeded") {
const emailTo = stripeEvent.data.object.billing_details.email;
const msg = {
to: emailTo,
from: process.env.FROM_EMAIL_ADDRESS,
subject: `Thanks!`,
html: `elox`,
};
await sgMail.send(msg);
}
return {
statusCode: 200,
body: JSON.stringify({ received: true }),
};
} catch (err) {
console.log(`Stripe webhook failed with ${err}`);
return {
statusCode: 400,
body: `Webhook Error: ${err.message}`,
};
}
};
Thanks!
I got the same issue.
Locally with the stripes-cli everything works fine.
It seems that the lambda didn't hand over the raw body to the stripes.webhook.constructEvent.
Therefore my solution was to change the method signature to the following and use the event.body object.
exports.handler = async(event, context ) => {
try {
const stripeEvent = stripe.webhooks.constructEvent(
event.body,
event.headers['stripe-signature'],
endpointSecret
);....

problem with emit from socket.io (server to client)

I'm having a problem with socket.io at the moment I try to send a second time from the server to the client
here is the server code with express and socket.io
io.on('connection', async function (socket) {
let socketId = socket.id;
const mta = new Client("20.64.24.144", 22005, "*", "*");
mta.resources.evokestats.getPlayerCount()
.then((result) => {
console.log("result", result);
socket.emit("players-start", { players: result })
})
.catch((err) => {
console.error(`Ooops! Something went wrong ${err}`);
});
app.post('/player_connect', async function (req, res) {
let ip = req.body[0];
let player = await players.findOne({ ip: ip })
if (player) {
await socket.emit("players", { players: req.body[1] })
} else {
try {
player = await players.create({ ip: ip, name: req.body[2] })
await socket.emit("players", { players: req.body[1] })
await socket.emit("last_24_players", { players: 1 });
} catch (error) {
console.log("error", error)
}
}
res.send("connected")
});
});
and here is my client with reactjs and socket.io
useEffect(() => {
getStats();
}, [])
async function getStats(params) {
socket.on("players-start", function (data) {
setNowPlayers(data.players)
});
socket.on("players", function (data) {
console.log("players", data)
setNowPlayers(data.players)
});});
And in my client using react, in useEffect I listen to the "players-start" and the "players" that was emit.
players-start: It is for every first time that I enter my client he only calls once, to bring all players connected
players: Every time someone connects to the game server, a post call is made to my server where I use the express with socket, in the url '/player_connect' and then immediately emit
The problem: whenever I issue an issue on 'players-start' and then immediately enter the game server that calls the url '/player_connect' it is not triggering the issue of 'players' or at least the client is not receiving.
Test I've done:
My first attempt was to stick everything to the listener "players" but it still doesn’t work
I really appreciate everyone's help.

Posting JSON request and reading EventStreams in Angular11

Tried following the article below to read eventstreams. Instead of using formData like it is done in the article, I'm using Json to post. It works smoothly with a 200 response. Even tells that some kb of data was sent over the wire, but the eventstream tab shows nothing. The same curl works on my terminal.
https://medium.com/swlh/how-do-server-sent-events-sse-or-eventsource-work-in-angular-e9e27b6a3295
As shown in the article
return Observable.create((observer) => {
const eventSource = this.sseService.getEventSourceWithPost(url, data);
// Launch query
eventSource.stream();
// on answer from message listener
eventSource.onmessage = (event) => {
this.zone.run(() => {
observer.next(event.progress);
});
};
eventSource.onerror = (error) => {
this.zone.run(() => {
observer.error(error);
});
};
});
Changing this part to
return Observable.create((observer) => {
const eventSource = this.sseService.getEventSourceWithPost(url, data);
// Launch query
eventSource.stream();
// on answer from message listener
eventSource.addEventListener('EVENT_NAME_FROM_STREAM', (event) => {
this.zone.run(() => {
observer.next(event.data);
});
};
});
Got the data to show up. But in the network tab I still don't see the events.

Firebase cloud message not sending to device

I am trying to allow users to receive push notifications if an action happened ( like, comment, etc). In the log I sometimes get sucesscount: 1 however device does not receive a notification. But most of the time it is faliurecount:1 the second time. Regardless I am not getting the push notification. When I deployed my functions there was no errors.
When I do send myself a test message from Firebase cloud messaging, that however does work correctly and sends a push notification to everyones devices successfully.
Here is observing likes for example
exports.observeLikes = functions.database.ref('/user-likes/{uid}/{postId}').onCreate((snapshot, event) => {
var uid = event.params.uid;
var postId = event.params.postId;
return admin.database().ref('/users/' + uid).once('value', snapshot => {
var userThatLikedPost = snapshot.val();
return admin.database().ref('/posts/' + postId).once('value', snapshot => {
var post = snapshot.val();
if(uid === post.ownerUid) {
return Promise.resolve();
}
return admin.database().ref('/users/' + post.ownerUid).once('value', snapshot => {
var postOwner = snapshot.val();
var payload = {
notification: {
body: userThatLikedPost.username + ' liked your post ',
sound: 'default'
}
};
admin.messaging().sendToDevice(postOwner.fcmToken, payload)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
return response;
})
.catch((error) => {
console.log('Error sending message:', error);
throw new Error('Error sending message:', error);
});
})
})
})
})
Log
So I found the issue. I deleted the app from my device and created a new account ( and it created a new FCM token for the account) and push notifications does work. I did another check and manually changed the FCM token on another device to a new one it registered with , and push notifications are successful. It appears I now need to find a way to update every current test users FCM token because their current devices aren't receiving notifications.

How to get receipt-data from Post request in Node.js

I'm trying to send a receipt to my Node.js server. At the moment It prints out the receipt-data in firebase which indicates its gotten it from the POST request I sent from my iOS App. However i can't pass properly in my code to be validated in const receipt = request.body;. How can I pass it along in the correct way?. Thanks.
exports.receiptValidation = functions.https.onRequest((request, response) => {
const receipt = request.body;
console.log(receipt);
iap.config({
applePassword: 'MySharedAppleKey',
test: true
});
iap.setup((error) => {
if (error) {
console.log('Failed to validate receipt', error);
}
});
iap.validate(receipt).then((pResponse) => {
//Check if receipt is valid
if (iap.isValidated(pResponse)) {
console.log('The receipt is valid', pResponse);
response.send(pResponse);
}
return pResponse;
})
.catch((error) => {
console.log(`Sorry couldn't validate receipt`, error);
response.send(error);
return error
});
});
Here is my output in Firebase. I'm using a firebase function
I solved it by changing my receipt-data string in both Swift and Server code
Swift
let receiptData = receipt!.base64EncodedString()
let requestReceiptDict = ["receipt": receiptData]
Node.js
const receipt = request.body.receipt;
console.log(receipt);

Categories

Resources