Si la marca que representa un agente tiene ubicaciones físicas, puedes asociarlas con el agente para que los usuarios puedan enviar mensajes a ubicaciones específicas con Business Messages. Business Messages identifica las ubicaciones según el ID de lugar.
Con los ID de lugar, puedes identificar a qué ubicación física envía un usuario y determinar el mejor procedimiento para responderle.
Debes reclamar la propiedad de las ubicaciones físicas a través del Perfil de Negocio para poder asociar ubicaciones con un agente de Business Messages.
Cómo administrar varias ubicaciones
Si la marca es parte de una cadena, debes agregar todas las ubicaciones de esa cadena en las que tengas permiso para habilitar la mensajería. Para verificar todas las ubicaciones de la cadena, realizarás una sola solicitud de verificación de una ubicación. Una vez que verifiquemos esa ubicación, verificaremos automáticamente las otras ubicaciones asociadas que hayas agregado.
Después de la verificación, si vuelves a agregar ubicaciones, deberás solicitar la verificación de ubicación nuevamente.
Para ver las ubicaciones asociadas con tu agente, consulta Enumera todas las ubicaciones de una marca y filtra los resultados por sus valores de agent
.
Crear una ubicación
Para agregar una ubicación a un agente, debes realizar una solicitud con la API de Business Communications a fin de crear la ubicación de la marca y asociar el agente con su valor name
.
Requisitos previos
Antes de crear una ubicación, debes reunir algunos elementos:
- Ruta de acceso a la clave de la cuenta de servicio de tu proyecto de GCP en tu máquina de desarrollo
name
de la marca, como aparece en la API de Business Communications (por ejemplo, "brands/12345")Si no conoces la
name
de la marca, consultabrands.list
.name
del agente, como aparece en la API de Business Communications (por ejemplo, "brands/12345/agents/67890")Si no conoces el
name
del agente, consulta Enumera todos los agentes de una marca.ID de lugar de la ubicación
Identifica el ID de lugar de una ubicación con el Buscador de ID de lugar. Si la ubicación es una empresa de servicio en área en lugar de una sola dirección, usa el Buscador de ID de lugar de empresa del área de servicio en su lugar.
La configuración regional en la que suele operar la ubicación, que se especifica con un código de idioma ISO 639-1 de dos caracteres
Crea la ubicación
Una vez que hayas recopilado tu información, es momento de crear la ubicación. En una terminal, ejecuta el siguiente comando.
Reemplaza las variables destacadas por los valores que identificaste en Requisitos previos. Reemplaza BRAND_ID por la parte del valor name
de la marca que sigue a "brands/". Por ejemplo, si name
es “marcas/12345”, el ID de la marca es “12345”.
cURL
# This code creates a location where a brand is available. # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/create # Replace the __BRAND_ID__ and __PLACE_ID__ # Make sure a service account key file exists at ./service_account_key.json curl -X POST "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/locations" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \ -d '{ "placeId": "__PLACE_ID__", "agent": "brands/__BRAND_ID__/agents/__AGENT_ID__", "defaultLocale": "en", }'
Node.js
/** * This code snippet creates a location. * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/create * * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js * Business Communications client library. */ /** * Edit the values below: */ const BRAND_ID = 'EDIT_HERE'; const PLACE_ID = 'EDIT_HERE'; const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); async function main() { const authClient = await initCredentials(); const brandName = 'brands/' + BRAND_ID; const agentName = 'brands/' + BRAND_ID + 'agents/' + AGENT_ID; if (authClient) { const locationObject = { placeId: PLACE_ID, agent: agentName, defaultLocale: 'en', }; // setup the parameters for the API call const apiParams = { auth: authClient, parent: brandName, resource: locationObject, }; bcApi.brands.locations.create(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { // Location created console.log(response.data); } }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // Configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // Authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } main();
Java
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.Location; import com.google.common.collect.ImmutableMap; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); String brandName = "brands/BRAND_ID"; BusinessCommunications.Brands.Locations.Create request = builder .build().brands().locations().create(brandName, new Location() .setDefaultLocale("LOCALE") .setAgent("FULL_AGENT_NAME") .setPlaceId("PLACE_ID")); Location location = request.execute(); System.out.println(location.toPrettyString()); } catch (Exception e) { e.printStackTrace(); } } }Este código se basa en la biblioteca cliente de Business Communications de Java.
Python
"""This code creates a location where a brand is available. Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/create This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1 from businesscommunications.businesscommunications_v1_messages import ( BusinesscommunicationsBrandsLocationsCreateRequest, Location ) # Edit the values below: BRAND_ID = 'EDIT_HERE' AGENT_ID = 'EDIT_HERE' PLACE_ID = 'EDIT_HERE' SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = './service_account_key.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) locations_service = BusinesscommunicationsV1.BrandsLocationsService(client) brand_name = 'brands/' + BRAND_ID agent_name = 'brands/' + BRAND_ID + 'agents/' + AGENT_ID location = locations_service.Create(BusinesscommunicationsBrandsLocationsCreateRequest( location=Location( agent=agent_name, placeId=PLACE_ID, defaultLocale='en' ), parent=brand_name )) print(location)
Para ver las opciones de formato y de valor, consulta brands.locations.create
.
Después de crear la ubicación, la API de Business Communications identifica otras ubicaciones asociadas y crea ubicaciones para la misma marca y agente.
Información de la tienda
Cuando creas una ubicación, la API de Business Communications muestra los valores de la ubicación, incluidos name
y testUrls
.
Almacena name
en un lugar al que puedas acceder. Necesitas name
para actualizar la ubicación.
Prueba una ubicación
Cada agente tiene URL de prueba que te permiten ver cómo se muestra una conversación con ese agente a los usuarios y te da la oportunidad de verificar tu infraestructura de mensajería.
Una TestUrl tiene los atributos url
y surface
.
Para probar una URL de ubicación con un dispositivo iOS, usa la URL de prueba con un valor de superficie de SURFACE_IOS_MAPS
. Si abres la URL en un dispositivo iOS que tiene instalada la app de Google Maps, se abrirá una conversación completamente funcional con el agente asociado.
Los dispositivos Android tienen dos URL de prueba. Las URL con un valor surface
de SURFACE_ANDROID_MAPS
conversaciones abiertas en Google Maps y que representan puntos de entrada conversacionales que aparecen en Google Maps.
Las URL con un valor surface
de SURFACE_ANDROID_WEB
conversaciones abiertas en una vista de conversación superpuesta y representan todos los demás puntos de entrada.
Una vez que se abre la superficie de conversación, la conversación incluye toda la información de marca que verían los usuarios y, cuando envías un mensaje al agente, tu webhook recibe el mensaje, incluida la carga útil completa de JSON que puedes esperar cuando se comunica con los usuarios.
La información de la ubicación aparece en el campo context
.
Para abrir la URL de prueba de una ubicación, presiona un vínculo o usa el Selector de agentes de Business Messages. La acción de copiar y pegar o navegar de forma manual a una URL de prueba no funciona debido a las medidas de seguridad del navegador.
Obtener información de ubicación
Para obtener información sobre una ubicación, como locationTestUrl
, puedes obtenerla de la API de Business Communications, siempre y cuando tengas el valor name
de la ubicación.
Obtener información de una sola ubicación
Para obtener información sobre la ubicación, ejecuta el siguiente comando. Reemplaza BRAND_ID y LOCATION_ID por los valores únicos de name
de las ubicaciones.
cURL
# This code gets the location where a brand is available. # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/get # Replace the __BRAND_ID__ and __LOCATION_ID__ # Make sure a service account key file exists at ./service_account_key.json curl -X GET \ "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/locations/__LOCATION_ID__" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json ./service_account_key.json businesscommunications)"
Node.js
/** * This code snippet gets the location of a brand. * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/get * * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js * Business Communications client library. */ /** * Edit the values below: */ const BRAND_ID = 'EDIT_HERE'; const LOCATION_ID = 'EDIT_HERE'; const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); async function main() { const authClient = await initCredentials(); if (authClient) { const apiParams = { auth: authClient, name: 'brands/' + BRAND_ID + '/locations/' + LOCATION_ID, }; bcApi.brands.locations.get(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { // Location found console.log(response.data); } }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // Configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // Authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } main();
Java
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.Location; import com.google.common.collect.ImmutableMap; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); BusinessCommunications.Brands.Locations.Get request = builder .build().brands().locations().get("brands/BRAND_ID/locations/LOCATION_ID"); Location location = request.execute(); System.out.println(location.toPrettyString()); } catch (Exception e) { e.printStackTrace(); } } }Este código se basa en la biblioteca cliente de Business Communications de Java.
Python
"""This code gets the location where a brand is available. Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/get This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1 from businesscommunications.businesscommunications_v1_messages import ( BusinesscommunicationsBrandsLocationsGetRequest, Location ) # Edit the values below: BRAND_ID = 'EDIT_HERE' LOCATION_ID = 'EDIT_HERE' SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = './service_account_key.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) locations_service = BusinesscommunicationsV1.BrandsLocationsService(client) location_name = 'brands/' + BRAND_ID + '/locations/' + LOCATION_ID location = locations_service.Get( BusinesscommunicationsBrandsLocationsGetRequest(name=location_name) ) print(location)
Para ver las opciones de formato y de valor, consulta brands.locations.get
.
Enumerar todas las ubicaciones de una marca
Si no conoces el name
de las ubicaciones, puedes obtener información de todos los agentes asociados con una marca si omites el valor LOCATION_ID de una URL de solicitud GET.
cURL
# This code gets all locations where a brand is available. # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/list # Replace the __BRAND_ID__ # Make sure a service account key file exists at ./service_account_key.json curl -X GET \ "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/locations/" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json ./service_account_key.json businesscommunications)"
Node.js
/** * This code snippet lists the locations of a brand. * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/list * * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js * Business Communications client library. */ /** * Edit the values below: */ const BRAND_ID = 'EDIT_HERE'; const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); async function main() { const authClient = await initCredentials(); if (authClient) { const apiParams = { auth: authClient, parent: 'brands/' + BRAND_ID, }; bcApi.brands.locations.list(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { console.log(response.data); } }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // Configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // Authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } main();
Java
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.Location; import com.google.common.collect.ImmutableMap; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); BusinessCommunications.Brands.Locations.List request = builder.build().brands().locations().list("brands/BRAND_ID"); ListEste código se basa en la biblioteca cliente de Business Communications de Java.locations = request.execute().getLocations(); locations.stream().forEach(location -> { try { System.out.println(location.toPrettyString()); } catch (IOException e) { e.printStackTrace(); } }); } catch (Exception e) { e.printStackTrace(); } } }
Python
"""This code gets all locations where a brand is available. Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/list This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1 from businesscommunications.businesscommunications_v1_messages import ( BusinesscommunicationsBrandsLocationsListRequest, Location ) # Edit the values below: BRAND_ID = 'EDIT_HERE' SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = './service_account_key.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) locations_service = BusinesscommunicationsV1.BrandsLocationsService(client) location_name = 'brands/' + BRAND_ID + '/locations' locations = locations_service.List( BusinesscommunicationsBrandsLocationsListRequest(name=location_name) ) print(locations)
Para ver las opciones de formato y de valor, consulta brands.locations.list
.
Actualizar una ubicación
Para actualizar una ubicación, realiza una solicitud PATCH con la API de Business Communications. Cuando realizas la llamada a la API, incluyes los nombres de los campos que estás editando como valores para el parámetro de URL "updateMask".
Por ejemplo, si actualizas los campos defaultLocale y agent, el parámetro de URL "updateMask" es "updateMask=defaultLocale,agent".
Para ver las opciones de formato y de valor, consulta brands.locations.patch
.
Si no conoces el name
de una ubicación, consulta Enumera todas las ubicaciones de una marca.
Ejemplo: Actualiza la configuración regional predeterminada
cURL
# This code updates the default locale of an agent. # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/patch # Replace the __BRAND_ID__ and __LOCATION_ID__ # Make sure a service account key file exists at ./service_account_key.json curl -X PATCH \ "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/locations/__LOCATION_ID__?updateMask=defaultLocale" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json ./service_account_key.json businesscommunications)" \ -d '{ "defaultLocale": "en" }'
Node.js
/** * This code snippet updates the defaultLocale of a Business Messages agent. * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/patch * * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js * Business Communications client library. */ /** * Edit the values below: */ const BRAND_ID = 'EDIT_HERE'; const LOCATION_ID = 'EDIT_HERE'; const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); async function main() { const authClient = await initCredentials(); if (authClient) { const locationObject = { defaultLocale: 'en' }; const apiParams = { auth: authClient, name: 'brands/' + BRAND_ID + '/locations/' + LOCATION_ID, resource: locationObject, updateMask: 'defaultLocale', }; bcApi.brands.locations.patch(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { console.log(response.data); } }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // Configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // Authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } main();
Java
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.businesscommunications.v1.BusinessCommunications; import com.google.api.services.businesscommunications.v1.model.Location; import com.google.common.collect.ImmutableMap; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); BusinessCommunications.Brands.Locations.Patch request = builder.build().brands().locations().patch("brands/BRAND_ID/locations/LOCATION_ID", new Location() .setDefaultLocale("en")); request.setUpdateMask("defaultLocale"); Location location = request.execute(); System.out.println(location.toPrettyString()); } catch (Exception e) { e.printStackTrace(); } } }Este código se basa en la biblioteca cliente de Business Communications de Java.
Python
"""This code updates the default locale of an agent. Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/patch This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1 from businesscommunications.businesscommunications_v1_messages import ( BusinesscommunicationsBrandsLocationsPatchRequest, Location ) # Edit the values below: BRAND_ID = 'EDIT_HERE' LOCATION_ID = 'EDIT_HERE' SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = './service_account_key.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) locations_service = BusinesscommunicationsV1.BrandsLocationsService(client) location = Location(defaultLocale='US') location_name = 'brands/' + BRAND_ID + '/locations/' + LOCATION_ID updated_location = locations_service.Patch( BusinesscommunicationsBrandsLocationsPatchRequest( location=location, name=location_name, updateMask='defaultLocale' ) ) print(updated_location)
Cómo borrar una ubicación
Cuando borras un agente, Business Messages borra todos los datos de ubicación. Business Messages no borra los mensajes que envió tu agente relacionados con la ubicación que está en tránsito o almacenada en el dispositivo de un usuario. Los mensajes para los usuarios no son datos de ubicación.
Las solicitudes de eliminación fallan si intentaste verificar la ubicación una o más veces. Para borrar una ubicación que verificaste o intentaste verificar, comunícate con nosotros. (Primero debes acceder con una Cuenta de Google de Business Messages. Para registrarte en una cuenta, consulta Regístrate con Business Messages.
Para borrar una ubicación, ejecuta el siguiente comando. Reemplaza BRAND_ID y LOCATION_ID por los valores únicos de name
de la ubicación.
cURL
# This code deletes a location where a brand is available. # Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/delete # Replace the __BRAND_ID__ and __LOCATION_ID__ # Make sure a service account key file exists at ./service_account_key.json curl -X DELETE \ "https://businesscommunications.googleapis.com/v1/brands/__BRAND_ID__/locations/__LOCATION_ID__" \ -H "Content-Type: application/json" \ -H "User-Agent: curl/business-communications" \ -H "$(oauth2l header --json ./service_account_key.json businesscommunications)"
Node.js
/** * This code snippet deletes a location. * Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/delete * * This code is based on the https://github.com/google-business-communications/nodejs-businesscommunications Node.js * Business Communications client library. */ /** * Edit the values below: */ const BRAND_ID = 'EDIT_HERE'; const LOCATION_ID = 'EDIT_HERE'; const PATH_TO_SERVICE_ACCOUNT_KEY = './service_account_key.json'; const businesscommunications = require('businesscommunications'); const {google} = require('googleapis'); // Initialize the Business Communications API const bcApi = new businesscommunications.businesscommunications_v1.Businesscommunications({}); // Set the scope that we need for the Business Communications API const scopes = [ 'https://www.googleapis.com/auth/businesscommunications', ]; // Set the private key to the service account file const privatekey = require(PATH_TO_SERVICE_ACCOUNT_KEY); async function main() { const authClient = await initCredentials(); if (authClient) { const apiParams = { auth: authClient, name: 'brands/' + BRAND_ID + '/locations/' + LOCATION_ID, }; bcApi.brands.locations.delete(apiParams, {}, (err, response) => { if (err !== undefined && err !== null) { console.dir(err); } else { console.log(response.data); } }); } else { console.log('Authentication failure.'); } } /** * Initializes the Google credentials for calling the * Business Messages API. */ async function initCredentials() { // Configure a JWT auth client const authClient = new google.auth.JWT( privatekey.client_email, null, privatekey.private_key, scopes, ); return new Promise(function(resolve, reject) { // Authenticate request authClient.authorize(function(err, tokens) { if (err) { reject(false); } else { resolve(authClient); } }); }); } main();
Java
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.businesscommunications.v1.BusinessCommunications; import com.google.common.collect.ImmutableMap; import java.io.FileInputStream; import java.util.Arrays; import java.util.UUID; class Main { /** * Initializes credentials used by the Business Communications API. */ private static BusinessCommunications.Builder getBusinessCommunicationsBuilder() { BusinessCommunications.Builder builder = null; try { GoogleCredential credential = GoogleCredential .fromStream(new FileInputStream("PATH_TO_SERVICE_ACCOUNT_KEY")); credential = credential.createScoped(Arrays.asList( "https://www.googleapis.com/auth/businesscommunications")); credential.refreshToken(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance(); // Create instance of the Business Communications API builder = new BusinessCommunications .Builder(httpTransport, jsonFactory, null) .setApplicationName(credential.getServiceAccountProjectId()); // Set the API credentials and endpoint builder.setHttpRequestInitializer(credential); } catch (Exception e) { e.printStackTrace(); } return builder; } public static void main(String args[]) { try { // Create client library reference BusinessCommunications.Builder builder = getBusinessCommunicationsBuilder(); BusinessCommunications.Brands.Locations.Delete request = builder.build().brands().locations() .delete("brands/BRAND_ID/locations/LOCATION_ID"); System.out.println(request.execute().toPrettyString()); } catch (Exception e) { e.printStackTrace(); } } }Este código se basa en la biblioteca cliente de Business Communications de Java.
Python
"""This code deletes a location where a brand is available. Read more: https://developers.google.com/business-communications/business-messages/reference/business-communications/rest/v1/brands.locations/delete This code is based on the https://github.com/google-business-communications/python-businessmessages Python Business Messages client library. """ from oauth2client.service_account import ServiceAccountCredentials from businesscommunications.businesscommunications_v1_client import BusinesscommunicationsV1 from businesscommunications.businesscommunications_v1_messages import ( BusinesscommunicationsBrandsLocationsDeleteRequest, LocationEntryPointConfig, Location ) # Edit the values below: BRAND_ID = 'EDIT_HERE' LOCATION_ID = 'EDIT_HERE' SCOPES = ['https://www.googleapis.com/auth/businesscommunications'] SERVICE_ACCOUNT_FILE = './service_account_key.json' credentials = ServiceAccountCredentials.from_json_keyfile_name( SERVICE_ACCOUNT_FILE, scopes=SCOPES) client = BusinesscommunicationsV1(credentials=credentials) locations_service = BusinesscommunicationsV1.BrandsLocationsService(client) location_name = 'brands/' + BRAND_ID + '/locations/' + LOCATION_ID location = locations_service.Delete(BusinesscommunicationsBrandsLocationsDeleteRequest( name=location_name )) print(location)
Para ver las opciones de formato y de valor, consulta brands.locations.delete
.
Próximos pasos
Ahora que tienes un agente con ubicaciones, puedes diseñar tus flujos de mensajería.