Getting customized message from GCM using Web push notifications - web-push

I'm using Web push notifications with Chrome, and they work great. But now I want to deliver a custom message in my notifications. I can have my Service Worker call out to my site to get content, as is done at https://simple-push-demo.appspot.com/—which is fine if I want every recipient to see the same message.
Is there any way to get either the recipient’s registration_id or the message_id that GCM returns? If I could get either of these and include them in the callback to the service, I could customize the response.
Also, any info on when we might be able to include a payload in the call to GCM?

The registration_id and message_id fields aren't exposed, but if the user is previously authenticated to your app, any fetch() to the server from your Service Worker will include credentials (and session information) which you can use to identify them.
If that doesn't work for your case, you can store user/session information in IndexedDB.
Payloads are coming soon—likely Chrome 50 or 51—based on the Web Push protocol. It's a bit of extra overhead and work to configure the (required) encryption.

It's possible, but I wouldn't do it since it's specific to GCM, while other browsers use other services.
You can either create a unique ID for each user (like we're doing in Mercurius) and store it in IndexedDB, or you can use the entire endpoint URL as an ID.
Here's the snippet to get the registration_id:
self.registration.pushManager.getSubscription()
.then(function(subscription) {
if (subscription) {
var endpoint = subscription.endpoint;
var endpointParts = endpoint.split('/');
var gcmRegistrationID = endpointParts[endpointParts.length - 1];
console.log(gcmRegistrationID);
}
});
P.S.: It returns a promise, so make sure your service worker waits for the promise to be resolved.

Related

Shopify Webhook Real Time changing

is there an api on shopify where I can see real time when data changes ? Maybe I have a node server and I use sockets to see when anyone has bought anything from my shop that I get a notification via nodejs on my backend. is it possible ? a few websites has this, they offers you to sell on their site and you can see real time changes data when anything was bought
Yes, you can subscribe to multiple Webhooks to get notified when a change occurs on your shop. Using the REST Admin API, available webhook event topics include:
orders/create: occurs whenever an order is created / someone buys from your shop.
orders/paid: occurs whenever an order is paid.
orders/fulfilled: occurs whenever an order is fulfilled.
orders/cancelled: occurs whenever an order is cancelled.
Use the /admin/api/2023-01/webhooks.json endpoint to subscribe to a webhook:
// Node.js - Session is built by the OAuth process
const webhook = new shopify.rest.Webhook({session: session});
webhook.topic = "orders/create";
webhook.address = "https://example.hostname.com/";
// format you want to receive the event data in
webhook.format = "json"; // or XML
// fields you want to receive
webhook.fields = [
"id",
"note"
];
await webhook.save({
update: true,
});
You can also use the GraphQL Admin API for the same purpose.

Need help and guidance for accessing operationId in nodejs application

We are using nodejs as my backend application and react native in front end. And azure application insights for logging. In UI side, we are redirecting to Stripe checkout page(external page) for payment and then coming back to our application's confirmation page. Here we are loosing the flow on end-to-end transaction. My requirement is to link pre-stripe and post-stripe operation into one single flow. For this my approach of solving this problem is accessing OPERATIONID and pass it to stripe and receive it back from Stripe and use it in confirmation page so that we will one single flow. I Need help in guiding me to the right documentation/ solution proposals.
I read some articles(eg: How to get Application Insights operation id in javascript?) and figured out that operationId is a uniqueID which gets created out of my application and cant access it in the application. I tried to use below code and got response of that operationID as "ai.operation.id" but seems like this is not the right pattern(value) of operationId.
import { defaultClient } from 'applicationinsights';
const telemetryClient = defaultClient;
// tslint:disable-next-line:no-console
console.log(telemetryClient.context.keys[`operationId`]);
The main function of operationId is to help tracking distributed systems so you can correlate requests. So as given in this documentation in nodejs client, you should set the setDistributedTracingMode to appInsights.DistributedTracingModes.AI_AND_W3C as shown below.
const appInsights = require("applicationinsights");
appInsights
.setup("<your ikey>")
.setDistributedTracingMode(appInsights.DistributedTracingModes.AI_AND_W3C)
.start()
You should be able to get the operation id using the following code snippet.
const AppInsights = require("applicationinsights");
var context = AppInsights.getCorrelationContext();
var oid = context.operation.id;
If it does not solve your problem then, I would suggest you to set telemetry.context.operation.id to be a unique id by yourself and confirm if this is tracked by the Application Insights properly.
Also note that the latest version of the JavaScript SDK (SDK v2) for Application Insights have some changes as given in this document.
Moved context.operation to context.telemetryTrace. Some fields were also changed (operation.id --> telemetryTrace.traceID).
To keep the trace ID unique, where you previously used Util.newId(), now use Util.generateW3CId(). Both ultimately end up being the operation ID.
For more information read this log custom telemetry document.

How can I get all envelopes status and their signers status in one request?

Is it possible to call the DocuSign API with the "docusign-client"-library in order to get status information about all envelopes with all of their recipients/signers in one request?
When we call the "EnvelopesApi.ListStatusAsync" method of the docusign client library we just retrieve an array of envelopes but without the status information of their signees.
public async Task<EnvelopesInformation> GetListStatus(EnvelopeIdsRequest envelopeIds, ListStatusOptions opt) {
return await Request(async api => await api.ListStatusAsync(settings.AccountId, envelopeIds, opt));
}
It seems that this information have to be determine in second request by calling
"EnvelopesApi.ListRecipientsAsync" method for every envelope.
Maybe someone have an idea or know how to call the API properly.
Are there any options we have to consider by calling the API or do we need to configure something in the DocuSign dashboard?
Thanks!
Remarks: In our environment we can't use webhooks. So we have to poll the DocuSign API.
No, it's not possible and maybe we should understand your statement about "we can't use webhooks".
My guess is that you have firewall or some private network and you can't have calls from outside into these servers. That's not a reason not to use webhooks.
There's a simple solution to this involving an intermediary cloud account that gets your webhooks and a queue mechanism for you to check for messages.
Here is a blog post by Larry that can help if you are willing to consider webhooks.
Yes, you're right. The main reason why we can't use webhooks is because the applicationn is behind a firewall and our customer do not want to make any changes on that.
Also I know the possibility of using DouSign with services like Azure or AWS to get notification about their bus-messaging system but this is something we do not want to implement yet. Maybe in the future.
We found out that we can use the "EnvelopesApi.ListStatusChangesAsync" method to get all of the status information we're interested in.
var options = new ListStatusChangesOptions {
envelopeIds = ids,
include = "recipients"
};
var result = await client.ListStatusChangesAsync(options);

Progressive Web Application receiving data to trigger notification

Hello i'm newbie and im hardly to understand this notification in service-worker, and because my knowledge isn't good yet then probably i will unable to explain my problem clearly.
so here's the code :
// triggered everytime, when a push notification is received.
self.addEventListener('push', function(event) {
console.info('Event: Push');
var title = 'New commit on Github Repo: RIL';
var body = {
'body': 'Click to see the latest commit',
'tag': 'pwa',
'icon': './images/48x48.png'
};
event.waitUntil(
self.registration.showNotification(title, body)
);
});
this is the code that trigger to POP the notification, what I do not understand is where the argument to accept/ receive the data ?
I've been searched a lot: https://auth0.com/blog/introduction-to-progressive-web-apps-push-notifications-part-3/ ,
https://developers.google.com/web/updates/2015/03/push-notifications-on-the-open-web
there's some new data JSON or from git-server or push api, but I still hardly to understand where's to accept the data.
sorry if you still do not understand what's my problem.
Here to make it simple what I want :
Let's say i make a button, and everytime i click the button it will value as 'True' and I want that 'True' value to pass into argument and trigger the push of notication in service-worker.
2nd questions: am I able to trigger notification with header or text in html ? since we can manipulate the text with DOM ?
am I able to trigger notification without GCM, or API cause I just want a simple notification in serivce-worker like above without passing much data.
If you give more advice or maybe notification without service-worker but real time , I am surely happy to read it but I hope Im able to understand.
There are basically two concepts involved that work well together but can be used independently. The first is the visible UI shown to a user that tells them information or prompts them for an action. The second is sending an event from a server to the browser without requiring the user to currently be active on the site. For full details I recommend reading Google's Web Push docs.
Before either of those scenarios you have to request permission from the user. Once permission is granted you can just create a notification. No server or service worker required.
If you want to send events from a server you will need a service worker and you will need to get a subscription for the user. Once you have a subscription you would send it to a server for when you want to send an event to that specific browser instance.
Once you receive a push event from a server you display the UI the same as in the first scenario except you have to do it from the service worker.

Is there any way to use our own server for storage of data generated using PUBNUB api? [duplicate]

I'm looking to develop a chat application with Pubnub where I want to make sure all the chat messages that are send is been stored in the database and also want to send messages in chat.
I found out that I can use the Parse with pubnub to provide storage options, But I'm not sure how to setup those two in a way where the messages and images send in the chat are been stored in the database.
Anyone have done this before with pubnub and parse? Are there any other easy options available to use with pubnub instead of using parse?
Sutha,
What you are seeking is not a trivial solution unless you are talking about a limited number of end users. So I wouldn't say there are no "easy" solutions, but there are solutions.
The reason is your server would need to listen (subscribe) to every chat channel that is active and store the messages being sent into your database. Imagine your app scaling to 1 million users (doesn't even need to get that big, but that number should help you realize how this can get tricky to scale where several server instances are listening to channels in a non-overlapping manner or with overlap but using a server queue implementation and de-duping messages).
That said, yes, there are PubNub customers that have implemented such a solution - Parse not being the key to making this happen, by the way.
You have three basic options for implementing this:
Implement a solution that will allow many instances of your server to subscribe to all of the channels as they become active and store the messages as they come in. There are a lot of details to making this happen so if you are not up to this then this is not likely where you want to go.
There is a way to monitor all channels that become active or inactive with PubNub Presence webhooks (enable Presence on your keys). You would use this to keep a list of all channels that your server would use to pull history (enable Storage & Playback on your keys) from in an on-demand (not completely realtime) fashion.
For every channel that goes active or inactive, your server will receive these events via the REST call (and endpoint that you implement on your server - your Parse server in this case):
channel active: record "start chat" timetoken in your Parse db
channel inactive: record "end chat" timetoken in your Parse db
the inactive event is the kickoff for a process that uses start/end timetokens that you recorded for that channel to get history from for channel from PubNub: pubnub.history({channel: channelName, start:startTT, end:endTT})
you will need to iterate on this history call until you receive < 100 messages (100 is the max number of messages you can retrieve at a time)
as you retrieve these messages you will save them to your Parse db
New Presence Webhooks have been added:
We now have webhooks for all presence events: join, leave, timeout, state-change.
Finally, you could just save each message to Parse db on success of every pubnub.publish call. I am not a Parse expert and barely know all of its capabilities but I believe they have some sort or store local then sync to cloud db option (like StackMob when that was a product), but even if not, you will save msg to Parse cloud db directly.
The code would look something like this (not complete, likely errors, figure it out or ask PubNub support for details) in your JavaScript client (on the browser).
var pubnub = PUBNUB({
publish_key : your_pub_key,
subscribe_key : your_sub_key
});
var msg = ... // get the message form your UI text box or whatever
pubnub.publish({
// this is some variable you set up when you enter a chat room
channel: chat_channel,
message: msg
callback: function(event){
// DISCLAIMER: code pulled from [Parse example][4]
// but there are some object creation details
// left out here and msg object is not
// fully fleshed out in this sample code
var ChatMessage = Parse.Object.extend("ChatMessage");
var chatMsg = new ChatMessage();
chatMsg.set("message", msg);
chatMsg.set("user", uuid);
chatMsg.set("channel", chat_channel);
chatMsg.set("timetoken", event[2]);
// this ChatMessage object can be
// whatever you want it to be
chatMsg.save();
}
error: function (error) {
// Handle error here, like retry until success, for example
console.log(JSON.stringify(error));
}
});
You might even just store the entire set of publishes (on both ends of the conversation) based on time interval, number of publishes or size of total data but be careful because either user could exit the chat and the browser without notice and you will fail to save. So the per publish save is probably best practice if a bit noisy.
I hope you find one of these techniques as a means to get started in the right direction. There are details left out so I expect you will have follow up questions.
Just some other links that might be helpful:
http://blog.parse.com/learn/building-a-killer-webrtc-video-chat-app-using-pubnub-parse/
http://www.pubnub.com/blog/realtime-collaboration-sync-parse-api-pubnub/
https://www.pubnub.com/knowledge-base/discussion/293/how-do-i-publish-a-message-from-parse
And we have a PubNub Parse SDK, too. :)

Resources