fcm

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2024 License: MIT Imports: 7 Imported by: 0

README

FCM Client Library

This library provides a simple interface to interact with Firebase Cloud Messaging (FCM v1) for sending notifications to devices.

Features

📲 Send messages to devices using FCM.
📢 Send messages to topics.
🔑 Set service account credentials.
🔧 Customize HTTP client for requests.

Installation

To use this library, simply import it into your Go project:

import "path/to/fcm"

Ensure you have the necessary dependencies installed:

go get -u github.com/patrickkabwe/go-fcm

Usage

Creating a New Client

To start sending messages, you need to create a new FCM client instance:

client := fcm.NewClient()
Setting Service Account Credentials

Before sending messages, set your service account credentials:

client = client.SetCredentialFile("path/to/serviceAccountKey.json")

OR

credentials := &fcm.Credentials{
    ProjectID: "your-project-id",
    PrivateKeyID: "your-private-key-id",
    PrivateKey: "yout-private-key",
    ClientEmail: "your-client-email",
    ClientID: "your-client-id",
    AuthURI: "your-auth-uri",
    TokenURI: "your-token-uri",
    AuthProviderX509CertURL: "your-auth-provider-x509-cert-url",
    ClientX509CertURL: "your-client-x509-cert-url",
}

client = client.SetCredential(credentials)
Sending a Message

To send a message, create a MessagePayload and use the Send method:

msg := &MessagePayload{
    // Populate your message payload
}
err := client.Send(msg)
if err != nil {
    log.Fatalf("Failed to send message: %v", err)
}

log.Println("Message sent successfully")
Sending a Message to a Topic

To send a message to a specific topic:

msg := &MessagePayload{
    // Populate your message payload
    Topic: "news",
}

err := client.SendToTopic(msg)
if err != nil {
    log.Fatalf("Failed to send message: %v", err)
}

log.Println("Message sent successfully")
Customizing HTTP Client

You can customize the HTTP client used for making requests:

customClient := &http.Client{Timeout: time.Second * 10}
client = client.SetHTTPClient(customClient)

Contributing

Contributions to this library are welcome. Please ensure to follow the coding standards and write tests for new features.

License

This library is licensed under the MIT License. See the LICENSE file for details.

Documentation

Overview

if err != nil {
	fmt.Println(err)
	t.Error("Expected no error")
}

}

Index

Constants

View Source
const (
	FCM_V1_URL = "https://fcm.googleapis.com/v1/projects/%s/messages:send"
	SCOPES     = "https://www.googleapis.com/auth/firebase.messaging"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type APNAlert

type APNAlert struct {
	Title        string `json:"title,omitempty"`
	Subtitle     string `json:"subtitle,omitempty"`
	Body         string `json:"body,omitempty"`
	TitleLocKey  string `json:"title-loc-key,omitempty"`
	TitleLocArgs string `json:"title-loc-args,omitempty"`
	ActionLocKey string `json:"action-loc-key,omitempty"`
	LocKey       string `json:"loc-key,omitempty"`
	LocArgs      string `json:"loc-args,omitempty"`
	LaunchImage  string `json:"launch-image,omitempty"`
}

type APNS

type APNS struct {
	Alert            APNAlert `json:"alert,omitempty"`
	Badge            int      `json:"badge,omitempty"`
	Sound            string   `json:"sound,omitempty"`
	ContentAvailable int      `json:"content_available,omitempty"`
	ThreadID         string   `json:"thread_id,omitempty"`
	Category         string   `json:"category,omitempty"`
}

type APNSConfig

type APNSConfig struct {
	Headers map[string]string `json:"headers,omitempty"`
	Payload APNSPayload       `json:"payload,omitempty"`
}

type APNSFcmOptions

type APNSFcmOptions struct {
	AnalyticsLabel string `json:"analytics_label,omitempty"`
	Image          string `json:"image,omitempty"`
}

type APNSPayload

type APNSPayload struct {
	Aps APNS `json:"aps,omitempty"`
}

type AndroidConfig

type AndroidConfig struct {
	CollapseKey           string            `json:"collapse_key,omitempty"`
	Priority              string            `json:"priority,omitempty"`
	Ttl                   string            `json:"ttl,omitempty"`
	RestrictedPackageName string            `json:"restricted_package_name,omitempty"`
	Data                  map[string]string `json:"data,omitempty"`
	Notification          Notification      `json:"notification,omitempty"`
	FcmOptions            map[string]string `json:"fcm_options,omitempty"`
	DirectBootOk          bool              `json:"direct_boot_ok,omitempty"`
}

type Credentials added in v1.2.0

type Credentials struct {
	Type                    string `json:"type,omitempty"`
	ProjectID               string `json:"project_id,omitempty"`
	PrivateKeyID            string `json:"private_key_id,omitempty"`
	PrivateKey              string `json:"private_key,omitempty"`
	ClientEmail             string `json:"client_email,omitempty"`
	ClientID                string `json:"client_id,omitempty"`
	AuthURI                 string `json:"auth_uri,omitempty"`
	TokenURI                string `json:"token_uri,omitempty"`
	AuthProviderX509CertURL string `json:"auth_provider_x509_cert_url,omitempty"`
	ClientX509CertURL       string `json:"client_x509_cert_url,omitempty"`
}

Credentials represents the service account credentials required to authenticate with the FCM server.

func (*Credentials) Validate added in v1.2.0

func (c *Credentials) Validate() error

Validate checks if the required fields are set in the credentials.

type FCMClient

type FCMClient struct {
	// contains filtered or unexported fields
}

FCMClient represents a client for interacting with the Firebase Cloud Messaging (FCM) service.

func NewClient

func NewClient() *FCMClient

NewClient creates a new FCMClient instance with the default HTTP client. This uses the new version of FCM API (v1) to send messages to devices.

func (*FCMClient) Send

func (f *FCMClient) Send(msg *MessagePayload) error

Send sends the given message payload to the FCM server. It returns an error if the API call fails.

func (*FCMClient) SendAll added in v1.0.0

func (f *FCMClient) SendAll(msg *MessagePayload) error

SendAll sends a message payload to all the provided tokens. It returns an error if no tokens are provided or if there is an issue making the API call. Create a list containing up to 500 messages.

func (*FCMClient) SendToCondition

func (f *FCMClient) SendToCondition(msg *MessagePayload) error

SendToCondition sends a message payload to a specific condition. It returns an error if the condition is empty or if there is an error making the API call.

func (*FCMClient) SendToMultiple

func (f *FCMClient) SendToMultiple(msg *MessagePayload) error

SendToMultiple sends a message payload to multiple FCM tokens. It returns an error if no tokens are provided or if there is an issue making the API call.

func (*FCMClient) SendToTopic

func (f *FCMClient) SendToTopic(msg *MessagePayload) error

SendToTopic sends a message payload to a specific topic. It returns an error if the topic is empty or if there was an error making the API call.

func (*FCMClient) SetCredentialFile added in v1.2.0

func (f *FCMClient) SetCredentialFile(serviceAccountFilePath string) *FCMClient

SetCredentialFile sets the service account credentials for the FCM client by reading the credentials from the specified file path. It returns the modified FCMClient instance. If the service account file is not found or there is an error parsing the file, it will panic with an appropriate error message.

func (*FCMClient) SetCredentials added in v1.2.0

func (f *FCMClient) SetCredentials(credentials *Credentials) *FCMClient

SetCredentials sets the service account credentials for the FCM client.

func (*FCMClient) SetHTTPClient added in v1.2.0

func (f *FCMClient) SetHTTPClient(httpClient HttpClient) *FCMClient

SetHTTPClient sets the HTTP client to be used by the FCM client. It allows you to customize the HTTP client used for making requests to the FCM server. The provided httpClient should implement the HttpClient interface. Returns the FCM client itself to allow for method chaining.

type HttpClient

type HttpClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HttpClient is an interface that represents an HTTP client.

type Message

type Message struct {
	Token        string            `json:"token,omitempty"`
	Tokens       []string          `json:"tokens,omitempty"`
	Topic        string            `json:"topic,omitempty"`
	Notification Notification      `json:"notification,omitempty"`
	Data         map[string]string `json:"data,omitempty"`
	Android      AndroidConfig     `json:"android,omitempty"`
	Webpush      WebpushConfig     `json:"webpush,omitempty"`
	APNS         APNSConfig        `json:"apns,omitempty"`
	Condition    string            `json:"condition,omitempty"`
}

type MessagePayload

type MessagePayload struct {
	Message Message `json:"message,omitempty"`
}

type Notification

type Notification struct {
	Title                string `json:"title,omitempty"`
	Body                 string `json:"body,omitempty"`
	Image                string `json:"image,omitempty"`
	Icon                 string `json:"icon,omitempty"`
	Sound                string `json:"sound,omitempty"`
	Tag                  string `json:"tag,omitempty"`
	Color                string `json:"color,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"`
	NotificationPriority string `json:"notification_priority,omitempty"`
}

type WebpushConfig

type WebpushConfig struct {
	Headers      map[string]string `json:"headers,omitempty"`
	Data         map[string]string `json:"data,omitempty"`
	Notification Notification      `json:"notification,omitempty"`
	FcmOptions   map[string]string `json:"fcm_options,omitempty"`
}

Jump to

Keyboard shortcuts

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