### Development command for vtex.js
Source: https://github.com/vtex/vtex.js/blob/master/docs/README.en.md
This command is used to set up vtex.js for development after cloning the repository and installing dependencies.
```shell
sudo grunt
```
--------------------------------
### Get Order Form Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Example demonstrating how to use the getOrderForm method to retrieve the current order form data.
```javascript
vtexjs.checkout.getOrderForm().done(function(orderForm) {
console.log(orderForm)
})
```
--------------------------------
### Include all vtex.js modules
Source: https://github.com/vtex/vtex.js/blob/master/docs/README.en.md
This snippet shows how to include all modules from vtex.js in your store by referencing the minified file.
```html
```
--------------------------------
### Get Order Form Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Example of how to use the getOrderForm method to retrieve the current order form.
```javascript
vtexjs.checkout.getOrderForm()
.done(function(orderForm) {
console.log(orderForm);
});
```
--------------------------------
### Get Profile by Email
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Example of logging in partially using email, after getting the order form.
```javascript
vtexjs.checkout.getOrderForm()
.then(function(orderForm) {
var email = "exemplo@vtex.com.br";
return vtexjs.checkout.getProfileByEmail(email);
})
.done(function(orderForm) {
console.log(orderForm);
});
```
--------------------------------
### getProductWithVariations Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/catalog/README.en.md
Example of how to use getProductWithVariations to retrieve product details with variations.
```html
vtexjs.catalog.getProductWithVariations(1000).done(function(product){
console.log(product);
});
```
--------------------------------
### getOrders Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Example of how to retrieve orders within an order group.
```javascript
var orderGroupId = "v50123456abc"
vtexjs.checkout.getOrders(orderGroupId).then(function(orders) {
console.log("Number of orders in this group: ", orders.length)
console.log(orders)
})
```
--------------------------------
### Get Address Information
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Example of getting address information using postal code and country.
```javascript
// O `postalCode` deve ser o CEP do cliente, no caso do Brasil
var postalCode = '22250-040';
// Desse jeito também funciona
// var postalCode = '22250040';
// O `country` deve ser a sigla de 3 letras do país
var country = 'BRA';
var address = {
postalCode: postalCode,
country: country
};
vtexjs.checkout.getAddressInformation(address)
.done(function(result) {
console.log(result);
});
```
--------------------------------
### changeItemsOrdination Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Example of how to change the order of items based on criteria.
```javascript
var criteria = "add_time"
var asceding = "false"
vtexjs.checkout
.changeItemsOrdination(criteria, ascending)
.then(function(orderForm) {
console.log("Sorting criteria: ", orderForm.itemsOrdination)
console.log("Array of items sorted by criteria: ", orderForm.items)
})
```
--------------------------------
### getLogoutURL Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Example of how to get a logout URL that keeps the cart.
```javascript
$(".logout").on("click", function() {
vtexjs.checkout.getOrderForm().then(function(orderForm) {
var logoutURL = vtexjs.checkout.getLogoutURL()
window.location = logoutURL
})
})
```
--------------------------------
### Include individual vtex.js modules
Source: https://github.com/vtex/vtex.js/blob/master/docs/README.en.md
This snippet demonstrates how to include individual modules of vtex.js, such as extended-ajax, catalog, and checkout.
```html
```
--------------------------------
### sendLocale Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Example of how to change the user's locale.
```javascript
vtexjs.checkout
.getOrderForm()
.then(function(orderForm) {
return vtexjs.checkout.sendLocale("en-US")
})
.then(function() {
alert("Now you're an American ;)")
})
```
--------------------------------
### Order Form Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.md
An example of the complete order form object, showing gift cards, available accounts, installment options, payment systems, and payments.
```json
{
"giftCards": [
{
"redemptionCode": "HYUO-TEZZ-QFFT-HTFR",
"value": 500,
"balance": 500,
"name": null,
"id": "-1390324156495k195pmab4rall3di",
"inUse": true,
"isSpecialCard": false
}, {
"redemptionCode": "MTHU-WNTD-VXJW-TIDC",
"value": 0,
"balance": 700000,
"name": "loyalty-program",
"id": "122",
"inUse": false,
"isSpecialCard": true
}
],
"availableAccounts": [
{
"accountId": "71F2775D46BF44B1BF217F828F4E6131",
"paymentSystem": "2",
"paymentSystemName": "Visa",
"cardNumber": "************1111",
"availableAddresses": ["-1363804954758", "-1366200971560"]
}
],
"installmentOptions": [
{
"paymentSystem": "2",
"value": 16175,
"installments": [
{
"count": 1,
"hasInterestRate": false,
"interestRate": 0,
"value": 16175,
"total": 16175
}, {
"count": 2,
"hasInterestRate": false,
"interestRate": 132,
"value": 4178,
"total": 16712
}
]
}
],
"paymentSystems": [
{
"id": 2,
"name": "Visa",
"groupName": "creditCardPaymentGroup",
"validator": {
"regex": "^4",
"mask": "9999 9999 9999 9999",
"cardCodeRegex": "[^0-9]",
"cardCodeMask": "999",
"weights": [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
},
"stringId": null,
"template": "creditCardPaymentGroup-template",
"requiresDocument": false,
"selected": false,
"isCustom": false,
"description": null
}
],
"payments": [
{
"accountId": null,
"bin: null,
"installments": 2,
"paymentSystem": "12",
"referenceValue": 16175,
"value": 16175
}
]
}
```
--------------------------------
### addBundleItemAttachment Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Example of how to add an attachment to a bundle item.
```javascript
var itemIndex = 0
var bundleItemId = 5
var attachmentName = "message"
var content = {
text: "Congratulations!",
}
vtexjs.checkout
.getOrderForm()
.then(function() {
return vtexjs.checkout.addBundleItemAttachment(
itemIndex,
bundleItemId,
attachmentName,
content
)
})
.done(function(orderForm) {
// Attachment added to the item!
console.log(orderForm)
})
```
--------------------------------
### addItemAttachment Example 1
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Example demonstrating how to add a 'Customization' attachment to an item, emphasizing the need to include all properties in the content object.
```javascript
var itemIndex = 0
var attachmentName = Customization
// User entered the value of the Name field. The object must also pass the Number field.
var content = { Name: Robert, Number: "" }
vtexjs.checkout.addItemAttachment(
itemIndex,
attachmentName,
content,
null,
false
)
```
--------------------------------
### Replace SKU Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Example of how to use the replaceSKU method to update items in the checkout.
```javascript
var items = [
{
seller: "1",
quantity: 0,
index: 0,
},
{
seller: "1",
quantity: 1,
id: "2",
},
]
vtexjs.checkout.replaceSKU(items).then(function(orderForm) {
console.log("New items: ", orderForm.items)
})
```
--------------------------------
### Example of adding an item attachment (with done callback)
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
A complete example of adding an item attachment, including the necessary preceding getOrderForm call and a .done callback to handle the response.
```javascript
// Chamado em algum momento antes
// vtexjs.checkout.getOrderForm()
var itemIndex = 0;
var attachmentName = 'Customização';
var content = {
Nome: 'Ronaldo',
Numero: '10'
};
vtexjs.checkout.addItemAttachment(itemIndex, attachmentName, content)
.done(function(orderForm) {
// Anexo incluído ao item!
console.log(orderForm);
});
```
--------------------------------
### Order Form Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.en.md
This is a comprehensive example of the order form structure returned by the VTEX API, including details on gift cards, available payment accounts, installment options, payment systems, and more.
```json
{
"giftCards": [
{
"redemptionCode": "HYUO-TEZZ-QFFT-HTFR",
"value": 500,
"balance": 500,
"name": null,
"id": "-1390324156495k195pmab4rall3di",
"inUse": true,
"isSpecialCard": false
}, {
"redemptionCode": "MTHU-WNTD-VXJW-TIDC",
"value": 0,
"balance": 700000,
"name": "loyalty-program",
"id": "122",
"inUse": false,
"isSpecialCard": true
}
],
"availableAccounts": [
{
"accountId": "71F2775D46BF44B1BF217F828F4E6131",
"paymentSystem": "2",
"paymentSystemName": "Visa",
"cardNumber": "************1111",
"availableAddresses": ["-1363804954758", "-1366200971560"]
}
],
"installmentOptions": [
{
"paymentSystem": "2",
"value": 16175,
"installments": [
{
"count": 1,
"hasInterestRate": false,
"interestRate": 0,
"value": 16175,
"total": 16175
}, {
"count": 2,
"hasInterestRate": false,
"interestRate": 132,
"value": 4178,
"total": 16712
}
]
}
],
"paymentSystems": [
{
"id": 2,
"name": "Visa",
"groupName": "creditCardPaymentGroup",
"validator": {
"regex": "^4",
"mask": "9999 9999 9999 9999",
"cardCodeRegex": "[^0-9]",
"cardCodeMask": "999",
"weights": [2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
},
"stringId": null,
"template": "creditCardPaymentGroup-template",
"requiresDocument": false,
"selected": false,
"isCustom": false,
"description": null
}
],
"payments": [
{
"accountId": null,
"bin": null,
"installments": 2,
"paymentSystem": "12",
"referenceValue": 16175,
"value": 16175
}
]
}
```
--------------------------------
### addOffering Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Illustrates how to add an offering (e.g., extended warranty) to a specific item in the order form.
```javascript
// Considerando a seguinte estrutura (resumida) de items:
var items = [{
"id": "2004075",
"productId": "4741",
"name": "Ração",
"skuName": "Ração 3 kg",
"quantity": 3,
"seller": "1",
"bundleItems": [],
"offerings": [{
"id": "1033",
"name": "A Oferta Magnifica",
"price": 100,
"type": "idk"
}],
"availability": "available"
}];
var offeringId = items[0].offerings[0].id;
var itemIndex = 0;
vtexjs.checkout.getOrderForm()
.then(function() {
return vtexjs.checkout.addOffering(offeringId, itemIndex);
})
.done(function(orderForm) {
// Oferta adicionada!
console.log(orderForm);
});
```
--------------------------------
### simulateShipping Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Demonstrates how to simulate shipping for items in an order, providing shipping options, delivery dates, and prices.
```javascript
// `logisticsInfo` must be an array of objects logisticsInfo and contain at least one selectedAddresses
var shippingData = [
{
logisticsInfo: logisticsInfoList,
selectedAddresses: selectedAddressesList,
},
]
// `orderFormId` must be an Id of the session's orderForm
var orderFormId = "9f879d435f8b402cb133167d6058c14f"
// `country` must be the 3-letter country abbreviation
var country = "BRA"
vtexjs.checkout
.simulateShipping(items, postalCode, country)
.done(function(result) {
/* `result.logisticsInfo` is an array of objects.
Each object corresponds to the logistics information (shipping) for each item, in the order in which the items were sent.
For example, in `result.logisticsInfo[0].slas` there will be the different carriers options (with deadline and price) for the first item.
For further details, check the orderForm documentation.
*/
})
```
--------------------------------
### simulateShipping Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Simulates the shipping of items to a given address.
```js
// `Items` must be an array of objects containing at least the information below
var items = [
{
id: 5987, // item sku
quantity: 1,
seller: "1",
},
]
// In the case of Brazil, `postalCode` must be the client’s CEP
var postalCode = "22250-040"
// This also works
// var postalCode = '22250040';
// `country` must be the 3-letter country abbreviation
var country = "BRA"
vtexjs.checkout
.simulateShipping(items, postalCode, country)
.done(function(result) {
/* `result.logisticsInfo` is an array of objects.
Each object corresponds to the logistics information (shipping) for each item, in the order in which the items were sent.
For example, in `result.logisticsInfo[0].slas` there will be the different carriers options (with deadline and price) for the first item.
For further details, check the orderForm documentation.
*/
})
```
--------------------------------
### Marketing Data Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.en.md
An example of the 'marketingData' field, which is currently marked as PENDING.
```json
null
```
--------------------------------
### getCurrentProductWithVariations Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/catalog/README.en.md
Example of how to use getCurrentProductWithVariations to retrieve product details for the current product page.
```html
vtexjs.catalog.getCurrentProductWithVariations().done(function(product){
console.log(product);
});
```
--------------------------------
### Finish Transaction Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Example of how to use the finishTransaction method to complete the checkout process.
```javascript
var orderGroupId = "959290226406"
vtexjs.checkout.finishTransaction(orderGroupId).then(function(response) {
console.log("Success", response.status)
})
```
--------------------------------
### cloneItem Example (With Options)
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Creates a new item based on item with index 0 with quantity 2 and an attachment already configured.
```js
var itemIndex = 0
var newItemsOptions = [
{
itemAttachments: [
{
name: "Customization",
content: {
Name: "Robert",
},
},
],
quantity: 2,
},
]
vtexjs.checkout.cloneItem(itemIndex, newItemsOptions).done(function(orderForm) {
console.log(orderForm)
})
```
--------------------------------
### getProfileByEmail Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Illustrates how to perform a partial user login using their email address.
```javascript
vtexjs.checkout
.getOrderForm()
.then(function(orderForm) {
var email = "example@vtex.com"
return vtexjs.checkout.getProfileByEmail(email)
})
.done(function(orderForm) {
console.log(orderForm)
})
```
--------------------------------
### shippingData Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.en.md
An example of the shippingData object, illustrating address, availableAddresses, and logisticsInfo.
```json
{
"attachmentId": "shippingData",
"address": {
"addressType": "residential",
"receiverName": "Gui***rme",
"addressId": "-1368194386810",
"postalCode": "******000",
"city": "Rio ** *******",
"state": "RJ",
"country": "BRA",
"street": "Rua *** *****nte",
"number": "***",
"neighborhood": "Bot*****",
"complement": "*** ** *",
"reference": null
},
"availableAddresses": [
{
"addressType": "residential",
"receiverName": "Gui***rme",
"addressId": "-1368194386810",
"postalCode": "******000",
"city": "Rio ** *******",
"state": "RJ",
"country": "BRA",
"street": "Rua *** *****nte",
"number": "***",
"neighborhood": "Bot*****",
"complement": "*** ** *",
"reference": null
}
],
"logisticsInfo": [
{
"itemIndex": 0,
"selectedSla": ".Carrier",
"slas": [
{
"id": ".Carrier",
"name": ".Carrier",
"deliveryIds": [
{
"courierId": "67",
"warehouseId": "1_1",
"dockId": "1_1_1",
"courierName": "Carrier",
"quantity": 1
}
],
"shippingEstimate": "3d",
"shippingEstimateDate": null,
"lockTTL": null,
"availableDeliveryWindows": [],
"deliveryWindow": null,
"price": 956,
"tax": 0
}, {
"id": "Agendada",
"name": "Scheduled",
"deliveryIds": [
{
"courierId": "FA02F72F-FEBD-41A0-AF70-83A77E8C77A0",
"warehouseId": "1_1",
"dockId": "1_1_1",
"courierName": "Scheduled delivery",
"quantity": 1
}
],
"shippingEstimate": "90d",
"shippingEstimateDate": null,
"lockTTL": null,
"availableDeliveryWindows": [
{
"startDateUtc": "2014-04-21T09:00:00+00:00",
"endDateUtc": "2014-04-21T12:00:00+00:00",
"price": 1000,
"tax": 0
}, {
"startDateUtc": "2014-04-21T13:00:00+00:00",
"endDateUtc": "2014-04-21T17:00:00+00:00",
"price": 1000,
"tax": 0
}
],
"deliveryWindow": null,
"price": 1220,
"tax": 0
}
]
}
]
}
```
--------------------------------
### clearMessages Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Example of how to clear messages from the order form.
```javascript
vtexjs.checkout
.getOrderForm()
.then(function(orderForm) {
return vtexjs.checkout.clearMessages()
})
.then(function() {
alert("Messages cleaned.")
})
```
--------------------------------
### addDiscountCoupon Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Shows how to add a discount coupon to the order form.
```javascript
vtexjs.checkout.getOrderForm()
.then(function(orderForm) {
var code = 'ABC123';
return vtexjs.checkout.addDiscountCoupon(code);
}).then(function(orderForm) {
alert('Cupom adicionado.');
console.log(orderForm);
console.log(orderForm.paymentData);
console.log(orderForm.totalizers);
});
```
--------------------------------
### addItemAttachment Example 2
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
A more complete example of adding an attachment, including a promise-based callback to handle the orderForm after the attachment is added.
```javascript
// Called sometime before
// vtexjs.checkout.getOrderForm()
var itemIndex = 0
var attachmentName = "Customization"
var content = {
Name: Robert,
Numero: "10",
}
vtexjs.checkout
.addItemAttachment(itemIndex, attachmentName, content)
.done(function(orderForm) {
// Attachment added to the item!
console.log(orderForm)
})
```
--------------------------------
### Simulate Shipping (Basic)
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Example of simulating shipping with items, postal code, and country.
```javascript
// O `items` deve ser um array de objetos que contenham, no mínimo, as informações abaixo
var items = [{
id: 5987, // sku do item
quantity: 1,
seller: '1'
}];
// O `postalCode` deve ser o CEP do cliente, no caso do Brasil
var postalCode = '22250-040';
// Desse jeito também funciona
// var postalCode = '22250040';
// O `country` deve ser a sigla de 3 letras do país
var country = 'BRA';
vtexjs.checkout.simulateShipping(items, postalCode, country)
.done(function(result) {
/* `result.logisticsInfo` é um array de objetos.
Cada objeto corresponde às informações de logística (frete) para cada item,
na ordem em que os items foram enviados.
Por exemplo, em `result.logisticsInfo[0].slas` estarão as diferentes opções
de transportadora (com prazo e preço) para o primeiro item.
Para maiores detalhes, consulte a documentação do orderForm.
*/
});
```
--------------------------------
### Items Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.en.md
This example shows the structure of an item object within the 'items' array. It includes details like product ID, name, price, quantity, and additional information.
```json
[
{
"id": "2004075",
"productId": "4741",
"name": "Ração Club Performance Junior - Royal Canin Ração Club Performance Junior Royal Canin - Promocional 15 kg + 3 kg",
"skuName": "Ração Club Performance Junior Royal Canin - Promocional 15 kg + 3 kg",
"tax": 0,
"price": 10490,
"listPrice": 10490,
"sellingPrice": 10490,
"isGift": false,
"additionalInfo": {
"brandName": "Royal Canin Cães",
"brandId": "37",
"offeringInfo": null
},
"preSaleDate": null,
"productCategoryIds": "/343/515/517/",
"defaultPicker": null,
"handlerSequence": 0,
"handling": false,
"quantity": 3,
"seller": "1",
"imageUrl": "/arquivos/ids/188329-71-71/racao-club-performance-junior.jpg",
"detailUrl": "/racao-royal-canin-club-performance-junior/p",
"components": [],
"bundleItems": [],
"offerings": [{
"id": "1033",
"name": "The Magnificent Offer",
"price": 100,
"type": "idk"
}],
"priceTags": [],
"availability": "available",
"measurementUnit": "un",
"unitMultiplier": 1
}
]
```
--------------------------------
### getAddressInformation Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Shows how to retrieve complete address details by providing a postal code and country.
```javascript
// In the case of Brazil, `postalCode` must be the client’s CEP
var postalCode = "22250-040"
// This also works
// var postalCode = '22250040';
// `country` must be the 3-letter country abbreviation
var country = "BRA"
var address = {
postalCode: postalCode,
country: country,
}
vtexjs.checkout.getAddressInformation(address).done(function(result) {
console.log(result)
})
```
--------------------------------
### Totalizers Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.en.md
This example shows the structure of a totalizer object within the 'totalizers' array. Each totalizer has an ID, a name, and a value.
```json
[
{
"id": "Items"
"name": "Items Total"
"value": 35620
}, {
"id": "Shipping"
"name": "Shipping Total"
"value": 399
}
]
```
--------------------------------
### removeOffering Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Demonstrates how to remove an offering from a specific item in the order form.
```javascript
vtexjs.checkout.getOrderForm()
.then(function(orderForm) {
return vtexjs.checkout.removeOffering(offeringId, itemIndex);
});
```
--------------------------------
### calculateShipping Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Records the address in the user's shippingData and calculates shipping.
```js
vtexjs.checkout.getOrderForm()
.then(function(orderForm) {
var postalCode = '22250-040'; // may also be without the hyphen
var country = 'BRA';
var address = {
"postalCode": postalCode,
"country": country
};
return vtexjs.checkout.calculateShipping(address)
})
.done(function(orderForm) {
alert('Shipping calculated.');
console.log(orderForm.shippingData);
console.log(orderForm.totalizers);
});
```
--------------------------------
### Sellers Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.en.md
An example of the 'sellers' array, which contains simple information about sellers operating in the store's marketplace.
```json
[
{
"id": "1",
"name": "sellername",
"logo": "http://portal.vtexcommerce.com.br/arquivos/logo.jpg"
}
]
```
--------------------------------
### Seller Information Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.md
An example of a seller object, containing basic information about a marketplace seller.
```json
[
{
"id": "1",
"name": "meuamigopet",
"logo": "http://portal.vtexcommerce.com.br/arquivos/logo.jpg"
}
]
```
--------------------------------
### OrderForm Structure Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.en.md
This is an example of the OrderForm structure, showing its main properties. Properties with '…' are explained in detail in the 'Sections' part of the documentation.
```json
{
"canEditData": true,
"clientPreferencesData": …,
"clientProfileData": …,
"giftRegistryData": …,
"items": …,
"loggedIn": false,
"marketingData": …,
"messages": …,
"orderFormId": "0123456789abcdeffedcba9876543210",
"paymentData": …,
"salesChannel": "1",
"sellers": …,
"shippingData": …,
"storePreferencesData": …,
"totalizers": …,
"userProfileId": null,
"userType": null,
"value": 20980
}
```
--------------------------------
### Client Preferences Data Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.en.md
An example of the 'clientPreferencesData' object, containing client preferences like locale and newsletter opt-in status.
```json
{
"attachmentId": "clientPreferencesData",
"locale": "pt-BR",
"optinNewsLetter": true
}
```
--------------------------------
### Store Preferences Data Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.en.md
An example of the 'storePreferencesData' object, containing store preferences such as country code, currency information, and time zone.
```json
{
"countryCode": "BRA",
"checkToSavePersonDataByDefault": true,
"templateOptions": {
"toggleCorporate": false
},
"timeZone": "E. South America Standard Time",
"currencyCode": "BRL",
"currencyLocale": 0,
"currencySymbol": "R$",
"currencyFormatInfo": {
"currencyDecimalDigits": 2,
"currencyDecimalSeparator": ",",
"currencyGroupSeparator": ".",
"currencyGroupSize": 3,
"startsWithCurrencySymbol": true
}
}
```
--------------------------------
### Messages Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.en.md
An example of the 'messages' array, which contains messages related to the API call, such as errors or informational notes.
```json
[
{
"code": null,
"status": "error",
"text": "The gift card with code AAAA-BBBB-CCCC-DDDD was not found."
}
]
```
--------------------------------
### Simulate Shipping (Advanced)
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Example of simulating shipping with shipping data, order form ID, and country.
```javascript
// O `logisticsInfo` deve ser um array de objetos logisticsInfo, e o selectedAddresses deve conter pelo menos um address
var shippingData = [{
logisticsInfo: logisticsInfoList,
selectedAddresses: selectedAddressesList
}];
// O `orderFormId` deve ser o Id do orderForm da sessão
var orderFormId = '9f879d435f8b402cb133167d6058c14f';
// O `country` deve ser a sigla de 3 letras do país
var country = 'BRA';
vtexjs.checkout.simulateShipping(shippingData, orderFormId, country)
.done(function(result) {
/* `result.logisticsInfo` é um array de objetos.
Cada objeto corresponde às informações de logística (frete) para cada item,
na ordem em que os items foram enviados.
Por exemplo, em `result.logisticsInfo[0].slas` estarão as diferentes opções
de transportadora (com prazo e preço) para o primeiro item.
Para maiores detalhes, consulte a documentação do orderForm.
*/
});
```
--------------------------------
### API Message Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.md
An example of a message array returned from an API call, indicating the status and text of the message.
```json
[
{
"code": null,
"status": "error",
"text": "O vale compra de código AAAA-BBBB-CCCC-DDDD não foi encontrado no sistema"
}
]
```
--------------------------------
### ClientProfileData Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.en.md
This example illustrates the structure of the 'clientProfileData' object, which contains information about the customer. Some fields may be null or censored if the email is not confirmed or provided.
```json
{
"attachmentId": "clientProfileData",
"email": "gadr90@gmail.com",
"firstName": "Gui******",
"lastName": "Rod******",
"document": "*1*3*8*7*0*",
"documentType": "cpf",
"phone": "******2121",
"corporateName": null,
"tradeName": null,
"corporateDocument": null,
"stateInscription": null,
"corporatePhone": null,
"isCorporate": false
}
```
--------------------------------
### Items Section Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.md
An example of the 'items' section, which is an array of 'item' objects, each containing details about a product in the customer's cart.
```json
[
{
"id": "2004075",
"productId": "4741",
"name": "Ração Club Performance Junior - Royal Canin Ração Club Performance Junior Royal Canin - Promocional 15 kg + 3 kg",
"skuName": "Ração Club Performance Junior Royal Canin - Promocional 15 kg + 3 kg",
"tax": 0,
"price": 10490,
"listPrice": 10490,
"sellingPrice": 10490,
"isGift": false,
"additionalInfo": {
"brandName": "Royal Canin Cães",
"brandId": "37",
"offeringInfo": null
},
"preSaleDate": null,
"productCategoryIds": "/343/515/517/",
"defaultPicker": null,
"handlerSequence": 0,
"handling": false,
"quantity": 3,
"seller": "1",
"imageUrl": "/arquivos/ids/188329-71-71/racao-club-performance-junior.jpg",
"detailUrl": "/racao-royal-canin-club-performance-junior/p",
"components": [],
"bundleItems": [],
"offerings": [{
"id": "1033",
"name": "A Oferta Magnifica",
"price": 100,
"type": "idk"
}],
"priceTags": [],
"availability": "available",
"measurementUnit": "un",
"unitMultiplier": 1
}
]
```
--------------------------------
### Totalizers Section Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.md
An example of the 'totalizers' section, which is an array of 'totalizer' objects, each with a unique 'id', a descriptive 'name', and a 'value'.
```json
[
{
"id": "Items"
"name": "Total dos Itens"
"value": 35620
}, {
"id": "Shipping"
"name": "Total do Frete"
"value": 399
}
]
```
--------------------------------
### removeDiscountCoupon Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Demonstrates how to remove a discount coupon from the order form.
```javascript
vtexjs.checkout.getOrderForm()
.then(function(orderForm) {
return vtexjs.checkout.removeDiscountCoupon();
}).then(function(orderForm) {
alert('Cupom removido.');
console.log(orderForm);
console.log(orderForm.paymentData);
console.log(orderForm.totalizers);
});
```
--------------------------------
### cloneItem Example (Basic)
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Creates a new item in the cart based on the item with index 0.
```js
var itemIndex = 0;
vtexjs.checkout.cloneItem(itemIndex)
.done(function(orderForm) {
console.log(orderForm);
});
```
--------------------------------
### removeGiftRegistry Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Shows how to remove a gift registry from the order form.
```javascript
vtexjs.checkout.getOrderForm()
.then(function(orderForm) {
return vtexjs.checkout.removeGiftRegistry();
})
.then(function(orderForm) {
alert('Lista de presente removida.');
console.log(orderForm);
});
```
--------------------------------
### removeAllItems Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Removes all items from the orderForm.
```html
vtexjs.checkout.removeAllItems()
.done(function(orderForm) {
alert('Empty cart.');
console.log(orderForm);
});
```
--------------------------------
### Add Offering
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Adds an offer (e.g., extended warranty, installation service) to an item in the order form. The offer will appear in the item's 'bundleItems' field. Requires offeringId and itemIndex. It's recommended to call getOrderForm first.
```javascript
// Considering the following (summarized) structure of items:
var items = [
{
id: "2004075",
productId: "4741",
name: "Dog food",
skuName: "3 kg Dog Food",
quantity: 3,
seller: "1",
bundleItems: [],
offerings: [
{
id: "1033",
name: "The Magnificent Offer",
price: 100,
type: "idk",
},
],
availability: "available",
},
]
var offeringId = items[0].offerings[0].id
var itemIndex = 0
vtexjs.checkout
.getOrderForm()
.then(function() {
return vtexjs.checkout.addOffering(offeringId, itemIndex)
})
.done(function(orderForm) {
// Offer added!
console.log(orderForm)
})
```
--------------------------------
### Example of removing an offering from an item
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Demonstrates how to remove a specific offering from an item in the order form using vtexjs.checkout.removeOffering.
```javascript
// Considerando a seguinte estrutura (resumida) de items:
var items = [{
"id": "2004075",
"productId": "4741",
"name": "Ração",
"skuName": "Ração 3 kg",
"quantity": 3,
"seller": "1",
"bundleItems": [{
"id": "1033",
"name": "A Oferta Magnifica",
"price": 100,
"type": "idk"
}],
"offerings": [{
"id": "1033",
"name": "A Oferta Magnifica",
"price": 100,
"type": "idk"
}],
"availability": "available"
}];
var offeringId = items[0].bundleItems[0].id;
var itemIndex = 0;
vtexjs.checkout.getOrderForm()
.then(function() {
return vtexjs.checkout.removeOffering(offeringId, itemIndex);
}).done(function(orderForm) {
// Oferta removida!
console.log(orderForm);
});
```
--------------------------------
### removeAccountId Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Demonstrates how to remove a payment account from the order form using its account ID.
```javascript
vtexjs.checkout.getOrderForm()
.then(function(orderForm) {
var accountId = orderForm.paymentData.availableAccounts[0].accountId;
return vtexjs.checkout.removeAccountId(accountId);
}).then(function() {
alert('Removido.');
});
```
--------------------------------
### Example of adding an item attachment
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Illustrates how to add an attachment to an item in the cart, such as customization details, using vtexjs.checkout.addItemAttachment. It emphasizes sending all properties of the content object, even if only one field has changed.
```javascript
var itemIndex = 0;
var attachmentName = 'Customização';
// Usuário inseriu o valor do campo Nome. O objeto deve também passar o campo Numero.
var content = { Nome: 'Ronaldo', Numero: '' };
vtexjs.checkout.addItemAttachment(itemIndex, attachmentName, content, null, false);
```
--------------------------------
### Order Form Updated Event Handler
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
An example of how to listen for the 'orderFormUpdated.vtex' event to be notified when the order form has been modified.
```javascript
$(window).on("orderFormUpdated.vtex", function(evt, orderForm) {
alert("Someone changed the orderForm!")
console.log(orderForm)
})
```
--------------------------------
### removeAccountId Example
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Demonstrates how to remove a saved payment account from the order form using its account ID.
```javascript
vtexjs.checkout
.getOrderForm()
.then(function(orderForm) {
var accountId = orderForm.paymentData.availableAccounts[0].accountId
return vtexjs.checkout.removeAccountId(accountId)
})
.then(function() {
alert("Removed.")
})
```
--------------------------------
### Order Form Updated Event Listener
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.md
Example of how to listen for the 'orderFormUpdated.vtex' event to be notified when the order form is updated.
```javascript
$(window).on('orderFormUpdated.vtex', function(evt, orderForm) {
alert('Alguem atualizou o orderForm!');
console.log(orderForm);
});
```
--------------------------------
### Example Order Form Data
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/order-form.md
A JSON representation of the order form, showcasing shipping and logistics information.
```json
{
"attachmentId": "shippingData",
"address": {
"addressType": "residential",
"receiverName": "Gui***rme",
"addressId": "-1368194386810",
"postalCode": "******000",
"city": "Rio ** *******",
"state": "RJ",
"country": "BRA",
"street": "Rua *** *****nte",
"number": "***",
"neighborhood": "Bot*****",
"complement": "*** ** *",
"reference": null
},
"availableAddresses": [
{
"addressType": "residential",
"receiverName": "Gui***rme",
"addressId": "-1368194386810",
"postalCode": "******000",
"city": "Rio ** *******",
"state": "RJ",
"country": "BRA",
"street": "Rua *** *****nte",
"number": "***",
"neighborhood": "Bot*****",
"complement": "*** ** *",
"reference": null
}
],
"logisticsInfo": [
{
"itemIndex": 0,
"selectedSla": ".Transportadora",
"slas": [
{
"id": ".Transportadora",
"name": ".Transportadora",
"deliveryIds": [
{
"courierId": "67",
"warehouseId": "1_1",
"dockId": "1_1_1",
"courierName": "Transportadora",
"quantity": 1
}
],
"shippingEstimate": "3d",
"shippingEstimateDate": null,
"lockTTL": null,
"availableDeliveryWindows": [],
"deliveryWindow": null,
"price": 956,
"tax": 0
}, {
"id": "Agendada",
"name": "Agendada",
"deliveryIds": [
{
"courierId": "FA02F72F-FEBD-41A0-AF70-83A77E8C77A0",
"warehouseId": "1_1",
"dockId": "1_1_1",
"courierName": "Entrega agendada",
"quantity": 1
}
],
"shippingEstimate": "90d",
"shippingEstimateDate": null,
"lockTTL": null,
"availableDeliveryWindows": [
{
"startDateUtc": "2014-04-21T09:00:00+00:00",
"endDateUtc": "2014-04-21T12:00:00+00:00",
"price": 1000,
"tax": 0
}, {
"startDateUtc": "2014-04-21T13:00:00+00:00",
"endDateUtc": "2014-04-21T17:00:00+00:00",
"price": 1000,
"tax": 0
}
],
"deliveryWindow": null,
"price": 1220,
"tax": 0
}
]
}
]
}
```
--------------------------------
### Add Discount Coupon
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Adds a discount coupon to the order form. Only one coupon can be applied per purchase.
```javascript
vtexjs.checkout
.getOrderForm()
.then(function(orderForm) {
var code = "ABC123"
return vtexjs.checkout.addDiscountCoupon(code)
})
.then(function(orderForm) {
alert("Coupon added.")
console.log(orderForm)
console.log(orderForm.paymentData)
console.log(orderForm.totalizers)
})
```
--------------------------------
### Change clientProfileData
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Changes the first name of the client by updating the `firstName` property of `clientProfileData` using `sendAttachment`.
```javascript
vtexjs.checkout
.getOrderForm()
.then(function(orderForm) {
var clientProfileData = orderForm.clientProfileData
clientProfileData.firstName = William
return vtexjs.checkout.sendAttachment(
"clientProfileData",
clientProfileData
)
})
.done(function(orderForm) {
alert("Name changed!")
console.log(orderForm)
console.log(orderForm.clientProfileData)
})
```
--------------------------------
### Add item to cart
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Adds a specified item to the order form with a given quantity and sales channel.
```javascript
var item = {
id: 2000017893,
quantity: 1,
seller: "1",
}
vtexjs.checkout.addToCart([item], null, 3).done(function(orderForm) {
alert("Item added!")
console.log(orderForm)
})
```
--------------------------------
### Update item quantity and seller
Source: https://github.com/vtex/vtex.js/blob/master/docs/checkout/README.en.md
Updates the quantity and seller of an existing item in the order form by its index.
```javascript
vtexjs.checkout
.getOrderForm()
.then(function(orderForm) {
var itemIndex = 0
var item = orderForm.items[itemIndex]
var updateItem = {
index: itemIndex,
quantity: 5,
}
return vtexjs.checkout.updateItems([updateItem], null, false)
})
.done(function(orderForm) {
alert("Items updated!")
console.log(orderForm)
})
```