fcm

package module
v0.0.0-...-3ff4f9c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 18, 2022 License: MIT Imports: 8 Imported by: 0

README

Firebase Cloud Messaging

Golang client library for Firebase Cloud Messaging. It uses Firebase Cloud Messaging HTTP protocol: https://firebase.google.com/docs/cloud-messaging/http-server-ref.

Note: It is using legacy HTTP Server Protocol

This project is forking from

Getting Started

$ go get github.com/dulabs/go-fcm

Send message


package main

import (
	"log"

	"github.com/dulabs/go-fcm"
)

func main() {
    // Create a client
    client, err := fcm.NewClient("your-api-key", "your-server-key")

	if err != nil {
		log.Fatalln(err)
	}

    // New message
    message := &fcm.Message{
        To: "device-token-or-topic", // /topics/topic-name
        Notification: &fcm.Notification{
            Title: "Title",
            Body:  "Body",
        },
    }

    // Send the message
    resp, err := client.Send(message)
    if err != nil {
        log.Fatalln(err)
    }

    log.Printf("%#v\n", resp)
}

Subscribe

// Subscribe
err := client.SubscribeToTopic([]string{"device-token"}, "/topics/test-topic-name")

// Unsubscribe
err = client.UnsubscribeFromTopic([]string{"device-token"}, "/topics/test-topic-name")

Device Info

// Get device info
info, err := client.GetDeviceInfo("device-token")
if err != nil {
    fmt.Println(info)
}

Documentation

Overview

Golang client library for Firebase Cloud Messaging. It uses Firebase Cloud Messaging HTTP protocol: https://firebase.google.com/docs/cloud-messaging/http-server-ref.

Index

Constants

View Source
const (
	// DefaultTimeout duration in second
	DefaultTimeout time.Duration = 30 * time.Second

	API_SEND_MESSAGE = "https://fcm.googleapis.com/fcm/send"

	API_APP_INSTANCE = "https://iid.googleapis.com/iid/info/%s?details=true"

	API_USER_LOOKUP = "https://identitytoolkit.googleapis.com/v1/accounts:lookup?key=%s"

	API_TOPIC_BATCH_ADD = "https://iid.googleapis.com/iid/v1:batchAdd"

	API_TOPIC_BATCH_REMOVE = "https://iid.googleapis.com/iid/v1:batchRemove"
)

Variables

View Source
var (
	// ErrInvalidAPIKey occurs if API key is not set.
	ErrInvalidAPIKey = errors.New("client API Key is invalid")

	ErrInvalidServerKey = errors.New("client Server Key is invalid")
)
View Source
var (
	// ErrInvalidMessage occurs if push notitication message is nil.
	ErrInvalidMessage = errors.New("message is invalid")

	// ErrInvalidTarget occurs if message topic is empty.
	ErrInvalidTarget = errors.New("topic is invalid or registration ids are not set")

	// ErrToManyRegIDs occurs when registration ids more then 1000.
	ErrToManyRegIDs = errors.New("too many registrations ids")

	// ErrInvalidTimeToLive occurs if TimeToLive more then 2419200.
	ErrInvalidTimeToLive = errors.New("messages time-to-live is invalid")
)

Functions

This section is empty.

Types

type Client

type Client struct {
	// API key
	ApiKey string
	// Server key
	// Firebase console > Project Settings > Cloud Messaging > Server key
	ServerKey string
	// contains filtered or unexported fields
}

func NewClient

func NewClient(apiKey, serverKey string, opts ...Option) (*Client, error)

func (*Client) GetUser

func (c *Client) GetUser(token string) (*User, error)

Get user info

https://firebase.google.com/docs/reference/rest/auth

func (*Client) Send

func (c *Client) Send(message *Message) (*MessageResponse, error)

Send sends a Message to Firebase Cloud Messaging.

The Message must specify exactly one of Token, Topic and Condition fields. FCM will customize the message for each target platform based on the arguments specified in the Message. Use Legacy HTTP Server Protocol

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

func (*Client) SubscribeToTopic

func (c *Client) SubscribeToTopic(tokens []string, topic string) error

SubscribeToTopic subscribes a list of registration tokens to a topic. The tokens list must not be empty, and have at most 1000 tokens.

func (*Client) UnsubscribeFromTopic

func (c *Client) UnsubscribeFromTopic(tokens []string, topic string) error

UnsubscribeFromTopic unsubscribes a list of registration tokens from a topic. The tokens list must not be empty, and have at most 1000 tokens.

type DeviceInfoResponse

type DeviceInfoResponse struct {
	ApplicationVersion string       `json:"applicationVersion,omitempty"`
	ConnectDate        string       `json:"connectDate,omitempty"`
	Application        string       `json:"application,omitempty"`
	Scope              string       `json:"scope,omitempty"`
	AuthorizedEntity   string       `json:"authorizedEntity,omitempty"`
	ConnectionType     string       `json:"connectionType,omitempty"`
	Platform           string       `json:"platform,omitempty"`
	Rel                Relationship `json:"rel,omitempty"`
}

type LookupUserResponse

type LookupUserResponse struct {
	Kind  string `json:"kind,omitempty"`
	Users []User `json:"users,omitempty"`
}

type Message

type Message struct {

	// Targets
	To              string   `json:"to,omitempty"`
	RegistrationIds []string `json:"registration_ids,omitempty"`
	Condition       string   `json:"condition,omitempty"`

	// Options
	CollapseKey           string `json:"collapse_key,omitempty"`
	Priority              string `json:"priority,omitempty"`
	ContentAvailable      bool   `json:"content_available,omitempty"`
	MutableContent        bool   `json:"mutable_content,omitempty"`
	DelayWhileIdle        bool   `json:"delay_while_idle,omitempty"`
	TimeToLive            *uint  `json:"time_to_live,omitempty"`
	RestrictedPackageName string `json:"restricted_package_name,omitempty"`
	DryRun                bool   `json:"dry_run,omitempty"`

	// Payload
	Data         map[string]string      `json:"data,omitempty"`
	Notification *Notification          `json:"notification,omitempty"`
	Apns         map[string]interface{} `json:"apns,omitempty"`
	Webpush      map[string]interface{} `json:"webpush,omitempty"`
}

Downstream HTTP messages (JSON)

https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream-http-messages-json

func (*Message) Validate

func (msg *Message) Validate() error

Validate returns an error if the message is not well-formed.

type MessageResponse

type MessageResponse struct {
	// Message
	MulticastId int64                   `bson:"multicast_id,omitempty" json:"multicast_id,omitempty"`
	Success     int                     `bson:"success,omitempty" json:"success,omitempty"`
	Failure     int                     `bson:"failure,omitempty" json:"failure,omitempty"`
	Results     []MessageResponseResult `bson:"results,omitempty" json:"results,omitempty"`

	// Topic
	TopicMessageResponse
}

Downstream HTTP message response body (JSON). Include topic message HTTP response body.

type MessageResponseResult

type MessageResponseResult struct {
	MessageId      string `bson:"message_id,omitempty" json:"message_id,omitempty"`
	RegistrationId string `bson:"registration_id,omitempty" json:"registration_id,omitempty"`
	Error          string `bson:"error,omitempty" json:"error,omitempty"`
}

type Notification

type Notification struct {
	Title        string   `json:"title,omitempty"`
	Body         string   `json:"body,omitempty"`
	Sound        string   `json:"sound,omitempty"`
	ClickAction  string   `json:"click_action,omitempty"`
	BodyLocKey   string   `json:"body_loc_key,omitempty"`
	BodyLocArgs  []string `json:"body_loc_args,omitempty"`
	TitleLocKey  string   `json:"title_loc_key,omitempty"`
	TitleLocArgs []string `json:"title_loc_args,omitempty"`

	/// iOS only
	Subtitle string `json:"subtitle,omitempty"`
	Badge    string `json:"badge,omitempty"`

	/// Android only
	AndroidChannelId string `json:"android_channel_id,omitempty"`
	Icon             string `json:"icon,omitempty"`
	Tag              string `json:"tag,omitempty"`
	Color            string `json:"color,omitempty"`
}

type Option

type Option func(*Client) error

Option configurates Client with defined option.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout returns Option to configure HTTP Client timeout.

type ProviderInfo

type ProviderInfo struct {
	ProviderId  string `json:"providerId,omitempty"`
	DisplayName string `json:"displayName,omitempty"`
	PhotoUrl    string `json:"photoUrl,omitempty"`
	Email       string `json:"email,omitempty"`
}

type RelDate

type RelDate struct {
	AddDate string `json:"addDate,omitempty"`
}

type Relationship

type Relationship struct {
	Topics map[string]RelDate `json:"topics,omitempty"`
}

type TopicMessageResponse

type TopicMessageResponse struct {
	MessageId int64  `bson:"message_id,omitempty" json:"message_id,omitempty"`
	Error     string `bson:"error,omitempty" json:"error,omitempty"`
}

Topic message HTTP response body (JSON)

type TopicSubscribe

type TopicSubscribe struct {
	To                 string   `bson:"to,omitempty" json:"to,omitempty"`
	RegistrationTokens []string `bson:"registration_tokens,omitempty" json:"registration_tokens,omitempty"`
}

type User

type User struct {
	LocalId       string `json:"localId,omitempty"`
	PhoneNumber   string `json:"phoneNumber,omitempty"`
	Email         string `json:"email,omitempty"`
	EmailVerified bool   `json:"emailVerified,omitempty"`
	DisplayName   string `json:"displayName,omitempty"`
	PhotoUrl      string `json:"photoUrl,omitempty"`
	ValidSince    string `json:"validSince,omitempty"`
	Disabled      string `json:"disabled,omitempty"`
	LastLoginAt   string `json:"lastLoginAt,omitempty"`
	CreatedAt     string `json:"createdAt,omitempty"`

	ProviderUserInfo []ProviderInfo `json:"providerUserInfo,omitempty"`
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL