Push notifications

Your Action can push notifications to users whenever relevant, such as sending a reminder when the due date for a task is near.

This guide describes how to set up push notifications for your Action.

Supported surfaces

Push notifications are available on Android and iOS devices (iOS devices must have the Assistant app installed to receive push notifications). They are not currently supported on voice-activated speakers, smart displays, or other surfaces.

Prerequisites

Your project must contain at least one global intent, which is invoked when the user taps a push notification received from Assistant.

Get started

The following sections describe how to set up push notifications in your Action.

Create an intent for triggering

The intent you create in this section triggers the notifications flow. To create this intent, follow these steps:

  1. Go to the Actions console and click Develop in the top menu.
  2. Click Intents in the left menu to expand the section.
  3. Click the at the bottom of the list and enter a name for the new intent.
  4. Press Enter/Return to create the new intent.
  5. Add training phrases for triggering the notifications flow. Some examples are:

    • Notify me
    • Send notifications
    • Subscribe to notifications
  6. Click Save.

Transition to system intent

To set up the transition to the Notifications system scene, follow these steps:

  1. Under Scenes in the left menu, click the scene you want to add the notifications subscription flow to.
  2. Under the User intent handling section of the scene, click + to add a new intent handler.
  3. Under Intent, select the intent you created in the previous section.
  4. Under Transition, select the Notifications system scene.

  5. Click Save.

Configure system scene

To configures the Notifications system scene, follow these steps:

  1. Under Scenes in the left menu, select the new Notifications system scene.
  2. Under the Configure intent section, click Select intent.
  3. Under the Select intent section, select the intent you want to be matched when a user taps a push notification.

  4. For Customize opt-in prompt, enter a prompt that is displayed to users when they're asked to subscribe to push notifications. The prompt is in the form of "Is it ok if I send push notifications for $prompt".

  5. Click Save.

Configure opt-in

To configure opting in to push notifications, follow these steps:

  1. Under Scenes, select the Notifications system scene.
  2. Under Conditions, select If the user says "yes".
  3. Enable Call your webhook and provide an event handler name, such as subscribe_to_notifications.
  4. Enable Send prompts and provide a simple prompt to let the user know they'll be sent notifications:

    candidates:
    - first simple:
      variants:
      - speech: 'Great, I'll send you notifications.'
    
  5. Under Transition, select End conversation to end the conversation after a user subscribes to notifications.

Configure opt-out

To configure opting out of push notifications, follow these steps:

  1. Under Conditions, select If the user says "no".
  2. Enable Send prompts and provide a simple prompt to let the user know they won't be sent notifications:

    candidates:
    - first simple:
      variants:
      - speech: Okay, I won't send you notifications.
    
  3. Under Transition, select End conversation to end the conversation after a user opts out of notifications.

Configure webhook

To configure your webhook, follow these steps:

  1. In your webhook, add an intent handler for storing the updatesUserId:

    app.handle('subscribe_to_notifications', conv => {
      const intentName = '<name_of_intent_to_trigger>';
      const notificationsSlot = conv.session.params['NotificationSlot_${intentName}'];
      if(notificationsSlot.permissionStatus == 'PERMISSION_GRANTED') {
        const updateUserId = notificationsSlot.additionalUserData.updateUserId;
        // Store the user ID and the notification's target intent for later use.
        // (Use a database, like Firestore, for best practice.)
      }
    });
    

Send notifications

Push notifications are sent to users using the Actions API. To use this API, you need to activate the API in your Google Cloud project and set up and download a JSON service account key.

You can then use the Google OAuth2 client library to exchange the service account key for an access token and use the token to authenticate your requests to the Actions API.

Get a service account key

  1. Go to the Google API console and select your project from the Select a project dropdown.
  2. Click Enable to enable the Actions API for your project.
  3. Go to the Google Cloud console credentials page and select your project from the Select a project dropdown.
  4. Click Create credentials > Service account.
  5. Enter a service account name and click Create.
  6. From the Select a role dropdown, select Project > Owner.
  7. Click Continue.
  8. Click Create key to download the service account JSON file.

Exchange the key for an access token and send a notification

To send push notifications through the Actions API, you need to exchange the service account key for an access token. We recommend using a Google API client library for this. In the series of code snippets that follow, we use the Google API Node.js client library.

  1. Install the Google API client library and request:

    npm install googleapis request --save

  2. Use the following code to get an access token from the service account key and send a push notification:

    // Use the Actions API to send a Google Assistant push notification.
    let client = auth.fromJSON(require('./service-account.json'));
    client.scopes = ['https://www.googleapis.com/auth/actions/fulfillment.conversation'];
    let notification = {
      userNotification: {
        title: 'Example notification title',
      },
      target: {
        userId: '<UPDATES_USER_ID>',
        Intent: 'Notifications Intent',
      },
    };
    client.authorize((err, tokens) => {
      if (err) {
        throw new Error('Auth error: ${err}');
      }
      request.post('https://actions.googleapis.com/v2/conversations:send', {
        'auth': {
          'bearer': tokens.access_token,
        },
        'json': true,
        'body': {'customPushMessage': notification, 'isInSandbox': true},
      }, (err, httpResponse, body) => {
        if (err) {
          throw new Error('API request error: ${err}');
        }
        console.log('${httpResponse.statusCode}: ' + '${httpResponse.statusMessage}');
        console.log(JSON.stringify(body));
      });
    });