I am trying to set up push notifications with strongloop. I don't understand which file the code below lives in. The docs don't say, which is confusing for newbies.
I understand that I have to add a push component to loopback restful api application, which I have done. But how do I reference the push component from my restful api app? Where's the 'glue'?
http://docs.strongloop.com/display/public/LB/Push+notifications
var badge = 1;
app.post('/notify/:id', function (req, res, next) {
var note = new Notification({
expirationInterval: 3600, // Expires 1 hour from now.
badge: badge++,
sound: 'ping.aiff',
alert: '\uD83D\uDCE7 \u2709 ' + 'Hello',
messageFrom: 'Ray'
});
PushModel.notifyById(req.params.id, note, function(err) {
if (err) {
// let the default error handling middleware
// report the error in an appropriate way
return next(err);
}
console.log('pushing notification to %j', req.params.id);
res.send(200, 'OK');
});
});
This should live in the app.js file as seen in the example here:
https://github.com/strongloop/loopback-component-push/blob/master/example/server/app.js#L137-L145
Related
I'm building an app for shopify and need to add the GDPR webhooks. My back end is handled using next.js and I'm writing a webhook handler to verify them. The docs havent been very helpful because they dont show how to do it with node. This is my verification function.
export function verifiedShopifyWebhookHandler(
next: (req, res, body) => Promise
): NextApiHandler {
return async (req, res) => {
const hmacHeader = req.headers['x-shopify-hmac-sha256'];
const rawBody = await getRawBody(req);
const digest = crypto.createHmac('sha256', process.env.SHOPIFY_API_SECRET).update(rawBody).digest('base64');
if (digest === hmacHeader) {
return next(req, res, rawBody);
}
const webhookId = req.headers['x-shopify-webhook-id'];
return res.status(401).end();
};
}
But I get this Error: error - InternalServerError: stream is not readable
I think it has to do with now Next.js parses the incoming requests before they are sent to my api. Any ideas?
I discovered the answer. Next.js was pre parsing the body in the context which made it so that I couldn't use the raw body parser to parse it. By setting this:
export const config = {
api: {
bodyParser: false
}
};
above the api function in the api file it prevented next from parsing it and causing the issue. I found the answer because people had the same issue integrating swipe and using the bodyParser.
I'm trying to make an app that can send payments to PayBill numbers with Safaricom's "Lipa Na M-Pesa" (a Kenyan thing). The call is a POST request to URL:
https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest
with header:
{
'Host': 'sandbox.safaricom.co.ke',
'Authorization': 'Bearer ${await mpesaAccessToken}',
'Content-Type': 'application/json',
}
and body:
{
"BusinessShortCode": "$businessShortCode",
"Password": "${generateLnmPassword(timeStamp)}",
"Timestamp": "$timeStamp",
"TransactionType": "CustomerPayBillOnline",
"Amount": "10",
"PartyA": "$userPhoneNumber",
"PartyB": "$businessShortCode",
"PhoneNumber": "$userPhoneNumber",
"CallBackURL": "?????????????????????????????",
"AccountReference": "account",
"TransactionDesc": "test",
}
I've received an access token, generated a password and made the call successfully, except for that CallBackURL thing... The M-Pesa docs describe their callback like this:
CallBackURL
This is the endpoint where you want the results of the transaction delivered. Same rules for Register URL API callbacks apply.
all API callbacks from transactional requests are POST requests, do not expect GET requests for callbacks. Also, the data is not formatted into application/x-www-form-urlencoded format, it is application/json, so do not expect the data in the usual POST fields/variables of your language, read the results directly from the incoming input stream.
(More info here, but you may need to be logged in: https://developer.safaricom.co.ke/get-started see "Lipa na M-Pesa")
My app is hosted on Firebase Cloud Firestore. Is there any way I can create a callback URL with them that will receive their callback as a document in a Firestore collection?...
Or would this be impossible, given that they would need authorization tokens and stuff to do so... and I can't influence what headers and body M-Pesa will send?
(PS Btw, I code in Flutter/Dart so plz don't answer in Javascript or anything! I'll be clueless... :p Flutter/Dart or just plain text will be fine. Thanks!)
Is there any way I can create a callback URL with them that will
receive their callback as a document in a Firestore collection?...
The most common way to do that in the Firebase ecosystem is to write an HTTPS Cloud Function that will be called by the Safaricom service.
Within the Cloud Function you will be able to update the Firestore document, based on the content of the POST request.
Something like:
exports.safaricom = functions.https.onRequest((req, res) => {
// Get the header and body through the req variable
// See https://firebase.google.com/docs/functions/http-events#read_values_from_the_request
return admin.firestore().collection('...').doc('...').update({ foo: bar })
.then(() => {
res.status(200).send("OK");
})
.catch(error => {
// ...
// See https://www.youtube.com/watch?v=7IkUgCLr5oA&t=1s&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=3
})
});
I did note that you ask us to not "answer in Javascript or anything" but in Flutter/Dart, but I don't think you will able to implement that in Flutter: you need to implement this webhook in an environment that you fully control and that exposes an API endpoint, like your own server or a Cloud Function.
Cloud Functions may seem complex at first sight, but implementing an HTTPS Cloud Functions is not that complicated. I suggest you read the Get Started documentation and watch the three videos about "JavaScript Promises" from the Firebase video series, and if you encounter any problem, ask a new question on SO.
Cloud functions are not Dart-based.
See below solution;
const functions = require("firebase-functions");
const admin = require("firebase-admin");
const parse = require("./parse");
admin.initializeApp();
exports.lmno_callback_url = functions.https.onRequest(async (req, res) => {
const callbackData = req.body.Body.stkCallback;
const parsedData = parse(callbackData);
let lmnoResponse = admin.firestore().collection('lmno_responses').doc('/' + parsedData.checkoutRequestID + '/');
let transaction = admin.firestore().collection('transactions').doc('/' + parsedData.checkoutRequestID + '/');
let wallets = admin.firestore().collection('wallets');
if ((await lmnoResponse.get()).exists) {
await lmnoResponse.update(parsedData);
} else {
await lmnoResponse.set(parsedData);
}
if ((await transaction.get()).exists) {
await transaction.update({
'amount': parsedData.amount,
'confirmed': true
});
} else {
await transaction.set({
'moneyType': 'money',
'type': 'deposit',
'amount': parsedData.amount,
'confirmed': true
});
}
let walletId = await transaction.get().then(value => value.data().toUserId);
let wallet = wallets.doc('/' + walletId + '/');
if ((await wallet.get()).exists) {
let balance = await wallet.get().then(value => value.data().moneyBalance);
await wallet.update({
'moneyBalance': parsedData.amount + balance
})
} else {
await wallet.set({
'moneyBalance': parsedData.amount
})
}
res.send("Completed");
});
Parse function.
const moment = require("moment");
function parse(responseData) {
const parsedData = {};
parsedData.merchantRequestID = responseData.MerchantRequestID;
parsedData.checkoutRequestID = responseData.CheckoutRequestID;
parsedData.resultDesc = responseData.ResultDesc;
parsedData.resultCode = responseData.ResultCode;
if (parsedData.resultCode === 0) {
responseData.CallbackMetadata.Item.forEach(element => {
switch (element.Name) {
case "Amount":
parsedData.amount = element.Value;
break;
case "MpesaReceiptNumber":
parsedData.mpesaReceiptNumber = element.Value;
break;
case "TransactionDate":
parsedData.transactionDate = moment(
element.Value,
"YYYYMMDDhhmmss"
).unix();
break;
case "PhoneNumber":
parsedData.phoneNumber = element.Value;
break;
}
});
}
return parsedData;
}
module.exports = parse;
I am integrating Huawei Push Kit (https://pub.dev/packages/huawei_push) in Flutter application.
I test to schedule a notification to notify every minutes in my Huawei phone, and I able to get the notification as expected. But when I tried to cancel the notification with clearNotification() function (shown below), the notification seem like not cancelled. Wondering do I miss out anything?
scheduleLocalNotification() async {
try {
Map<String, dynamic> localNotification = {
HMSLocalNotificationAttr.TITLE: 'Notification Title',
HMSLocalNotificationAttr.MESSAGE: 'Notification Message',
HMSLocalNotificationAttr.TICKER: "OptionalTicker",
HMSLocalNotificationAttr.TAG: "push-tag",
HMSLocalNotificationAttr.BIG_TEXT: 'This is a bigText',
HMSLocalNotificationAttr.SUB_TEXT: 'This is a subText',
HMSLocalNotificationAttr.LARGE_ICON: 'ic_launcher',
HMSLocalNotificationAttr.SMALL_ICON: 'ic_notification',
HMSLocalNotificationAttr.COLOR: "white",
HMSLocalNotificationAttr.VIBRATE: true,
HMSLocalNotificationAttr.VIBRATE_DURATION: 1000.0,
HMSLocalNotificationAttr.ONGOING: false,
HMSLocalNotificationAttr.DONT_NOTIFY_IN_FOREGROUND: false,
HMSLocalNotificationAttr.AUTO_CANCEL: false,
HMSLocalNotificationAttr.INVOKE_APP: false,
HMSLocalNotificationAttr.ACTIONS: ["Yes", "No"],
HMSLocalNotificationAttr.REPEAT_TYPE: RepeatType.MINUTE,
HMSLocalNotificationAttr.FIRE_DATE:
DateTime.now().add(Duration(minutes: 1)).millisecondsSinceEpoch,
};
Map<String, dynamic> response =
await Push.localNotificationSchedule(localNotification);
print("Scheduled a local notification: " + response.toString());
} catch (e) {
print("Error: " + e.toString());
}
}
clearNotification() async {
Push.cancelNotificationsWithTag('push-tag');
}
Currently, Huawei Push Kit does not support clearNotification() function. You can use the Sending Downlink Messages API. There is an auto_clear parameter, and you can set message display duration, in milliseconds. Messages are automatically deleted after the duration expires.
Please refer to the following code:
{
"validate_only": false,
"message": {
"android": {
"notification":{"body":"Big Boom Body!","click_action":{"type":3},"title":"Big Boom Title","auto_clear": 360000}
},
"token":[
"token1",
"token2"]
}
}
For more information, see docs
Your clearNotification function which calls Push.cancelNotificationWithTag('push-tag') is async.
Possibility is Push.cancelNotificationWithTag might get called before.
Either call it directly and not thru async function or add await.
I am prototyping browser push notifications with FCM. I just copied the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging). Messages are recieved and displayed as they should be. But when I try to modify the message in the Service Worker (messaging.setBackgroundMessageHandler) nothing happens. The service worker is called, and if I implement an event listener in that service worker for the push notifications, it catches the event. But the method setBackgroundMessageHandler is never called.
I am trying this on Chrome 54.
Any ideas what I need to do to customize the message in the service worker?
Thank you very much!
For anyone experiencing the same problem, here is the answer: https://github.com/firebase/quickstart-js/issues/71
short summary: do not include a "notification" element in your json message.
This is a solution that worked for me in a webapp. It displays the notification with title and body text along with an image and handles the user click.
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
// Initialize Firebase
var config = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
databaseURL: 'YOUR_DB_URL',
projectId: 'YOUR_PROJ_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_SENDER_ID',
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('Handling background message ', payload);
return self.registration.showNotification(payload.data.title, {
body: payload.data.body,
icon: payload.data.icon,
tag: payload.data.tag,
data: payload.data.link,
});
});
self.addEventListener('notificationclick', function (event) {
event.notification.close();
event.waitUntil(self.clients.openWindow(event.notification.data));
});
JSON Message
{
"message": {
"token": "YOUR_TARGET_APP_TOKEN",
"data": {
"title": "FCM Message",
"body": "This is an FCM Message",
"icon": "https://shortcut-test2.s3.amazonaws.com/uploads/role_image/attachment/10461/thumb_image.jpg",
"link": "https://yourapp.com/somewhere"
}
}
}
As mentioned by others, including notification in the payload stops it working on the web JS SDK, however you need it present for it to work in native apps.
The workaround I found for the web was to use the web browser native EH push to handle the event manually:
https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/onpush
self.addEventListener('notificationclick', function(event) {
console.log('SW: Clicked notification', event)
let data = event.notification.data
event.notification.close()
self.clients.openWindow(event.notification.data.link)
})
self.addEventListener('push', event => {
let data = {}
if (event.data) {
data = event.data.json()
}
console.log('SW: Push received', data)
if (data.notification && data.notification.title) {
self.registration.showNotification(data.notification.title, {
body: data.notification.body,
icon: 'https://example.com/img/icons/icon-144x144.png',
data
})
} else {
console.log('SW: No notification payload, not showing notification')
}
})
When you try to send a push message are you doing it while your app is on focus or not? Because from the documentation, it says that setBackgroundMessageHandler is only called when the Web app is closed or not in browser focus.
Based on the example code from the quickstart (https://github.com/firebase/quickstart-js/tree/master/messaging).
If your app is in focus: the push message is received via messaging.onMessage() on the index.html
If your app does not have focus : the push message is received via setBackgroundMessageHandler() on teh service worker file.
I'm using the Firebase node module and trying to convert it's callbacks to thunks to be able to use them in Koa.
This is the original event listener callback as per the Firebase documentation:
projects.on('value', function (snapshot) {
console.log('The read succeeded: ' + snapshot.val());
}, function (errorObject) {
console.log('The read failed: ' + errorObject.code);
});
And this is the where I want to add it in my Koa project:
function *list() {
// Get the data here and set it to the projects var
this.body = yield render('list', { projects: projects });
}
Anyone know how to to do it? Have tried thunkify, thunker and thu without success...
I don't think you can use thunkify etc because they are trying to convert a standard node function to a thunk. The firebase api doesn't follow the standard node.js callback signature of
fn(param1, parm2,.., function(err, result){});
which thunkify is expecting.
I think this would do it
var findProjectsByValue = function(value){
return function(callback){
projects.on(value, function(result){
callback(null, result);
}, function(err){
callback(err);
})
}
};
then you would consume it
var projects = yield findProjectsByValue('value');
Or you could just do rest api calls, which I assume is what you want. The firebase api seems to be more for evented scenarios, socketio etc