Publish to a specific User

Beams allows you to send notifications to individual users of your application via their user ID (whatever ID you use in your system). You can do this by associating users with their devices using the Authenticated Users feature.

Overview

Incorporating Authenticated Users into your application is a four step process:

  1. Create an endpoint in your server that returns Beams Tokens to your users
  2. Set up a TokenProvider in your mobile app that the Beams SDK can use to request the token from your server
  3. Call the setUserId method in your mobile app after the user logs in and clearAllState when they log out
  4. Use one of our server SDKs to send notifications to your users.

Creating a Beams auth endpoint

Before we allow devices to get access to notifications sent to a particular user, we require that they send us a Beams Token. To facilitate this you will need to set up an endpoint on your server that can verify that the device belongs to the requested user and return a Beams Token generated using one of our server SDKs.

How do I get the user ID?
You should determine the ID of the user being authenticated by using your existing authorization system. By default, the SDK will include the user ID as a query parameter (user_id) — you can use this to validate that the session is associated with the correct user. However, you shouldn't solely rely on this parameter for production use.

The BeamsTokenProvider will perform a GET request and expects the response to be JSON.

  • PHP
  • Go
  • Node.js
  • python
  • Java

PHP (Laravel)

1
2
3
4
5
6
7
8
9
10
11
Route::middleware('auth:api')->get('/pusher/beams-auth', function (Request $request) {
    $userID = $request->user()->id; // If you use a different auth system, do your checks here
    $userIDinQueryParam = Input::get('user_id');

    if ($userID != $userIDinQueryParam) {
        return response('Inconsistent request', 401);
    } else {
        $beamsToken = $beamsClient->generateToken($userID);
        return response()->json($beamsToken);
    }
});

Setting up a TokenProvider

Once you have created a Beams auth endpoint you need to setup the Beams client SDK so that it can request a Beams Token from that endpoint. You can do this by creating a BeamsTokenProvider instance.

What is a BeamsTokenProvider?
When the Beams SDK tries to authenticate a device it will verify the user's identity by requesting a Beams Token from your application backend. The SDK will do this using the BeamsTokenProvider that you pass to setUserId. The BeamsTokenProvider must have access to the data needed to authenticate with your application backend. It gets this data using an AuthData callback.

What is an AuthData callback?
Your application backend will need certain values from the client to authenticate requests in the Beams auth endpoint created above. Your AuthData callback is responsible for retreiving these values and putting them in the headers/query parameters required by your application backend. For example, you may want to put your application session token into an auth header.

Android

  • Kotlin
  • Java

Android (Kotlin)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
val tokenProvider = BeamsTokenProvider(
    "<YOUR_BEAMS_AUTH_URL_HERE>",
    object: AuthDataGetter {
      override fun getAuthData(): AuthData {
        return AuthData(
            // Headers and URL query params your auth endpoint needs to
            // request a Beams Token for a given user
            headers = hashMapOf(
                // for example:
                // "Authorization" to sessionToken
            ),
            queryParams = hashMapOf()
        )
      }
    }
)

iOS

  • Swift
  • Objective-C

iOS (Swift)

1
2
3
4
5
6
let tokenProvider = BeamsTokenProvider(authURL: "<YOUR_BEAMS_AUTH_URL_HERE>") { () -> AuthData in
  let sessionToken = "SESSION-TOKEN"
  let headers = ["Authorization": "Bearer \(sessionToken)"] // Headers your auth endpoint needs
  let queryParams: [String: String] = [:] // URL query params your auth endpoint needs
  return AuthData(headers: headers, queryParams: queryParams)
}

Integrating Beams into your auth process

Now that you have everything set up, you can integrate Beams into the auth process of your mobile app. This means:

  • Associating the device with the user when they log in
  • Disassociating the device from the user when they log out

Associating the device with the user when they log in

After a user logs into your application, you should call the setUserId method in the SDK.

You must call setUserId both when the user logs in and every time your app launches whilst the user is still authenticated.

  • Kotlin
  • Java
  • Swift
  • Objective-C

Android (Kotlin)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
val tokenProvider = BeamsTokenProvider(
    "<YOUR_BEAMS_AUTH_URL_HERE>",
    object: AuthDataGetter {
      override fun getAuthData(): AuthData {
        return AuthData(
            // Headers and URL query params your auth endpoint needs to
            // request a Beams Token for a given user
            headers = hashMapOf(
                // for example:
                // "Authorization" to sessionToken
            ),
            queryParams = hashMapOf()
        )
      }
    }
)

PushNotifications.setUserId(
    "<USER_ID_GOES_HERE>",
    tokenProvider,
    object : BeamsCallback<Void, PusherCallbackError> {
      override fun onFailure(error: PusherCallbackError) {
        Log.e("BeamsAuth", "Could not login to Beams: ${error.message}");
      }

      override fun onSuccess(vararg values: Void) {
        Log.i("BeamsAuth", "Beams login success");
      }
    }
)

Deauthenticating when a user logs out

When a user logs of your application, you will want to ensure that notifications are no longer sent to that users' device. You can do this by calling the clearAllState method in the SDK. This will dissasociate the device from that user and put the SDK into a clean state.

Calling clearAllState will also clear any Device Interests present on the device. If you would like to retain any Device Interests after logging out, you should re-subscribe to them.

  • Kotlin
  • Java
  • Swift
  • Objective-C

Android (Kotlin)

1
PushNotifications.clearAllState()

Publishing to users from your server

You should now be able to associate devices with users in your application. This will allow you to send notifications to all devices belonging to a particular user by publishing to their user ID. Use one of our server SDKs to publish to your users:

  • PHP
  • JavaScript
  • python
  • Java
  • Kotlin
  • Go
  • Swift
  • Ruby

PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
include 'src/PushNotifications.php';
$publishResponse = $beamsClient->publishToUsers(
  array("user-001", "user-002"),
  array(
    "fcm" => array(
      "notification" => array(
        "title" => "Hi!",
        "body" => "This is my first Push Notification!"
      )
    ),
    "apns" => array("aps" => array(
      "alert" => array(
        "title" => "Hi!",
        "body" => "This is my first Push Notification!"
      )
    ))
));