Git Product home page Git Product logo

fcm-notification's Introduction

The fcm plugin for push notificaton on Android, ios and web.

fcm-notification

New reliesed of firebase team with admin.messaging() to send push notification to iOS, Android and web, March 21, 2018.

Usage

We tried to make this plugin as user (developer) friendly as possible, but if anything is unclear, please submit any questions as issues on GitHub: https://github.com/smartnav/fcm-notification/issues

###Install from NPM

$ npm install fcm-notification --save

Examples

**Before starting you need to download privatekey.json file from ** This link

Check Steps:

  • Go Choose a project to continue to the Firebase console - If already have then click on it otherwise create new one.
  • Go to Service account tab and generate new private key (In node.js)
  • Add this file in your project's workspace
  • Import that file with a require('path/to/privatekey.json') style call and pass the object to the FCM constructor

Start:

Send to single token

var fcm = require('fcm-notification');
var FCM = new fcm('path/to/privatekey.json');
var token = 'token here';

	var message = {
		data: {    //This is only optional, you can send any data
			score: '850',
			time: '2:45'
		},
		notification:{
			title : 'Title of notification',
			body : 'Body of notification'
		},
		token : token
		};

FCM.send(message, function(err, response) {
    if(err){
        console.log('error found', err);
    }else {
        console.log('response here', response);
    }
})

Send to multiple tokens

var fcm = require('fcm-notification');
var Tokens = [ 'token1 here', '....', 'token n here'];
var FCM = new fcm('path/to/privatekey.json');

var message = {
  data: {
    score: '850',
    time: '2:45'
  },
  notification:{
    title : 'Navish',
    body : 'Test message by navish'
  }
};
FCM.sendToMultipleToken(message, Tokens, function(err, response) {
    if(err){
        console.log('err--', err);
    }else {
        console.log('response-----', response);
    }

})

Send to a topic

FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. But before this we need to subscribe to topic.

Subscribe to topic

var fcm = require('fcm-notification');
var FCM = new fcm('path/to/privatekey.json');
var tokens =[ 'token1 here', '....', 'token n here'];

FCM.subscribeToTopic(tokens, 'TopicName', function(err, response) {
    if(err){
        console.log('error found', err);
    }else {
        console.log('response here', response);
    }
})

Unsubscribe to topic

var fcm = require('fcm-notification');
var FCM = new fcm('path/to/privatekey.json');
var tokens =[ 'token1 here', '....', 'token n here'];

FCM.unsubscribeFromTopic(tokens, 'TopicName', function(err, response) {
    if(err){
        console.log('error found', err);
    }else {
        console.log('response here', response);
    }
})

Send push to topic

var fcm = require('fcm-notification');
var FCM = new fcm('path/to/privatekey.json');
var TopicName = 'TopicName';


var message = {
  data: {
    score: '850',
    time: '2:45'
  },
  notification:{
    title : 'Title name',
    body : 'Test body..'
  },
  topic: TopicName
};
FCM.send(message, function(err, response) {
    if(err){
        console.log('error found', err);
    }else {
        console.log('response here', response);
    }
})

Send push to multiple topics

var fcm = require('fcm-notification');
var FCM = new fcm('path/to/privatekey.json');
var Topics = ['Topic one',  '..',  'Topic n'];


var message = {
	  data: {
			score: '850',
			time: '2:45'
	  },
	  notification:{
			title : 'Title name',
			body : 'Test body..'
	  }
};
FCM.sendToMultipleTopic(message, Topics,  function(err, response) {
    if(err){
        console.log('error found', err);
    }else {
        console.log('response here', response);
    }
})

Defining the message

It is possible to set android, apns, webpush and notification fields on the same message. FCM service will take all specified parameters into account and customize the message for each platform. However, a message must contain exactly one of the token, topic or condition fields. It is an error to specify zero or multiple fields.

Android-specific fields

var message = {
  android: {
    ttl: 3600 * 1000, // 1 hour in milliseconds
    priority: 'normal',
    notification: {
      title: '$GOOG up 1.43% on the day',
      body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
      icon: 'stock_ticker_update',
      color: '#f45342'
    }
  },
  topic: 'TopicName'
};

APNS-specific fields (IOS)

var message = {
  android: {
    ttl: 3600 * 1000, // 1 hour in milliseconds
    priority: 'normal',
    notification: {
      title: '$GOOG up 1.43% on the day',
      body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
      icon: 'stock_ticker_update',
      color: '#f45342'
    }
  },
  topic: 'TopicName'
};

WebPush-specific fields

var message = {
  webpush: {
    notification: {
      title: '$GOOG up 1.43% on the day',
      body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
      icon: 'https://my-server/icon.png'
    }
  },
  topic: 'TopicName'
};

Putting it all together

A message may contain configuration parameters for multiple device platforms. This means it is possible to include android, apns and webpush fields in the same message. The FCM service customizes the message for each target platform when delivering. The following example shows how a notification has been customized for Android and iOS platforms:

var message = {
  notification: {
    title: '$GOOG up 1.43% on the day',
    body: '$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
  },
  android: {
    ttl: 3600 * 1000,
    notification: {
      icon: 'stock_ticker_update',
      color: '#f45342',
    },
  },
  apns: {
    payload: {
      aps: {
        badge: 42,
      },
    },
  },
  topic: 'TopicName'
};

In the same vein, it is possible include both data and notification fields in the same message.

License

MIT

fcm-notification's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

fcm-notification's Issues

Dead?

Is this repository unmaintained?

firebase-admin is in v9.11 and package.json is using v5.11.0 and I am having problems with that, because it uses a deprecated version of gRPC in firestore/google-gax

npm ERR! command failed

When I run npm i fcm-notification I get this error
"npm ERR! path C:\d\solify-server\node_modules\grpc
npm ERR! command failed
npm ERR! command C:\Windows\system32\cmd.exe /d /s /c node-pre-gyp install --fallback-to-build --library=static_library
npm ERR! Failed to execute 'C:\Program Files\nodejs\node.exe C:\Users\babek\AppData\Roaming\nvm\v18.17.1\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js configure --fallback-to-build --library=static_library --module=C:\d\solify-server\node_modules\grpc\src\node\extension_binary\node-v108-win32-x64-unknown\grpc_node.node --module_name=grpc_node --module_path=C:\d\solify-server\node_modules\grpc\src\node\extension_binary\node-v108-win32-x64-unknown --napi_version=9 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v108' (1)
npm ERR! node-pre-gyp info it worked if it ends with ok
npm ERR! node-pre-gyp info using [email protected]
npm ERR! node-pre-gyp info using [email protected] | win32 | x64
npm ERR! node-pre-gyp info check checked for "C:\d\solify-server\node_modules\grpc\src\node\extension_binary\node-v108-win32-x64-unknown\grpc_node.node" (not found)
npm ERR! node-pre-gyp http GET https://node-precompiled-binaries.grpc.io/grpc/v1.24.11/node-v108-win32-x64-unknown.tar.gz
npm ERR! node-pre-gyp ERR! install response status 404 Not Found on https://node-precompiled-binaries.grpc.io/grpc/v1.24.11/node-v108-win32-x64-unknown.tar.gz
npm ERR! node-pre-gyp WARN Pre-built binaries not installable for [email protected] and [email protected] (node-v108 ABI, unknown) (falling back to source compile with node-gyp)
npm ERR! node-pre-gyp WARN Hit error response status 404 Not Found on https://node-precompiled-binaries.grpc.io/grpc/v1.24.11/node-v108-win32-x64-unknown.tar.gz
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using [email protected]
npm ERR! gyp info using [email protected] | win32 | x64
npm ERR! gyp info ok
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using [email protected]
npm ERR! gyp info using [email protected] | win32 | x64
npm ERR! gyp info find Python using Python version 3.11.4 found at "C:\Users\babek\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\python.exe"
npm ERR! gyp http GET https://nodejs.org/download/release/v18.17.1/node-v18.17.1-headers.tar.gz
npm ERR! gyp http 200 https://nodejs.org/download/release/v18.17.1/node-v18.17.1-headers.tar.gz
npm ERR! gyp http GET https://nodejs.org/download/release/v18.17.1/SHASUMS256.txt
npm ERR! gyp http GET https://nodejs.org/download/release/v18.17.1/win-x86/node.lib
npm ERR! gyp http GET https://nodejs.org/download/release/v18.17.1/win-x64/node.lib
npm ERR! gyp http GET https://nodejs.org/download/release/v18.17.1/win-arm64/node.lib
npm ERR! gyp http 200 https://nodejs.org/download/release/v18.17.1/SHASUMS256.txt
npm ERR! gyp http 404 https://nodejs.org/download/release/v18.17.1/win-arm64/node.lib
npm ERR! gyp http 200 https://nodejs.org/download/release/v18.17.1/win-x64/node.lib
npm ERR! gyp http 200 https://nodejs.org/download/release/v18.17.1/win-x86/node.lib
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS msvs_version not set from command line or npm config
npm ERR! gyp ERR! find VS VCINSTALLDIR not set, not running in VS Command Prompt
npm ERR! gyp ERR! find VS could not use PowerShell to find Visual Studio 2017 or newer, try re-running with '--loglevel silly'
for more details
npm ERR! gyp ERR! find VS looking for Visual Studio 2015
npm ERR! gyp ERR! find VS - not found
npm ERR! gyp ERR! find VS not looking for VS2013 as it is only supported up to Node.js 8
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS You need to install the latest version of Visual Studio
npm ERR! gyp ERR! find VS including the "Desktop development with C++" workload.
npm ERR! gyp ERR! find VS For more information consult the documentation at:
npm ERR! gyp ERR! find VS https://github.com/nodejs/node-gyp#on-windows
npm ERR! gyp ERR! find VS **************************************************************
npm ERR! gyp ERR! find VS
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Could not find any Visual Studio installation to use
npm ERR! gyp ERR! stack at VisualStudioFinder.fail (C:\Users\babek\AppData\Roaming\nvm\v18.17.1\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:122:47)
npm ERR! gyp ERR! stack at C:\Users\babek\AppData\Roaming\nvm\v18.17.1\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:75:16
npm ERR! gyp ERR! stack at VisualStudioFinder.findVisualStudio2013 (C:\Users\babek\AppData\Roaming\nvm\v18.17.1\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:369:14)
npm ERR! gyp ERR! stack at C:\Users\babek\AppData\Roaming\nvm\v18.17.1\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:71:14
npm ERR! gyp ERR! stack at C:\Users\babek\AppData\Roaming\nvm\v18.17.1\node_modules\npm\node_modules\node-gyp\lib\find-visualstudio.js:390:16
npm ERR! gyp ERR! stack at C:\Users\babek\AppData\Roaming\nvm\v18.17.1\node_modules\npm\node_modules\node-gyp\lib\util.js:54:7
npm ERR! gyp ERR! stack at C:\Users\babek\AppData\Roaming\nvm\v18.17.1\node_modules\npm\node_modules\node-gyp\lib\util.js:33:16
npm ERR! gyp ERR! stack at ChildProcess.exithandler (node:child_process:427:5)
npm ERR! gyp ERR! stack at ChildProcess.emit (node:events:514:28)
npm ERR! gyp ERR! stack at maybeClose (node:internal/child_process:1091:16)
npm ERR! gyp ERR! System Windows_NT 10.0.19045
npm ERR! gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\babek\AppData\Roaming\nvm\v18.17.1\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "configure" "--fallback-to-build" "--library=static_library" "--module=C:\d\solify-server\node_modules\grpc\src\node\extension_binary\node-v108-win32-x64-unknown\grpc_node.node" "--module_name=grpc_node" "--module_path=C:\d\solify-server\node_modules\grpc\src\node\extension_binary\node-v108-win32-x64-unknown" "--napi_version=9" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v108"
npm ERR! gyp ERR! cwd C:\d\solify-server\node_modules\grpc
npm ERR! gyp ERR! node -v v18.17.1
npm ERR! gyp ERR! node-gyp -v v9.3.1
npm ERR! gyp ERR! not ok
npm ERR! node-pre-gyp ERR! build error
npm ERR! node-pre-gyp ERR! stack Error: Failed to execute 'C:\Program Files\nodejs\node.exe C:\Users\babek\AppData\Roaming\nvm\v18.17.1\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js configure --fallback-to-build --library=static_library --module=C:\d\solify-server\node_modules\grpc\src\node\extension_binary\node-v108-win32-x64-unknown\grpc_node.node --module_name=grpc_node --module_path=C:\d\solify-server\node_modules\grpc\src\node\extension_binary\node-v108-win32-x64-unknown --napi_version=9 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v108' (1)
npm ERR! node-pre-gyp ERR! stack at ChildProcess. (C:\d\solify-server\node_moduleshttps://github.com/mapbox\node-pre-gyp\lib\util\compile.js:89:23)
npm ERR! node-pre-gyp ERR! stack at ChildProcess.emit (node:events:514:28)
npm ERR! node-pre-gyp ERR! stack at maybeClose (node:internal/child_process:1091:16)
npm ERR! node-pre-gyp ERR! stack at ChildProcess._handle.onexit (node:internal/child_process:302:5)
npm ERR! node-pre-gyp ERR! System Windows_NT 10.0.19045
npm ERR! node-pre-gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\d\solify-server\node_modules@mapbox\node-pre-gyp\bin\node-pre-gyp" "install" "--fallback-to-build" "--library=static_library"
npm ERR! node-pre-gyp ERR! cwd C:\d\solify-server\node_modules\grpc
npm ERR! node-pre-gyp ERR! node -v v18.17.1
npm ERR! node-pre-gyp ERR! node-pre-gyp -v v1.0.11
npm ERR! node-pre-gyp ERR! not ok

npm ERR! A complete log of this run can be found in: C:\Users\babek\AppData\Local\npm-cache_logs\2023-08-19T11_05_09_822Z-debug-0.log"

while installing at production level we face issue reported below

when in try to install and run the command as
npm install fcm-notification --save

below issue reported

node-pre-gyp WARN Using needle for node-pre-gyp https download
node-pre-gyp ERR! UNCAUGHT EXCEPTION
node-pre-gyp ERR! stack TypeError: Object https://node-precompiled-binaries.grpc.io/grpc/v1.24.2/node-v11-linux-x64-glibc.tar.gz has no method 'startsWith'
node-pre-gyp ERR! stack at /usr/id-multiple-city-core-api/node_modules/fcm-notification/node_modules/firebase-admin/node_modules/@google-cloud/firestore/node_modules/google-gax/node_modules/grpc/node_modules/node-pre-gyp/lib/install.js:263:45
node-pre-gyp ERR! stack at /usr/id-multiple-city-core-api/node_modules/fcm-notification/node_modules/firebase-admin/node_modules/@google-cloud/firestore/node_modules/google-gax/node_modules/grpc/node_modules/mkdirp/index.js:30:20
node-pre-gyp ERR! stack at Object.oncomplete (fs.js:108:15)
node-pre-gyp ERR! System Linux 3.10.0-327.36.1.el7.x86_64
node-pre-gyp ERR! command "node" "/usr/id-multiple-city-core-api/node_modules/fcm-notification/node_modules/firebase-admin/node_modules/@google-cloud/firestore/node_modules/google-gax/node_modules/grpc/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build" "--library=static_library"
node-pre-gyp ERR! cwd /usr/id-multiple-city-core-api/node_modules/fcm-notification/node_modules/firebase-admin/node_modules/@google-cloud/firestore/node_modules/google-gax/node_modules/grpc
node-pre-gyp ERR! node -v v0.10.46
node-pre-gyp ERR! node-pre-gyp -v v0.14.0
node-pre-gyp ERR! This is a bug in node-pre-gyp.
node-pre-gyp ERR! Try to update node-pre-gyp and file an issue if it does not help:
node-pre-gyp ERR! https://github.com/mapbox/node-pre-gyp/issues
npm ERR! Linux 3.10.0-327.36.1.el7.x86_64
npm ERR! argv "/usr/bin/node" "/bin/npm" "install" "fcm-notification" "--save"
npm ERR! node v0.10.46
npm ERR! npm v2.15.1
npm ERR! code ELIFECYCLE

npm ERR! [email protected] install: node-pre-gyp install --fallback-to-build --library=static_library
npm ERR! Exit status 7
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-pre-gyp install --fallback-to-build --library=static_library'.
npm ERR! This is most likely a problem with the grpc package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-pre-gyp install --fallback-to-build --library=static_library
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs grpc
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!
npm ERR! npm owner ls grpc
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR! /usr/id-multiple-city-core-api/npm-debug.log
any solution??? thanks in advance

Hey Is there a way i can add server key in the request

const admin = require('firebase-admin')
const fcm = require('fcm-notification')

// For Notification
const serviceAccount = require('../../firebase/push-notification-key.json')

const certPath = admin.credential.cert(serviceAccount)
//here goes my server key
const FCM = new fcm(certPath, { legacyServerKey: config.FIREBASE_SERVER_KEY }))

const Helper = {}



Helper.pushNotification = async (notificationTitle, notificationBody, notificationData, fcm_token) => {

  try {
    let message = {
      notification: {
        title: notificationTitle,
        body: notificationBody
      },
      data: {productId: notificationData},
      token: fcm_token
    }



    FCM.send(message, (err) => {
      if (err) {
        return err
      }
      else {
        return err
      }
    })
  } catch (err) {
    return err
  }

}
```  this is my code 

BUG

Hey,

When i use the function "send", all is good. I have the message "Successfully sent message..." but the problem is that my function not stopping.

fcm.send(message, function (err, response) {
if (err) {
console.log('ERREUUUUURRR ', err);
} else {
console.log('Notification envoyé à : ', response);
return
}
return
})

i try to return it but nothing append, my script is still running . Can you help me please ?

Firebase App already exists

i'm using this package in adonis js and i use the code below:

const FCM = require('fcm-notification');
class NotificationController {
async send({request,response}){
const data = request.only(['api_key', 'login_tokens', 'title','body']);
let login_tokens = data.login_tokens;
let fcm_tokens = new Array();
login_tokens.forEach(async function(login_token){
fcm_token = await Notification.findBy('login_token',login_token);
fcm_tokens.push(fcm_token);
});
let message = {
notification:{
title : data.title,
body : data.body
}
}
const fcm = new FCM('./private-key.json');
return fcm;
fcm.sendMultipleToken(message,fcm_tokens,function(err,response){
if(err){
console.log('err:\n',err);
}else{
console.log('response:\n',response);
}
});
}
}
`
and i receive below error:
The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.

Error sending message

I am trying to send a simple FCM notification to Android devices using sendToMultipleToken(). It always returns response like:
[{ "response": "Error sending message:", "token": "dc9x65gKLLo:APA91bFnku__06dRI7CHjaMLy1A9a4ixzu.........." }]

Update dependencies

High Server-Side Request Forgery

Package axios

Patched in >=0.21.1

Dependency of fcm-notification

Path fcm-notification > firebase-admin > @google-cloud/firestore
> @google-cloud/common > axios

More info https://npmjs.com/advisories/1594

It'll only take a sec :)

problem in npm install fcm-notification --save

when i excute npm install fcm-notification --save
Downloaded vs_BuildTools.exe. Saved to C:\Users\harme.windows-build-tools\vs_BuildTools.exe.
npm ERR!
npm ERR! Starting installation...
npm ERR! Downloading installers failed. Error: TypeError: 'process.env' only accepts a configurable, writable, and enumerable data descriptor
npm ERR! at Function.defineProperty ()
npm ERR! at Object.removePath (C:\Users\harme\AppData\Roaming\npm\node_modules\windows-build-tools\dist\utils\remove-path.js:11:12)
npm ERR! at Object.install (C:\Users\harme\AppData\Roaming\npm\node_modules\windows-build-tools\dist\install\index.js:29:19)
npm ERR! at C:\Users\harme\AppData\Roaming\npm\node_modules\windows-build-tools\dist\start.js:17:19
npm ERR! at Object.download (C:\Users\harme\AppData\Roaming\npm\node_modules\windows-build-tools\dist\download.js:35:5)
npm ERR! at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
npm ERR! at async Object.aquireInstallers (C:\Users\harme\AppData\Roaming\npm\node_modules\windows-build-tools\dist\aquire-installers.js:32:13) {
npm ERR! code: 'ERR_INVALID_OBJECT_DEFINE_PROPERTY'
npm ERR! }
npm ERR! windows-build-tools will now exit.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\harme\AppData\Local\npm-cache_logs\2023-06-19T21_38_30_081Z-debug-0.log

Icon Configuration

Hi guys,
How to configure lib to send notification with icons?
Thanks for help

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.