Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Firebase/messaging #223

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions MessagingDoc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Iterable's Messaging Integration

Firebase Messaging Service is a powerful cloud-based messaging platform that enables developers to send notifications and messages to users across various platforms, including web, mobile, and desktop. we are offering integration of Firebase Messaging Service through Iterable's Web SDK, and allowing developers to harness the full potential of Firebase Message in their web applications.

# Installation

To install this SDK through NPM:

```
$ npm install @iterable/web-sdk
```

with yarn:

```
$ yarn add @iterable/web-sdk
```

or with a CDN:

Configure Firebase
https://support.iterable.com/hc/en-us/articles/115004760086-Web-Push-Overview-#configuring-firebase


Add firebase-messaging-sw.js file to app's public folder
https://github.com/firebase/quickstart-js/blob/master/messaging/firebase-messaging-sw.js


# Example

```ts
import { PMessaging } from '@iterable/web-sdk';

function App() {

React.useEffect(() => {
const init = async () => {
const PMObject = new PMessaging({
apiKey: "AIzaSyBQ_MAq2O-lTxq7eHGfn_H1_u9j9b0JgZU",
authDomain: "iterable-web-sdk.firebaseapp.com",
projectId: "iterable-web-sdk",
storageBucket: "iterable-web-sdk.appspot.com",
messagingSenderId: "254172754825",
appId: "1:254172754825:web:71536f92e90c2a5969e758",
vapidkey: "BKab2TK0UC8jpQRWHRVXkb58MXGMJE6KidcuUxIUIvPHME3il_JXImADp7_JKdU7ViU0TLOiu4yt_DRaMbugEoc",
});

PMObject.setUserId("user1234");

PMObject.addEventListener((data: any) => {
console.log("On-Message Triggered", data);
});
}

init();
}, []);
}
```

By passing configuration params, initialize PMessaging instance which internally create instace of firebase app and messaging module,
Listene push notifications by adding listener using PMObject.addEventListener(callback).
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
"@pabra/sortby": "^1.0.1",
"axios": "^0.21.4",
"buffer": "^6.0.3",
"firebase": "^10.0.0",
"firebase-messaging": "^1.0.6",
"idb-keyval": "^6.2.0",
"throttle-debounce": "^3.0.1",
"yup": "^0.32.9"
Expand Down Expand Up @@ -102,4 +104,4 @@
"eslint"
]
}
}
}
2 changes: 2 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ export const BASE_URL = process.env.BASE_URL || 'https://api.iterable.com/api';

export const GETMESSAGES_PATH = '/inApp/web/getMessages';

export const REGISTER_TOKEN = '/users/registerBrowserToken';

/** @todo update once new endpoint is ready */
export const CACHE_ENABLED_GETMESSAGES_PATH = '/newEndpoint';

Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ export * from './inapp';
export * from './events';
export * from './commerce';
export * from './types';
export * from './message';
export { config } from './utils/config';
1 change: 1 addition & 0 deletions src/message/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './utils';
9 changes: 9 additions & 0 deletions src/message/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export interface IMessageService {
apiKey: string;
authDomain: string;
projectId: string;
storageBucket: string;
messagingSenderId: string;
appId: string;
vapidkey: string;
}
71 changes: 71 additions & 0 deletions src/message/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { IMessageService } from './types';
import { baseIterableRequest } from '../request';
import { IterableResponse } from '../types';
import { REGISTER_TOKEN } from '../constants';
import { initializeApp } from 'firebase/app';
import type { FirebaseApp } from 'firebase/app';
import { getMessaging, getToken, onMessage } from 'firebase/messaging';
import type { Messaging } from 'firebase/messaging';

export class PMessaging {
private fireAppInstance: FirebaseApp;
private messaging: Messaging;
private listeners: Array<Function>;
private userId: string;

constructor(config: IMessageService) {
this.fireAppInstance = initializeApp(config);
this.messaging = getMessaging(this.fireAppInstance);
this.requestPermission(config.vapidkey);
this.listeners = [];
this.userId = "";

onMessage(this.messaging, (payload: any) => {
this.triggerEvent(payload);
});
}

public addEventListener(callback: Function) {
this.listeners.push(callback);
}

public setUserId(userId: string) {
this.userId = userId;
}

private triggerEvent(eventData: any) {
if (this.listeners.length) {
this.listeners.forEach((callback: Function) => callback(eventData));
}
}

private async requestPermission (vapidKey: string) {
let me = this;
Notification.requestPermission().then(async (permission) => {
if (permission === 'granted') {
const currentToken = await getToken(me.messaging, { vapidKey: vapidKey });
if (currentToken) {
await me.registerBrowserToken(currentToken);
} else {
console.warn('Failed to generate the app registration token.');
}
} else {
console.warn('User Permission Denied.');
}
});
};

private async registerBrowserToken (token: string) {
return baseIterableRequest<IterableResponse>({
method: 'POST',
url: REGISTER_TOKEN,
headers: {
"Api-Key": "1d925bbf54f34bcb92a15da14bfb5d1d"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Need to remove the hardcoded api key here from the commit history and make this use the environment variable in .env.example.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, we added the "initialize(process.env.API_KEY)" call on the example app, to add "API_KEY" for API calls, that's why we removed the static header

},
data: {
userId: this.userId,
browserToken: token
}
});
};
}
Loading
Loading