利用商家管理的付款 (Dialogflow) 构建实体交易

本指南将逐步介绍 Action 项目的开发流程,该项目使用由您的网站管理的付款方式整合实体商品的交易。

交易流程

当您的 Actions 项目使用商家管理的付款处理实体交易时,它会使用以下流程:

  1. 收集信息(可选)- 根据事务的性质,您可能需要在对话开始时向用户收集以下信息:
    1. 验证交易要求 - 在对话开始时使用交易要求帮助程序,确保用户的付款信息已正确配置且在用户添加购物车之前可用。
    2. 请求配送地址 - 如果您的交易需要配送地址,您可以请求执行配送地址帮助程序 intent,以向用户收集地址。
  2. 构建订单 - 引导用户完成“购物车组装”,让他们选择想要购买的商品。
  3. 执行帐号关联 - 为了让用户能够使用他们保存在您服务中的付款方式,请使用帐号关联功能将其 Google 帐号与其在您服务中的帐号相关联。
  4. 建议订单 - 购物车完成后,向用户建议订单,以便他们确认订单是否正确。如果订单得到确认,您会收到包含订单详情和付款令牌的响应。
  5. 敲定订单并发送收据 - 确认订单后,更新商品目录跟踪或其他履单服务,然后向用户发送收据。
  6. 发送订单更新 - 在履单的整个生命周期内,通过向 Orders API 发送 PATCH 请求向用户提供订单更新。

限制和审核指南

请注意,有其他政策适用于“与交易相关的 Action”。审核涉及交易的 Action 最多可能需要 6 周的时间,因此在规划发布时间表时请将这段时间考虑在内。为了简化审核流程,请确保先遵守交易政策和准则,然后再提交 Action 以供审核。

您只能在以下国家/地区部署销售实体商品的 Action:

澳大利亚
巴西
加拿大
印度尼西亚
日本
墨西哥
卡塔尔
俄罗斯
新加坡
瑞士
泰国
土耳其
英国
美国

构建您的项目

如需查看事务性对话的详细示例,请参阅 Node.jsJava 中的事务示例。

项目设置

创建 Action 时,您必须指定要在 Actions 控制台中执行事务。此外,如果您使用的是 Node.JS 客户端库,请将执行方式设置为使用最新版本的 Orders API。

如需设置项目和执行方式,请执行以下操作:

  1. 创建新项目或导入现有项目。
  2. 依次点击 Deploy > Directory information
  3. 其他信息 > 交易 > 下,选中显示“您的 Action 是否使用 Transaction API 执行实体商品的交易?”复选框。

  4. 如果您使用 Node.JS 客户端库构建 Action 的执行方式,请打开执行方式代码并更新应用声明,将 ordersv3 标志设置为 true。以下代码段展示了订单版本 3 的应用声明示例。

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,
});

登录设置

如果您使用自己的付款方式向用户扣款,我们建议您将用户的 Google 帐号与其使用您自己的服务的帐号相关联,以检索和显示存储在其中的付款方式以及扣款。

我们提供 OAuth 2.0 帐号关联来满足此要求。我们强烈建议您启用 OAuth 2.0 断言流程,因为它可以实现非常精简的用户体验。

我们提供了 actions.intent.SIGN_IN intent,让您可以请求用户在对话过程中关联帐号。您必须在 Actions 控制台启用帐号关联,才能使用 actions.intent.SIGN_IN intent。

如果您在 webhook 请求的 User 对象中找不到 accessToken,则应使用此 intent。这意味着用户尚未关联其帐号。

请求 actions.intent.SIGN_IN intent 后,您将收到一个 Argument,其中包含一个值为 "OK""CANCELLED""ERROR"SignInStatus。如果状态为 "OK",您应该能在 User 对象中找到 accessToken

履单

请求登录

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\"}}"
}
接收登录结果

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. 收集信息(可选)

1a. 验证交易要求(可选)

用户体验

触发 actions.intent.TRANSACTION_REQUIREMENTS_CHECK intent 可快速检查用户能否执行事务。此步骤将确保用户可以继续操作,并让用户有机会修正任何导致他们无法完成交易的设置。

例如,调用时,您的 Action 可能会询问“您想订购鞋子还是查看帐号余额?”如果用户说“订购鞋子”,您应该立即请求此 intent,这样可确保他们可以继续操作,并让用户有机会修正任何导致他们无法继续进行交易的设置。

请求事务要求检查 intent 将导致以下结果之一:

  • 如果满足要求,系统会将 intent 发送回具有成功条件的执行方式,然后您可以继续构建用户的订单。
  • 如果无法满足一项或多项要求,系统会将 intent 发送回您的执行方式,并附带失败条件。在这种情况下,您应该将对话从事务体验转向,或结束对话。
    • 如果导致失败状态的任何错误可由用户修复,系统会提示他们在设备上解决这些问题。如果对话是在仅支持语音的界面上进行,系统将启动移交到用户的手机上。
履单

为确保用户满足交易要求,请使用 TransactionRequirementsCheckSpec 对象请求执行 actions.intent.TRANSACTION_REQUIREMENTS_CHECK intent。

查看要求

您可以使用客户端库查看用户是否满足事务要求:

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\"}}"
}
接收要求检查的结果

Google 助理在执行 intent 后,会向您的执行方式发送包含 actions.intent.TRANSACTION_REQUIREMENTS_CHECK intent 的请求,其中包含检查结果。为了正确处理此请求,请声明由 actions_intent_TRANSACTION_REQUIREMENTS_CHECK 事件触发的 Dialogflow intent。触发后,使用客户端库在执行方式中处理它:

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. 申请配送地址(可选)

如果您的交易需要用户的配送地址,您可以请求执行 actions.intent.DELIVERY_ADDRESS intent。这有助于确定总价、送货/自提位置,或确保用户在您的服务区域内。

请求执行此 intent 时,您需要传入一个 reason 选项,该选项可让您在 Google 助理的请求前面加上字符串来获取地址。例如,如果您指定“知道将订单发送到哪里”,Google 助理可能会询问用户:

“我需要知道您的送货地址,才能知道要将订单配送到哪个地址”

用户体验

在有屏幕的 surface 上,用户可以选择希望使用哪个地址进行交易。如果他们之前没有提供地址,则可以输入新地址。

在仅支持语音的 surface 上,Google 助理会要求用户提供分享交易的默认地址的权限。如果他们之前没有提供地址,则对话将移交给手机以供进入。

请求地址

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\"}}"
}
接收地址

Google 助理在执行 intent 后,会向您的执行方式发送包含 actions.intent.DELIVERY_ADDRESS intent 的请求。

为了正确处理此请求,请声明由 actions_intent_DELIVERY_ADDRESS 事件触发的 Dialogflow intent。触发后,使用客户端库在执行方式中对其进行处理:

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. 构建订单

用户体验

获得所需的用户信息后,您可以打造“购物车组装”体验,引导用户构建订单。每个 Action 的购物车组装流程都会因其产品或服务而略有不同。

最基本的购物车组装体验是让用户从列表中选择要添加到订单中的商品,但您可以设计对话以简化用户体验。您可以打造一种购物车组装体验,让用户能够通过简单的“是”或“否”问题重新订购最近购买的商品。您还可以向用户展示包含热门“精选”或“推荐”商品的轮播界面或列表卡片。

我们建议使用富响应,以直观的方式呈现用户的选项,但同时也要设计对话,让用户只需通过语音就能构建自己的购物车。如需了解优质购物车组装体验的一些最佳实践和示例,请参阅交易设计准则

履单

在整个对话中,您需要收集用户想要购买的商品,然后构建 Order 对象。

您的 Order 必须至少包含以下内容:

  • buyerInfo - 进行购买的用户的相关信息。
  • transactionMerchant - 提供订单处理工具的商家的相关信息。
  • contents - 列为 lineItems 的订单的实际内容。
  • priceAttributes - 订单的价格详情,包括订单的总费用(含折扣和税费)。

如需了解如何构建购物车,请参阅 Order 响应文档。请注意,您可能需要根据订单添加不同的字段。

以下示例代码显示了一个完整订单,其中包括可选字段:

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. 执行账号关联

如果您使用自己的付款方式向用户扣款,我们建议您将用户的 Google 帐号与其使用您自己的服务的帐号相关联,以检索和显示存储在其中的付款方式以及扣款。

我们提供 OAuth 2.0 帐号关联来满足此要求。我们强烈建议您启用 OAuth 2.0 断言流程,因为它可以实现非常精简的用户体验。

我们提供了 actions.intent.SIGN_IN intent,让您可以请求用户在对话过程中关联帐号。您必须在 Actions 控制台启用帐号关联,才能使用 actions.intent.SIGN_IN intent。

如果您在 webhook 请求的 User 对象中找不到 accessToken,则应使用此 intent。这意味着用户尚未关联其帐号。

请求 actions.intent.SIGN_IN intent 后,您将收到一个 Argument,其中包含一个值为 "OK""CANCELLED""ERROR"SignInStatus。如果状态为 "OK",您应该能在 User 对象中找到 accessToken

履单

请求登录

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\"}}"
}
接收登录结果

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. 提出订单建议

构建订单后,您必须向用户显示其确认或拒绝。请求 actions.intent.TRANSACTION_DECISION intent 并提供您使用用户存储的付款信息构建的订单。

用户体验

当您请求 actions.intent.TRANSACTION_DECISION intent 时,Google 助理会启动一种内置体验,让您传递的 Order 会直接呈现到“购物车预览卡片”上。用户可以说“下单”、拒绝交易、更改付款方式(如信用卡或地址),或请求更改订单的内容。

此时,用户也可以请求更改订单。在这种情况下,您应确保您的执行方式可以在完成购物车组装体验后处理订单更改请求。

履单

当您请求 actions.intent.TRANSACTION_DECISION intent 时,您需要创建一个包含 Order 以及 orderOptionspaymentParametersTransactionDecision。您的 paymentParameters 对象包含一个 merchantPaymentOption,其中包含描述用户付款方式的字段。

以下代码展示了使用 Visa 信用卡付款的订单的 TransactionsDecision 示例:

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\"}}"
}

处理用户的决定

Google 助理在执行 intent 后,会向您的执行方式发送包含 actions_intent_TRANSACTION_DECISION intent 的请求,其中包含用户对交易决策的回答。您将收到一个包含 TransactionDecisionValue 的 Argument。此值将包含以下内容:

  • transactionDecision - 用户关于提议的订单的决定。可能的值包括 ORDER_ACCEPTEDORDER_REJECTEDDELIVERY_ADDRESS_UPDATEDCART_CHANGE_REQUESTEDUSER_CANNOT_TRANSACT
  • deliveryAddress - 用户更改了送货地址时更新后的送货地址。在这种情况下,transactionDecision 的值为 DELIVERY_ADDRESS_UPDATED

为了正确处理此请求,请声明由 actions_intent_TRANSACTION_DECISION 事件触发的 Dialogflow intent。触发后,在执行方式中对其进行处理:

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. 完成订单并发送收据

actions.intent.TRANSACTION_DECISION intent 返回 transactionDecisionORDER_ACCEPTED 时,您必须立即执行“确认”订单所需的任何处理(例如,将其保留在您自己的数据库中并向用户收费)。

您可以使用此响应结束对话,但必须包含简单响应才能使对话继续进行。在您提供此初始 orderUpdate 后,用户会看到“收起的收据卡片”以及其余响应。此卡片将反映用户在“订单记录”中找到的收据。

在订单确认过程中,您的订单对象可以包含 userVisibleOrderId,即用户看到的订单 ID。您可以在此字段中重复使用 merchantOrderId

OrderUpdate 对象的部分需要包含一个后续 action 对象,该对象以网址按钮的形式出现在订单详情底部,用户可以在 Google 助理订单记录中找到这些按钮。

履单

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. 发送订单动态

您需要在订单的整个生命周期内使用户随时了解订单状态。向 Orders API 发送包含订单状态和详细信息的 HTTP PATCH 请求,以发送用户订单更新。

设置向 Orders API 发送的异步请求

对 Orders API 的订单更新请求由访问令牌进行授权。如需修补 Orders API 的订单更新,请下载与您的 Actions 控制台项目关联的 JSON 服务帐号密钥,然后用服务帐号密钥交换可以传递到 HTTP 请求的 Authorization 标头的不记名令牌。

如需检索您的服务帐号密钥,请执行以下步骤:

  1. Google Cloud 控制台中,依次点击“菜单”图标 ☰ >“API 和服务”>“凭据”>“创建凭据”>“服务帐号密钥”
  2. 服务帐号下,选择新的服务帐号
  3. 将服务帐号设置为 service-account
  4. 角色设置为项目 > Owner
  5. 将密钥类型设置为 JSON
  6. 选择创建
  7. 一个 JSON 私钥服务账号密钥将下载到您的本地机器。

在订单更新代码中,您可以使用 Google API 客户端库和 "https://www.googleapis.com/auth/actions.order.developer" 范围将服务密钥交换为不记名令牌。您可以在 API 客户端库的 GitHub 页面上找到安装步骤和示例。

您还可以在我们的 Node.jsJava 示例中引用 order-update.js,查看密钥交换示例。

发送订单动态

将服务帐号密钥换成 OAuth 不记名令牌后,您可以将订单更新作为已获授权的 PATCH 请求发送到 Orders API。

Orders API 网址 PATCH https://actions.googleapis.com/v3/orders/${orderId}

在请求中提供以下标头:

  • "Authorization: Bearer token" 替换为您交换的服务帐号密钥的 OAuth 不记名令牌。
  • "Content-Type: application/json".

PATCH 请求应采用以下格式的 JSON 正文:

{ "orderUpdate": OrderUpdate }

OrderUpdate 对象包含以下顶级字段:

  • updateMask - 要更新的订单的字段。如需更新订单状态,请将值设置为 purchase.status, purchase.userVisibleStatusLabel
  • order - 更新的内容。如果要更新订单内容,请将值设置为更新后的 Order 对象。如果您要更新订单的状态(例如,从 "CONFIRMED" 更新为 "SHIPPED"),该对象包含以下字段:

    • merchantOrderId - 您在 Order 对象中设置的同一 ID。
    • lastUpdateTime - 此更新的时间戳。
    • purchase - 包含以下内容的对象:
      • status - 订单的状态,为 PurchaseStatus,例如“SHIPPED”或“DELIVERED”。
      • userVisibleStatusLabel - 一个面向用户的标签,提供订单状态的详细信息,例如“您的订单已发货,并在运输途中”。
  • userNotification 对象。请注意,添加此对象不能保证通知会显示在用户的设备上。

以下示例代码展示了一个将订单状态更新为 DELIVERED 的示例 OrderUpdate

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();
设置购买状态

订单更新的 status 必须描述订单的当前状态。在更新的 order.purchase.status 字段中,使用以下某个值:

  • CREATED - 订单被用户接受并从 Action 的角度“创建”,但需要后端手动处理。
  • CONFIRMED - 订单处于有效状态,且正在接受履单。
  • IN_PREPARATION - 订单正在准备配送/配送,例如正在烹饪食物或商品正在包装。
  • READY_FOR_PICKUP - 订单商品可由收货人自提。
  • DELIVERED - 订单已送达收货人
  • OUT_OF_STOCK - 订单中的一件或多件商品缺货。
  • CHANGE_REQUESTED - 用户请求更改订单,并且更改正在处理中。
  • RETURNED - 订单商品送达后用户已退货。
  • REJECTED - 如果您无法处理订单、收取订单费用或以其他方式“激活”订单。
  • CANCELLED - 用户取消了订单。

您应该发送与交易相关的每个状态的订单更新。例如,如果您的交易需要手动处理才能在下单后记录订单,请发送 CREATED 订单更新,直到额外的处理完成为止。并非每个订单都需要每个状态值。

问题排查

如果您在测试期间遇到任何问题,请阅读我们针对事务的问题排查步骤