Search in sources :

Example 1 with OrderV3

use of com.google.api.services.actions_fulfillment.v2.model.OrderV3 in project dialogflow-transactions-java by actions-on-google.

the class TransactionsApp method sendOrderUpdate.

private static void sendOrderUpdate(String orderId) throws IOException {
    // Setup service account credentials
    String serviceAccountKeyFileName = "service-account.json";
    // Setup service account credentials
    String serviceAccountFile = TransactionsApp.class.getClassLoader().getResource(serviceAccountKeyFileName).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 request = new HttpPatch("https://actions.googleapis.com/v3/orders/" + orderId);
    request.setHeader("Content-type", "application/json");
    request.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());
    request.setEntity(entity);
    // Make request
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse response = httpClient.execute(request);
    LOGGER.info(response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase());
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JsonObject(com.google.gson.JsonObject) Gson(com.google.gson.Gson) HttpResponse(org.apache.http.HttpResponse) FileInputStream(java.io.FileInputStream) HttpPatch(org.apache.http.client.methods.HttpPatch) OrderV3(com.google.api.services.actions_fulfillment.v2.model.OrderV3) StringEntity(org.apache.http.entity.StringEntity) AccessToken(com.google.auth.oauth2.AccessToken) OrderUpdateV3(com.google.api.services.actions_fulfillment.v2.model.OrderUpdateV3) HttpClient(org.apache.http.client.HttpClient) ServiceAccountCredentials(com.google.auth.oauth2.ServiceAccountCredentials) FieldMask(com.google.protobuf.FieldMask) PurchaseOrderExtension(com.google.api.services.actions_fulfillment.v2.model.PurchaseOrderExtension) JsonParser(com.google.gson.JsonParser)

Example 2 with OrderV3

use of com.google.api.services.actions_fulfillment.v2.model.OrderV3 in project dialogflow-transactions-java by actions-on-google.

the class TransactionsApp method transactionDecision.

@ForIntent("Transaction Decision")
public ActionResponse transactionDecision(ActionRequest request) {
    LOGGER.info("Checking Transaction Decision.");
    Map<String, Object> conversationData = request.getConversationData();
    String orderId = generateRandomOrderId();
    conversationData.put("UNIQUE_ORDER_ID", orderId);
    // Build the Order
    // Transaction Merchant
    MerchantV3 transactionMerchant = new MerchantV3().setId("http://www.example.com").setName("Example Merchant");
    // Line Items
    LineItemV3 firstItem = new LineItemV3().setId("memoirs_1").setName("My Memoirs").setPriceAttributes(Arrays.asList(new PriceAttribute().setType("REGULAR").setName("Item Price").setState("ACTUAL").setAmount(new MoneyV3().setCurrencyCode("USD").setAmountInMicros(3990000L)).setTaxIncluded(true), new PriceAttribute().setType("TOTAL").setName("Total Price").setState("ACTUAL").setAmount(new MoneyV3().setCurrencyCode("USD").setAmountInMicros(3990000L)).setTaxIncluded(true))).setNotes(Collections.singletonList("Note from the author.")).setPurchase(new PurchaseItemExtension().setQuantity(1));
    LineItemV3 secondItem = new LineItemV3().setId("memoirs_2").setName("Memoirs of a person").setPriceAttributes(Arrays.asList(new PriceAttribute().setType("REGULAR").setName("Item Price").setState("ACTUAL").setAmount(new MoneyV3().setCurrencyCode("USD").setAmountInMicros(5990000L)).setTaxIncluded(true), new PriceAttribute().setType("TOTAL").setName("Total Price").setState("ACTUAL").setAmount(new MoneyV3().setCurrencyCode("USD").setAmountInMicros(5990000L)).setTaxIncluded(true))).setNotes(Collections.singletonList("Special introduction by author.")).setPurchase(new PurchaseItemExtension().setQuantity(1));
    LineItemV3 thirdItem = new LineItemV3().setId("memoirs_3").setName("Their memoirs").setPriceAttributes(Arrays.asList(new PriceAttribute().setType("REGULAR").setName("Item Price").setState("ACTUAL").setAmount(new MoneyV3().setCurrencyCode("USD").setAmountInMicros(15750000L)).setTaxIncluded(true), new PriceAttribute().setType("TOTAL").setName("Total Price").setState("ACTUAL").setAmount(new MoneyV3().setCurrencyCode("USD").setAmountInMicros(15750000L)).setTaxIncluded(true))).setPurchase(new PurchaseItemExtension().setQuantity(1).setItemOptions(Collections.singletonList(new PurchaseItemExtensionItemOption().setId("memoirs_epilogue").setName("Special memoir epilogue").setPrices(Arrays.asList(new PriceAttribute().setType("REGULAR").setName("Item Price").setState("ACTUAL").setAmount(new MoneyV3().setCurrencyCode("USD").setAmountInMicros(3990000L)).setTaxIncluded(true), new PriceAttribute().setType("TOTAL").setName("Total Price").setState("ACTUAL").setAmount(new MoneyV3().setCurrencyCode("USD").setAmountInMicros(3990000L)).setTaxIncluded(true))))));
    LineItemV3 fourthItem = new LineItemV3().setId("memoirs_4").setName("Our memoirs").setPriceAttributes(Arrays.asList(new PriceAttribute().setType("REGULAR").setName("Item Price").setState("ACTUAL").setAmount(new MoneyV3().setCurrencyCode("USD").setAmountInMicros(6490000L)).setTaxIncluded(true), new PriceAttribute().setType("TOTAL").setName("Total Price").setState("ACTUAL").setAmount(new MoneyV3().setCurrencyCode("USD").setAmountInMicros(6490000L)).setTaxIncluded(true))).setNotes(Collections.singletonList("Special introduction by author.")).setPurchase(new PurchaseItemExtension().setQuantity(1));
    // Order Contents
    OrderContents contents = new OrderContents().setLineItems(Arrays.asList(firstItem, secondItem, thirdItem, fourthItem));
    // 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(32220000L)).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(2780000L)).setTaxIncluded(true);
    PriceAttribute totalPrice = new PriceAttribute().setType("TOTAL").setName("Total Price").setState("ESTIMATE").setAmount(new MoneyV3().setCurrencyCode("USD").setAmountInMicros(37000000L)).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 = "https://example.com";
    String orderNote = "The Memoir collection";
    Location location = GSON_BUILDER.create().fromJson((String) conversationData.get("location"), Location.class);
    // Purchase Order Extension
    PurchaseOrderExtension purchaseOrderExtension = new PurchaseOrderExtension().setStatus("CREATED").setUserVisibleStatusLabel("CREATED").setType("RETAIL").setReturnsInfo(new PurchaseReturnsInfo().setIsReturnable(false).setDaysToReturn(1).setPolicyUrl("https://example.com")).setFulfillmentInfo(new PurchaseFulfillmentInfo().setId("FULFILLMENT_SERVICE_ID").setFulfillmentType("DELIVERY").setExpectedFulfillmentTime(new TimeV3().setTimeIso8601("2025-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");
    String now = Instant.now().toString();
    OrderV3 order = new OrderV3().setCreateTime(now).setLastUpdateTime(now).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).setPurchase(purchaseOrderExtension);
    // Create presentation options
    PresentationOptionsV3 presentationOptions = new PresentationOptionsV3().setActionDisplayName("PLACE_ORDER");
    // Create order options
    OrderOptionsV3 orderOptions = new OrderOptionsV3().setUserInfoOptions(new UserInfoOptions().setUserInfoProperties(Collections.singletonList("EMAIL")));
    // Create payment parameters
    PaymentParameters paymentParameters = new PaymentParameters();
    if (request.getContext("google_payment") != null) {
        JSONObject merchantInfo = new JSONObject();
        merchantInfo.put("merchantName", "Example Merchant");
        JSONObject facilitationSpec = new JSONObject();
        facilitationSpec.put("apiVersion", 2);
        facilitationSpec.put("apiVersionMinor", 0);
        facilitationSpec.put("merchantInfo", merchantInfo);
        JSONObject allowedPaymentMethod = new JSONObject();
        allowedPaymentMethod.put("type", "CARD");
        JSONArray allowedAuthMethods = new JSONArray();
        allowedAuthMethods.addAll(Arrays.asList("PAN_ONLY", "CRYPTOGRAM_3DS"));
        JSONArray allowedCardNetworks = new JSONArray();
        allowedCardNetworks.addAll(Arrays.asList("AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"));
        JSONObject allowedPaymentMethodParameters = new JSONObject();
        allowedPaymentMethodParameters.put("allowedAuthMethods", allowedAuthMethods);
        allowedPaymentMethodParameters.put("allowedCardNetworks", allowedCardNetworks);
        allowedPaymentMethod.put("parameters", allowedPaymentMethodParameters);
        JSONObject tokenizationSpecificationParameters = new JSONObject();
        tokenizationSpecificationParameters.put("gateway", "example");
        tokenizationSpecificationParameters.put("gatewayMerchantId", "exampleGatewayMerchantId");
        JSONObject tokenizationSpecification = new JSONObject();
        tokenizationSpecification.put("type", "PAYMENT_GATEWAY");
        tokenizationSpecification.put("parameters", tokenizationSpecificationParameters);
        allowedPaymentMethod.put("tokenizationSpecification", tokenizationSpecification);
        JSONArray allowedPaymentMethods = new JSONArray();
        allowedPaymentMethods.add(allowedPaymentMethod);
        facilitationSpec.put("allowedPaymentMethods", allowedPaymentMethods);
        JSONObject transactionInfo = new JSONObject();
        transactionInfo.put("totalPriceStatus", "FINAL");
        transactionInfo.put("totalPrice", "37.00");
        transactionInfo.put("currencyCode", "USD");
        facilitationSpec.put("transactionInfo", transactionInfo);
        GooglePaymentOption googlePaymentOption = new GooglePaymentOption().setFacilitationSpec(facilitationSpec.toJSONString());
        paymentParameters.setGooglePaymentOption(googlePaymentOption);
    } else {
        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();
}
Also used : PurchaseReturnsInfo(com.google.api.services.actions_fulfillment.v2.model.PurchaseReturnsInfo) OpenUrlAction(com.google.api.services.actions_fulfillment.v2.model.OpenUrlAction) Action(com.google.api.services.actions_fulfillment.v2.model.Action) MerchantPaymentOption(com.google.api.services.actions_fulfillment.v2.model.MerchantPaymentOption) UserInfo(com.google.api.services.actions_fulfillment.v2.model.UserInfo) PresentationOptionsV3(com.google.api.services.actions_fulfillment.v2.model.PresentationOptionsV3) OrderV3(com.google.api.services.actions_fulfillment.v2.model.OrderV3) GooglePaymentOption(com.google.api.services.actions_fulfillment.v2.model.GooglePaymentOption) PaymentMethodDisplayInfo(com.google.api.services.actions_fulfillment.v2.model.PaymentMethodDisplayInfo) PaymentMethodStatus(com.google.api.services.actions_fulfillment.v2.model.PaymentMethodStatus) UserInfoOptions(com.google.api.services.actions_fulfillment.v2.model.UserInfoOptions) PriceAttribute(com.google.api.services.actions_fulfillment.v2.model.PriceAttribute) MoneyV3(com.google.api.services.actions_fulfillment.v2.model.MoneyV3) TimeV3(com.google.api.services.actions_fulfillment.v2.model.TimeV3) OpenUrlAction(com.google.api.services.actions_fulfillment.v2.model.OpenUrlAction) OrderOptionsV3(com.google.api.services.actions_fulfillment.v2.model.OrderOptionsV3) PurchaseFulfillmentInfo(com.google.api.services.actions_fulfillment.v2.model.PurchaseFulfillmentInfo) JSONArray(org.json.simple.JSONArray) MerchantV3(com.google.api.services.actions_fulfillment.v2.model.MerchantV3) MerchantPaymentMethod(com.google.api.services.actions_fulfillment.v2.model.MerchantPaymentMethod) JSONObject(org.json.simple.JSONObject) OrderContents(com.google.api.services.actions_fulfillment.v2.model.OrderContents) TransactionDecision(com.google.actions.api.response.helperintent.transactions.v3.TransactionDecision) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) PurchaseItemExtension(com.google.api.services.actions_fulfillment.v2.model.PurchaseItemExtension) PurchaseItemExtensionItemOption(com.google.api.services.actions_fulfillment.v2.model.PurchaseItemExtensionItemOption) LineItemV3(com.google.api.services.actions_fulfillment.v2.model.LineItemV3) Location(com.google.api.services.actions_fulfillment.v2.model.Location) PurchaseOrderExtension(com.google.api.services.actions_fulfillment.v2.model.PurchaseOrderExtension) PaymentParameters(com.google.api.services.actions_fulfillment.v2.model.PaymentParameters) ForIntent(com.google.actions.api.ForIntent)

Example 3 with OrderV3

use of com.google.api.services.actions_fulfillment.v2.model.OrderV3 in project dialogflow-transactions-java by actions-on-google.

the class TransactionsApp method transactionDecisionComplete.

// Check result of asking to perform transaction / place order
@ForIntent("Transaction Decision Complete")
public ActionResponse transactionDecisionComplete(ActionRequest request) {
    ResourceBundle rb = ResourceBundle.getBundle("resources", request.getLocale());
    // 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"));
        order.setLastUpdateTime(Instant.now().toString());
        // 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("UNIQUE_ORDER_ID");
        String response = MessageFormat.format(rb.getString("transaction_decision_result_success"), orderId);
        responseBuilder.add(response).add(new StructuredResponse().setOrderUpdateV3(orderUpdate));
    } else {
        responseBuilder.add(rb.getString("transaction_failed"));
    }
    return responseBuilder.endConversation().build();
}
Also used : StructuredResponse(com.google.api.services.actions_fulfillment.v2.model.StructuredResponse) Argument(com.google.api.services.actions_fulfillment.v2.model.Argument) OrderUpdateV3(com.google.api.services.actions_fulfillment.v2.model.OrderUpdateV3) ResourceBundle(java.util.ResourceBundle) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) ResponseBuilder(com.google.actions.api.response.ResponseBuilder) OrderV3(com.google.api.services.actions_fulfillment.v2.model.OrderV3) PurchaseOrderExtension(com.google.api.services.actions_fulfillment.v2.model.PurchaseOrderExtension) ForIntent(com.google.actions.api.ForIntent)

Aggregations

OrderV3 (com.google.api.services.actions_fulfillment.v2.model.OrderV3)3 PurchaseOrderExtension (com.google.api.services.actions_fulfillment.v2.model.PurchaseOrderExtension)3 JsonObject (com.google.gson.JsonObject)3 ForIntent (com.google.actions.api.ForIntent)2 OrderUpdateV3 (com.google.api.services.actions_fulfillment.v2.model.OrderUpdateV3)2 JSONObject (org.json.simple.JSONObject)2 ResponseBuilder (com.google.actions.api.response.ResponseBuilder)1 TransactionDecision (com.google.actions.api.response.helperintent.transactions.v3.TransactionDecision)1 Action (com.google.api.services.actions_fulfillment.v2.model.Action)1 Argument (com.google.api.services.actions_fulfillment.v2.model.Argument)1 GooglePaymentOption (com.google.api.services.actions_fulfillment.v2.model.GooglePaymentOption)1 LineItemV3 (com.google.api.services.actions_fulfillment.v2.model.LineItemV3)1 Location (com.google.api.services.actions_fulfillment.v2.model.Location)1 MerchantPaymentMethod (com.google.api.services.actions_fulfillment.v2.model.MerchantPaymentMethod)1 MerchantPaymentOption (com.google.api.services.actions_fulfillment.v2.model.MerchantPaymentOption)1 MerchantV3 (com.google.api.services.actions_fulfillment.v2.model.MerchantV3)1 MoneyV3 (com.google.api.services.actions_fulfillment.v2.model.MoneyV3)1 OpenUrlAction (com.google.api.services.actions_fulfillment.v2.model.OpenUrlAction)1 OrderContents (com.google.api.services.actions_fulfillment.v2.model.OrderContents)1 OrderOptionsV3 (com.google.api.services.actions_fulfillment.v2.model.OrderOptionsV3)1