Download the PHP package specialist/yii2-fcm-both-api without Composer

On this page you can find all versions of the php package specialist/yii2-fcm-both-api. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package yii2-fcm-both-api

yii2-fcm-both-api

Yii2 Extension for sending push notification with both Firebase Cloud Messaging (FCM) HTTP Server Protocols (APIs).

Latest Stable Version Total Downloads Build Status

This extension supports sending push notification through both currently supported FCM API versions:

Note: The XMPP protocol is not currently supported.

Installation

The preferred way to install this extension is through composer. Check the composer.json for this extension's requirements and dependencies.

To install, either run

or add

to the require section of your composer.json file.

Configuration

In order to use this library, you have to configure the Fcm class in your application configuration.

For ApiV1:

privateKey - used to authenticate the service account and authorize it to access Firebase services. You must generate a private key file in JSON format and use this key to retrieve a short-lived OAuth 2.0 token. privateKey can be set with json-file '/path/to/your/file/privateKeyFile.json' or simply with json-string '{"type":"service_account"}'

For Legacy API:

serverKey - a server key that authorizes your app server for access to Google services, including sending messages via the Firebase Cloud Messaging legacy protocols. You obtain the server key when you create your Firebase project. You can view it in the Cloud Messaging tab of the Firebase console Settings pane.

senderId - a unique numerical value created when you create your Firebase project, available in the Cloud Messaging tab of the Firebase console Settings pane. The sender ID is used to identify each sender that can send messages to the client app.

Also add this to your Yii.php file in the root directory of the project for IDE code autocompletion.
Now you can get access to extension's methods through:
In order to use both HTTP v1 and legacy API at the same time, you need to register them separately:

Now you can use Yii::$app->fcmApiV1 when need APIV1 and Yii::$app->fcmLegacyApi for legacy one.

Basic Usage

N.B. The main thing about this library is to be used in queues, so we tried to balance between OOP and low amount of objects used.

APIv1

The APIv1 part of extension can send:

  1. A message to a specific token (device).
  2. A message to a given topic.
  3. A message to several topics by condition.

A message can contain:

  1. Two types of messages: Notification messages and Data messages (both are optional).
  2. Their combination.
  3. Target platform specific configuration.
Send push-notification to a single token (device)

You need to have a registration token for the target device. Registration tokens are strings generated by the client FCM SDKs. Each of the Firebase client SDKs are able to generate these registration tokens: iOS, Android, Web. In order to sent push to the single token you need to use setTarget(\specialist\fcm\source\builders\apiV1\MessageOptionsBuilder::TOKEN, 'your_token') method with \specialist\fcm\source\builders\apiV1\MessageOptionsBuilder::TOKEN constant:

Send push-notification to a topic

Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.

To (un)subscribe devices to a topic look for Topic management section below

For example, users of a local weather forecasting app could opt in to a “severe weather alerts” topic and receive notifications of storms threatening specified areas. Users of a sports app could subscribe to automatic updates in live game scores for their favorite teams.

The main things to keep in mind about topics:

In order to sent push to the topic you need to use setTarget(\specialist\fcm\source\builders\apiV1\MessageOptionsBuilder::TOPIC, 'your_token') method with \specialist\fcm\source\builders\apiV1\MessageOptionsBuilder::TOPIC constant:

Send push-notification to a combination of topics by condition

The condition is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to 'TopicA' and either 'TopicB' or 'TopicC':

FCM first evaluates any conditions in parentheses, and then evaluates the expression from left to right. In the above expression, a user subscribed to any single topic does not receive the message. Likewise, a user who does not subscribe to TopicA does not receive the message. These combinations do receive it:

In order to sent push to the several topics by condition you need to use setTarget(\aksafan\fcm\source\builders\apiV1\MessageOptionsBuilder::TOPIC_CONDITION, 'your_token') method with \specialist\fcm\source\builders\apiV1\MessageOptionsBuilder::TOPIC_CONDITION constant:

Send push-notification with only 'Data' message type.
Send push-notification with only 'Notification' message type.
Send push-notification with both 'Notification' and 'Data' message type.
Send push-notification without 'Notification' and 'Data' message type.
Send push-notification with platform specific configuration.
Android config:
APNs config:
Web-push config:
All together config:

N.B. Pay attention that platform specific config will replace the general one.

In example above Android client will receive this notification info:

and NOT this:

Handling response.

After sending the request to FCM you will get an instance of \specialist\fcm\source\responses\apiV1\TokenResponse.

If the result is OK you can get raw message from FCM in format - projects/your_project_id/messages/message_id:

or only the message ID in format - message_id:

If something has happened, you can get error description with the information about the problem:

Also tokens, that should be deleted from your DB, if the problem was with invalid tokens:

As well as the technical information from FCM:

Validating messages (dry run mode).

You can validate a message by sending a validation-only request to the Firebase REST API.

If the message is invalid, you will receive info in error description:

If it is valid, you will get fake_message - projects/your_project_id/messages/fake_message_id:

Legacy API

The Legacy API part of extension can send:

  1. A message to a specific token (device).
  2. A message to a several tokens (devices).
  3. A message to device group.
  4. A message to a given topic.
  5. A message to several topics by condition.

A message can contain:

  1. Two types of messages: Notification messages and Data messages (both are optional).
  2. Their combination.
  3. Target platform specific configuration.

Note: Legacy HTTP Server Protocol is still under support, is used by many people and is not in trouble of being deprecated, but Google aimed us to use HTTP v1 API.

Send push-notification to a single token (device)

You need to have a registration token for the target device. Registration tokens are strings generated by the client FCM SDKs. Each of the Firebase client SDKs are able to generate these registration tokens: iOS, Android, Web.

In order to sent push to the single token you need to use setTarget(\specialist\fcm\source\builders\legacyApi\MessageOptionsBuilder::TOKEN, 'your_token') method with \specialist\fcm\source\builders\legacyApi\MessageOptionsBuilder::TOKEN constant:

Send push-notification to multiple tokens (devices)

Max amount of tokens in one request is 1000. In order to sent push to the single token you need to use setTarget(\specialist\fcm\source\builders\legacyApi\MessageOptionsBuilder::TOKENS, ['your_token_1', 'your_token_2', 'your_token_3']) method with \specialist\fcm\source\builders\legacyApi\MessageOptionsBuilder::TOKENS constant:

Send push-notification to a topic

Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.

For example, users of a local weather forecasting app could opt in to a “severe weather alerts” topic and receive notifications of storms threatening specified areas. Users of a sports app could subscribe to automatic updates in live game scores for their favorite teams.

The main things to keep in mind about topics:

In order to sent push to the topic you need to use setTarget(\specialist\fcm\source\builders\legacyApi\MessageOptionsBuilder::TOPIC, 'your_token') method with \specialist\fcm\source\builders\legacyApi\MessageOptionsBuilder::TOPIC constant and createRequest(\specialist\fcm\source\builders\StaticBuilderFactory::FOR_TOPIC_SENDING) with \specialist\fcm\source\builders\StaticBuilderFactory::FOR_TOPIC_SENDING constant:

Send push-notification to a combination of topics by condition

The condition is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to 'TopicA' and either 'TopicB' or 'TopicC':

FCM first evaluates any conditions in parentheses, and then evaluates the expression from left to right. In the above expression, a user subscribed to any single topic does not receive the message. Likewise, a user who does not subscribe to TopicA does not receive the message. These combinations do receive it:

In order to sent push to the several topics by condition you need to use setTarget(\specialist\fcm\source\builders\legacyApi\MessageOptionsBuilder::TOPIC_CONDITION, 'your_token') method with \specialist\fcm\source\builders\legacyApi\MessageOptionsBuilder::TOPIC_CONDITION constant: and createRequest(\specialist\fcm\source\builders\StaticBuilderFactory::FOR_TOPIC_SENDING) with \specialist\fcm\source\builders\StaticBuilderFactory::FOR_TOPIC_SENDING constant:

Send push-notification to a group of tokens (devices)

FCM device groups allows you to send a message to multiple devices that have opted in to a particular group. You compose group of devices as needed, and FCM handles routing and delivering the message reliably to the right devices.

In order to sent push to the topic you need to use setTarget(\specialist\fcm\source\builders\legacyApi\MessageOptionsBuilder::GROUP, 'your_notification_key') method with \specialist\fcm\source\builders\legacyApi\MessageOptionsBuilder::GROUP constant: and createRequest(\specialist\fcm\source\builders\StaticBuilderFactory::FOR_GROUP_SENDING) with \specialist\fcm\source\builders\StaticBuilderFactory::FOR_GROUP_SENDING constant:

Send push-notification with only 'Data' message type.
Send push-notification with only 'Notification' message type.
Send push-notification with both 'Notification' and 'Data' message type.
Send push-notification without 'Notification' and 'Data' message type.
Send push-notification with platform specific configuration.
Android config:
APNs config:
Web-push config:
All together config.

You can set additional configurations with these methods:

All together can be:

N.B. Pay attention that platform specific configuration will replace the general one and repeating from other platform configurations (shortage in legacy API version), one by one in order:

In example above any client will receive this notification info:

and NOT all mentioned.

Handling response.

After sending the request to FCM you will get an instance of these:

For sending push-messages to single (multiply) token(s):

If the result is OK you can get the message ID in format - message_id:

You can see the number of successfully sent messages:

The number of failed attempts:

The number of device that you need to modify their token:

If something has happened, you can get error description with the information about the problem:

List of common errors and info about handling them for legacy API is here

Also tokens, that should be deleted from your DB as invalid ones:

Tokens, that should be changed in your storage - ['oldToken' => 'newToken']:

Tokens, that should be resend. You should to use exponential backoff to retry sending:

Time to retry after if it was in response headers:

Tokens, that have errors. You should check these tokens in order to delete broken ones:

For sending push-messages to topic or topics by condition:

If the result is OK you can get the message ID in format - message_id:

If something has happened, you can get error description with the information about the problem:

And error message:

For sending push-messages to device group:

If the result is OK you can get the number of tokens successfully sent messages to:

The number of tokens unsuccessfully sent messages to:

If the server attempts to send a message to a device group that has no members, the response will be with 0 success and 0 failure.

If something has happened, you can get error description with the information about the problem:

And an array of tokens failed:

When a message fails to be delivered to one or more of the registration tokens associated with a notification_key, the app server should retry with backoff between retries.

Validating messages (dry run mode).

You can validate a message by sending a validation-only request to the Firebase REST API.

If the message is invalid, you will receive info in error description:

If it is valid, you will get fake_message - -1:

Device group management.

There are three main definitions here:

The groupName and notificationKey are unique to a group of registration tokens. It is important that groupName is unique per client app if you have multiple client apps for the same sender ID. This ensures that messages only go to the intended target app.

Optionally, Android client apps can manage device groups from the client side.

Create group:

To create a device group, you need to use createGroup(string $groupName, array $tokens) method with a name for the group and a list of registration tokens for the devices. Also creating request with \specialist\fcm\source\builders\StaticBuilderFactory::FOR_GROUP_MANAGEMENT argument.

After sending the request to FCM you will get an instance of \specialist\fcm\source\responses\legacyApi\GroupManagementResponse.

FCM returns a new notificationKey that represents the device group. Save it and the corresponding groupName to use in subsequent operations.

If there was an error, you will receive info in error description:

N.B. You can add to group up to 1,000 devices in a single request. If you provide an array with over 1,000 registration tokens, the request will fail with an InvalidArgumentException.

Retrieve notificationKey from a group:

If you need to retrieve an existing notificationKey, you need to use getNotificationKey(string $groupName) method with a name for the group. Also creating request with \specialist\fcm\source\builders\StaticBuilderFactory::FOR_GROUP_MANAGEMENT argument.

After sending the request to FCM you will get an instance of \specialist\fcm\source\responses\legacyApi\GroupManagementResponse.

FCM returns the notificationKey that represents the device group.

If there was an error, you will receive info in error description:

Note: Notification_key_name is not required for adding/removing registration tokens, but including it protects you against accidentally using the incorrect notification_key. In order to be safe, current extension make you use groupName always.

Add token(s) to group:

You can add tokens to device group passing registration tokens to the addToGroup(string $groupName, string $notificationKey, array $tokens) method and creating request with \specialist\fcm\source\builders\StaticBuilderFactory::FOR_GROUP_MANAGEMENT argument:

After sending the request to FCM you will get an instance of \specialist\fcm\source\responses\legacyApi\GroupManagementResponse.

FCM returns a new notificationKey that represents the device group.

If there was an error, you will receive info in error description:

Remove token(s) from group:

You can add tokens to device group passing registration tokens to the removeFromGroup(string $groupName, string $notificationKey, array $tokens) method and creating request with \specialist\fcm\source\builders\StaticBuilderFactory::FOR_GROUP_MANAGEMENT argument:

After sending the request to FCM you will get an instance of \specialist\fcm\source\responses\legacyApi\GroupManagementResponse.

FCM returns a new notificationKey that represents the device group.

If there was an error, you will receive info in error description:

If you remove all existing registration tokens from a device group, FCM deletes the device group.

Topic management.

Note: You can (un)subscribe to (from) topic through both API versions, just chose your favorite and configure it properly.

Subscribe to a topic:

You can subscribe one or multiple devices to a topic by passing registration tokens to the subscribeToTopic(string $topic, array $tokens) method and creating request with \specialist\fcm\source\builders\StaticBuilderFactory::FOR_TOPIC_MANAGEMENT argument:

N.B. You can subscribe up to 1,000 devices in a single request. If you provide an array with over 1,000 registration tokens, the request will fail with an InvalidArgumentException.

After sending the request to FCM you will get an instance of \specialist\fcm\source\responses\TopicSubscribeResponse. Now you can grab tokens with errors:

This is an array of tokens with their correspondents errors in format:

All other tokens were subscribed correctly.

Unsubscribe from a topic:

You can unubscribe one or multiple devices to a topic by passing registration tokens to the unsubscribeFromTopic(string $topic, array $tokens) method and creating request with \specialist\fcm\source\builders\StaticBuilderFactory::FOR_TOPIC_MANAGEMENT argument:

N.B. You can unsubscribe up to 1,000 devices in a single request. If you provide an array with over 1,000 registration tokens, the request will fail with a messaging/invalid-argument error.

After sending the request to FCM you will get an instance of \specialist\fcm\source\responses\TopicSubscribeResponse. Now you can grab tokens with errors:

This is an array of tokens with their correspondents errors in format:

All other tokens were unsubscribed correctly.

Logging

This extension uses native Yii2 error logger through \Yii::error(). List of used error categories can be found here specialist\fcm\source\helpers\ErrorsHelper::LOGS_ERRORS.

License

Copyright 2022 by Specialist001.

Available under the MIT license.

Complete FCM documentation can be found here Firebase Cloud Messaging.


All versions of yii2-fcm-both-api with dependencies

PHP Build Version
Package Version
Requires php Version >=7.0
yiisoft/yii2 Version ~2.0.6
guzzlehttp/guzzle Version ^6.0
google/auth Version ^1.2.1
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package specialist/yii2-fcm-both-api contains the following files

Loading the files please wait ....