Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Votre action peut envoyer des notifications push aux utilisateurs chaque fois que cela est pertinent, par exemple en envoyant un rappel lorsque la date limite d'une tâche approche.
Ce guide explique comment configurer les notifications push pour votre action.
Surfaces compatibles
Les notifications push sont disponibles sur les appareils Android et iOS (l'application Assistant doit être installée sur les appareils iOS pour recevoir des notifications push). Elles ne sont actuellement pas compatibles avec les enceintes à commande vocale, les écrans connectés ou d'autres surfaces.
Prérequis
Votre projet doit contenir au moins un intent global, qui est appelé lorsque l'utilisateur appuie sur une notification push reçue de l'Assistant.
Commencer
Les sections suivantes décrivent comment configurer les notifications push dans votre action.
Créer un intent pour le déclenchement
L'intent que vous créez dans cette section déclenche le flux de notifications. Pour créer
cet intent, procédez comme suit:
Accédez à la console Actions, puis cliquez sur Développer dans le menu supérieur.
Cliquez sur Intents dans le menu de gauche pour développer la section.
Cliquez sur add_circle_outline en bas de la liste et saisissez un nom pour le nouvel intent.
Appuyez sur Enter/Return pour créer l'intent.
Ajoutez des phrases d'entraînement pour déclencher le flux de notifications. Par exemple :
Notify me
Send notifications
Subscribe to notifications
Cliquez sur Enregistrer.
Transition vers l'intent système
Pour configurer la transition vers la scène système Notifications, procédez comme suit:
Sous Scenes (Scènes) dans le menu de gauche, cliquez sur la scène à laquelle vous souhaitez ajouter le flux de notifications.
Dans la section User intent management (Gestion des intents utilisateur) de la scène, cliquez sur + pour ajouter un gestionnaire d'intents.
Sous Intent, sélectionnez l'intent que vous avez créé dans la section précédente.
Sous Transition, sélectionnez la scène système Notifications.
Cliquez sur Enregistrer.
Configurer la scène système
Pour configurer la scène système Notifications, procédez comme suit:
Sous Scenes (Scènes) dans le menu de gauche, sélectionnez la nouvelle scène système Notifications.
Dans la section Configure intent (Configurer l'intent), cliquez sur Select intent (Sélectionner un intent).
Dans la section Sélectionner un intent, sélectionnez l'intent que vous souhaitez mettre en correspondance lorsqu'un utilisateur appuie sur une notification push.
Dans le champ Personnaliser l'invite d'activation, saisissez une invite qui s'affiche lorsque les utilisateurs sont invités à s'abonner aux notifications push. L'invite se présente sous la forme "Puis-je envoyer des notifications push pour $prompt ?".
Cliquez sur Enregistrer.
Configurer l'activation
Pour configurer l'activation des notifications push, procédez comme suit:
Sous Scenes (Scènes), sélectionnez la scène système Notifications.
Sous Conditions, sélectionnez Si l'utilisateur dit "oui".
Activez l'option Call your webhook (Appeler votre webhook) et indiquez un nom de gestionnaire d'événements, tel que subscribe_to_notifications.
Activez l'option Send invites (Envoyer des invites) et fournissez une invite simple pour informer l'utilisateur qu'il recevra des notifications:
Sous Transition, sélectionnez End conversation (Terminer la conversation) pour mettre fin à la conversation une fois qu'un utilisateur s'est abonné aux notifications.
Configurer la désactivation
Pour configurer la désactivation des notifications push, procédez comme suit:
Sous Conditions, sélectionnez Si l'utilisateur dit "non".
Activez l'option Send invites (Envoyer des invites) et fournissez une invite simple pour informer l'utilisateur qu'il ne recevra pas de notifications:
candidates:-firstsimple:variants:-speech:Okay,Iwon't send you notifications.
Sous Transition, sélectionnez End conversation (Terminer la conversation) pour mettre fin à la conversation une fois qu'un utilisateur a désactivé les notifications.
Configurer le webhook
Pour configurer votre webhook, procédez comme suit:
Dans votre webhook, ajoutez un gestionnaire d'intent pour stocker updatesUserId:
app.handle('subscribe_to_notifications',conv=>{constintentName='<name_of_intent_to_trigger>';constnotificationsSlot=conv.session.params['NotificationSlot_${intentName}'];if(notificationsSlot.permissionStatus=='PERMISSION_GRANTED'){constupdateUserId=notificationsSlot.additionalUserData.updateUserId;//StoretheuserIDandthenotification's target intent for later use.//(Useadatabase,likeFirestore,forbestpractice.)}});
Envoyer des notifications
Les notifications push sont envoyées aux utilisateurs à l'aide de l'API Actions. Pour utiliser cette API, vous devez l'activer dans votre projet Google Cloud, puis configurer et télécharger une clé de compte de service JSON.
Vous pouvez ensuite utiliser la bibliothèque cliente Google OAuth2 pour échanger la clé du compte de service contre un jeton d'accès, puis utiliser ce jeton pour authentifier vos requêtes auprès de l'API Actions.
Obtenir une clé de compte de service
Accédez à la console Google APIs, puis sélectionnez votre projet dans le menu déroulant Sélectionner un projet.
Cliquez sur Activer pour activer l'API Actions pour votre projet.
Cliquez sur Créer des identifiants > Compte de service.
Saisissez un nom de compte de service, puis cliquez sur Créer.
Dans le menu déroulant Sélectionnez un rôle, sélectionnez Projet > Propriétaire.
Cliquez sur Continuer.
Cliquez sur Créer une clé pour télécharger le fichier JSON du compte de service.
Échanger la clé contre un jeton d'accès et envoyer une notification
Pour envoyer des notifications push via l'API Actions, vous devez échanger la clé du compte de service contre un jeton d'accès. Pour cela, nous vous recommandons d'utiliser une bibliothèque cliente des API Google. Dans la série d'extraits de code qui suit, nous utilisons la bibliothèque cliente Node.js de l'API Google.
Installez la bibliothèque cliente des API Google et exécutez la requête suivante:
npm install googleapis request --save
Utilisez le code suivant pour obtenir un jeton d'accès à partir de la clé du compte de service et envoyer une notification push:
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/07/25 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Il n'y a pas l'information dont j'ai besoin","missingTheInformationINeed","thumb-down"],["Trop compliqué/Trop d'étapes","tooComplicatedTooManySteps","thumb-down"],["Obsolète","outOfDate","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Mauvais exemple/Erreur de code","samplesCodeIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/07/25 (UTC)."],[[["\u003cp\u003ePush notifications can be sent to Android and iOS users to provide timely reminders or updates from your Action.\u003c/p\u003e\n"],["\u003cp\u003eYou need to create a global intent that will be triggered when the user interacts with the notification.\u003c/p\u003e\n"],["\u003cp\u003eUsers must explicitly opt-in to receive push notifications through a prompt within your Action.\u003c/p\u003e\n"],["\u003cp\u003eSending notifications requires using the Actions API with a service account key for authentication.\u003c/p\u003e\n"],["\u003cp\u003eStore the \u003ccode\u003eupdatesUserId\u003c/code\u003e securely to target specific users with notifications.\u003c/p\u003e\n"]]],[],null,["# Push notifications\n\nYour Action can push notifications to users whenever relevant, such as sending a reminder when the due date for a task is near.\n\nThis guide describes how to set up push notifications for your Action.\n\nSupported surfaces\n------------------\n\nPush 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.\n\nPrerequisites\n-------------\n\nYour project must contain at least one [global intent](/assistant/conversational/intents#custom_intents), which is invoked when the user taps a push notification received from Assistant.\n\nGet started\n-----------\n\nThe following sections describe how to set up push notifications in your Action.\n\n### Create an intent for triggering\n\nThe intent you create in this section triggers the notifications flow. To create\nthis intent, follow these steps:\n\n1. Go to the [Actions console](//console.actions.google.com/) and click **Develop** in the top menu.\n2. Click **Intents** in the left menu to expand the section.\n3. Click the add_circle_outline at the bottom of the list and enter a name for the new intent.\n4. Press `Enter/Return` to create the new intent.\n5. Add training phrases for triggering the notifications flow. Some examples are:\n\n - `Notify me`\n - `Send notifications`\n - `Subscribe to notifications`\n6. Click **Save**.\n\n### Transition to system intent\n\nTo set up the transition to the `Notifications` system scene, follow these steps:\n\n1. Under **Scenes** in the left menu, click the scene you want to add the notifications subscription flow to.\n2. Under the **User intent handling** section of the scene, click **+** to add a new intent handler.\n3. Under **Intent**, select the intent you created in the previous section.\n4. Under **Transition** , select the **Notifications** system scene.\n\n5. Click **Save**.\n\n### Configure system scene\n\nTo configures the `Notifications` system scene, follow these steps:\n\n1. Under **Scenes** in the left menu, select the new **Notifications** system scene.\n2. Under the **Configure intent** section, click **Select intent**.\n3. Under the **Select intent** section, select the intent you want to be matched when a user taps a push notification.\n\n | **Note:** The intent you choose for this step needs to be a global intent.\n4. 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\".\n\n5. Click **Save**.\n\n### Configure opt-in\n\nTo configure opting in to push notifications, follow these steps:\n\n1. Under **Scenes** , select the **Notifications** system scene.\n2. Under **Conditions** , select **If the user says \"yes\"**.\n3. Enable **Call your webhook** and provide an event handler name, such as `subscribe_to_notifications`.\n4. Enable **Send prompts** and provide a simple prompt to let the user know they'll be sent notifications:\n\n candidates:\n - first simple:\n variants:\n - speech: 'Great, I'll send you notifications.'\n\n5. Under **Transition** , select **End conversation** to end the conversation after a user subscribes to notifications.\n\n### Configure opt-out\n\nTo configure opting out of push notifications, follow these steps:\n\n1. Under **Conditions** , select **If the user says \"no\"**.\n2. Enable **Send prompts** and provide a simple prompt to let the user know they won't be sent notifications:\n\n candidates:\n - first simple:\n variants:\n - speech: Okay, I won't send you notifications.\n\n3. Under **Transition** , select **End conversation** to end the conversation after a user opts out of notifications.\n\n### Configure webhook\n\nTo configure your webhook, follow these steps:\n\n1. In your webhook, add an intent handler for storing the `updatesUserId`:\n\n app.handle('subscribe_to_notifications', conv =\u003e {\n const intentName = '\u003cname_of_intent_to_trigger\u003e';\n const notificationsSlot = conv.session.params['NotificationSlot_${intentName}'];\n if(notificationsSlot.permissionStatus == 'PERMISSION_GRANTED') {\n const updateUserId = notificationsSlot.additionalUserData.updateUserId;\n // Store the user ID and the notification's target intent for later use.\n // (Use a database, like Firestore, for best practice.)\n }\n });\n\nSend notifications\n------------------\n\nPush 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.\n\nYou 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.\n\n### Get a service account key\n\n1. Go to the [Google API console](//console.developers.google.com/apis/api/actions.googleapis.com/overview) and select your project from the **Select a project** dropdown.\n2. Click **Enable** to enable the Actions API for your project.\n3. Go to the [Google Cloud console credentials page](//console.developers.google.com/apis/credentials) and select your project from the **Select a project** dropdown.\n4. Click **Create credentials \\\u003e Service account**.\n5. Enter a service account name and click **Create**.\n6. From the **Select a role** dropdown, select **Project \\\u003e Owner**.\n7. Click **Continue**.\n8. Click **Create key** to download the service account JSON file.\n\n### Exchange the key for an access token and send a notification\n\nTo 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.\n\n1. Install the Google API client library and request:\n\n `npm install googleapis request --save`\n2. Use the following code to get an access token from the service account key and send a push notification:\n\n // Use the Actions API to send a Google Assistant push notification.\n let client = auth.fromJSON(require('./service-account.json'));\n client.scopes = ['https://www.googleapis.com/auth/actions.fulfillment.conversation'];\n let notification = {\n userNotification: {\n title: 'Example notification title',\n },\n target: {\n userId: '\u003cUPDATES_USER_ID\u003e',\n intent: 'Notifications Intent',\n },\n };\n client.authorize((err, tokens) =\u003e {\n if (err) {\n throw new Error('Auth error: ${err}');\n }\n request.post('https://actions.googleapis.com/v2/conversations:send', {\n 'auth': {\n 'bearer': tokens.access_token,\n },\n 'json': true,\n 'body': {'customPushMessage': notification, 'isInSandbox': true},\n }, (err, httpResponse, body) =\u003e {\n if (err) {\n throw new Error('API request error: ${err}');\n }\n console.log('${httpResponse.statusCode}: ' + '${httpResponse.statusMessage}');\n console.log(JSON.stringify(body));\n });\n });"]]