Crea transacciones físicas con pagos administrados por el comercio (Dialogflow)

En esta guía, te explicaremos el proceso de desarrollo de un proyecto de Acciones que incorpore transacciones de bienes físicos con formas de pago administradas por tu sitio.

Flujo de transacciones

Cuando tu proyecto de Acciones controla transacciones físicas con pagos administrados por comercios, usa el siguiente flujo:

  1. Recopilar información (opcional): Según la naturaleza de la transacción, es posible que desees recopilar la siguiente información del usuario al comienzo de la conversación:
    1. Valida los requisitos de las transacciones: Usa el asistente de requisitos de las transacciones al comienzo de la conversación para asegurarte de que la información de pago del usuario esté configurada correctamente y esté disponible antes de que el usuario cree su carrito.
    2. Solicita una dirección de entrega: Si tu transacción requiere una dirección de entrega, solicita la entrega del intent auxiliar de la dirección de entrega para obtener una del usuario.
  2. Crea el pedido: Guía al usuario a través de un "ensamblaje del carrito" en el que elige los artículos que desea comprar.
  3. Vincular cuentas: Para que el usuario pueda usar una forma de pago que haya guardado con tu servicio, usa la vinculación de cuentas a fin de asociar su Cuenta de Google con su cuenta en tu servicio.
  4. Proponer el pedido: Una vez que el carrito esté completo, propón el pedido al usuario para que pueda confirmar que es correcto. Si se confirma el pedido, recibirás una respuesta con los detalles del pedido y un token de pago.
  5. Finalizar el pedido y enviar una confirmación: Una vez confirmado el pedido, actualiza el seguimiento de inventario o algún otro servicio de entrega y, luego, envía una confirmación al usuario.
  6. Enviar actualizaciones de pedidos: Durante el transcurso de la vida útil de la entrega del pedido, envía solicitudes PATCH a la API de pedidos para proporcionar al usuario actualizaciones del pedido.

Restricciones y lineamientos para la revisión

Ten en cuenta que se aplican políticas adicionales a las Acciones con transacciones. Podemos demorar hasta seis semanas en revisar las Acciones con transacciones, así que ten en cuenta ese tiempo cuando planifiques tu programa de lanzamientos. Para facilitar el proceso de revisión, asegúrate de cumplir con las políticas y los lineamientos para las transacciones antes de enviar tu Acción a revisión.

Solo puedes implementar Acciones que vendan bienes físicos en los siguientes países:

Australia
Brasil
Canadá
Indonesia
Japón
México
Catar
Rusia
Singapur
Suiza
Tailandia
Turquía
Reino Unido
Estados Unidos

Cómo compilar un proyecto

Si deseas ver una amplia variedad de ejemplos de conversaciones transaccionales, consulta nuestros ejemplos de transacciones en Node.js y Java.

Configuración del proyecto

Cuando creas tu acción, debes especificar que deseas realizar transacciones en la Consola de Actions. Además, si usas la biblioteca cliente de Node.JS, configura tu entrega para que use la versión más reciente de la API de Orders.

Para configurar tu proyecto y la entrega, haz lo siguiente:

  1. Crea un proyecto nuevo o importa uno existente.
  2. Ve a Implementar > Información del directorio.
  3. En Información adicional > Transacciones > marca la casilla que dice “¿Tus acciones usan la API de transacciones para realizar transacciones de bienes físicos?”.

  4. Si usas la biblioteca cliente de Node.JS para compilar la entrega de tu acción, abre el código de entrega y actualiza la delegación de la app a fin de establecer la marca ordersv3 en true. En el siguiente fragmento de código, se muestra un ejemplo de declaración de app para la versión 3 de Orders.

Node.js

const {dialogflow} = require('actions-on-google');
let app = dialogflow({
  clientId, // If using account linking
  debug: true,
  ordersv3: true,
});

Node.js

const {actionssdk} = require('actions-on-google');
let app = actionssdk({
  clientId, // If using account linking
  debug: true,
  ordersv3: true,
});

Configuración de acceso

Cuando uses tu propia forma de pago para cobrar al usuario, te recomendamos que vincules su Cuenta de Google con una cuenta que tenga en tu propio servicio para recuperar, presentar y cobrar a las formas de pago almacenadas allí.

Para satisfacer este requisito, proporcionamos la vinculación de cuentas mediante OAuth 2.0. Recomendamos habilitar el flujo de aserción de OAuth 2.0, ya que permite una experiencia del usuario muy optimizada.

Proporcionamos el intent actions.intent.SIGN_IN, que te permite solicitar que un usuario vincule cuentas durante una conversación. Debes habilitar la vinculación de cuentas en la Consola de Actions para usar el intent actions.intent.SIGN_IN.

Debes usar este intent si no puedes encontrar un accessToken en el objeto User de la solicitud de webhook. Esto significa que el usuario aún no ha vinculado su cuenta.

Después de solicitar el intent actions.intent.SIGN_IN, recibirás un Argument que contiene un SignInStatus con un valor de "OK", "CANCELLED" o "ERROR". Si el estado es "OK", deberías poder encontrar un accessToken en el objeto User.

Entrega

Solicitar acceso

Node.js

app.intent('Sign In', (conv) => {
  conv.ask(new SignIn('To get your account details'));
});

Node.js

conv.ask(new SignIn('To get your account details'));

Java

@ForIntent("Sign In")
public ActionResponse signIn(ActionRequest request) {
  return getResponseBuilder(request).add(
      new SignIn()
          .setContext("To get your account details"))
      .build();
}

Java

return getResponseBuilder(request).add(
    new SignIn()
        .setContext("To get your account details"))
    .build();

JSON

{
    "payload": {
      "google": {
        "expectUserResponse": true,
        "systemIntent": {
          "intent": "actions.intent.SIGN_IN",
          "data": {
            "@type": "type.googleapis.com/google.actions.v2.SignInValueSpec",
            "optContext": "To get your account details"
          }
        }
      }
    }
  }

JSON

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.SIGN_IN",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.SignInValueSpec",
            "optContext": "To get your account details"
          }
        }
      ]
    }
  ],
  "conversationToken": "{\"data\":{\"paymentType\":\"merchant_payment\"}}"
}
Recibe el resultado de acceso

Node.js

app.intent('Sign In Complete', (conv, params, signin) => {
  if (signin.status !== 'OK') {
    conv.ask('You need to sign in before making a transaction.');
  } else {
    const accessToken = conv.user.access.token;
    // possibly do something with access token
    conv.ask('You must meet all the requirements necessary ' +
      'to make a transaction. Try saying ' +
      '"check transaction requirements".');
      conv.ask(new Suggestions(`check requirements`));
  }
});

Node.js

app.intent('actions.intent.SIGN_IN', (conv, params, signin) => {
  if (signin.status !== 'OK') {
    conv.ask('You need to sign in before making a transaction.');
  } else {
    const accessToken = conv.user.access.token;
    // possibly do something with access token
    conv.ask('You must meet all the requirements necessary ' +
      'to make a transaction. Try saying ' +
      '"check transaction requirements".');
      conv.ask(new Suggestions(`check requirements`));
  }
});

Java

@ForIntent("Sign In Complete")
public ActionResponse signInComplete(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (request.isSignInGranted()) {
    responseBuilder
        .add("You must meet all the requirements necessary to make a " +
            "transaction. Try saying \"check transaction requirements\".")
        .addSuggestions(new String[] {
            "check requirements"
        });
  } else {
    responseBuilder.add("You need to sign in before making a transaction.");
  }
  return responseBuilder.build();
}

Java

@ForIntent("actions.intent.SIGN_IN")
public ActionResponse signInComplete(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (request.isSignInGranted()) {
    responseBuilder
        .add("You must meet all the requirements necessary to make a " +
            "transaction. Try saying \"check transaction requirements\".")
        .addSuggestions(new String[] {
            "check requirements"
        });
  } else {
    responseBuilder.add("You need to sign in before making a transaction.");
  }
  return responseBuilder.build();
}

JSON

{
    "responseId": "d2123d8d-3f00-466e-b5a9-1a4ed53a7cb7-594de0a7",
    "queryResult": {
      "queryText": "actions_intent_SIGN_IN",
      "parameters": {},
      "allRequiredParamsPresent": true,
      "fulfillmentMessages": [
        {
          "text": {
            "text": [
              ""
            ]
          }
        }
      ],
      "outputContexts": [
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/merchant_payment",
          "lifespanCount": 2
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_web_browser"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_screen_output"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_account_linking"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_media_response_audio"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_audio_output"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/google_assistant_input_type_keyboard"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_intent_sign_in",
          "parameters": {
            "SIGN_IN": {
              "@type": "type.googleapis.com/google.actions.v2.SignInValue",
              "status": "OK"
            },
            "text": ""
          }
        }
      ],
      "intent": {
        "name": "projects/df-transactions/agent/intents/105b925b-b186-4f5d-8bde-a9a782a0fa9f",
        "displayName": "Sign In Complete"
      },
      "intentDetectionConfidence": 1,
      "languageCode": "en"
    },
    "originalDetectIntentRequest": {
      "source": "google",
      "version": "2",
      "payload": {
        "user": {
          "locale": "en-US",
          "lastSeen": "2019-09-23T19:49:18Z",
          "userVerificationStatus": "VERIFIED"
        },
        "conversation": {
          "conversationId": "ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy",
          "type": "ACTIVE",
          "conversationToken": "[]"
        },
        "inputs": [
          {
            "intent": "actions.intent.SIGN_IN",
            "rawInputs": [
              {
                "inputType": "KEYBOARD"
              }
            ],
            "arguments": [
              {
                "name": "SIGN_IN",
                "extension": {
                  "@type": "type.googleapis.com/google.actions.v2.SignInValue",
                  "status": "OK"
                }
              },
              {
                "name": "text"
              }
            ]
          }
        ],
        "surface": {
          "capabilities": [
            {
              "name": "actions.capability.WEB_BROWSER"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.ACCOUNT_LINKING"
            },
            {
              "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
            },
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            }
          ]
        },
        "availableSurfaces": [
          {
            "capabilities": [
              {
                "name": "actions.capability.WEB_BROWSER"
              },
              {
                "name": "actions.capability.AUDIO_OUTPUT"
              },
              {
                "name": "actions.capability.SCREEN_OUTPUT"
              }
            ]
          }
        ]
      }
    },
    "session": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy"
  }

JSON

{
  "user": {
    "locale": "en-US",
    "lastSeen": "2019-11-11T23:55:52Z",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHGFwStZlYaQ9YT8rg9t_idVsxZrku1pUDrEbGSJmSUMatVdPwPEEQSCe1IwIBoN4sS4Weyn9pmgetEgbsWgw3JSvQmw",
    "type": "ACTIVE",
    "conversationToken": "{\"data\":{\"paymentType\":\"merchant_payment\"}}"
  },
  "inputs": [
    {
      "intent": "actions.intent.SIGN_IN",
      "rawInputs": [
        {}
      ],
      "arguments": [
        {
          "name": "SIGN_IN",
          "extension": {
            "@type": "type.googleapis.com/google.actions.v2.SignInValue",
            "status": "OK"
          }
        },
        {
          "name": "text"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      }
    ]
  },
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        }
      ]
    }
  ]
}

1. Recopila información (opcional)

1a. Valida los requisitos de las transacciones (opcional)

Experiencia del usuario

Activa el intent actions.intent.TRANSACTION_REQUIREMENTS_CHECK para comprobar rápidamente si los usuarios podrán realizar una transacción o no. Este paso garantizará que los usuarios puedan continuar y les dará la oportunidad de corregir cualquier configuración que les impida completar una transacción.

Por ejemplo, cuando se invoca, tu Acción podría preguntar: "¿Te gustaría pedir zapatos o consultar el saldo de tu cuenta?" Si el usuario dice "pedir calzado", debes solicitar este intent de inmediato, lo que garantizará que pueda continuar y le dará la oportunidad de corregir cualquier configuración que impida continuar con la transacción.

Solicitar el intent de verificación de requisitos de las transacciones dará como resultado uno de los siguientes resultados:

  • Si se cumplen los requisitos, el intent se enviará de vuelta a tu entrega con una condición de éxito y podrás continuar con la creación del pedido del usuario.
  • Si no se pueden cumplir uno o más de los requisitos, el intent se enviará de vuelta a tu entrega con una condición de falla. En este caso, debes alejar la conversación de la experiencia transaccional o finalizar la conversación.
    • Si el usuario puede corregir los errores que generan el estado de falla, se le solicitará que resuelvan esos problemas en el dispositivo. Si la conversación se realiza en una superficie solo de voz, se iniciará una transferencia en el teléfono del usuario.
Entrega

Para asegurarte de que un usuario cumpla con los requisitos de la transacción, solicita la entrega del intent actions.intent.TRANSACTION_REQUIREMENTS_CHECK con un objeto TransactionRequirementsCheckSpec.

Cómo consultar los requisitos

Puedes verificar si un usuario cumple con los requisitos de las transacciones mediante la biblioteca cliente:

Node.js

conv.ask(new TransactionRequirements());

Node.js

conv.ask(new TransactionRequirements());

Java

return getResponseBuilder(request)
    .add(new TransactionRequirements())
    .build();

Java

return getResponseBuilder(request)
    .add(new TransactionRequirements())
    .build();

JSON

{
    "payload": {
      "google": {
        "expectUserResponse": true,
        "systemIntent": {
          "intent": "actions.intent.TRANSACTION_REQUIREMENTS_CHECK",
          "data": {
            "@type": "type.googleapis.com/google.actions.transactions.v3.TransactionRequirementsCheckSpec"
          }
        }
      }
    }
  }

JSON

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.TEXT"
        }
      ],
      "inputPrompt": {
        "richInitialPrompt": {
          "items": [
            {
              "simpleResponse": {
                "textToSpeech": "Looks like you're good to go! Next I'll need your delivery address.Try saying \"get delivery address\"."
              }
            }
          ],
          "suggestions": [
            {
              "title": "get delivery address"
            }
          ]
        }
      }
    }
  ],
  "conversationToken": "{\"data\":{\"paymentType\":\"merchant_payment\"}}"
}
Cómo recibir el resultado de una verificación de requisitos

Una vez que Asistente entrega el intent, le envía a tu entrega una solicitud con el intent actions.intent.TRANSACTION_REQUIREMENTS_CHECK con el resultado de la verificación. Para manejar de forma correcta esta solicitud, declara un intent de Dialogflow que se active con el evento actions_intent_TRANSACTION_REQUIREMENTS_CHECK. Cuando se active, controla la entrega en tu entrega con la biblioteca cliente:

Node.js

app.intent('Transaction Check Complete', (conv) => {
  const arg = conv.arguments.get('TRANSACTION_REQUIREMENTS_CHECK_RESULT');
  if (arg && arg.resultType === 'CAN_TRANSACT') {
    // Normally take the user through cart building flow
    conv.ask(`Looks like you're good to go! ` +
      `Next I'll need your delivery address.` +
      `Try saying "get delivery address".`);
    conv.ask(new Suggestions('get delivery address'));
  } else {
    // Exit conversation
    conv.close('Transaction failed.');
  }
});

Node.js

app.intent('actions.intent.TRANSACTION_REQUIREMENTS_CHECK', (conv) => {
  const arg = conv.arguments.get('TRANSACTION_REQUIREMENTS_CHECK_RESULT');
  if (arg && arg.resultType === 'CAN_TRANSACT') {
    // Normally take the user through cart building flow
    conv.ask(`Looks like you're good to go! ` +
      `Next I'll need your delivery address.` +
      `Try saying "get delivery address".`);
    conv.ask(new Suggestions('get delivery address'));
  } else {
    // Exit conversation
    conv.close('Transaction failed.');
  }
});

Java

@ForIntent("Transaction Check Complete")
public ActionResponse transactionCheckComplete(ActionRequest request) {
  LOGGER.info("Checking Transaction Requirements Result.");

  // Check result of transaction requirements check
  Argument transactionCheckResult = request
      .getArgument("TRANSACTION_REQUIREMENTS_CHECK_RESULT");
  boolean result = false;
  if (transactionCheckResult != null) {
    Map<String, Object> map = transactionCheckResult.getExtension();
    if (map != null) {
      String resultType = (String) map.get("resultType");
      result = resultType != null && resultType.equals("CAN_TRANSACT");
    }
  }

  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (result) {
    // Normally take the user through cart building flow
    responseBuilder
        .add("Looks like you're good to go! Next " +
            "I'll need your delivery address. Try saying " +
            "\"get delivery address\".")
        .addSuggestions(new String[]{"get delivery address"});
  } else {
    // Exit conversation
    responseBuilder.add("Transaction failed.");
  }
  return responseBuilder.build();
}

Java

@ForIntent("actions.intent.TRANSACTION_REQUIREMENTS_CHECK")
public ActionResponse transactionCheckComplete(ActionRequest request) {
  LOGGER.info("Checking Transaction Requirements Result.");

  // Check result of transaction requirements check
  Argument transactionCheckResult = request
      .getArgument("TRANSACTION_REQUIREMENTS_CHECK_RESULT");
  boolean result = false;
  if (transactionCheckResult != null) {
    Map<String, Object> map = transactionCheckResult.getExtension();
    if (map != null) {
      String resultType = (String) map.get("resultType");
      result = resultType != null && resultType.equals("CAN_TRANSACT");
    }
  }

  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (result) {
    // Normally take the user through cart building flow
    responseBuilder
        .add("Looks like you're good to go! Next " +
            "I'll need your delivery address. Try saying " +
            "\"get delivery address\".")
        .addSuggestions(new String[]{"get delivery address"});
  } else {
    // Exit conversation
    responseBuilder.add("Transaction failed.");
  }
  return responseBuilder.build();
}

JSON

{
    "responseId": "db1a333c-2781-41e3-84b1-cc0cc37643d7-594de0a7",
    "queryResult": {
      "queryText": "actions_intent_TRANSACTION_REQUIREMENTS_CHECK",
      "action": "transaction.check.complete",
      "parameters": {},
      "allRequiredParamsPresent": true,
      "fulfillmentText": "Failed to get transaction check results",
      "fulfillmentMessages": [
        {
          "text": {
            "text": [
              "Failed to get transaction check results"
            ]
          }
        }
      ],
      "outputContexts": [
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_media_response_audio"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_audio_output"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_account_linking"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_screen_output"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_web_browser"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/google_assistant_input_type_keyboard"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/merchant_payment",
          "lifespanCount": 1
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_intent_transaction_requirements_check",
          "parameters": {
            "TRANSACTION_REQUIREMENTS_CHECK_RESULT": {
              "@type": "type.googleapis.com/google.actions.transactions.v3.TransactionRequirementsCheckResult",
              "resultType": "CAN_TRANSACT"
            },
            "text": ""
          }
        }
      ],
      "intent": {
        "name": "projects/df-transactions/agent/intents/fd16d86b-60db-4d19-a683-5b52a22f4795",
        "displayName": "Transaction Check Complete"
      },
      "intentDetectionConfidence": 1,
      "languageCode": "en"
    },
    "originalDetectIntentRequest": {
      "source": "google",
      "version": "2",
      "payload": {
        "user": {
          "locale": "en-US",
          "lastSeen": "2019-09-23T19:49:32Z",
          "userVerificationStatus": "VERIFIED"
        },
        "conversation": {
          "conversationId": "ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy",
          "type": "ACTIVE",
          "conversationToken": "[\"merchant_payment\"]"
        },
        "inputs": [
          {
            "intent": "actions.intent.TRANSACTION_REQUIREMENTS_CHECK",
            "rawInputs": [
              {
                "inputType": "KEYBOARD"
              }
            ],
            "arguments": [
              {
                "name": "TRANSACTION_REQUIREMENTS_CHECK_RESULT",
                "extension": {
                  "@type": "type.googleapis.com/google.actions.transactions.v3.TransactionRequirementsCheckResult",
                  "resultType": "CAN_TRANSACT"
                }
              },
              {
                "name": "text"
              }
            ]
          }
        ],
        "surface": {
          "capabilities": [
            {
              "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
            },
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            },
            {
              "name": "actions.capability.ACCOUNT_LINKING"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.WEB_BROWSER"
            }
          ]
        },
        "availableSurfaces": [
          {
            "capabilities": [
              {
                "name": "actions.capability.WEB_BROWSER"
              },
              {
                "name": "actions.capability.AUDIO_OUTPUT"
              },
              {
                "name": "actions.capability.SCREEN_OUTPUT"
              }
            ]
          }
        ]
      }
    },
    "session": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy"
  }

JSON

{
  "user": {
    "locale": "en-US",
    "lastSeen": "2019-11-11T23:56:03Z",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHGFwStZlYaQ9YT8rg9t_idVsxZrku1pUDrEbGSJmSUMatVdPwPEEQSCe1IwIBoN4sS4Weyn9pmgetEgbsWgw3JSvQmw",
    "type": "ACTIVE",
    "conversationToken": "{\"data\":{\"paymentType\":\"merchant_payment\"}}"
  },
  "inputs": [
    {
      "intent": "actions.intent.TRANSACTION_REQUIREMENTS_CHECK",
      "rawInputs": [
        {}
      ],
      "arguments": [
        {
          "name": "TRANSACTION_REQUIREMENTS_CHECK_RESULT",
          "extension": {
            "@type": "type.googleapis.com/google.actions.transactions.v3.TransactionRequirementsCheckResult",
            "resultType": "CAN_TRANSACT"
          }
        },
        {
          "name": "text"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      }
    ]
  },
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        }
      ]
    }
  ]
}

1b. Solicitar una dirección de entrega (opcional)

Si tu transacción requiere la dirección de entrega de un usuario, puedes solicitar la entrega del intent actions.intent.DELIVERY_ADDRESS. Esto puede ser útil para determinar el precio total o la ubicación de entrega o retiro, o para garantizar que el usuario se encuentre dentro de tu región de servicio.

Cuando solicitas que se entregue este intent, pasas una opción reason que te permite anteponer la solicitud de Asistente para obtener una dirección con una cadena. Por ejemplo, si especificas "saber a dónde enviar el pedido", Asistente podría preguntar al usuario lo siguiente:

"Para saber a dónde enviar el pedido, necesito tu dirección de entrega"

Experiencia del usuario

En las plataformas que tienen pantalla, el usuario elegirá la dirección que desea usar para la transacción. Si no proporcionó una dirección antes, podrá ingresar una nueva.

En plataformas solo de voz, Asistente le pedirá permiso al usuario para compartir su dirección predeterminada de la transacción. Si no proporcionó una dirección antes, la conversación se entregará a un teléfono para que ingrese.

Solicita la dirección

Node.js

app.intent('Delivery Address', (conv) => {
  conv.ask(new DeliveryAddress({
    addressOptions: {
      reason: 'To know where to send the order',
    },
  }));
});

Node.js

conv.ask(new DeliveryAddress({
  addressOptions: {
    reason: 'To know where to send the order',
  },
}));

Java

@ForIntent("Delivery Address")
public ActionResponse deliveryAddress(ActionRequest request) {
  DeliveryAddressValueSpecAddressOptions addressOptions =
      new DeliveryAddressValueSpecAddressOptions()
          .setReason("To know where to send the order");
  return getResponseBuilder(request)
      .add(new DeliveryAddress()
          .setAddressOptions(addressOptions))
      .build();
}

Java

DeliveryAddressValueSpecAddressOptions addressOptions =
    new DeliveryAddressValueSpecAddressOptions()
        .setReason("To know where to send the order");
return getResponseBuilder(request)
    .add(new DeliveryAddress()
        .setAddressOptions(addressOptions))
    .build();

JSON

{
    "payload": {
      "google": {
        "expectUserResponse": true,
        "systemIntent": {
          "intent": "actions.intent.DELIVERY_ADDRESS",
          "data": {
            "@type": "type.googleapis.com/google.actions.v2.DeliveryAddressValueSpec",
            "addressOptions": {
              "reason": "To know where to send the order"
            }
          }
        }
      }
    }
  }

JSON

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.DELIVERY_ADDRESS",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.DeliveryAddressValueSpec",
            "addressOptions": {
              "reason": "To know where to send the order"
            }
          }
        }
      ]
    }
  ],
  "conversationToken": "{\"data\":{\"paymentType\":\"merchant_payment\"}}"
}
Recibe la dirección

Una vez que Asistente entrega el intent, envía una solicitud a tu entrega con el intent actions.intent.DELIVERY_ADDRESS.

Para manejar de forma correcta esta solicitud, declara un intent de Dialogflow que se active con el evento actions_intent_DELIVERY_ADDRESS. Cuando se active, controla esto en tu entrega mediante la biblioteca cliente:

Node.js

app.intent('Delivery Address Complete', (conv) => {
  const arg = conv.arguments.get('DELIVERY_ADDRESS_VALUE');
  if (arg && arg.userDecision ==='ACCEPTED') {
    conv.data.location = arg.location;
    conv.ask('Great, got your address! Now say "confirm transaction".');
    conv.ask(new Suggestions('confirm transaction'));
  } else {
    conv.close('Transaction failed.');
  }
});

Node.js

app.intent('actions.intent.DELIVERY_ADDRESS', (conv) => {
  const arg = conv.arguments.get('DELIVERY_ADDRESS_VALUE');
  if (arg && arg.userDecision ==='ACCEPTED') {
    conv.data.location = arg.location;
    conv.ask('Great, got your address! Now say "confirm transaction".');
    conv.ask(new Suggestions('confirm transaction'));
  } else {
    conv.close('Transaction failed.');
  }
});

Java

@ForIntent("Delivery Address Complete")
public ActionResponse deliveryAddressComplete(ActionRequest request) {
  Argument deliveryAddressValue = request.getArgument("DELIVERY_ADDRESS_VALUE");
  Location deliveryAddress = null;
  if (deliveryAddressValue != null) {
    Map<String, Object> map = deliveryAddressValue.getExtension();
    if (map != null) {
      String userDecision = (String) map.get("userDecision");
      Location location = (Location) map.get("location");
      deliveryAddress = userDecision != null && userDecision.equals("ACCEPTED") ? location : null;
    }
  }
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (deliveryAddress != null) {
    // Cache delivery address in conversation data for later use
    Map<String, Object> conversationData = request.getConversationData();
    conversationData.put("location",
        GSON_BUILDER.create().toJson(deliveryAddress, Location.class));
    responseBuilder
        .add("Great, got your address! Now say \"confirm transaction\".")
        .addSuggestions(new String[] {
            "confirm transaction"
        });
  } else {
    responseBuilder.add("Transaction failed.").endConversation();
  }
  return responseBuilder.build();
}

Java

@ForIntent("actions.intent.DELIVERY_ADDRESS")
public ActionResponse deliveryAddressComplete(ActionRequest request) {
  Argument deliveryAddressValue = request.getArgument("DELIVERY_ADDRESS_VALUE");
  Location deliveryAddress = null;
  if (deliveryAddressValue != null) {
    Map<String, Object> map = deliveryAddressValue.getExtension();
    if (map != null) {
      String userDecision = (String) map.get("userDecision");
      Location location = (Location) map.get("location");
      deliveryAddress = userDecision != null && userDecision.equals("ACCEPTED") ? location : null;
    }
  }
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (deliveryAddress != null) {
    // Cache delivery address in conversation data for later use
    Map<String, Object> conversationData = request.getConversationData();
    conversationData.put("location",
        GSON_BUILDER.create().toJson(deliveryAddress, Location.class));
    responseBuilder
        .add("Great, got your address! Now say \"confirm transaction\".")
        .addSuggestions(new String[] {
            "confirm transaction"
        });
  } else {
    responseBuilder.add("Transaction failed.").endConversation();
  }
  return responseBuilder.build();
}

JSON

{
    "responseId": "58b0c305-b437-47ac-8593-4fb0122a19e6-594de0a7",
    "queryResult": {
      "queryText": "actions_intent_DELIVERY_ADDRESS",
      "parameters": {},
      "allRequiredParamsPresent": true,
      "fulfillmentMessages": [
        {
          "text": {
            "text": [
              ""
            ]
          }
        }
      ],
      "outputContexts": [
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_media_response_audio"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_audio_output"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_account_linking"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_screen_output"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_web_browser"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_intent_delivery_address",
          "parameters": {
            "DELIVERY_ADDRESS_VALUE": {
              "@type": "type.googleapis.com/google.actions.v2.DeliveryAddressValue",
              "userDecision": "ACCEPTED",
              "location": {
                "coordinates": {
                  "latitude": 37.432524,
                  "longitude": -122.098545
                },
                "zipCode": "94043-1351",
                "city": "MOUNTAIN VIEW",
                "postalAddress": {
                  "regionCode": "US",
                  "postalCode": "94043-1351",
                  "administrativeArea": "CA",
                  "locality": "MOUNTAIN VIEW",
                  "addressLines": [
                    "1600 AMPHITHEATRE PKWY"
                  ],
                  "recipients": [
                    "John Doe"
                  ]
                },
                "phoneNumber": "+1 123-456-7890"
              }
            },
            "text": "1600 AMPHITHEATRE PKWY"
          }
        }
      ],
      "intent": {
        "name": "projects/df-transactions/agent/intents/0be5d130-1760-4355-85e9-4dc01da8bf3c",
        "displayName": "Delivery Address Complete"
      },
      "intentDetectionConfidence": 1,
      "languageCode": "en"
    },
    "originalDetectIntentRequest": {
      "source": "google",
      "version": "2",
      "payload": {
        "user": {
          "locale": "en-US",
          "lastSeen": "2019-09-23T19:49:55Z",
          "userVerificationStatus": "VERIFIED"
        },
        "conversation": {
          "conversationId": "ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy",
          "type": "ACTIVE",
          "conversationToken": "[]"
        },
        "inputs": [
          {
            "intent": "actions.intent.DELIVERY_ADDRESS",
            "rawInputs": [
              {
                "query": "1600 AMPHITHEATRE PKWY"
              }
            ],
            "arguments": [
              {
                "name": "DELIVERY_ADDRESS_VALUE",
                "extension": {
                  "@type": "type.googleapis.com/google.actions.v2.DeliveryAddressValue",
                  "userDecision": "ACCEPTED",
                  "location": {
                    "coordinates": {
                      "latitude": 37.432524,
                      "longitude": -122.098545
                    },
                    "zipCode": "94043-1351",
                    "city": "MOUNTAIN VIEW",
                    "postalAddress": {
                      "regionCode": "US",
                      "postalCode": "94043-1351",
                      "administrativeArea": "CA",
                      "locality": "MOUNTAIN VIEW",
                      "addressLines": [
                        "1600 AMPHITHEATRE PKWY"
                      ],
                      "recipients": [
                        "John Doe"
                      ]
                    },
                    "phoneNumber": "+1 123-456-7890"
                  }
                }
              }
            ]
          }
        ],
        "surface": {
          "capabilities": [
            {
              "name": "actions.capability.WEB_BROWSER"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.ACCOUNT_LINKING"
            },
            {
              "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
            },
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            }
          ]
        },
        "availableSurfaces": [
          {
            "capabilities": [
              {
                "name": "actions.capability.WEB_BROWSER"
              },
              {
                "name": "actions.capability.AUDIO_OUTPUT"
              },
              {
                "name": "actions.capability.SCREEN_OUTPUT"
              }
            ]
          }
        ]
      }
    },
    "session": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy"
  }

JSON

{
  "user": {
    "locale": "en-US",
    "lastSeen": "2019-11-11T23:57:20Z",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHGFwStZlYaQ9YT8rg9t_idVsxZrku1pUDrEbGSJmSUMatVdPwPEEQSCe1IwIBoN4sS4Weyn9pmgetEgbsWgw3JSvQmw",
    "type": "ACTIVE",
    "conversationToken": "{\"data\":{\"paymentType\":\"merchant_payment\"}}"
  },
  "inputs": [
    {
      "intent": "actions.intent.DELIVERY_ADDRESS",
      "rawInputs": [
        {
          "inputType": "VOICE",
          "query": "1600 AMPHITHEATRE PKWY"
        }
      ],
      "arguments": [
        {
          "name": "DELIVERY_ADDRESS_VALUE",
          "extension": {
            "@type": "type.googleapis.com/google.actions.v2.DeliveryAddressValue",
            "userDecision": "ACCEPTED",
            "location": {
              "coordinates": {
                "latitude": 37.421578499999995,
                "longitude": -122.0837816
              },
              "zipCode": "94043-1351",
              "city": "MOUNTAIN VIEW",
              "postalAddress": {
                "regionCode": "US",
                "postalCode": "94043-1351",
                "administrativeArea": "CA",
                "locality": "MOUNTAIN VIEW",
                "addressLines": [
                  "1600 AMPHITHEATRE PKWY"
                ],
                "recipients": [
                  "John Doe"
                ]
              },
              "phoneNumber": "+1 123-456-7890"
            }
          }
        },
        {
          "name": "text",
          "rawText": "1600 AMPHITHEATRE PKWY",
          "textValue": "1600 AMPHITHEATRE PKWY"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      },
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      }
    ]
  },
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        },
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        }
      ]
    }
  ]
}

2. Arma el pedido

Experiencia del usuario

Una vez que tengas la información del usuario que necesitas, podrás crear una experiencia de "ensamblaje del carrito" que guíe al usuario para crear un pedido. Cada acción tendrá un flujo de ensamblaje del carrito ligeramente diferente según corresponda para su producto o servicio.

En la experiencia de ensamblaje del carrito más básica, el usuario puede elegir elementos de una lista para agregar a su pedido, aunque puedes diseñar la conversación para simplificar la experiencia del usuario. Podrías crear una experiencia de armado del carrito que le permita al usuario volver a pedir su compra más reciente a través de una simple pregunta de sí o no. También puedes presentar al usuario un carrusel o una tarjeta de lista con los elementos principales "destacados" o "recomendados".

Recomendamos usar respuestas enriquecidas para presentar las opciones del usuario de forma visual, pero también diseñar la conversación de modo que el usuario pueda crear su carrito solo con su voz. Para obtener algunas prácticas recomendadas y ejemplos de experiencias de ensamblaje de carritos de alta calidad, consulta los Lineamientos de diseño de transacciones.

Entrega

A lo largo de la conversación, deberás recopilar los elementos que un usuario desea comprar y, luego, construir un objeto Order.

Como mínimo, tu Order debe contener lo siguiente:

  • buyerInfo: Es la información sobre el usuario que realiza la compra.
  • transactionMerchant: Es información sobre el comercio que facilitó el pedido.
  • contents: Es el contenido real del pedido que aparece como lineItems.
  • priceAttributes: Son los detalles de precios del pedido, incluido su costo total, con impuestos y descuentos.

Consulta la documentación sobre la respuesta de Order para crear tu carrito. Ten en cuenta que es posible que debas incluir diferentes campos según el orden.

El código de muestra que aparece a continuación presenta un orden completo, incluidos los campos opcionales:

Node.js

const order = {
  createTime: '2019-09-24T18:00:00.877Z',
  lastUpdateTime: '2019-09-24T18:00:00.877Z',
  merchantOrderId: orderId, // A unique ID String for the order
  userVisibleOrderId: orderId,
  transactionMerchant: {
    id: 'http://www.example.com',
    name: 'Example Merchant',
  },
  contents: {
    lineItems: [
      {
        id: 'LINE_ITEM_ID',
        name: 'Pizza',
        description: 'A four cheese pizza.',
        priceAttributes: [
          {
            type: 'REGULAR',
            name: 'Item Price',
            state: 'ACTUAL',
            amount: {
              currencyCode: 'USD',
              amountInMicros: 8990000,
            },
            taxIncluded: true,
          },
          {
            type: 'TOTAL',
            name: 'Total Price',
            state: 'ACTUAL',
            amount: {
              currencyCode: 'USD',
              amountInMicros: 9990000,
            },
            taxIncluded: true,
          },
        ],
        notes: [
          'Extra cheese.',
        ],
        purchase: {
          quantity: 1,
          unitMeasure: {
            measure: 1,
            unit: 'POUND',
          },
          itemOptions: [
            {
              id: 'ITEM_OPTION_ID',
              name: 'Pepperoni',
              prices: [
                {
                  type: 'REGULAR',
                  state: 'ACTUAL',
                  name: 'Item Price',
                  amount: {
                    currencyCode: 'USD',
                    amountInMicros: 1000000,
                  },
                  taxIncluded: true,
                },
                {
                  type: 'TOTAL',
                  name: 'Total Price',
                  state: 'ACTUAL',
                  amount: {
                    currencyCode: 'USD',
                    amountInMicros: 1000000,
                  },
                  taxIncluded: true,
                },
              ],
              note: 'Extra pepperoni',
              quantity: 1,
              subOptions: [],
            },
          ],
        },
      },
    ],
  },
  buyerInfo: {
    email: 'janedoe@gmail.com',
    firstName: 'Jane',
    lastName: 'Doe',
    displayName: 'Jane Doe',
  },
  priceAttributes: [
    {
      type: 'SUBTOTAL',
      name: 'Subtotal',
      state: 'ESTIMATE',
      amount: {
        currencyCode: 'USD',
        amountInMicros: 9990000,
      },
      taxIncluded: true,
    },
    {
      type: 'DELIVERY',
      name: 'Delivery',
      state: 'ACTUAL',
      amount: {
        currencyCode: 'USD',
        amountInMicros: 2000000,
      },
      taxIncluded: true,
    },
    {
      type: 'TAX',
      name: 'Tax',
      state: 'ESTIMATE',
      amount: {
        currencyCode: 'USD',
        amountInMicros: 3780000,
      },
      taxIncluded: true,
    },
    {
      type: 'TOTAL',
      name: 'Total Price',
      state: 'ESTIMATE',
      amount: {
        currencyCode: 'USD',
        amountInMicros: 15770000,
      },
      taxIncluded: true,
    },
  ],
  followUpActions: [
    {
      type: 'VIEW_DETAILS',
      title: 'View details',
      openUrlAction: {
        url: 'http://example.com',
      },
    },
    {
      type: 'CALL',
      title: 'Call us',
      openUrlAction: {
        url: 'tel:+16501112222',
      },
    },
    {
      type: 'EMAIL',
      title: 'Email us',
      openUrlAction: {
        url: 'mailto:person@example.com',
      },
    },
  ],
  termsOfServiceUrl: 'http://www.example.com',
  note: 'Sale event',
  promotions: [
    {
      coupon: 'COUPON_CODE',
    },
  ],
  purchase: {
    status: 'CREATED',
    userVisibleStatusLabel: 'CREATED',
    type: 'FOOD',
    returnsInfo: {
      isReturnable: false,
      daysToReturn: 1,
      policyUrl: 'http://www.example.com',
    },
    fulfillmentInfo: {
      id: 'FULFILLMENT_SERVICE_ID',
      fulfillmentType: 'DELIVERY',
      expectedFulfillmentTime: {
        timeIso8601: '2019-09-25T18:00:00.877Z',
      },
      location: location,
      price: {
        type: 'REGULAR',
        name: 'Delivery Price',
        state: 'ACTUAL',
        amount: {
          currencyCode: 'USD',
          amountInMicros: 2000000,
        },
        taxIncluded: true,
      },
      fulfillmentContact: {
        email: 'johnjohnson@gmail.com',
        firstName: 'John',
        lastName: 'Johnson',
        displayName: 'John Johnson',
      },
    },
    purchaseLocationType: 'ONLINE_PURCHASE',
  },
};

Node.js

const order = {
  createTime: '2019-09-24T18:00:00.877Z',
  lastUpdateTime: '2019-09-24T18:00:00.877Z',
  merchantOrderId: orderId, // A unique ID String for the order
  userVisibleOrderId: orderId,
  transactionMerchant: {
    id: 'http://www.example.com',
    name: 'Example Merchant',
  },
  contents: {
    lineItems: [
      {
        id: 'LINE_ITEM_ID',
        name: 'Pizza',
        description: 'A four cheese pizza.',
        priceAttributes: [
          {
            type: 'REGULAR',
            name: 'Item Price',
            state: 'ACTUAL',
            amount: {
              currencyCode: 'USD',
              amountInMicros: 8990000,
            },
            taxIncluded: true,
          },
          {
            type: 'TOTAL',
            name: 'Total Price',
            state: 'ACTUAL',
            amount: {
              currencyCode: 'USD',
              amountInMicros: 9990000,
            },
            taxIncluded: true,
          },
        ],
        notes: [
          'Extra cheese.',
        ],
        purchase: {
          quantity: 1,
          unitMeasure: {
            measure: 1,
            unit: 'POUND',
          },
          itemOptions: [
            {
              id: 'ITEM_OPTION_ID',
              name: 'Pepperoni',
              prices: [
                {
                  type: 'REGULAR',
                  state: 'ACTUAL',
                  name: 'Item Price',
                  amount: {
                    currencyCode: 'USD',
                    amountInMicros: 1000000,
                  },
                  taxIncluded: true,
                },
                {
                  type: 'TOTAL',
                  name: 'Total Price',
                  state: 'ACTUAL',
                  amount: {
                    currencyCode: 'USD',
                    amountInMicros: 1000000,
                  },
                  taxIncluded: true,
                },
              ],
              note: 'Extra pepperoni',
              quantity: 1,
              subOptions: [],
            },
          ],
        },
      },
    ],
  },
  buyerInfo: {
    email: 'janedoe@gmail.com',
    firstName: 'Jane',
    lastName: 'Doe',
    displayName: 'Jane Doe',
  },
  priceAttributes: [
    {
      type: 'SUBTOTAL',
      name: 'Subtotal',
      state: 'ESTIMATE',
      amount: {
        currencyCode: 'USD',
        amountInMicros: 9990000,
      },
      taxIncluded: true,
    },
    {
      type: 'DELIVERY',
      name: 'Delivery',
      state: 'ACTUAL',
      amount: {
        currencyCode: 'USD',
        amountInMicros: 2000000,
      },
      taxIncluded: true,
    },
    {
      type: 'TAX',
      name: 'Tax',
      state: 'ESTIMATE',
      amount: {
        currencyCode: 'USD',
        amountInMicros: 3780000,
      },
      taxIncluded: true,
    },
    {
      type: 'TOTAL',
      name: 'Total Price',
      state: 'ESTIMATE',
      amount: {
        currencyCode: 'USD',
        amountInMicros: 15770000,
      },
      taxIncluded: true,
    },
  ],
  followUpActions: [
    {
      type: 'VIEW_DETAILS',
      title: 'View details',
      openUrlAction: {
        url: 'http://example.com',
      },
    },
    {
      type: 'CALL',
      title: 'Call us',
      openUrlAction: {
        url: 'tel:+16501112222',
      },
    },
    {
      type: 'EMAIL',
      title: 'Email us',
      openUrlAction: {
        url: 'mailto:person@example.com',
      },
    },
  ],
  termsOfServiceUrl: 'http://www.example.com',
  note: 'Sale event',
  promotions: [
    {
      coupon: 'COUPON_CODE',
    },
  ],
  purchase: {
    status: 'CREATED',
    userVisibleStatusLabel: 'CREATED',
    type: 'FOOD',
    returnsInfo: {
      isReturnable: false,
      daysToReturn: 1,
      policyUrl: 'http://www.example.com',
    },
    fulfillmentInfo: {
      id: 'FULFILLMENT_SERVICE_ID',
      fulfillmentType: 'DELIVERY',
      expectedFulfillmentTime: {
        timeIso8601: '2019-09-25T18:00:00.877Z',
      },
      location: location,
      price: {
        type: 'REGULAR',
        name: 'Delivery Price',
        state: 'ACTUAL',
        amount: {
          currencyCode: 'USD',
          amountInMicros: 2000000,
        },
        taxIncluded: true,
      },
      fulfillmentContact: {
        email: 'johnjohnson@gmail.com',
        firstName: 'John',
        lastName: 'Johnson',
        displayName: 'John Johnson',
      },
    },
    purchaseLocationType: 'ONLINE_PURCHASE',
  },
};

Java

// Transaction Merchant
MerchantV3 transactionMerchant = new MerchantV3()
    .setId("http://www.example.com")
    .setName("Example Merchant");

// Line Item
PriceAttribute itemPrice = new PriceAttribute()
    .setType("REGULAR")
    .setName("Item Price")
    .setState("ACTUAL")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(8990000L)
    )
    .setTaxIncluded(true);

PriceAttribute totalItemPrice = new PriceAttribute()
    .setType("TOTAL")
    .setName("Total Price")
    .setState("ACTUAL")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(9990000L)
    )
    .setTaxIncluded(true);

// Purchase Item Extension
PurchaseItemExtension purchaseItemExtension = new PurchaseItemExtension()
    .setQuantity(1)
    .setUnitMeasure(new MerchantUnitMeasure()
        .setMeasure(1.0)
        .setUnit("POUND"))
    .setItemOptions(Arrays.asList(new PurchaseItemExtensionItemOption()
        .setId("ITEM_OPTION_ID")
        .setName("Pepperoni")
        .setPrices(Arrays.asList(
            new PriceAttribute()
              .setType("REGULAR")
              .setState("ACTUAL")
              .setName("Item Price")
              .setAmount(new MoneyV3()
                  .setCurrencyCode("USD")
                  .setAmountInMicros(1000000L))
              .setTaxIncluded(true),
            new PriceAttribute()
                .setType("TOTAL")
                .setState("ACTUAL")
                .setName("Total Price")
                .setAmount(new MoneyV3()
                    .setCurrencyCode("USD")
                    .setAmountInMicros(1000000L))
                .setTaxIncluded(true)
            ))
        .setNote("Extra pepperoni")
        .setQuantity(1)));

LineItemV3 lineItem = new LineItemV3()
    .setId("LINE_ITEM_ID")
    .setName("Pizza")
    .setDescription("A four cheese pizza.")
    .setPriceAttributes(Arrays.asList(itemPrice, totalItemPrice))
    .setNotes(Collections.singletonList("Extra cheese."))
    .setPurchase(purchaseItemExtension);

// Order Contents
OrderContents contents = new OrderContents()
    .setLineItems(Collections.singletonList(lineItem));

// User Info
UserInfo buyerInfo = new UserInfo()
    .setEmail("janedoe@gmail.com")
    .setFirstName("Jane")
    .setLastName("Doe")
    .setDisplayName("Jane Doe");

// Price Attributes
PriceAttribute subTotal = new PriceAttribute()
    .setType("SUBTOTAL")
    .setName("Subtotal")
    .setState("ESTIMATE")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(9990000L)
    )
    .setTaxIncluded(true);
PriceAttribute deliveryFee = new PriceAttribute()
    .setType("DELIVERY")
    .setName("Delivery")
    .setState("ACTUAL")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(2000000L)
    )
    .setTaxIncluded(true);
PriceAttribute tax = new PriceAttribute()
    .setType("TAX")
    .setName("Tax")
    .setState("ESTIMATE")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(3780000L)
    )
    .setTaxIncluded(true);
PriceAttribute totalPrice = new PriceAttribute()
    .setType("TOTAL")
    .setName("Total Price")
    .setState("ESTIMATE")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(15770000L)
    )
    .setTaxIncluded(true);

// Follow up actions
Action viewDetails = new Action()
    .setType("VIEW_DETAILS")
    .setTitle("View details")
    .setOpenUrlAction(new OpenUrlAction()
        .setUrl("https://example.com"));
Action call = new Action()
    .setType("CALL")
    .setTitle("Call us")
    .setOpenUrlAction(new OpenUrlAction()
        .setUrl("tel:+16501112222"));
Action email = new Action()
    .setType("EMAIL")
    .setTitle("Email us")
    .setOpenUrlAction(new OpenUrlAction()
        .setUrl("mailto:person@example.com"));

// Terms of service and order note
String termsOfServiceUrl = "http://example.com";
String orderNote = "Sale event";

// Promotions
PromotionV3 promotion = new PromotionV3()
    .setCoupon("COUPON_CODE");

// Purchase Order Extension
Location location = GSON_BUILDER.create().fromJson(
    (String) conversationData.get("location"), Location.class);

PurchaseOrderExtension purchaseOrderExtension = new PurchaseOrderExtension()
    .setStatus("CREATED")
    .setUserVisibleStatusLabel("CREATED")
    .setType("FOOD")
    .setReturnsInfo(new PurchaseReturnsInfo()
        .setIsReturnable(false)
        .setDaysToReturn(1)
        .setPolicyUrl("https://example.com"))
    .setFulfillmentInfo(new PurchaseFulfillmentInfo()
        .setId("FULFILLMENT_SERVICE_ID")
        .setFulfillmentType("DELIVERY")
        .setExpectedFulfillmentTime(new TimeV3()
            .setTimeIso8601("2019-09-25T18:00:00.877Z"))
        .setLocation(location)
        .setPrice(new PriceAttribute()
            .setType("REGULAR")
            .setName("Delivery price")
            .setState("ACTUAL")
            .setAmount(new MoneyV3()
                .setCurrencyCode("USD")
                .setAmountInMicros(2000000L))
            .setTaxIncluded(true))
        .setFulfillmentContact(new UserInfo()
            .setEmail("johnjohnson@gmail.com")
            .setFirstName("John")
            .setLastName("Johnson")
            .setDisplayName("John Johnson")))
    .setPurchaseLocationType("ONLINE_PURCHASE");

OrderV3 order = new OrderV3()
    .setCreateTime("2019-09-24T18:00:00.877Z")
    .setLastUpdateTime("2019-09-24T18:00:00.877Z")
    .setMerchantOrderId(orderId)
    .setUserVisibleOrderId(orderId)
    .setTransactionMerchant(transactionMerchant)
    .setContents(contents)
    .setBuyerInfo(buyerInfo)
    .setPriceAttributes(Arrays.asList(
        subTotal,
        deliveryFee,
        tax,
        totalPrice
    ))
    .setFollowUpActions(Arrays.asList(
        viewDetails,
        call,
        email
    ))
    .setTermsOfServiceUrl(termsOfServiceUrl)
    .setNote(orderNote)
    .setPromotions(Collections.singletonList(promotion))
    .setPurchase(purchaseOrderExtension);

Java

// Transaction Merchant
MerchantV3 transactionMerchant = new MerchantV3()
    .setId("http://www.example.com")
    .setName("Example Merchant");

// Line Item
PriceAttribute itemPrice = new PriceAttribute()
    .setType("REGULAR")
    .setName("Item Price")
    .setState("ACTUAL")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(8990000L)
    )
    .setTaxIncluded(true);

PriceAttribute totalItemPrice = new PriceAttribute()
    .setType("TOTAL")
    .setName("Total Price")
    .setState("ACTUAL")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(9990000L)
    )
    .setTaxIncluded(true);

// Purchase Item Extension
PurchaseItemExtension purchaseItemExtension = new PurchaseItemExtension()
    .setUnitMeasure(new MerchantUnitMeasure()
        .setMeasure(1.0)
        .setUnit("POUND"))
    .setItemOptions(Arrays.asList(new PurchaseItemExtensionItemOption()
        .setId("ITEM_OPTION_ID")
        .setName("Pepperoni")
        .setPrices(Arrays.asList(
            new PriceAttribute()
              .setType("REGULAR")
              .setState("ACTUAL")
              .setName("Item Price")
              .setAmount(new MoneyV3()
                  .setCurrencyCode("USD")
                  .setAmountInMicros(1000000L))
              .setTaxIncluded(true),
            new PriceAttribute()
                .setType("TOTAL")
                .setState("ACTUAL")
                .setName("Total Price")
                .setAmount(new MoneyV3()
                    .setCurrencyCode("USD")
                    .setAmountInMicros(1000000L))
                .setTaxIncluded(true)
            ))
        .setNote("Extra pepperoni")));

LineItemV3 lineItem = new LineItemV3()
    .setId("LINE_ITEM_ID")
    .setName("Pizza")
    .setDescription("A four cheese pizza.")
    .setPriceAttributes(Arrays.asList(itemPrice, totalItemPrice))
    .setNotes(Collections.singletonList("Extra cheese."))
    .setPurchase(purchaseItemExtension);

// Order Contents
OrderContents contents = new OrderContents()
    .setLineItems(Collections.singletonList(lineItem));

// User Info
UserInfo buyerInfo = new UserInfo()
    .setEmail("janedoe@gmail.com")
    .setFirstName("Jane")
    .setLastName("Doe")
    .setDisplayName("Jane Doe");

// Price Attributes
PriceAttribute subTotal = new PriceAttribute()
    .setType("SUBTOTAL")
    .setName("Subtotal")
    .setState("ESTIMATE")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(9990000L)
    )
    .setTaxIncluded(true);
PriceAttribute deliveryFee = new PriceAttribute()
    .setType("DELIVERY")
    .setName("Delivery")
    .setState("ACTUAL")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(2000000L)
    )
    .setTaxIncluded(true);
PriceAttribute tax = new PriceAttribute()
    .setType("TAX")
    .setName("Tax")
    .setState("ESTIMATE")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(3780000L)
    )
    .setTaxIncluded(true);
PriceAttribute totalPrice = new PriceAttribute()
    .setType("TOTAL")
    .setName("Total Price")
    .setState("ESTIMATE")
    .setAmount(new MoneyV3()
        .setCurrencyCode("USD")
        .setAmountInMicros(15770000L)
    )
    .setTaxIncluded(true);

// Follow up actions
Action viewDetails = new Action()
    .setType("VIEW_DETAILS")
    .setTitle("View details")
    .setOpenUrlAction(new OpenUrlAction()
        .setUrl("https://example.com"));
Action call = new Action()
    .setType("CALL")
    .setTitle("Call us")
    .setOpenUrlAction(new OpenUrlAction()
        .setUrl("tel:+16501112222"));
Action email = new Action()
    .setType("EMAIL")
    .setTitle("Email us")
    .setOpenUrlAction(new OpenUrlAction()
        .setUrl("mailto:person@example.com"));

// Terms of service and order note
String termsOfServiceUrl = "http://example.com";
String orderNote = "Sale event";

// Promotions
PromotionV3 promotion = new PromotionV3()
    .setCoupon("COUPON_CODE");

// Purchase Order Extension
Location location = GSON_BUILDER.create().fromJson(
    (String) conversationData.get("location"), Location.class);

PurchaseOrderExtension purchaseOrderExtension = new PurchaseOrderExtension()
    .setStatus("CREATED")
    .setUserVisibleStatusLabel("CREATED")
    .setType("FOOD")
    .setReturnsInfo(new PurchaseReturnsInfo()
        .setIsReturnable(false)
        .setDaysToReturn(1)
        .setPolicyUrl("https://example.com"))
    .setFulfillmentInfo(new PurchaseFulfillmentInfo()
        .setId("FULFILLMENT_SERVICE_ID")
        .setFulfillmentType("DELIVERY")
        .setExpectedFulfillmentTime(new TimeV3()
            .setTimeIso8601("2019-09-25T18:00:00.877Z"))
        .setLocation(location)
        .setPrice(new PriceAttribute()
            .setType("REGULAR")
            .setName("Delivery price")
            .setState("ACTUAL")
            .setAmount(new MoneyV3()
                .setCurrencyCode("USD")
                .setAmountInMicros(2000000L))
            .setTaxIncluded(true))
        .setFulfillmentContact(new UserInfo()
            .setEmail("johnjohnson@gmail.com")
            .setFirstName("John")
            .setLastName("Johnson")
            .setDisplayName("John Johnson")))
    .setPurchaseLocationType("ONLINE_PURCHASE");

OrderV3 order = new OrderV3()
    .setCreateTime("2019-09-24T18:00:00.877Z")
    .setLastUpdateTime("2019-09-24T18:00:00.877Z")
    .setMerchantOrderId(orderId)
    .setUserVisibleOrderId(orderId)
    .setTransactionMerchant(transactionMerchant)
    .setContents(contents)
    .setBuyerInfo(buyerInfo)
    .setPriceAttributes(Arrays.asList(
        subTotal,
        deliveryFee,
        tax,
        totalPrice
    ))
    .setFollowUpActions(Arrays.asList(
        viewDetails,
        call,
        email
    ))
    .setTermsOfServiceUrl(termsOfServiceUrl)
    .setNote(orderNote)
    .setPromotions(Collections.singletonList(promotion))
    .setPurchase(purchaseOrderExtension);

3. Vincular cuentas

Cuando uses tu propia forma de pago para cobrar al usuario, te recomendamos que vincules su Cuenta de Google con una cuenta que tenga en tu propio servicio para recuperar, presentar y cobrar a las formas de pago almacenadas allí.

Para satisfacer este requisito, proporcionamos la vinculación de cuentas mediante OAuth 2.0. Recomendamos habilitar el flujo de aserción de OAuth 2.0, ya que permite una experiencia del usuario muy optimizada.

Proporcionamos el intent actions.intent.SIGN_IN, que te permite solicitar que un usuario vincule cuentas durante una conversación. Debes habilitar la vinculación de cuentas en la Consola de Actions para usar el intent actions.intent.SIGN_IN.

Debes usar este intent si no puedes encontrar un accessToken en el objeto User de la solicitud de webhook. Esto significa que el usuario aún no ha vinculado su cuenta.

Después de solicitar el intent actions.intent.SIGN_IN, recibirás un Argument que contiene un SignInStatus con un valor de "OK", "CANCELLED" o "ERROR". Si el estado es "OK", deberías poder encontrar un accessToken en el objeto User.

Entrega

Solicitar acceso

Node.js

app.intent('Sign In', (conv) => {
  conv.ask(new SignIn('To get your account details'));
});

Node.js

conv.ask(new SignIn('To get your account details'));

Java

@ForIntent("Sign In")
public ActionResponse signIn(ActionRequest request) {
  return getResponseBuilder(request).add(
      new SignIn()
          .setContext("To get your account details"))
      .build();
}

Java

return getResponseBuilder(request).add(
    new SignIn()
        .setContext("To get your account details"))
    .build();

JSON

{
    "payload": {
      "google": {
        "expectUserResponse": true,
        "systemIntent": {
          "intent": "actions.intent.SIGN_IN",
          "data": {
            "@type": "type.googleapis.com/google.actions.v2.SignInValueSpec",
            "optContext": "To get your account details"
          }
        }
      }
    }
  }

JSON

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.SIGN_IN",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.v2.SignInValueSpec",
            "optContext": "To get your account details"
          }
        }
      ]
    }
  ],
  "conversationToken": "{\"data\":{\"paymentType\":\"merchant_payment\"}}"
}
Recibe el resultado de acceso

Node.js

app.intent('Sign In Complete', (conv, params, signin) => {
  if (signin.status !== 'OK') {
    conv.ask('You need to sign in before making a transaction.');
  } else {
    const accessToken = conv.user.access.token;
    // possibly do something with access token
    conv.ask('You must meet all the requirements necessary ' +
      'to make a transaction. Try saying ' +
      '"check transaction requirements".');
      conv.ask(new Suggestions(`check requirements`));
  }
});

Node.js

app.intent('actions.intent.SIGN_IN', (conv, params, signin) => {
  if (signin.status !== 'OK') {
    conv.ask('You need to sign in before making a transaction.');
  } else {
    const accessToken = conv.user.access.token;
    // possibly do something with access token
    conv.ask('You must meet all the requirements necessary ' +
      'to make a transaction. Try saying ' +
      '"check transaction requirements".');
      conv.ask(new Suggestions(`check requirements`));
  }
});

Java

@ForIntent("Sign In Complete")
public ActionResponse signInComplete(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (request.isSignInGranted()) {
    responseBuilder
        .add("You must meet all the requirements necessary to make a " +
            "transaction. Try saying \"check transaction requirements\".")
        .addSuggestions(new String[] {
            "check requirements"
        });
  } else {
    responseBuilder.add("You need to sign in before making a transaction.");
  }
  return responseBuilder.build();
}

Java

@ForIntent("actions.intent.SIGN_IN")
public ActionResponse signInComplete(ActionRequest request) {
  ResponseBuilder responseBuilder = getResponseBuilder(request);
  if (request.isSignInGranted()) {
    responseBuilder
        .add("You must meet all the requirements necessary to make a " +
            "transaction. Try saying \"check transaction requirements\".")
        .addSuggestions(new String[] {
            "check requirements"
        });
  } else {
    responseBuilder.add("You need to sign in before making a transaction.");
  }
  return responseBuilder.build();
}

JSON

{
    "responseId": "d2123d8d-3f00-466e-b5a9-1a4ed53a7cb7-594de0a7",
    "queryResult": {
      "queryText": "actions_intent_SIGN_IN",
      "parameters": {},
      "allRequiredParamsPresent": true,
      "fulfillmentMessages": [
        {
          "text": {
            "text": [
              ""
            ]
          }
        }
      ],
      "outputContexts": [
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/merchant_payment",
          "lifespanCount": 2
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_web_browser"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_screen_output"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_account_linking"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_media_response_audio"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_audio_output"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/google_assistant_input_type_keyboard"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_intent_sign_in",
          "parameters": {
            "SIGN_IN": {
              "@type": "type.googleapis.com/google.actions.v2.SignInValue",
              "status": "OK"
            },
            "text": ""
          }
        }
      ],
      "intent": {
        "name": "projects/df-transactions/agent/intents/105b925b-b186-4f5d-8bde-a9a782a0fa9f",
        "displayName": "Sign In Complete"
      },
      "intentDetectionConfidence": 1,
      "languageCode": "en"
    },
    "originalDetectIntentRequest": {
      "source": "google",
      "version": "2",
      "payload": {
        "user": {
          "locale": "en-US",
          "lastSeen": "2019-09-23T19:49:18Z",
          "userVerificationStatus": "VERIFIED"
        },
        "conversation": {
          "conversationId": "ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy",
          "type": "ACTIVE",
          "conversationToken": "[]"
        },
        "inputs": [
          {
            "intent": "actions.intent.SIGN_IN",
            "rawInputs": [
              {
                "inputType": "KEYBOARD"
              }
            ],
            "arguments": [
              {
                "name": "SIGN_IN",
                "extension": {
                  "@type": "type.googleapis.com/google.actions.v2.SignInValue",
                  "status": "OK"
                }
              },
              {
                "name": "text"
              }
            ]
          }
        ],
        "surface": {
          "capabilities": [
            {
              "name": "actions.capability.WEB_BROWSER"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.ACCOUNT_LINKING"
            },
            {
              "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
            },
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            }
          ]
        },
        "availableSurfaces": [
          {
            "capabilities": [
              {
                "name": "actions.capability.WEB_BROWSER"
              },
              {
                "name": "actions.capability.AUDIO_OUTPUT"
              },
              {
                "name": "actions.capability.SCREEN_OUTPUT"
              }
            ]
          }
        ]
      }
    },
    "session": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy"
  }

JSON

{
  "user": {
    "locale": "en-US",
    "lastSeen": "2019-11-11T23:55:52Z",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHGFwStZlYaQ9YT8rg9t_idVsxZrku1pUDrEbGSJmSUMatVdPwPEEQSCe1IwIBoN4sS4Weyn9pmgetEgbsWgw3JSvQmw",
    "type": "ACTIVE",
    "conversationToken": "{\"data\":{\"paymentType\":\"merchant_payment\"}}"
  },
  "inputs": [
    {
      "intent": "actions.intent.SIGN_IN",
      "rawInputs": [
        {}
      ],
      "arguments": [
        {
          "name": "SIGN_IN",
          "extension": {
            "@type": "type.googleapis.com/google.actions.v2.SignInValue",
            "status": "OK"
          }
        },
        {
          "name": "text"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      }
    ]
  },
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        }
      ]
    }
  ]
}

4. Proponer el orden

Una vez que hayas creado un pedido, debes presentárselo al usuario para que lo confirme o lo rechace. Solicita el intent actions.intent.TRANSACTION_DECISION y proporciona el pedido que compilaste con la información de pago almacenada del usuario.

Experiencia del usuario

Cuando solicitas el intent actions.intent.TRANSACTION_DECISION, Asistente inicia una experiencia integrada en la que el Order que pasaste se renderiza directamente en una "tarjeta de vista previa del carrito". El usuario puede decir "realizar pedido", rechazar la transacción, cambiar una opción de pago (como la tarjeta de crédito o la dirección) o solicitar que se cambie el contenido del pedido.

En este momento, el usuario también puede solicitar cambios en el pedido. En este caso, debes asegurarte de que tu entrega pueda controlar las solicitudes de cambio de pedido después de finalizar la experiencia de ensamblado del carrito.

Entrega

Cuando solicitas el intent actions.intent.TRANSACTION_DECISION, debes crear un TransactionDecision que contenga el Order, así como orderOptions y paymentParameters. Tu objeto paymentParameters incluye un merchantPaymentOption con campos que describen la forma de pago del usuario.

En el siguiente código, se muestra un ejemplo de TransactionsDecision para un pedido que se pagó con una tarjeta de crédito Visa:

Node.js

conv.ask(new TransactionDecision({
  orderOptions: {
    userInfoOptions: {
      userInfoProperties: [
        'EMAIL',
      ],
    },
  },
  paymentParameters: {
    merchantPaymentOption: {
      defaultMerchantPaymentMethodId: '12345678',
      managePaymentMethodUrl: 'https://example.com/managePayment',
      merchantPaymentMethod: [
        {
          paymentMethodDisplayInfo: {
            paymentMethodDisplayName: 'VISA **** 1234',
            paymentType: 'PAYMENT_CARD',
          },
          paymentMethodGroup: 'Payment method group',
          paymentMethodId: '12345678',
          paymentMethodStatus: {
            status: 'STATUS_OK',
            statusMessage: 'Status message',
          },
        },
      ],
    },
  },
  presentationOptions: {
    actionDisplayName: 'PLACE_ORDER',
  },
  order: order,
}));

Node.js

conv.ask(new TransactionDecision({
  orderOptions: {
    userInfoOptions: {
      userInfoProperties: [
        'EMAIL',
      ],
    },
  },
  paymentParameters: {
    merchantPaymentOption: {
      defaultMerchantPaymentMethodId: '12345678',
      managePaymentMethodUrl: 'https://example.com/managePayment',
      merchantPaymentMethod: [
        {
          paymentMethodDisplayInfo: {
            paymentMethodDisplayName: 'VISA **** 1234',
            paymentType: 'PAYMENT_CARD',
          },
          paymentMethodGroup: 'Payment method group',
          paymentMethodId: '12345678',
          paymentMethodStatus: {
            status: 'STATUS_OK',
            statusMessage: 'Status message',
          },
        },
      ],
    },
  },
  presentationOptions: {
    actionDisplayName: 'PLACE_ORDER',
  },
  order: order,
}));

Java

// Create order options
OrderOptionsV3 orderOptions = new OrderOptionsV3()
    .setUserInfoOptions(new UserInfoOptions()
        .setUserInfoProperties(Collections.singletonList("EMAIL")));

// Create presentation options
PresentationOptionsV3 presentationOptions = new PresentationOptionsV3()
    .setActionDisplayName("PLACE_ORDER");

// Create payment parameters
MerchantPaymentMethod merchantPaymentMethod = new MerchantPaymentMethod()
    .setPaymentMethodDisplayInfo(new PaymentMethodDisplayInfo()
        .setPaymentMethodDisplayName("VISA **** 1234")
        .setPaymentType("PAYMENT_CARD"))
    .setPaymentMethodGroup("Payment method group")
    .setPaymentMethodId("12345678")
    .setPaymentMethodStatus(new PaymentMethodStatus()
        .setStatus("STATUS_OK")
        .setStatusMessage("Status message"));

MerchantPaymentOption merchantPaymentOption = new MerchantPaymentOption()
    .setDefaultMerchantPaymentMethodId("12345678")
    .setManagePaymentMethodUrl("https://example.com/managePayment")
    .setMerchantPaymentMethod(Collections.singletonList(merchantPaymentMethod));

paymentParameters.setMerchantPaymentOption(merchantPaymentOption);

return getResponseBuilder(request)
    .add(new TransactionDecision()
        .setOrder(order)
        .setOrderOptions(orderOptions)
        .setPresentationOptions(presentationOptions)
        .setPaymentParameters(paymentParameters)
    )
    .build();

Java

// Create order options
OrderOptionsV3 orderOptions = new OrderOptionsV3()
    .setUserInfoOptions(new UserInfoOptions()
        .setUserInfoProperties(Collections.singletonList("EMAIL")));

// Create presentation options
PresentationOptionsV3 presentationOptions = new PresentationOptionsV3()
    .setActionDisplayName("PLACE_ORDER");

// Create payment parameters
MerchantPaymentMethod merchantPaymentMethod = new MerchantPaymentMethod()
    .setPaymentMethodDisplayInfo(new PaymentMethodDisplayInfo()
        .setPaymentMethodDisplayName("VISA **** 1234")
        .setPaymentType("PAYMENT_CARD"))
    .setPaymentMethodGroup("Payment method group")
    .setPaymentMethodId("12345678")
    .setPaymentMethodStatus(new PaymentMethodStatus()
        .setStatus("STATUS_OK")
        .setStatusMessage("Status message"));

MerchantPaymentOption merchantPaymentOption = new MerchantPaymentOption()
    .setDefaultMerchantPaymentMethodId("12345678")
    .setManagePaymentMethodUrl("https://example.com/managePayment")
    .setMerchantPaymentMethod(Collections.singletonList(merchantPaymentMethod));

paymentParameters.setMerchantPaymentOption(merchantPaymentOption);

return getResponseBuilder(request)
    .add(new TransactionDecision()
        .setOrder(order)
        .setOrderOptions(orderOptions)
        .setPresentationOptions(presentationOptions)
        .setPaymentParameters(paymentParameters)
    )
    .build();

JSON

{
    "payload": {
      "google": {
        "expectUserResponse": true,
        "richResponse": {
          "items": [
            {
              "simpleResponse": {
                "textToSpeech": "Transaction Decision Placeholder."
              }
            }
          ]
        },
        "systemIntent": {
          "intent": "actions.intent.TRANSACTION_DECISION",
          "data": {
            "@type": "type.googleapis.com/google.actions.transactions.v3.TransactionDecisionValueSpec",
            "orderOptions": {
              "userInfoOptions": {
                "userInfoProperties": [
                  "EMAIL"
                ]
              }
            },
            "paymentParameters": {
              "merchantPaymentOption": {
                "defaultMerchantPaymentMethodId": "12345678",
                "managePaymentMethodUrl": "https://example.com/managePayment",
                "merchantPaymentMethod": [
                  {
                    "paymentMethodDisplayInfo": {
                      "paymentMethodDisplayName": "VISA **** 1234",
                      "paymentType": "PAYMENT_CARD"
                    },
                    "paymentMethodGroup": "Payment method group",
                    "paymentMethodId": "12345678",
                    "paymentMethodStatus": {
                      "status": "STATUS_OK",
                      "statusMessage": "Status message"
                    }
                  }
                ]
              }
            },
            "presentationOptions": {
              "actionDisplayName": "PLACE_ORDER"
            },
            "order": {
              "createTime": "2019-09-24T18:00:00.877Z",
              "lastUpdateTime": "2019-09-24T18:00:00.877Z",
              "merchantOrderId": "ORDER_ID",
              "userVisibleOrderId": "ORDER_ID",
              "transactionMerchant": {
                "id": "http://www.example.com",
                "name": "Example Merchant"
              },
              "contents": {
                "lineItems": [
                  {
                    "id": "LINE_ITEM_ID",
                    "name": "Pizza",
                    "description": "A four cheese pizza.",
                    "priceAttributes": [
                      {
                        "type": "REGULAR",
                        "name": "Item Price",
                        "state": "ACTUAL",
                        "amount": {
                          "currencyCode": "USD",
                          "amountInMicros": 8990000
                        },
                        "taxIncluded": true
                      },
                      {
                        "type": "TOTAL",
                        "name": "Total Price",
                        "state": "ACTUAL",
                        "amount": {
                          "currencyCode": "USD",
                          "amountInMicros": 9990000
                        },
                        "taxIncluded": true
                      }
                    ],
                    "notes": [
                      "Extra cheese."
                    ],
                    "purchase": {
                      "quantity": 1,
                      "unitMeasure": {
                        "measure": 1,
                        "unit": "POUND"
                      },
                      "itemOptions": [
                        {
                          "id": "ITEM_OPTION_ID",
                          "name": "Pepperoni",
                          "prices": [
                            {
                              "type": "REGULAR",
                              "state": "ACTUAL",
                              "name": "Item Price",
                              "amount": {
                                "currencyCode": "USD",
                                "amountInMicros": 1000000
                              },
                              "taxIncluded": true
                            },
                            {
                              "type": "TOTAL",
                              "name": "Total Price",
                              "state": "ACTUAL",
                              "amount": {
                                "currencyCode": "USD",
                                "amountInMicros": 1000000
                              },
                              "taxIncluded": true
                            }
                          ],
                          "note": "Extra pepperoni",
                          "quantity": 1,
                          "subOptions": []
                        }
                      ]
                    }
                  }
                ]
              },
              "buyerInfo": {
                "email": "janedoe@gmail.com",
                "firstName": "Jane",
                "lastName": "Doe",
                "displayName": "Jane Doe"
              },
              "priceAttributes": [
                {
                  "type": "SUBTOTAL",
                  "name": "Subtotal",
                  "state": "ESTIMATE",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": 9990000
                  },
                  "taxIncluded": true
                },
                {
                  "type": "DELIVERY",
                  "name": "Delivery",
                  "state": "ACTUAL",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": 2000000
                  },
                  "taxIncluded": true
                },
                {
                  "type": "TAX",
                  "name": "Tax",
                  "state": "ESTIMATE",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": 3780000
                  },
                  "taxIncluded": true
                },
                {
                  "type": "TOTAL",
                  "name": "Total Price",
                  "state": "ESTIMATE",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": 15770000
                  },
                  "taxIncluded": true
                }
              ],
              "followUpActions": [
                {
                  "type": "VIEW_DETAILS",
                  "title": "View details",
                  "openUrlAction": {
                    "url": "http://example.com"
                  }
                },
                {
                  "type": "CALL",
                  "title": "Call us",
                  "openUrlAction": {
                    "url": "tel:+16501112222"
                  }
                },
                {
                  "type": "EMAIL",
                  "title": "Email us",
                  "openUrlAction": {
                    "url": "mailto:person@example.com"
                  }
                }
              ],
              "termsOfServiceUrl": "http://www.example.com",
              "note": "Sale event",
              "promotions": [
                {
                  "coupon": "COUPON_CODE"
                }
              ],
              "purchase": {
                "status": "CREATED",
                "userVisibleStatusLabel": "CREATED",
                "type": "FOOD",
                "returnsInfo": {
                  "isReturnable": false,
                  "daysToReturn": 1,
                  "policyUrl": "http://www.example.com"
                },
                "fulfillmentInfo": {
                  "id": "FULFILLMENT_SERVICE_ID",
                  "fulfillmentType": "DELIVERY",
                  "expectedFulfillmentTime": {
                    "timeIso8601": "2019-09-25T18:00:00.877Z"
                  },
                  "location": {
                    "city": "MOUNTAIN VIEW",
                    "coordinates": {
                      "latitude": 37.432524,
                      "longitude": -122.098545
                    },
                    "phoneNumber": "+1 123-456-7890",
                    "postalAddress": {
                      "addressLines": [
                        "1600 AMPHITHEATRE PKWY"
                      ],
                      "administrativeArea": "CA",
                      "locality": "MOUNTAIN VIEW",
                      "postalCode": "94043-1351",
                      "recipients": [
                        "John Doe"
                      ],
                      "regionCode": "US"
                    },
                    "zipCode": "94043-1351"
                  },
                  "price": {
                    "type": "REGULAR",
                    "name": "Delivery Price",
                    "state": "ACTUAL",
                    "amount": {
                      "currencyCode": "USD",
                      "amountInMicros": 2000000
                    },
                    "taxIncluded": true
                  },
                  "fulfillmentContact": {
                    "email": "johnjohnson@gmail.com",
                    "firstName": "John",
                    "lastName": "Johnson",
                    "displayName": "John Johnson"
                  }
                },
                "purchaseLocationType": "ONLINE_PURCHASE"
              }
            }
          }
        }
      }
    },
    "outputContexts": [
      {
        "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/_actions_on_google",
        "lifespanCount": 99,
        "parameters": {
          "data": "{\"location\":{\"coordinates\":{\"latitude\":37.432524,\"longitude\":-122.098545},\"zipCode\":\"94043-1351\",\"city\":\"MOUNTAIN VIEW\",\"postalAddress\":{\"regionCode\":\"US\",\"postalCode\":\"94043-1351\",\"administrativeArea\":\"CA\",\"locality\":\"MOUNTAIN VIEW\",\"addressLines\":[\"1600 AMPHITHEATRE PKWY\"],\"recipients\":[\"John Doe\"]},\"phoneNumber\":\"+1 123-456-7890\"},\"latestOrderId\":\"ORDER_ID\"}"
        }
      }
    ]
  }

JSON

{
  "expectUserResponse": true,
  "expectedInputs": [
    {
      "possibleIntents": [
        {
          "intent": "actions.intent.TRANSACTION_DECISION",
          "inputValueData": {
            "@type": "type.googleapis.com/google.actions.transactions.v3.TransactionDecisionValueSpec",
            "orderOptions": {
              "userInfoOptions": {
                "userInfoProperties": [
                  "EMAIL"
                ]
              }
            },
            "paymentParameters": {
              "merchantPaymentOption": {
                "defaultMerchantPaymentMethodId": "12345678",
                "managePaymentMethodUrl": "https://example.com/managePayment",
                "merchantPaymentMethod": [
                  {
                    "paymentMethodDisplayInfo": {
                      "paymentMethodDisplayName": "VISA **** 1234",
                      "paymentType": "PAYMENT_CARD"
                    },
                    "paymentMethodGroup": "Payment method group",
                    "paymentMethodId": "12345678",
                    "paymentMethodStatus": {
                      "status": "STATUS_OK",
                      "statusMessage": "Status message"
                    }
                  }
                ]
              }
            },
            "presentationOptions": {
              "actionDisplayName": "PLACE_ORDER"
            },
            "order": {
              "createTime": "2019-09-24T18:00:00.877Z",
              "lastUpdateTime": "2019-09-24T18:00:00.877Z",
              "merchantOrderId": "ORDER_ID",
              "userVisibleOrderId": "ORDER_ID",
              "transactionMerchant": {
                "id": "http://www.example.com",
                "name": "Example Merchant"
              },
              "contents": {
                "lineItems": [
                  {
                    "id": "LINE_ITEM_ID",
                    "name": "Pizza",
                    "description": "A four cheese pizza.",
                    "priceAttributes": [
                      {
                        "type": "REGULAR",
                        "name": "Item Price",
                        "state": "ACTUAL",
                        "amount": {
                          "currencyCode": "USD",
                          "amountInMicros": 8990000
                        },
                        "taxIncluded": true
                      },
                      {
                        "type": "TOTAL",
                        "name": "Total Price",
                        "state": "ACTUAL",
                        "amount": {
                          "currencyCode": "USD",
                          "amountInMicros": 9990000
                        },
                        "taxIncluded": true
                      }
                    ],
                    "notes": [
                      "Extra cheese."
                    ],
                    "purchase": {
                      "quantity": 1,
                      "unitMeasure": {
                        "measure": 1,
                        "unit": "POUND"
                      },
                      "itemOptions": [
                        {
                          "id": "ITEM_OPTION_ID",
                          "name": "Pepperoni",
                          "prices": [
                            {
                              "type": "REGULAR",
                              "state": "ACTUAL",
                              "name": "Item Price",
                              "amount": {
                                "currencyCode": "USD",
                                "amountInMicros": 1000000
                              },
                              "taxIncluded": true
                            },
                            {
                              "type": "TOTAL",
                              "name": "Total Price",
                              "state": "ACTUAL",
                              "amount": {
                                "currencyCode": "USD",
                                "amountInMicros": 1000000
                              },
                              "taxIncluded": true
                            }
                          ],
                          "note": "Extra pepperoni",
                          "quantity": 1,
                          "subOptions": []
                        }
                      ]
                    }
                  }
                ]
              },
              "buyerInfo": {
                "email": "janedoe@gmail.com",
                "firstName": "Jane",
                "lastName": "Doe",
                "displayName": "Jane Doe"
              },
              "priceAttributes": [
                {
                  "type": "SUBTOTAL",
                  "name": "Subtotal",
                  "state": "ESTIMATE",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": 9990000
                  },
                  "taxIncluded": true
                },
                {
                  "type": "DELIVERY",
                  "name": "Delivery",
                  "state": "ACTUAL",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": 2000000
                  },
                  "taxIncluded": true
                },
                {
                  "type": "TAX",
                  "name": "Tax",
                  "state": "ESTIMATE",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": 3780000
                  },
                  "taxIncluded": true
                },
                {
                  "type": "TOTAL",
                  "name": "Total Price",
                  "state": "ESTIMATE",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": 15770000
                  },
                  "taxIncluded": true
                }
              ],
              "followUpActions": [
                {
                  "type": "VIEW_DETAILS",
                  "title": "View details",
                  "openUrlAction": {
                    "url": "http://example.com"
                  }
                },
                {
                  "type": "CALL",
                  "title": "Call us",
                  "openUrlAction": {
                    "url": "tel:+16501112222"
                  }
                },
                {
                  "type": "EMAIL",
                  "title": "Email us",
                  "openUrlAction": {
                    "url": "mailto:person@example.com"
                  }
                }
              ],
              "termsOfServiceUrl": "http://www.example.com",
              "note": "Sale event",
              "promotions": [
                {
                  "coupon": "COUPON_CODE"
                }
              ],
              "purchase": {
                "status": "CREATED",
                "userVisibleStatusLabel": "CREATED",
                "type": "FOOD",
                "returnsInfo": {
                  "isReturnable": false,
                  "daysToReturn": 1,
                  "policyUrl": "http://www.example.com"
                },
                "fulfillmentInfo": {
                  "id": "FULFILLMENT_SERVICE_ID",
                  "fulfillmentType": "DELIVERY",
                  "expectedFulfillmentTime": {
                    "timeIso8601": "2019-09-25T18:00:00.877Z"
                  },
                  "location": {
                    "coordinates": {
                      "latitude": 37.421578499999995,
                      "longitude": -122.0837816
                    },
                    "zipCode": "94043-1351",
                    "city": "MOUNTAIN VIEW",
                    "postalAddress": {
                      "regionCode": "US",
                      "postalCode": "94043-1351",
                      "administrativeArea": "CA",
                      "locality": "MOUNTAIN VIEW",
                      "addressLines": [
                        "1600 AMPHITHEATRE PKWY"
                      ],
                      "recipients": [
                        "John Doe"
                      ]
                    },
                    "phoneNumber": "+1 123-456-7890"
                  },
                  "price": {
                    "type": "REGULAR",
                    "name": "Delivery Price",
                    "state": "ACTUAL",
                    "amount": {
                      "currencyCode": "USD",
                      "amountInMicros": 2000000
                    },
                    "taxIncluded": true
                  },
                  "fulfillmentContact": {
                    "email": "johnjohnson@gmail.com",
                    "firstName": "John",
                    "lastName": "Johnson",
                    "displayName": "John Johnson"
                  }
                },
                "purchaseLocationType": "ONLINE_PURCHASE"
              }
            }
          }
        }
      ],
      "inputPrompt": {
        "richInitialPrompt": {
          "items": [
            {
              "simpleResponse": {
                "textToSpeech": "Transaction Decision Placeholder."
              }
            }
          ]
        }
      }
    }
  ],
  "conversationToken": "{\"data\":{\"paymentType\":\"merchant_payment\",\"location\":{\"coordinates\":{\"latitude\":37.421578499999995,\"longitude\":-122.0837816},\"zipCode\":\"94043-1351\",\"city\":\"MOUNTAIN VIEW\",\"postalAddress\":{\"regionCode\":\"US\",\"postalCode\":\"94043-1351\",\"administrativeArea\":\"CA\",\"locality\":\"MOUNTAIN VIEW\",\"addressLines\":[\"1600 AMPHITHEATRE PKWY\"],\"recipients\":[\"John Doe\"]},\"phoneNumber\":\"+1 123-456-7890\"},\"latestOrderId\":\"ORDER_ID\"}}"
}

Cómo controlar la decisión del usuario

Después de que Asistente entrega el intent, envía a tu entrega una solicitud con el intent actions_intent_TRANSACTION_DECISION con la respuesta del usuario a la decisión de transacción. Recibirás un Argument que contiene un TransactionDecisionValue. Este valor contendrá lo siguiente:

  • transactionDecision: Es la decisión del usuario con respecto al pedido propuesto. Los valores posibles son ORDER_ACCEPTED, ORDER_REJECTED, DELIVERY_ADDRESS_UPDATED, CART_CHANGE_REQUESTED y USER_CANNOT_TRANSACT.
  • deliveryAddress: Es una dirección de entrega actualizada, en caso de que el usuario haya cambiado su dirección de entrega. En este caso, el valor de transactionDecision será DELIVERY_ADDRESS_UPDATED.

Para manejar de forma correcta esta solicitud, declara un intent de Dialogflow que se active con el evento actions_intent_TRANSACTION_DECISION. Cuando se active, controla esto en tu entrega:

Node.js

const arg = conv.arguments.get('TRANSACTION_DECISION_VALUE');
if (arg && arg.transactionDecision === 'ORDER_ACCEPTED') {
  console.log('Order accepted.');
  const order = arg.order;
}

Node.js

const arg = conv.arguments.get('TRANSACTION_DECISION_VALUE');
if (arg && arg.transactionDecision === 'ORDER_ACCEPTED') {
  console.log('Order accepted.');
  const order = arg.order;
}

Java

// Check transaction decision value
Argument transactionDecisionValue = request
    .getArgument("TRANSACTION_DECISION_VALUE");
Map<String, Object> extension = null;
if (transactionDecisionValue != null) {
  extension = transactionDecisionValue.getExtension();
}

String transactionDecision = null;
if (extension != null) {
  transactionDecision = (String) extension.get("transactionDecision");
}
ResponseBuilder responseBuilder = getResponseBuilder(request);
if ((transactionDecision != null && transactionDecision.equals("ORDER_ACCEPTED"))) {
  OrderV3 order = ((OrderV3) extension.get("order"));
}

Java

// Check transaction decision value
Argument transactionDecisionValue = request
    .getArgument("TRANSACTION_DECISION_VALUE");
Map<String, Object> extension = null;
if (transactionDecisionValue != null) {
  extension = transactionDecisionValue.getExtension();
}

String transactionDecision = null;
if (extension != null) {
  transactionDecision = (String) extension.get("transactionDecision");
}
ResponseBuilder responseBuilder = getResponseBuilder(request);
if ((transactionDecision != null && transactionDecision.equals("ORDER_ACCEPTED"))) {
  OrderV3 order = ((OrderV3) extension.get("order"));
}

JSON

{
    "responseId": "aba44717-4236-4602-af55-e5ae1fc2d97a-594de0a7",
    "queryResult": {
      "queryText": "actions_intent_TRANSACTION_DECISION",
      "action": "transaction.decision.complete",
      "parameters": {},
      "allRequiredParamsPresent": true,
      "fulfillmentText": "Failed to get transaction decision",
      "fulfillmentMessages": [
        {
          "text": {
            "text": [
              "Failed to get transaction decision"
            ]
          }
        }
      ],
      "outputContexts": [
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_media_response_audio"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_audio_output"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_account_linking"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_screen_output"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_capability_web_browser"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/google_assistant_input_type_voice"
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/_actions_on_google",
          "lifespanCount": 97,
          "parameters": {
            "data": "{\"location\":{\"coordinates\":{\"latitude\":37.432524,\"longitude\":-122.098545},\"zipCode\":\"94043-1351\",\"city\":\"MOUNTAIN VIEW\",\"postalAddress\":{\"regionCode\":\"US\",\"postalCode\":\"94043-1351\",\"administrativeArea\":\"CA\",\"locality\":\"MOUNTAIN VIEW\",\"addressLines\":[\"1600 AMPHITHEATRE PKWY\"],\"recipients\":[\"John Doe\"]},\"phoneNumber\":\"+1 123-456-7890\"}}"
          }
        },
        {
          "name": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy/contexts/actions_intent_transaction_decision",
          "parameters": {
            "TRANSACTION_DECISION_VALUE": {
              "@type": "type.googleapis.com/google.actions.transactions.v3.TransactionDecisionValue",
              "transactionDecision": "ORDER_ACCEPTED",
              "order": {
                "createTime": "2019-09-24T18:00:00.877Z",
                "lastUpdateTime": "2019-09-24T18:00:00.877Z",
                "merchantOrderId": "ORDER_ID",
                "userVisibleOrderId": "ORDER_ID",
                "transactionMerchant": {
                  "id": "http://www.example.com",
                  "name": "Example Merchant"
                },
                "contents": {
                  "lineItems": [
                    {
                      "id": "LINE_ITEM_ID",
                      "name": "Pizza",
                      "description": "A four cheese pizza.",
                      "priceAttributes": [
                        {
                          "type": "REGULAR",
                          "name": "Line Item Price",
                          "state": "ACTUAL",
                          "amount": {
                            "currencyCode": "USD",
                            "amountInMicros": 8990000
                          },
                          "taxIncluded": true
                        },
                        {
                          "type": "TOTAL",
                          "name": "Total Price",
                          "state": "ACTUAL",
                          "amount": {
                            "currencyCode": "USD",
                            "amountInMicros": 9990000
                          },
                          "taxIncluded": true
                        }
                      ],
                      "notes": [
                        "Extra cheese."
                      ],
                      "purchase": {
                        "quantity": 1,
                        "unitMeasure": {
                          "measure": 1,
                          "unit": "POUND"
                        },
                        "itemOptions": [
                          {
                            "id": "ITEM_OPTION_ID",
                            "name": "Pepperoni",
                            "prices": [
                              {
                                "type": "REGULAR",
                                "state": "ACTUAL",
                                "name": "Item Price",
                                "amount": {
                                  "currencyCode": "USD",
                                  "amountInMicros": 1000000
                                },
                                "taxIncluded": true
                              },
                              {
                                "type": "TOTAL",
                                "name": "Total Price",
                                "state": "ACTUAL",
                                "amount": {
                                  "currencyCode": "USD",
                                  "amountInMicros": 1000000
                                },
                                "taxIncluded": true
                              }
                            ],
                            "note": "Extra pepperoni",
                            "quantity": 1,
                            "subOptions": []
                          }
                        ]
                      }
                    }
                  ]
                },
                "buyerInfo": {
                  "email": "janedoe@gmail.com",
                  "firstName": "Jane",
                  "lastName": "Doe",
                  "displayName": "Jane Doe"
                },
                "priceAttributes": [
                  {
                    "type": "SUBTOTAL",
                    "name": "Subtotal",
                    "state": "ESTIMATE",
                    "amount": {
                      "currencyCode": "USD",
                      "amountInMicros": 9990000
                    },
                    "taxIncluded": true
                  },
                  {
                    "type": "DELIVERY",
                    "name": "Delivery",
                    "state": "ACTUAL",
                    "amount": {
                      "currencyCode": "USD",
                      "amountInMicros": 2000000
                    },
                    "taxIncluded": true
                  },
                  {
                    "type": "TAX",
                    "name": "Tax",
                    "state": "ESTIMATE",
                    "amount": {
                      "currencyCode": "USD",
                      "amountInMicros": 3780000
                    },
                    "taxIncluded": true
                  },
                  {
                    "type": "TOTAL",
                    "name": "Total Price",
                    "state": "ESTIMATE",
                    "amount": {
                      "currencyCode": "USD",
                      "amountInMicros": 15770000
                    },
                    "taxIncluded": true
                  }
                ],
                "followUpActions": [
                  {
                    "type": "VIEW_DETAILS",
                    "title": "View details",
                    "openUrlAction": {
                      "url": "http://example.com"
                    }
                  },
                  {
                    "type": "CALL",
                    "title": "Call us",
                    "openUrlAction": {
                      "url": "tel:+16501112222"
                    }
                  },
                  {
                    "type": "EMAIL",
                    "title": "Email us",
                    "openUrlAction": {
                      "url": "mailto:person@example.com"
                    }
                  }
                ],
                "termsOfServiceUrl": "www.example.com",
                "note": "Sale event",
                "promotions": [
                  {
                    "coupon": "COUPON_CODE"
                  }
                ],
                "purchase": {
                  "status": "CREATED",
                  "userVisibleStatusLabel": "CREATED",
                  "type": "FOOD",
                  "returnsInfo": {
                    "isReturnable": false,
                    "daysToReturn": 1,
                    "policyUrl": "http://www.example.com"
                  },
                  "fulfillmentInfo": {
                    "id": "FULFILLMENT_SERVICE_ID",
                    "fulfillmentType": "DELIVERY",
                    "expectedFulfillmentTime": {
                      "timeIso8601": "2019-09-25T18:00:00.877Z"
                    },
                    "location": {},
                    "price": {
                      "type": "REGULAR",
                      "name": "Delivery Price",
                      "state": "ACTUAL",
                      "amount": {
                        "currencyCode": "USD",
                        "amountInMicros": 2000000
                      },
                      "taxIncluded": true
                    },
                    "fulfillmentContact": {
                      "email": "johnjohnson@gmail.com",
                      "firstName": "John",
                      "lastName": "Johnson",
                      "displayName": "John Johnson"
                    }
                  },
                  "purchaseLocationType": "ONLINE_PURCHASE"
                }
              }
            },
            "text": ""
          }
        }
      ],
      "intent": {
        "name": "projects/df-transactions/agent/intents/fd16d86b-60db-4d19-a683-5b52a22f4795",
        "displayName": "Transaction Decision Complete"
      },
      "intentDetectionConfidence": 1,
      "languageCode": "en"
    },
    "originalDetectIntentRequest": {
      "source": "google",
      "version": "2",
      "payload": {
        "user": {
          "locale": "en-US",
          "lastSeen": "2019-09-23T19:49:32Z",
          "userVerificationStatus": "VERIFIED"
        },
        "conversation": {
          "conversationId": "ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy",
          "type": "ACTIVE",
          "conversationToken": "[\"merchant_payment\"]"
        },
        "inputs": [
          {
            "intent": "actions.intent.TRANSACTION_DECISION",
            "rawInputs": [
              {
                "inputType": "KEYBOARD"
              }
            ],
            "arguments": [
              {
                "name": "TRANSACTION_DECISION_VALUE",
                "extension": {
                  "@type": "type.googleapis.com/google.actions.transactions.v3.TransactionDecisionValue",
                  "transactionDecision": "ORDER_ACCEPTED",
                  "order": {
                    "createTime": "2019-09-24T18:00:00.877Z",
                    "lastUpdateTime": "2019-09-24T19:00:00.877Z",
                    "merchantOrderId": "ORDER_ID",
                    "userVisibleOrderId": "ORDER_ID",
                    "transactionMerchant": {
                      "id": "http://www.example.com",
                      "name": "Example Merchant"
                    },
                    "contents": {
                      "lineItems": [
                        {
                          "id": "LINE_ITEM_ID",
                          "name": "Pizza",
                          "description": "A four cheese pizza.",
                          "priceAttributes": [
                            {
                              "type": "REGULAR",
                              "name": "Line Item Price",
                              "state": "ACTUAL",
                              "amount": {
                                "currencyCode": "USD",
                                "amountInMicros": 8990000
                              },
                              "taxIncluded": true
                            },
                            {
                              "type": "TOTAL",
                              "name": "Total Price",
                              "state": "ACTUAL",
                              "amount": {
                                "currencyCode": "USD",
                                "amountInMicros": 9990000
                              },
                              "taxIncluded": true
                            }
                          ],
                          "notes": [
                            "Extra cheese."
                          ],
                          "purchase": {
                            "quantity": 1,
                            "unitMeasure": {
                              "measure": 1,
                              "unit": "POUND"
                            },
                            "itemOptions": [
                              {
                                "id": "ITEM_OPTION_ID",
                                "name": "Pepperoni",
                                "prices": [
                                  {
                                    "type": "REGULAR",
                                    "state": "ACTUAL",
                                    "name": "Item Price",
                                    "amount": {
                                      "currencyCode": "USD",
                                      "amountInMicros": 1000000
                                    },
                                    "taxIncluded": true
                                  },
                                  {
                                    "type": "TOTAL",
                                    "name": "Total Price",
                                    "state": "ACTUAL",
                                    "amount": {
                                      "currencyCode": "USD",
                                      "amountInMicros": 1000000
                                    },
                                    "taxIncluded": true
                                  }
                                ],
                                "note": "Extra pepperoni",
                                "quantity": 1,
                                "subOptions": []
                              }
                            ]
                          }
                        }
                      ]
                    },
                    "buyerInfo": {
                      "email": "janedoe@gmail.com",
                      "firstName": "Jane",
                      "lastName": "Doe",
                      "displayName": "Jane Doe"
                    },
                    "priceAttributes": [
                      {
                        "type": "SUBTOTAL",
                        "name": "Subtotal",
                        "state": "ESTIMATE",
                        "amount": {
                          "currencyCode": "USD",
                          "amountInMicros": 9990000
                        },
                        "taxIncluded": true
                      },
                      {
                        "type": "DELIVERY",
                        "name": "Delivery",
                        "state": "ACTUAL",
                        "amount": {
                          "currencyCode": "USD",
                          "amountInMicros": 2000000
                        },
                        "taxIncluded": true
                      },
                      {
                        "type": "TAX",
                        "name": "Tax",
                        "state": "ESTIMATE",
                        "amount": {
                          "currencyCode": "USD",
                          "amountInMicros": 3780000
                        },
                        "taxIncluded": true
                      },
                      {
                        "type": "TOTAL",
                        "name": "Total Price",
                        "state": "ESTIMATE",
                        "amount": {
                          "currencyCode": "USD",
                          "amountInMicros": 15770000
                        },
                        "taxIncluded": true
                      }
                    ],
                    "followUpActions": [
                      {
                        "type": "VIEW_DETAILS",
                        "title": "View details",
                        "openUrlAction": {
                          "url": "http://example.com"
                        }
                      },
                      {
                        "type": "CALL",
                        "title": "Call us",
                        "openUrlAction": {
                          "url": "tel:+16501112222"
                        }
                      },
                      {
                        "type": "EMAIL",
                        "title": "Email us",
                        "openUrlAction": {
                          "url": "mailto:person@example.com"
                        }
                      }
                    ],
                    "termsOfServiceUrl": "www.example.com",
                    "note": "Sale event",
                    "promotions": [
                      {
                        "coupon": "COUPON_CODE"
                      }
                    ],
                    "purchase": {
                      "status": "CREATED",
                      "userVisibleStatusLabel": "CREATED",
                      "type": "FOOD",
                      "returnsInfo": {
                        "isReturnable": false,
                        "daysToReturn": 1,
                        "policyUrl": "http://www.example.com"
                      },
                      "fulfillmentInfo": {
                        "id": "FULFILLMENT_SERVICE_ID",
                        "fulfillmentType": "DELIVERY",
                        "expectedFulfillmentTime": {
                          "timeIso8601": "2019-09-25T18:00:00.877Z"
                        },
                        "location": {},
                        "price": {
                          "type": "REGULAR",
                          "name": "Delivery Price",
                          "state": "ACTUAL",
                          "amount": {
                            "currencyCode": "USD",
                            "amountInMicros": 2000000
                          },
                          "taxIncluded": true
                        },
                        "fulfillmentContact": {
                          "email": "johnjohnson@gmail.com",
                          "firstName": "John",
                          "lastName": "Johnson",
                          "displayName": "John Johnson"
                        }
                      },
                      "purchaseLocationType": "ONLINE_PURCHASE"
                    }
                  }
                }
              },
              {
                "name": "text"
              }
            ]
          }
        ],
        "surface": {
          "capabilities": [
            {
              "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
            },
            {
              "name": "actions.capability.AUDIO_OUTPUT"
            },
            {
              "name": "actions.capability.ACCOUNT_LINKING"
            },
            {
              "name": "actions.capability.SCREEN_OUTPUT"
            },
            {
              "name": "actions.capability.WEB_BROWSER"
            }
          ]
        },
        "availableSurfaces": [
          {
            "capabilities": [
              {
                "name": "actions.capability.WEB_BROWSER"
              },
              {
                "name": "actions.capability.AUDIO_OUTPUT"
              },
              {
                "name": "actions.capability.SCREEN_OUTPUT"
              }
            ]
          }
        ]
      }
    },
    "session": "projects/df-transactions/agent/sessions/ABwppHGYEP2Fj7tJBxoaKMevL6lZ2rs063lOEWhSW5etZWVOoJe7Dzm_bLejRTYIYXL3D78ER7YvA5aN9Wpy"
  }

JSON

{
  "user": {
    "locale": "en-US",
    "lastSeen": "2019-11-11T23:57:31Z",
    "userVerificationStatus": "VERIFIED"
  },
  "conversation": {
    "conversationId": "ABwppHGFwStZlYaQ9YT8rg9t_idVsxZrku1pUDrEbGSJmSUMatVdPwPEEQSCe1IwIBoN4sS4Weyn9pmgetEgbsWgw3JSvQmw",
    "type": "ACTIVE",
    "conversationToken": "{\"data\":{\"paymentType\":\"merchant_payment\",\"location\":{\"coordinates\":{\"latitude\":37.421578499999995,\"longitude\":-122.0837816},\"zipCode\":\"94043-1351\",\"city\":\"MOUNTAIN VIEW\",\"postalAddress\":{\"regionCode\":\"US\",\"postalCode\":\"94043-1351\",\"administrativeArea\":\"CA\",\"locality\":\"MOUNTAIN VIEW\",\"addressLines\":[\"1600 AMPHITHEATRE PKWY\"],\"recipients\":[\"John Doe\"]},\"phoneNumber\":\"+1 123-456-7890\"},\"latestOrderId\":\"ORDER_ID\"}}"
  },
  "inputs": [
    {
      "intent": "actions.intent.TRANSACTION_DECISION",
      "rawInputs": [
        {}
      ],
      "arguments": [
        {
          "name": "TRANSACTION_DECISION_VALUE",
          "extension": {
            "@type": "type.googleapis.com/google.actions.transactions.v3.TransactionDecisionValue",
            "transactionDecision": "ORDER_ACCEPTED",
            "order": {
              "googleOrderId": "05528125187071048269",
              "merchantOrderId": "ORDER_ID",
              "userVisibleOrderId": "ORDER_ID",
              "buyerInfo": {
                "email": "janedoe@example.com",
                "firstName": "Jane",
                "lastName": "Doe",
                "displayName": "Jane Doe"
              },
              "createTime": "2019-09-24T18:00:00.877Z",
              "lastUpdateTime": "2019-09-24T18:00:00.877Z",
              "transactionMerchant": {
                "id": "http://www.example.com",
                "name": "Example Merchant"
              },
              "contents": {
                "lineItems": [
                  {
                    "id": "LINE_ITEM_ID",
                    "name": "Pizza",
                    "priceAttributes": [
                      {
                        "type": "REGULAR",
                        "name": "Item Price",
                        "state": "ACTUAL",
                        "amount": {
                          "currencyCode": "USD",
                          "amountInMicros": "8990000"
                        },
                        "taxIncluded": true
                      },
                      {
                        "type": "TOTAL",
                        "name": "Total Price",
                        "state": "ACTUAL",
                        "amount": {
                          "currencyCode": "USD",
                          "amountInMicros": "9990000"
                        },
                        "taxIncluded": true
                      }
                    ],
                    "description": "A four cheese pizza.",
                    "notes": [
                      "Extra cheese."
                    ],
                    "purchase": {
                      "quantity": 1,
                      "itemOptions": [
                        {
                          "id": "ITEM_OPTION_ID",
                          "name": "Pepperoni",
                          "prices": [
                            {
                              "type": "REGULAR",
                              "name": "Item Price",
                              "state": "ACTUAL",
                              "amount": {
                                "currencyCode": "USD",
                                "amountInMicros": "1000000"
                              },
                              "taxIncluded": true
                            },
                            {
                              "type": "TOTAL",
                              "name": "Total Price",
                              "state": "ACTUAL",
                              "amount": {
                                "currencyCode": "USD",
                                "amountInMicros": "1000000"
                              },
                              "taxIncluded": true
                            }
                          ],
                          "note": "Extra pepperoni",
                          "quantity": 1
                        }
                      ],
                      "unitMeasure": {
                        "measure": 1,
                        "unit": "POUND"
                      }
                    },
                    "vertical": {
                      "@type": "type.googleapis.com/google.actions.orders.v3.verticals.purchase.PurchaseItemExtension",
                      "quantity": 1,
                      "itemOptions": [
                        {
                          "id": "ITEM_OPTION_ID",
                          "name": "Pepperoni",
                          "prices": [
                            {
                              "type": "REGULAR",
                              "name": "Item Price",
                              "state": "ACTUAL",
                              "amount": {
                                "currencyCode": "USD",
                                "amountInMicros": "1000000"
                              },
                              "taxIncluded": true
                            },
                            {
                              "type": "TOTAL",
                              "name": "Total Price",
                              "state": "ACTUAL",
                              "amount": {
                                "currencyCode": "USD",
                                "amountInMicros": "1000000"
                              },
                              "taxIncluded": true
                            }
                          ],
                          "note": "Extra pepperoni",
                          "quantity": 1
                        }
                      ],
                      "unitMeasure": {
                        "measure": 1,
                        "unit": "POUND"
                      }
                    }
                  }
                ]
              },
              "priceAttributes": [
                {
                  "type": "SUBTOTAL",
                  "name": "Subtotal",
                  "state": "ESTIMATE",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": "9990000"
                  },
                  "taxIncluded": true
                },
                {
                  "type": "DELIVERY",
                  "name": "Delivery",
                  "state": "ACTUAL",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": "2000000"
                  },
                  "taxIncluded": true
                },
                {
                  "type": "TAX",
                  "name": "Tax",
                  "state": "ESTIMATE",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": "3780000"
                  },
                  "taxIncluded": true
                },
                {
                  "type": "TOTAL",
                  "name": "Total Price",
                  "state": "ESTIMATE",
                  "amount": {
                    "currencyCode": "USD",
                    "amountInMicros": "15770000"
                  },
                  "taxIncluded": true
                }
              ],
              "followUpActions": [
                {
                  "type": "VIEW_DETAILS",
                  "title": "View details",
                  "openUrlAction": {
                    "url": "http://example.com"
                  }
                },
                {
                  "type": "CALL",
                  "title": "Call us",
                  "openUrlAction": {
                    "url": "tel:+16501112222"
                  }
                },
                {
                  "type": "EMAIL",
                  "title": "Email us",
                  "openUrlAction": {
                    "url": "mailto:person@example.com"
                  }
                }
              ],
              "termsOfServiceUrl": "http://www.example.com",
              "note": "Sale event",
              "paymentData": {
                "paymentResult": {
                  "merchantPaymentMethodId": "12345678"
                },
                "paymentInfo": {
                  "paymentMethodDisplayInfo": {
                    "paymentType": "PAYMENT_CARD",
                    "paymentMethodDisplayName": "VISA **** 1234"
                  },
                  "paymentMethodProvenance": "PAYMENT_METHOD_PROVENANCE_MERCHANT"
                }
              },
              "promotions": [
                {
                  "coupon": "COUPON_CODE"
                }
              ],
              "purchase": {
                "status": "CREATED",
                "type": "FOOD",
                "returnsInfo": {
                  "daysToReturn": 1,
                  "policyUrl": "http://www.example.com"
                },
                "fulfillmentInfo": {
                  "id": "FULFILLMENT_SERVICE_ID",
                  "fulfillmentType": "DELIVERY",
                  "expectedFulfillmentTime": {
                    "timeIso8601": "2019-09-25T18:00:00.877Z"
                  },
                  "location": {
                    "coordinates": {
                      "latitude": 37.421578499999995,
                      "longitude": -122.0837816
                    },
                    "zipCode": "94043-1351",
                    "city": "MOUNTAIN VIEW",
                    "postalAddress": {
                      "regionCode": "US",
                      "postalCode": "94043-1351",
                      "administrativeArea": "CA",
                      "locality": "MOUNTAIN VIEW",
                      "addressLines": [
                        "1600 AMPHITHEATRE PKWY"
                      ],
                      "recipients": [
                        "John Doe"
                      ]
                    },
                    "phoneNumber": "+1 123-456-7890"
                  },
                  "price": {
                    "type": "REGULAR",
                    "name": "Delivery Price",
                    "state": "ACTUAL",
                    "amount": {
                      "currencyCode": "USD",
                      "amountInMicros": "2000000"
                    },
                    "taxIncluded": true
                  },
                  "fulfillmentContact": {
                    "email": "johnjohnson@gmail.com",
                    "firstName": "John",
                    "lastName": "Johnson",
                    "displayName": "John Johnson"
                  }
                },
                "purchaseLocationType": "ONLINE_PURCHASE",
                "userVisibleStatusLabel": "CREATED"
              },
              "vertical": {
                "@type": "type.googleapis.com/google.actions.orders.v3.verticals.purchase.PurchaseOrderExtension",
                "status": "CREATED",
                "type": "FOOD",
                "returnsInfo": {
                  "daysToReturn": 1,
                  "policyUrl": "http://www.example.com"
                },
                "fulfillmentInfo": {
                  "id": "FULFILLMENT_SERVICE_ID",
                  "fulfillmentType": "DELIVERY",
                  "expectedFulfillmentTime": {
                    "timeIso8601": "2019-09-25T18:00:00.877Z"
                  },
                  "location": {
                    "coordinates": {
                      "latitude": 37.421578499999995,
                      "longitude": -122.0837816
                    },
                    "zipCode": "94043-1351",
                    "city": "MOUNTAIN VIEW",
                    "postalAddress": {
                      "regionCode": "US",
                      "postalCode": "94043-1351",
                      "administrativeArea": "CA",
                      "locality": "MOUNTAIN VIEW",
                      "addressLines": [
                        "1600 AMPHITHEATRE PKWY"
                      ],
                      "recipients": [
                        "John Doe"
                      ]
                    },
                    "phoneNumber": "+1 123-456-7890"
                  },
                  "price": {
                    "type": "REGULAR",
                    "name": "Delivery Price",
                    "state": "ACTUAL",
                    "amount": {
                      "currencyCode": "USD",
                      "amountInMicros": "2000000"
                    },
                    "taxIncluded": true
                  },
                  "fulfillmentContact": {
                    "email": "johnjohnson@gmail.com",
                    "firstName": "John",
                    "lastName": "Johnson",
                    "displayName": "John Johnson"
                  }
                },
                "purchaseLocationType": "ONLINE_PURCHASE",
                "userVisibleStatusLabel": "CREATED"
              }
            }
          }
        },
        {
          "name": "text"
        }
      ]
    }
  ],
  "surface": {
    "capabilities": [
      {
        "name": "actions.capability.AUDIO_OUTPUT"
      },
      {
        "name": "actions.capability.MEDIA_RESPONSE_AUDIO"
      },
      {
        "name": "actions.capability.ACCOUNT_LINKING"
      },
      {
        "name": "actions.capability.SCREEN_OUTPUT"
      }
    ]
  },
  "availableSurfaces": [
    {
      "capabilities": [
        {
          "name": "actions.capability.SCREEN_OUTPUT"
        },
        {
          "name": "actions.capability.WEB_BROWSER"
        },
        {
          "name": "actions.capability.AUDIO_OUTPUT"
        }
      ]
    }
  ]
}

5. Finaliza el pedido y envía un recibo

Cuando el intent actions.intent.TRANSACTION_DECISION se muestra con un transactionDecision de ORDER_ACCEPTED, debes realizar de inmediato el procesamiento necesario para “confirmar” el pedido (como conservarlo en tu propia base de datos y cobrar al usuario).

Puedes finalizar la conversación con esta respuesta, pero debes incluir una respuesta simple para mantener la conversación. Cuando proporciones esta orderUpdate inicial, el usuario verá una "tarjeta de recibo contraída" junto con el resto de tu respuesta. Esta tarjeta duplicará el recibo que el usuario encuentre en su Historial de pedidos.

Durante la confirmación del pedido, tu objeto de pedido puede incluir un userVisibleOrderId, que es el ID que el usuario ve para el pedido. Puedes volver a usar tu merchantOrderId para este campo.

Parte del objeto OrderUpdate deberá contener un objeto action de seguimiento, que se manifiesta como botones de URL en la parte inferior de los detalles del pedido que el usuario puede encontrar en su Historial de pedidos de Asistente.

Entrega

Node.js

// Set lastUpdateTime and update status of order
const order = arg.order;
order.lastUpdateTime = '2019-09-24T19:00:00.877Z';
order.purchase.status = 'CONFIRMED';
order.purchase.userVisibleStatusLabel = 'Order confirmed';

// Send synchronous order update
conv.ask(`Transaction completed! Your order`
+ ` ${conv.data.latestOrderId} is all set!`);
conv.ask(new Suggestions('send order update'));
conv.ask(new OrderUpdate({
  type: 'SNAPSHOT',
  reason: 'Reason string',
  order: order,
}));

Node.js

// Set lastUpdateTime and update status of order
const order = arg.order;
order.lastUpdateTime = '2019-09-24T19:00:00.877Z';
order.purchase.status = 'CONFIRMED';
order.purchase.userVisibleStatusLabel = 'Order confirmed';

// Send synchronous order update
conv.ask(`Transaction completed! Your order `
+ `${conv.data.latestOrderId} is all set!`);
conv.ask(new Suggestions('send order update'));
conv.ask(new OrderUpdate({
  type: 'SNAPSHOT',
  reason: 'Reason string',
  order: order,
}));

Java

OrderV3 order = ((OrderV3) extension.get("order"));
order.setLastUpdateTime("2019-09-24T19:00:00.877Z");

// Update order status
PurchaseOrderExtension purchaseOrderExtension = order.getPurchase();
purchaseOrderExtension.setStatus("CONFIRMED");
purchaseOrderExtension.setUserVisibleStatusLabel("Order confirmed");
order.setPurchase(purchaseOrderExtension);

// Order update
OrderUpdateV3 orderUpdate = new OrderUpdateV3()
    .setType("SNAPSHOT")
    .setReason("Reason string")
    .setOrder(order);

Map<String, Object> conversationData = request.getConversationData();
String orderId = (String) conversationData.get("latestOrderId");
responseBuilder
    .add("Transaction completed! Your order " + orderId + " is all set!")
    .addSuggestions(new String[] {"send order update"})
    .add(new StructuredResponse().setOrderUpdateV3(orderUpdate));

Java

OrderV3 order = ((OrderV3) extension.get("order"));
order.setLastUpdateTime("2019-09-24T19:00:00.877Z");

// Update order status
PurchaseOrderExtension purchaseOrderExtension = order.getPurchase();
purchaseOrderExtension.setStatus("CONFIRMED");
purchaseOrderExtension.setUserVisibleStatusLabel("Order confirmed");
order.setPurchase(purchaseOrderExtension);

// Order update
OrderUpdateV3 orderUpdate = new OrderUpdateV3()
    .setType("SNAPSHOT")
    .setReason("Reason string")
    .setOrder(order);

Map<String, Object> conversationData = request.getConversationData();
String orderId = (String) conversationData.get("latestOrderId");
responseBuilder
    .add("Transaction completed! Your order " + orderId + " is all set!")
    .addSuggestions(new String[] {"send order update"})
    .add(new StructuredResponse().setOrderUpdateV3(orderUpdate));

JSON

{
    "payload": {
        "google": {
          "expectUserResponse": true,
          "richResponse": {
                "items": [
                    {
                        "simpleResponse": {
                        "textToSpeech": "Transaction completed! Your order undefined is all set!"
                        }
                    },
                    {
                        "structuredResponse": {
                        "orderUpdateV3": {
                            "order": {
                            "buyerInfo": {
                                "displayName": "Jane Doe",
                                "email": "janedoe@gmail.com",
                                "firstName": "Jane",
                                "lastName": "Doe"
                            },
                            "contents": {
                                "lineItems": [
                                {
                                    "description": "A four cheese pizza.",
                                    "id": "LINE_ITEM_ID",
                                    "name": "Pizza",
                                    "notes": [
                                    "Extra cheese."
                                    ],
                                    "priceAttributes": [
                                    {
                                        "amount": {
                                        "amountInMicros": 8990000,
                                        "currencyCode": "USD"
                                        },
                                        "name": "Line Item Price",
                                        "state": "ACTUAL",
                                        "taxIncluded": true,
                                        "type": "REGULAR"
                                    },
                                    {
                                        "amount": {
                                        "amountInMicros": 9990000,
                                        "currencyCode": "USD"
                                        },
                                        "name": "Total Price",
                                        "state": "ACTUAL",
                                        "taxIncluded": true,
                                        "type": "TOTAL"
                                    }
                                    ],
                                    "purchase": {
                                    "itemOptions": [
                                        {
                                        "id": "ITEM_OPTION_ID",
                                        "name": "Pepperoni",
                                        "note": "Extra pepperoni",
                                        "prices": [
                                            {
                                            "amount": {
                                                "amountInMicros": 1000000,
                                                "currencyCode": "USD"
                                            },
                                            "name": "Item Price",
                                            "state": "ACTUAL",
                                            "taxIncluded": true,
                                            "type": "REGULAR"
                                            },
                                            {
                                            "amount": {
                                                "amountInMicros": 1000000,
                                                "currencyCode": "USD"
                                            },
                                            "name": "Total Price",
                                            "state": "ACTUAL",
                                            "taxIncluded": true,
                                            "type": "TOTAL"
                                            }
                                        ],
                                        "quantity": 1,
                                        "subOptions": []
                                        }
                                    ],
                                    "quantity": 1,
                                    "unitMeasure": {
                                        "measure": 1,
                                        "unit": "POUND"
                                    }
                                    }
                                }
                                ]
                            },
                            "createTime": "2019-09-24T18:00:00.877Z",
                            "followUpActions": [
                                {
                                "openUrlAction": {
                                    "url": "http://example.com"
                                },
                                "title": "View details",
                                "type": "VIEW_DETAILS"
                                },
                                {
                                "openUrlAction": {
                                    "url": "tel:+16501112222"
                                },
                                "title": "Call us",
                                "type": "CALL"
                                },
                                {
                                "openUrlAction": {
                                    "url": "mailto:person@example.com"
                                },
                                "title": "Email us",
                                "type": "EMAIL"
                                }
                            ],
                            "lastUpdateTime": "2019-09-24T19:00:00.877Z",
                            "merchantOrderId": "ORDER_ID",
                            "note": "Sale event",
                            "priceAttributes": [
                                {
                                "amount": {
                                    "amountInMicros": 9990000,
                                    "currencyCode": "USD"
                                },
                                "name": "Subtotal",
                                "state": "ESTIMATE",
                                "taxIncluded": true,
                                "type": "SUBTOTAL"
                                },
                                {
                                "amount": {
                                    "amountInMicros": 2000000,
                                    "currencyCode": "USD"
                                },
                                "name": "Delivery",
                                "state": "ACTUAL",
                                "taxIncluded": true,
                                "type": "DELIVERY"
                                },
                                {
                                "amount": {
                                    "amountInMicros": 3780000,
                                    "currencyCode": "USD"
                                },
                                "name": "Tax",
                                "state": "ESTIMATE",
                                "taxIncluded": true,
                                "type": "TAX"
                                },
                                {
                                "amount": {
                                    "amountInMicros": 15770000,
                                    "currencyCode": "USD"
                                },
                                "name": "Total Price",
                                "state": "ESTIMATE",
                                "taxIncluded": true,
                                "type": "TOTAL"
                                }
                            ],
                            "promotions": [
                                {
                                "coupon": "COUPON_CODE"
                                }
                            ],
                            "purchase": {
                                "fulfillmentInfo": {
                                "expectedFulfillmentTime": {
                                    "timeIso8601": "2019-09-25T18:00:00.877Z"
                                },
                                "fulfillmentContact": {
                                    "displayName": "John Johnson",
                                    "email": "johnjohnson@gmail.com",
                                    "firstName": "John",
                                    "lastName": "Johnson"
                                },
                                "fulfillmentType": "DELIVERY",
                                "id": "FULFILLMENT_SERVICE_ID",
                                "location": {},
                                "price": {
                                    "amount": {
                                    "amountInMicros": 2000000,
                                    "currencyCode": "USD"
                                    },
                                    "name": "Delivery Price",
                                    "state": "ACTUAL",
                                    "taxIncluded": true,
                                    "type": "REGULAR"
                                }
                                },
                                "purchaseLocationType": "ONLINE_PURCHASE",
                                "returnsInfo": {
                                "daysToReturn": 1,
                                "isReturnable": false,
                                "policyUrl": "http://www.example.com"
                                },
                                "status": "CONFIRMED",
                                "type": "FOOD",
                                "userVisibleStatusLabel": "Order confirmed"
                            },
                            "termsOfServiceUrl": "www.example.com",
                            "transactionMerchant": {
                                "id": "http://www.example.com",
                                "name": "Example Merchant"
                            },
                            "userVisibleOrderId": "ORDER_ID"
                            },
                            "reason": "Reason string",
                            "type": "SNAPSHOT"
                        }
                        }
                    }
                ],
                "suggestions": [
                    {
                        "title": "send order update"
                    }
                ]
            }
        }
      }
}

JSON

{
    "expectUserResponse": true,
    "expectedInputs": [
      {
        "possibleIntents": [
          {
            "intent": "actions.intent.TEXT"
          }
        ],
        "inputPrompt": {
          "richInitialPrompt": {
            "items": [
              {
                "simpleResponse": {
                  "textToSpeech": "Transaction completed! Your order ORDER_ID is all set!"
                }
              },
              {
                "structuredResponse": {
                  "orderUpdateV3": {
                    "type": "SNAPSHOT",
                    "reason": "Reason string",
                    "order": {
                      "googleOrderId": "05528125187071048269",
                      "merchantOrderId": "ORDER_ID",
                      "userVisibleOrderId": "ORDER_ID",
                      "buyerInfo": {
                        "email": "janedoe@example.com",
                        "firstName": "Jane",
                        "lastName": "Doe",
                        "displayName": "Jane Doe"
                      },
                      "createTime": "2019-09-24T18:00:00.877Z",
                      "lastUpdateTime": "2019-09-24T19:00:00.877Z",
                      "transactionMerchant": {
                        "id": "http://www.example.com",
                        "name": "Example Merchant"
                      },
                      "contents": {
                        "lineItems": [
                          {
                            "id": "LINE_ITEM_ID",
                            "name": "Pizza",
                            "priceAttributes": [
                              {
                                "type": "REGULAR",
                                "name": "Item Price",
                                "state": "ACTUAL",
                                "amount": {
                                  "currencyCode": "USD",
                                  "amountInMicros": "8990000"
                                },
                                "taxIncluded": true
                              },
                              {
                                "type": "TOTAL",
                                "name": "Total Price",
                                "state": "ACTUAL",
                                "amount": {
                                  "currencyCode": "USD",
                                  "amountInMicros": "9990000"
                                },
                                "taxIncluded": true
                              }
                            ],
                            "description": "A four cheese pizza.",
                            "notes": [
                              "Extra cheese."
                            ],
                            "purchase": {
                              "quantity": 1,
                              "itemOptions": [
                                {
                                  "id": "ITEM_OPTION_ID",
                                  "name": "Pepperoni",
                                  "prices": [
                                    {
                                      "type": "REGULAR",
                                      "name": "Item Price",
                                      "state": "ACTUAL",
                                      "amount": {
                                        "currencyCode": "USD",
                                        "amountInMicros": "1000000"
                                      },
                                      "taxIncluded": true
                                    },
                                    {
                                      "type": "TOTAL",
                                      "name": "Total Price",
                                      "state": "ACTUAL",
                                      "amount": {
                                        "currencyCode": "USD",
                                        "amountInMicros": "1000000"
                                      },
                                      "taxIncluded": true
                                    }
                                  ],
                                  "note": "Extra pepperoni",
                                  "quantity": 1
                                }
                              ],
                              "unitMeasure": {
                                "measure": 1,
                                "unit": "POUND"
                              }
                            },
                            "vertical": {
                              "@type": "type.googleapis.com/google.actions.orders.v3.verticals.purchase.PurchaseItemExtension",
                              "quantity": 1,
                              "itemOptions": [
                                {
                                  "id": "ITEM_OPTION_ID",
                                  "name": "Pepperoni",
                                  "prices": [
                                    {
                                      "type": "REGULAR",
                                      "name": "Item Price",
                                      "state": "ACTUAL",
                                      "amount": {
                                        "currencyCode": "USD",
                                        "amountInMicros": "1000000"
                                      },
                                      "taxIncluded": true
                                    },
                                    {
                                      "type": "TOTAL",
                                      "name": "Total Price",
                                      "state": "ACTUAL",
                                      "amount": {
                                        "currencyCode": "USD",
                                        "amountInMicros": "1000000"
                                      },
                                      "taxIncluded": true
                                    }
                                  ],
                                  "note": "Extra pepperoni",
                                  "quantity": 1
                                }
                              ],
                              "unitMeasure": {
                                "measure": 1,
                                "unit": "POUND"
                              }
                            }
                          }
                        ]
                      },
                      "priceAttributes": [
                        {
                          "type": "SUBTOTAL",
                          "name": "Subtotal",
                          "state": "ESTIMATE",
                          "amount": {
                            "currencyCode": "USD",
                            "amountInMicros": "9990000"
                          },
                          "taxIncluded": true
                        },
                        {
                          "type": "DELIVERY",
                          "name": "Delivery",
                          "state": "ACTUAL",
                          "amount": {
                            "currencyCode": "USD",
                            "amountInMicros": "2000000"
                          },
                          "taxIncluded": true
                        },
                        {
                          "type": "TAX",
                          "name": "Tax",
                          "state": "ESTIMATE",
                          "amount": {
                            "currencyCode": "USD",
                            "amountInMicros": "3780000"
                          },
                          "taxIncluded": true
                        },
                        {
                          "type": "TOTAL",
                          "name": "Total Price",
                          "state": "ESTIMATE",
                          "amount": {
                            "currencyCode": "USD",
                            "amountInMicros": "15770000"
                          },
                          "taxIncluded": true
                        }
                      ],
                      "followUpActions": [
                        {
                          "type": "VIEW_DETAILS",
                          "title": "View details",
                          "openUrlAction": {
                            "url": "http://example.com"
                          }
                        },
                        {
                          "type": "CALL",
                          "title": "Call us",
                          "openUrlAction": {
                            "url": "tel:+16501112222"
                          }
                        },
                        {
                          "type": "EMAIL",
                          "title": "Email us",
                          "openUrlAction": {
                            "url": "mailto:person@example.com"
                          }
                        }
                      ],
                      "termsOfServiceUrl": "http://www.example.com",
                      "note": "Sale event",
                      "paymentData": {
                        "paymentResult": {
                          "merchantPaymentMethodId": "12345678"
                        },
                        "paymentInfo": {
                          "paymentMethodDisplayInfo": {
                            "paymentType": "PAYMENT_CARD",
                            "paymentMethodDisplayName": "VISA **** 1234"
                          },
                          "paymentMethodProvenance": "PAYMENT_METHOD_PROVENANCE_MERCHANT"
                        }
                      },
                      "promotions": [
                        {
                          "coupon": "COUPON_CODE"
                        }
                      ],
                      "purchase": {
                        "status": "CONFIRMED",
                        "type": "FOOD",
                        "returnsInfo": {
                          "daysToReturn": 1,
                          "policyUrl": "http://www.example.com"
                        },
                        "fulfillmentInfo": {
                          "id": "FULFILLMENT_SERVICE_ID",
                          "fulfillmentType": "DELIVERY",
                          "expectedFulfillmentTime": {
                            "timeIso8601": "2019-09-25T18:00:00.877Z"
                          },
                          "location": {
                            "coordinates": {
                              "latitude": 37.421578499999995,
                              "longitude": -122.0837816
                            },
                            "zipCode": "94043-1351",
                            "city": "MOUNTAIN VIEW",
                            "postalAddress": {
                              "regionCode": "US",
                              "postalCode": "94043-1351",
                              "administrativeArea": "CA",
                              "locality": "MOUNTAIN VIEW",
                              "addressLines": [
                                "1600 AMPHITHEATRE PKWY"
                              ],
                              "recipients": [
                                "John Doe"
                              ]
                            },
                            "phoneNumber": "+1 123-456-7890"
                          },
                          "price": {
                            "type": "REGULAR",
                            "name": "Delivery Price",
                            "state": "ACTUAL",
                            "amount": {
                              "currencyCode": "USD",
                              "amountInMicros": "2000000"
                            },
                            "taxIncluded": true
                          },
                          "fulfillmentContact": {
                            "email": "johnjohnson@gmail.com",
                            "firstName": "John",
                            "lastName": "Johnson",
                            "displayName": "John Johnson"
                          }
                        },
                        "purchaseLocationType": "ONLINE_PURCHASE",
                        "userVisibleStatusLabel": "Order confirmed"
                      },
                      "vertical": {
                        "@type": "type.googleapis.com/google.actions.orders.v3.verticals.purchase.PurchaseOrderExtension",
                        "status": "CREATED",
                        "type": "FOOD",
                        "returnsInfo": {
                          "daysToReturn": 1,
                          "policyUrl": "http://www.example.com"
                        },
                        "fulfillmentInfo": {
                          "id": "FULFILLMENT_SERVICE_ID",
                          "fulfillmentType": "DELIVERY",
                          "expectedFulfillmentTime": {
                            "timeIso8601": "2019-09-25T18:00:00.877Z"
                          },
                          "location": {
                            "coordinates": {
                              "latitude": 37.421578499999995,
                              "longitude": -122.0837816
                            },
                            "zipCode": "94043-1351",
                            "city": "MOUNTAIN VIEW",
                            "postalAddress": {
                              "regionCode": "US",
                              "postalCode": "94043-1351",
                              "administrativeArea": "CA",
                              "locality": "MOUNTAIN VIEW",
                              "addressLines": [
                                "1600 AMPHITHEATRE PKWY"
                              ],
                              "recipients": [
                                "John Doe"
                              ]
                            },
                            "phoneNumber": "+1 123-456-7890"
                          },
                          "price": {
                            "type": "REGULAR",
                            "name": "Delivery Price",
                            "state": "ACTUAL",
                            "amount": {
                              "currencyCode": "USD",
                              "amountInMicros": "2000000"
                            },
                            "taxIncluded": true
                          },
                          "fulfillmentContact": {
                            "email": "johnjohnson@gmail.com",
                            "firstName": "John",
                            "lastName": "Johnson",
                            "displayName": "John Johnson"
                          }
                        },
                        "purchaseLocationType": "ONLINE_PURCHASE",
                        "userVisibleStatusLabel": "CREATED"
                      }
                    }
                  }
                }
              }
            ],
            "suggestions": [
              {
                "title": "send order update"
              }
            ]
          }
        }
      }
    ],
    "conversationToken": "{\"data\":{\"paymentType\":\"merchant_payment\",\"location\":{\"coordinates\":{\"latitude\":37.421578499999995,\"longitude\":-122.0837816},\"zipCode\":\"94043-1351\",\"city\":\"MOUNTAIN VIEW\",\"postalAddress\":{\"regionCode\":\"US\",\"postalCode\":\"94043-1351\",\"administrativeArea\":\"CA\",\"locality\":\"MOUNTAIN VIEW\",\"addressLines\":[\"1600 AMPHITHEATRE PKWY\"],\"recipients\":[\"John Doe\"]},\"phoneNumber\":\"+1 123-456-7890\"},\"latestOrderId\":\"ORDER_ID\"}}"
  }

6. Enviar actualizaciones del pedido

Deberás mantener informado al usuario sobre el estado del pedido durante su ciclo de vida. Envía al usuario actualizaciones de pedidos mediante el envío de solicitudes HTTP PATCH a la API de Orders con el estado y los detalles del pedido.

Configura solicitudes asíncronas en la API de Orders

Las solicitudes de actualización de pedidos a la API de Orders están autorizadas por un token de acceso. Para empaquetar una actualización de pedido en la API de Orders, descarga una clave de cuenta de servicio JSON asociada con tu proyecto de Actions Console y, luego, intercambia la clave de la cuenta de servicio por un token del portador que se pueda pasar al encabezado Authorization de la solicitud HTTP.

Para recuperar la clave de tu cuenta de servicio, sigue estos pasos:

  1. En la consola de Google Cloud, ve a Menú \r > APIs y servicios > Credenciales > Crear credenciales > Clave de cuenta de servicio.
  2. En Cuenta de servicio, selecciona Nueva cuenta de servicio.
  3. Establece la cuenta de servicio en service-account.
  4. Configura el Rol como Proyecto > Propietario.
  5. Establece el tipo de clave en JSON.
  6. Selecciona Crear.
  7. Se descargará una clave de cuenta de servicio JSON privada en tu máquina local.

En tu código de actualizaciones de pedido, puedes intercambiar tu clave de servicio por un token del portador mediante la biblioteca cliente de las APIs de Google y el alcance "https://www.googleapis.com/auth/actions.order.developer". Puedes encontrar pasos de instalación y ejemplos en la página de GitHub de la biblioteca cliente de la API.

También puedes hacer referencia a order-update.js en nuestras muestras de Node.js y Java para obtener un intercambio de claves de ejemplo.

Enviar actualizaciones del pedido

Una vez que hayas intercambiado la clave de tu cuenta de servicio por un token del portador de OAuth, puedes enviar actualizaciones de pedidos como solicitudes PATCH autorizadas a la API de pedidos.

URL de la API de Orders: PATCH https://actions.googleapis.com/v3/orders/${orderId}

Proporciona los siguientes encabezados en tu solicitud:

  • "Authorization: Bearer token" por el token del portador de OAuth por el que intercambiaste la clave de tu cuenta de servicio.
  • "Content-Type: application/json".

La solicitud PATCH debe tener un cuerpo JSON con el siguiente formato:

{ "orderUpdate": OrderUpdate }

El objeto OrderUpdate consta de los siguientes campos de nivel superior:

  • updateMask: Son los campos del pedido que estás actualizando. Para actualizar el estado del pedido, establece el valor en purchase.status, purchase.userVisibleStatusLabel.
  • order: Es el contenido de la actualización. Si actualizas el contenido del pedido, establece el valor en el objeto Order actualizado. Si actualizas el estado del pedido (por ejemplo, de "CONFIRMED" a "SHIPPED"), el objeto contendrá los siguientes campos:

    • merchantOrderId: Es el mismo ID que configuraste en tu objeto Order.
    • lastUpdateTime: Es la marca de tiempo de esta actualización.
    • purchase: Es un objeto que contiene lo siguiente:
      • status: Es el estado del pedido como PurchaseStatus, como "SHIPPED" o "DELIVERED".
      • userVisibleStatusLabel: Es una etiqueta visible para el usuario que proporciona detalles sobre el estado del pedido, como “Tu pedido se envió y está en camino”.
  • userNotification que se puede mostrar en el dispositivo del usuario cuando se envía esta actualización. Ten en cuenta que incluir este objeto no garantiza que aparezca una notificación en el dispositivo del usuario.

En el siguiente código de muestra, se presenta un OrderUpdate de ejemplo que actualiza el estado del pedido a DELIVERED:

Node.js

// Import the 'googleapis' module for authorizing the request.
const {google} = require('googleapis');
// Import the 'request-promise' module for sending an HTTP POST request.
const request = require('request-promise');
// Import the OrderUpdate class from the Actions on Google client library.
const {OrderUpdate} = require('actions-on-google');

// Import the service account key used to authorize the request.
// Replacing the string path with a path to your service account key.
// i.e. const serviceAccountKey = require('./service-account.json')

// Create a new JWT client for the Actions API using credentials
// from the service account key.
let jwtClient = new google.auth.JWT(
    serviceAccountKey.client_email,
    null,
    serviceAccountKey.private_key,
    ['https://www.googleapis.com/auth/actions.order.developer'],
    null,
);

// Authorize the client
let tokens = await jwtClient.authorize();

// Declare order update
const orderUpdate = new OrderUpdate({
    updateMask: [
      'lastUpdateTime',
      'purchase.status',
      'purchase.userVisibleStatusLabel',
    ].join(','),
    order: {
      merchantOrderId: orderId, // Specify the ID of the order to update
      lastUpdateTime: new Date().toISOString(),
      purchase: {
        status: 'DELIVERED',
        userVisibleStatusLabel: 'Order delivered',
      },
    },
    reason: 'Order status updated to delivered.',
});

// Set up the PATCH request header and body,
// including the authorized token and order update.
let options = {
  method: 'PATCH',
  uri: `https://actions.googleapis.com/v3/orders/${orderId}`,
  auth: {
    bearer: tokens.access_token,
  },
  body: {
    header: {
      isInSandbox: true,
    },
    orderUpdate,
  },
  json: true,
};

// Send the PATCH request to the Orders API.
try {
  await request(options);
  conv.close(`The order has been updated.`);
} catch (e) {
  console.log(`Error: ${e}`);
  conv.close(`There was an error sending an order update.`);
}

Node.js

// Import the 'googleapis' module for authorizing the request.
const {google} = require('googleapis');
// Import the 'request-promise' module for sending an HTTP POST request.
const request = require('request-promise');
// Import the OrderUpdate class from the Actions on Google client library.
const {OrderUpdate} = require('actions-on-google');

// Import the service account key used to authorize the request.
// Replacing the string path with a path to your service account key.
// i.e. const serviceAccountKey = require('./service-account.json')

// Create a new JWT client for the Actions API using credentials
// from the service account key.
let jwtClient = new google.auth.JWT(
    serviceAccountKey.client_email,
    null,
    serviceAccountKey.private_key,
    ['https://www.googleapis.com/auth/actions.order.developer'],
    null,
);

// Authorize the client
let tokens = await jwtClient.authorize();

// Declare order update
const orderUpdate = new OrderUpdate({
    updateMask: [
      'lastUpdateTime',
      'purchase.status',
      'purchase.userVisibleStatusLabel',
    ].join(','),
    order: {
      merchantOrderId: orderId, // Specify the ID of the order to update
      lastUpdateTime: new Date().toISOString(),
      purchase: {
        status: 'DELIVERED',
        userVisibleStatusLabel: 'Order delivered',
      },
    },
    reason: 'Order status updated to delivered.',
});

// Set up the PATCH request header and body,
// including the authorized token and order update.
let options = {
  method: 'PATCH',
  uri: `https://actions.googleapis.com/v3/orders/${orderId}`,
  auth: {
    bearer: tokens.access_token,
  },
  body: {
    header: {
      isInSandbox: true,
    },
    orderUpdate,
  },
  json: true,
};

// Send the PATCH request to the Orders API.
try {
  await request(options);
  conv.close(`The order has been updated.`);
} catch (e) {
  console.log(`Error: ${e}`);
  conv.close(`There was an error sending an order update.`);
}

Java

// Setup service account credentials
String serviceAccountFile = MyActionsApp.class.getClassLoader()
    .getResource(SERVICE_ACCOUNT_KEY_FILE_NAME)
    .getFile();
InputStream actionsApiServiceAccount = new FileInputStream(
    serviceAccountFile);
ServiceAccountCredentials serviceAccountCredentials = (ServiceAccountCredentials)
    ServiceAccountCredentials.fromStream(actionsApiServiceAccount)
        .createScoped(Collections.singleton(
            "https://www.googleapis.com/auth/actions.order.developer"));
AccessToken token = serviceAccountCredentials.refreshAccessToken();

// Setup request with headers
HttpPatch patchRequest = new HttpPatch(
    "https://actions.googleapis.com/v3/orders/" + orderId);
patchRequest.setHeader("Content-type", "application/json");
patchRequest.setHeader("Authorization", "Bearer " + token.getTokenValue());

// Create order update
FieldMask fieldMask = FieldMask.newBuilder().addAllPaths(Arrays.asList(
    "lastUpdateTime",
    "purchase.status",
    "purchase.userVisibleStatusLabel"))
    .build();

OrderUpdateV3 orderUpdate = new OrderUpdateV3()
    .setOrder(new OrderV3()
        .setMerchantOrderId(orderId)
        .setLastUpdateTime(Instant.now().toString())
        .setPurchase(new PurchaseOrderExtension()
            .setStatus("DELIVERED")
            .setUserVisibleStatusLabel("Order delivered.")))
    .setUpdateMask(FieldMaskUtil.toString(fieldMask))
    .setReason("Order status was updated to delivered.");

// Setup JSON body containing order update
JsonParser parser = new JsonParser();
JsonObject orderUpdateJson =
    parser.parse(new Gson().toJson(orderUpdate)).getAsJsonObject();
JsonObject body = new JsonObject();
body.add("orderUpdate", orderUpdateJson);
JsonObject header = new JsonObject();
header.addProperty("isInSandbox", true);
body.add("header", header);
StringEntity entity = new StringEntity(body.toString());
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
patchRequest.setEntity(entity);

// Make request
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(patchRequest);
LOGGER.info(response.getStatusLine().getStatusCode() + " " + response
    .getStatusLine().getReasonPhrase());

return getResponseBuilder(request)
    .add("The order has been updated.")
    .build();

Java

// Setup service account credentials
String serviceAccountFile = MyActionsApp.class.getClassLoader()
    .getResource(SERVICE_ACCOUNT_KEY_FILE_NAME)
    .getFile();
InputStream actionsApiServiceAccount = new FileInputStream(
    serviceAccountFile);
ServiceAccountCredentials serviceAccountCredentials = (ServiceAccountCredentials)
    ServiceAccountCredentials.fromStream(actionsApiServiceAccount)
        .createScoped(Collections.singleton(
            "https://www.googleapis.com/auth/actions.order.developer"));
AccessToken token = serviceAccountCredentials.refreshAccessToken();

// Setup request with headers
HttpPatch patchRequest = new HttpPatch(
    "https://actions.googleapis.com/v3/orders/" + orderId);
patchRequest.setHeader("Content-type", "application/json");
patchRequest.setHeader("Authorization", "Bearer " + token.getTokenValue());

// Create order update
FieldMask fieldMask = FieldMask.newBuilder().addAllPaths(Arrays.asList(
    "lastUpdateTime",
    "purchase.status",
    "purchase.userVisibleStatusLabel"))
    .build();

OrderUpdateV3 orderUpdate = new OrderUpdateV3()
    .setOrder(new OrderV3()
        .setMerchantOrderId(orderId)
        .setLastUpdateTime(Instant.now().toString())
        .setPurchase(new PurchaseOrderExtension()
            .setStatus("DELIVERED")
            .setUserVisibleStatusLabel("Order delivered.")))
    .setUpdateMask(FieldMaskUtil.toString(fieldMask))
    .setReason("Order status was updated to delivered.");

// Setup JSON body containing order update
JsonParser parser = new JsonParser();
JsonObject orderUpdateJson =
    parser.parse(new Gson().toJson(orderUpdate)).getAsJsonObject();
JsonObject body = new JsonObject();
body.add("orderUpdate", orderUpdateJson);
JsonObject header = new JsonObject();
header.addProperty("isInSandbox", true);
body.add("header", header);
StringEntity entity = new StringEntity(body.toString());
entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
patchRequest.setEntity(entity);

// Make request
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse response = httpClient.execute(patchRequest);
LOGGER.info(response.getStatusLine().getStatusCode() + " " + response
    .getStatusLine().getReasonPhrase());

return getResponseBuilder(request)
    .add("The order has been updated.")
    .build();
Establece el estado de la compra

El elemento status de una actualización de pedido debe describir el estado actual del pedido. En el campo order.purchase.status de tu actualización, usa uno de los siguientes valores:

  • CREATED: El usuario acepta el pedido y "se crea" desde la perspectiva de tu Acción, pero requiere procesamiento manual en tu backend.
  • CONFIRMED: El pedido está activo y se está procesando para su entrega.
  • IN_PREPARATION: El pedido se está preparando para el envío o la entrega, como cuando se cocina la comida o se empaqueta un artículo.
  • READY_FOR_PICKUP: El pedido está disponible para que lo retire el destinatario.
  • DELIVERED: El pedido se entregó al destinatario
  • OUT_OF_STOCK: Uno o más artículos del pedido están agotados.
  • CHANGE_REQUESTED: El usuario solicitó un cambio en el pedido y se está procesando el cambio.
  • RETURNED: El usuario devolvió el pedido después de la entrega.
  • REJECTED: si no pudiste procesar, cobrar ni “activar” el pedido de alguna otra manera.
  • CANCELLED: el usuario canceló el pedido.

Debes enviar actualizaciones del pedido para cada estado que sea relevante para tu transacción. Por ejemplo, si tu transacción requiere procesamiento manual para registrar el pedido después de que se realiza, envía una actualización del pedido de CREATED hasta que se complete el procesamiento adicional. No todos los pedidos requieren todos los valores de estado.

Solución de problemas

Si tienes algún problema durante la prueba, lee nuestros pasos para solucionar problemas de transacciones.