Giter VIP home page Giter VIP logo

go-fcm's Introduction

go-fcm : FCM Library for Go

Firebase Cloud Messaging ( FCM ) Library using golang ( Go )

This library uses HTTP/JSON Firebase Cloud Messaging connection server protocol

Features
  • Send messages to a topic
  • Send messages to a device list
  • Message can be a notification or data payload
  • Supports condition attribute (fcm only)
  • Instace Id Features
    • Get info about app Instance
    • Subscribe app Instance to a topic
    • Batch Subscribe/Unsubscribe to/from a topic
    • Create registration tokens for APNs tokens

Usage

go get github.com/NaySoftware/go-fcm

Docs - go-fcm API

https://godoc.org/github.com/NaySoftware/go-fcm

Firebase Cloud Messaging HTTP Protocol Specs

https://firebase.google.com/docs/cloud-messaging/http-server-ref

Firebase Cloud Messaging Developer docs

https://firebase.google.com/docs/cloud-messaging/

(Google) Instance Id Server Reference

https://developers.google.com/instance-id/reference/server

Notes

a note from firebase console

Firebase Cloud Messaging tokens have replaced server keys for
sending messages. While you may continue to use them, support
is being deprecated for server keys.
Firebase Cloud Messaging token ( new token )

serverKey variable will also hold the new FCM token by Firebase Cloud Messaging

Firebase Cloud Messaging token can be found in:

  1. Firebase project settings
  2. Cloud Messaging
  3. then copy the Firebase Cloud Messaging token
Server Key

serverKey is the server key by Firebase Cloud Messaging

Server Key can be found in:

  1. Firebase project settings
  2. Cloud Messaging
  3. then copy the server key

[will be deprecated by firabase as mentioned above!]

Retry mechanism

Retry should be implemented based on the requirements. Sending a request will result with a "FcmResponseStatus" struct, which holds a detailed information based on the Firebase Response, with RetryAfter (response header) if available - with a failed request. its recommended to use a backoff time to retry the request - (if RetryAfter header is not available).

Examples

Send to A topic

package main

import (
	"fmt"
    "github.com/NaySoftware/go-fcm"
)

const (
	 serverKey = "YOUR-KEY"
     topic = "/topics/someTopic"
)

func main() {

	data := map[string]string{
		"msg": "Hello World1",
		"sum": "Happy Day",
	}

	c := fcm.NewFcmClient(serverKey)
	c.NewFcmMsgTo(topic, data)


	status, err := c.Send()


	if err == nil {
    status.PrintResults()
	} else {
		fmt.Println(err)
	}

}

Send to a list of Devices (tokens)

package main

import (
	"fmt"
    "github.com/NaySoftware/go-fcm"
)

const (
	 serverKey = "YOUR-KEY"
)

func main() {

	data := map[string]string{
		"msg": "Hello World1",
		"sum": "Happy Day",
	}

  ids := []string{
      "token1",
  }


  xds := []string{
      "token5",
      "token6",
      "token7",
  }

	c := fcm.NewFcmClient(serverKey)
    c.NewFcmRegIdsMsg(ids, data)
    c.AppendDevices(xds)

	status, err := c.Send()


	if err == nil {
    status.PrintResults()
	} else {
		fmt.Println(err)
	}

}

go-fcm's People

Contributors

07pia05 avatar betrok avatar gngeorgiev avatar naysoftware avatar

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  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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-fcm's Issues

Topic Notification returns 200 OK, but no Successes

Hello and thank you for developing this package.

I was trying to use Topic Subscription and Topic Notification, but I'm having some difficulties.

When I try to subscribe a token to a topic, fmt.Printf("Firebase response is: %v", response) returns Firebase response is: &{ [map[]] 200 OK 200}.

When then I try to send a message to that topic, response is {true 200 0 0 0 0 [] NUMERIC_CODE }.

It seems like I have messed up something in the subscription, but I don't know what.

// subscription snippet
package subscription

apiKey := "API_KEY"
topics := []string{"/topics/t1", "/topics/t2"}
tokens := []string{"token1", "token2", "token3"}
client := fcm.NewFcmClient(apiKey)
for _, topic := range topics {
  response, err := client.BatchSubscribeToTopic(tokens, topic)
  if err != nil {
  // log err
  }
}

// sending snippet
package sending

apiKey := "API_KEY"
payload := &fcm.NotificationPayload{
  Title:  "title"
  Body: "body"
}
client = fcm.NewFcmClient(apiKey)
client.SetNotificationPayload(payload)
data := map[string]string{
  "source":   "source",
  "category": "category",
}
topics := []string{"/topics/t1", "/topics/t2"}
for _, topic := range topics {
  client.NewFcmMsgTo(topic, data)
}
status, err := client.Send()
if err != nil {
  // log err
}

If I try to send the same message using NewFcmRegIdsMsg it works

// sending snippet
package sending

apiKey := "API_KEY"
payload := &fcm.NotificationPayload{
  Title:  "title"
  Body: "body"
}
client = fcm.NewFcmClient(apiKey)
client.SetNotificationPayload(payload)
data := map[string]string{
  "source":   "source",
  "category": "category",
}
tokens := []string{"token1", "token2", "token3"}
client.NewFcmRegIdsMsg(tokens, data)
status, err := client.Send()
if err != nil {
  // log err
}

Thank you for your attention

Thread safety

Hi,
quick question is this library thread safe?

Thanks

push notification timeout

thank you for the package, I have problems when using this package, when I will send a notification, sometimes it sends sometimes it timeouts, is there a solution?

Invalid Registration

I am trying to send a simple notification using your library and following you simple example.
I get Invalid Registration. I have tried many different keys from Firebase Project settings as written. But the result is always the same:
Key: AAAAVC5OXEc:APA91bE_-H82q9b4qo1Bh9COR5w3VrLz4FjTN19y-TgXsY2JVEPs2_mtJQr_xOaDFCVC-nhoaMHXV7bklcG8DVkhUFbUNaMK9-FMrii3lBwzKrLsGmlrCGtF5BSC2pVKCRLvAvm5jgxo

Status Code   : 200
Success       : 0
Fail          : 1
Canonical_ids : 0
Topic MsgId   : 0
Topic Err     : 
Result(0)> 
         error  :  InvalidRegistration

PROTOCOL ERROR

I'm trying to use your library with the sample application of posting to a topic. Every time I send a request I get a PROTOCOL_ERROR message back. Here's what I'm doing in Go

fcmClient := fcm.NewFcmClient(ApiKey)
    go func() {
        for {
            // Add ourselves into the worker queue.
            w.WorkerQueue <- w.Work

            select {
            case work := <-w.Work:
                //arr := []byte(work.Message)

                log.Println(work.Message)
                data := map[string]string{
                    "msg": work.Message,
                }
                topic := "/topics/" + work.Topic
                log.Println("Topic:", topic)
                fcmClient.NewFcmMsgTo(topic, data)
                status, err := fcmClient.Send()
                if err == nil {
                    status.PrintResults()
                } else {
                    status.PrintResults()
                    log.Println(err)
                }
                // Receive a work request.
                //log.Println("Job Received")
                //fmt.Printf("worker%d: Hello, %s!\n", w.ID, work.Name)

            case <-w.QuitChan:
                // We have been asked to stop.
                fmt.Printf("worker%d stopping\n", w.ID)
                return
            }
        }
    }()

This is what I get back:

2016/09/20 16:53:27 Post https://fcm.googleapis.com/fcm/send: stream error: stream ID 1; PROTOCOL_ERROR

I've tested my keys using curl and hand crafting the JSON to send to FCM and everything is coming back successful.

Support for FCM Token

Hello there ๐Ÿ‘‹

First of all thanks for the work you've put in this library ๐ŸŽ‰

I just noticed that on the Firebase project's setting page :

Firebase Cloud Messaging tokens have replaced server keys for sending messages. While you may continue to use them, support is being deprecated for server keys.

Would that be possible for you to add support for the FCM Tokens ?

Thanks a lot ๐Ÿ™‡

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.