Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Al momento il tuo webhook utilizza dati hardcoded nella funzione accountBalanceCheck.
In questo passaggio del tutorial,
creerai un database
Spanner, lo completerai con i dati del saldo
e aggiornerai la funzione per eseguire query sul database.
Configurazione progetto
È importante che l'agente Dialogflow e il database
si trovino entrambi nello stesso progetto.
Questo è il modo più semplice per consentire alla funzione di accedere in modo sicuro al database.
Inoltre, devi attivare l'API Spanner.
Prima di creare il database,
seleziona il progetto dalla Google Cloud console.
Come nome dell'istanza, inserisci Tutorial Instance.
L'ID istanza viene inserito automaticamente in base al nome dell'istanza.
In Scegli la configurazione, mantieni l'opzione predefinita Regionale e seleziona la stessa regione
posizione
che hai scelto durante la creazione della funzione.
In Alloca la capacità di calcolo,
inserisci 100 unità di elaborazione.
Questa impostazione fornisce una capacità minima per il tutorial.
Fai clic su Crea.
La Google Cloud console mostra la pagina Panoramica dell'istanza
che hai creato.
Creazione di un database Spanner
Ora che hai un'istanza,
devi creare un database.
Per creare un database:
Nella pagina Panoramica dell'istanza, fai clic su Crea database.
Per il nome del database, inserisci tutorial-database.
Seleziona il dialetto del database Google SQL standard.
Fai clic su Crea.
La Google Cloud console mostra la pagina Panoramica per il database
che hai creato.
Creare tabelle per il database
Ora che hai un database,
devi creare le tabelle per il database.
Per creare tabelle:
Nella sezione Tabelle della pagina Panoramica del database,
fai clic su Crea tabella.
Fai clic su Invia.
La Google Cloud console torna alla pagina Panoramica del database e
mostra che sono in corso aggiornamenti dello schema.
Attendi il completamento dell'aggiornamento.
Nella sezione Tabelle della pagina Panoramica del database,
fai clic su Crea tabella.
Fai clic su Invia.
La Google Cloud console torna alla pagina Panoramica del database e
mostra che sono in corso aggiornamenti dello schema.
Attendi il completamento dell'aggiornamento.
Inserire dati nelle tabelle
Ora che il database contiene tabelle,
devi aggiungere i dati alle tabelle.
Per aggiungere dati:
Nell'elenco delle tabelle nella pagina Panoramica del database,
fai clic sulla tabella Controllo.
La Google Cloud console mostra la pagina Schema della tabella.
Nel menu di navigazione a sinistra,
fai clic su Dati per visualizzare la pagina Dati della tabella.
Fai clic su Inserisci.
La Google Cloud console mostra la pagina Query della tabella con una nuova scheda di query contenente istruzioni INSERT e SELECT.
Sostituisci queste istruzioni con quanto segue:
Nel menu di navigazione a sinistra, fai nuovamente clic su Dati per visualizzare i dati della tabella.
Verifica che la tabella contenga i dati desiderati.
Fai clic sul link tutorial-database: Panoramica per tornare alla pagina Panoramica del database.
Nell'elenco delle tabelle nella pagina Panoramica del database,
fai clic sulla tabella Risparmi.
La Google Cloud console mostra la pagina Schema della tabella.
Nel menu di navigazione a sinistra,
fai clic su Dati per visualizzare la pagina Dati della tabella.
Fai clic su Inserisci.
La Google Cloud console mostra la pagina Query della tabella con una nuova scheda di query contenente istruzioni INSERT e SELECT.
Sostituisci queste istruzioni con quanto segue:
Nel menu di navigazione a sinistra, fai nuovamente clic su Dati per visualizzare i dati della tabella.
Verifica che la tabella contenga i dati desiderati.
Aggiorna la Cloud Function per eseguire query sul database
La funzione accountBalanceCheck nel codice dell'webhook controlla se sono impostate variabili di ambiente specifiche con informazioni per la connessione al database.
Se queste variabili di ambiente non sono impostate, la funzione utilizza un saldo dell'account hardcoded.
Ora che hai configurato un database, aggiornate la Cloud Function per impostare le variabili di ambiente richieste:
Fai clic sulla funzione tutorial-banking-webhook per visualizzare la relativa pagina dei dettagli.
Fai clic su Modifica.
Apri la sezione Impostazioni di runtime, build e connessioni.
Seleziona la scheda Runtime.
Aggiungi le seguenti variabili nella sezione Variabili di ambiente runtime:
PROJECT_ID: il tuo ID progetto
SPANNER_INSTANCE_ID: il tuo ID istanza Spanner (probabilmente tutorial-instance)
SPANNER_DATABASE_ID: l'ID del database Spanner (probabilmente tutorial-database)
Fai clic su Avanti.
Fai clic su Esegui il deployment.
Attendi che l'indicatore di stato mostri che la funzione è stata dispiegamento correttamente.
Testa l'agente
L'agente è ora pronto per essere provato.
Fai clic sul pulsante Test agent nella console Dialogflow per aprire il simulatore.
Prova a tenere la seguente conversazione con l'agente:
Turno di conversazione
Tu
Agente
1
Ciao
Ciao, grazie per aver scelto la Banca ACME.
2
Voglio conoscere il saldo del mio conto
Per quale conto vuoi il saldo: di risparmio o corrente?
3
Controllo in corso…
Ecco il tuo saldo aggiornato: 10,00 $
Se esamini il codice,
10 $ non è il valore hardcoded.
Ciò significa che il tuo webhook si è connesso correttamente al database, che ha un saldo di 10 $.
Risoluzione dei problemi
Il codice webhook include istruzioni di logging.
In caso di problemi, prova a visualizzare i log della Cloud Function.
Se la funzione non si connette al database e viene visualizzato un errore di autorizzazione nei log, potrebbe essere necessario correggere il ruolo per l'account di servizio predefinito utilizzato dalla funzione.
Questo account di servizio è nel formato
PROJECT_ID@appspot.gserviceaccount.com.
Puoi risolvere il problema in uno dei seguenti modi:
Se nella pagina principale di IAM viene visualizzato l'account di servizio predefinito,
modifica le autorizzazioni per l'account di servizio.
Il ruolo Editor andrà bene, ma in uno scenario di produzione potresti volere un ruolo più granulare.
Se nella pagina principale di IAM non è visualizzato un account di servizio predefinito,
concedi il ruolo richiesto
aggiungendo l'account di servizio come nuova entità.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-04 UTC."],[[["\u003cp\u003eThis tutorial guides you through replacing hardcoded data in a webhook's \u003ccode\u003eaccountBalanceCheck\u003c/code\u003e function with a Spanner database.\u003c/p\u003e\n"],["\u003cp\u003eYou will learn how to create a Spanner instance and database, and populate it with account balance data in \u003ccode\u003eChecking\u003c/code\u003e and \u003ccode\u003eSavings\u003c/code\u003e tables.\u003c/p\u003e\n"],["\u003cp\u003eThe process includes enabling the Spanner API, setting up project configurations, defining the database schema with tables, and inserting data into those tables.\u003c/p\u003e\n"],["\u003cp\u003eThe final steps cover updating the Cloud Function's runtime environment variables to connect to the newly created database and deploying these changes.\u003c/p\u003e\n"],["\u003cp\u003eAfter deployment, the tutorial provides instructions to test your agent and details on troubleshooting connection or permission errors using the function's logs and the IAM page.\u003c/p\u003e\n"]]],[],null,["# Query a database\n\nYour webhook currently uses hardcoded data in the\n`accountBalanceCheck` function.\nIn this step of the tutorial,\nyou will create a\n[Spanner](/spanner/docs)\ndatabase, populate it with balance data,\nand update your function to query the database.\n\nProject configuration\n---------------------\n\nIt is important that your Dialogflow agent and the database\nare both in the same project.\nThis is the easiest way for your function to have\nsecure access to your database.\nAlso, you must enable the Spanner API.\n\n1. Before creating the database,\n select your project from the Google Cloud console.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n2. Enable the Spanner API for the project.\n\n [Enable the Spanner API](https://console.cloud.google.com/flows/enableapi?apiid=spanner.googleapis.com)\n\nCreate a Spanner instance\n-------------------------\n\nWhen you first use Spanner,\nyou must create an instance,\nwhich is an allocation of resources\nthat are used by Spanner databases in that instance.\n\n1. In the Google Cloud console, go to the **Spanner Instances** page.\n\n [Go to Spanner instances](https://console.cloud.google.com/spanner/instances)\n2. Click **Create instance**.\n\n3. For the instance name, enter **Tutorial Instance**.\n\n4. The instance ID is automatically entered based on the instance name.\n\n5. In **Choose your configuration** ,\n retain the default option **Regional** and select the same region\n [location](/dialogflow/es/docs/how/region)\n that you chose when creating the function.\n\n6. In **Allocate compute capacity**,\n enter 100 processing units.\n This provides a minimal capacity for the tutorial.\n\n7. Click **Create** .\n The Google Cloud console displays the **Overview** page for the instance\n you created.\n\nCreate a Spanner database\n-------------------------\n\nNow that you have an instance,\nyou need to create a database.\nTo create a database:\n\n1. In the instance **Overview** page, click **Create database**.\n2. For the database name, enter **tutorial-database**.\n3. Select the **Google Standard SQL** database dialect.\n4. Click **Create** . The Google Cloud console displays the **Overview** page for the database you created.\n\nCreate tables for your database\n-------------------------------\n\nNow that you have a database,\nyou need to create tables for the database.\nTo create tables:\n\n1. In the Tables section of the database **Overview** page, click **Create table**.\n2. In the **Write DDL statements** page, enter:\n\n CREATE TABLE Checking (\n AccountId INT64,\n Balance INT64,\n ) PRIMARY KEY(AccountId);\n\n3. Click **Submit** .\n The Google Cloud console returns to the database **Overview** page and\n shows that **Schema updates** are underway.\n Wait until the update is complete.\n\n4. In the Tables section of the database **Overview** page,\n click **Create table**.\n\n5. In the **Write DDL statements** page, enter:\n\n CREATE TABLE Savings (\n AccountId INT64,\n Balance INT64,\n ) PRIMARY KEY(AccountId);\n\n6. Click **Submit** .\n The Google Cloud console returns to the database **Overview** page and\n shows that **Schema updates** are underway.\n Wait until the update is complete.\n\nInsert data into your tables\n----------------------------\n\nNow that your database has tables,\nyou need to add data to the tables.\nTo add data:\n\n1. In the list of tables on the database **Overview** page, click the Checking table. The Google Cloud console displays the table's **Schema** page.\n2. In the left navigation menu, click **Data** to display the table's **Data** page.\n3. Click **Insert** .\n The Google Cloud console displays the table's **Query** page with a\n new query tab that contains `INSERT` and `SELECT` statements.\n Overwrite those statements with the following:\n\n INSERT INTO Checking (AccountId, Balance)\n VALUES(1, 1000),\n (2, 2000);\n\n4. Click **Run**.\n\n5. In the left navigation menu,\n click **Data** again to display the table's data.\n Confirm that the table contains the desired data.\n\n6. Click the **tutorial-database: Overview** link\n to return to the database overview page.\n\n7. In the list of tables on the database **Overview** page,\n click the Savings table.\n The Google Cloud console displays the table's **Schema** page.\n\n8. In the left navigation menu,\n click **Data** to display the table's **Data** page.\n\n9. Click **Insert** .\n The Google Cloud console displays the table's **Query** page with a\n new query tab that contains `INSERT` and `SELECT` statements.\n Overwrite those statements with the following:\n\n INSERT INTO Savings (AccountId, Balance)\n VALUES(1, 10000),\n (2, 20000);\n\n10. Click **Run**.\n\n11. In the left navigation menu,\n click **Data** again to display the table's data.\n Confirm that the table contains the desired data.\n\nUpdate the Cloud Function to query the database\n-----------------------------------------------\n\nThe `accountBalanceCheck` function in the webhook code\nchecks whether specific environment variables are set\nwith information for connecting to the database.\nIf these environment variables are not set,\nthe function uses a hardcoded account balance.\n\nNow that you have a database set up,\nupdate your Cloud Function to set required environment variables:\n\n1. Open the Cloud Functions overview page.\n\n [Go to Cloud Functions overview](https://console.cloud.google.com/functions/list)\n2. Click the tutorial-banking-webhook function to go to its details page.\n\n3. Click **Edit**.\n\n4. Open the **Runtime, build and connections settings** section.\n\n5. Select the **Runtime** tab.\n\n6. Add the following variables in the Runtime environment variables section:\n\n - `PROJECT_ID`: your project ID\n - `SPANNER_INSTANCE_ID`: your Spanner instance ID (probably `tutorial-instance`)\n - `SPANNER_DATABASE_ID`: your spanner database ID (probably `tutorial-database`)\n7. Click **Next**.\n\n8. Click **Deploy**.\n\n9. Wait until the status indicator shows that the function\n has successfully deployed.\n\nTest your agent\n---------------\n\nYour agent is now ready to try.\nClick the **Test Agent** button from the Dialogflow console\nto open the simulator.\nAttempt to have the following conversation with the agent:\n\nIf you examine the code,\n$10 is not the hardcoded value.\nThis means that your webhook has successfully connected to the database,\nwhich does have a balance of $10.\n\nTroubleshooting\n---------------\n\nThe webhook code includes logging statements.\nIf you are having issues, try viewing the logs for your Cloud Function.\n\nIf your function is not connecting to the database,\nand you see a permission error in the logs,\nyou may need to fix the role for the default service account\nused by your function.\nThis service account is of the form\n\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e`@appspot.gserviceaccount.com`.\nYou can fix this in one of the following ways:\n\n- If the default service account is shown on the IAM main page,\n [change permissions for the service account](/functions/docs/securing/function-identity#default).\n The *Editor* role will work,\n but you may want a more granular role in a production scenario.\n\n [Go to the IAM main page](https://console.cloud.google.com/iam-admin/iam)\n- If the a default service account is not shown on the IAM main page,\n [grant the required role](/iam/docs/grant-role-console#grant_an_iam_role)\n by adding the service account as a new principal.\n\n- Alternatively, you can\n [use a service account that you create](/functions/docs/securing/function-identity#individual).\n\nMore information\n----------------\n\nFor more information about the steps above, see:\n\n- [Using Cloud Spanner with Cloud Functions](/functions/docs/tutorials/use-cloud-spanner)\n- [Create and query a database by using the Google Cloud console](/spanner/docs/create-query-database-console)\n- [Google Standard SQL data definition language](/spanner/docs/reference/standard-sql/data-definition-language)\n- [Google Standard SQL data manipulation language](/spanner/docs/reference/standard-sql/dml-syntax)"]]