Skip to main content

Plugin javaScript

A powerful and flexible library that easily connects with any web platform.

Plugin javaScript

Tuna.js Library#

Tuna's JavaScript library will allow you to tokenize customer information, collect sensitive card data and accept payments on your website. In this section, you will find all details, objects and configurations needed to run the library from the browser with JavaScript js.

Getting started: Adding tuna.js#

To start using tuna.js is as easy as including tuna.js in your checkout page. It is highly recommended that you do not store the js file at your server, for security reasons. You should always load it directly from https://js.tuna.uy

HTML
1<script src="https://js.tuna.uy/tuna.js"></script>

You can choose whether to use your own style components, or ours. To use our default style: you should include the .css classes to your checkout page. Add the file that is bellow

HTML
1<script src="https://js.tuna.uy/css/components.min.css"></script>

Initializing Tuna#

First thing you need to do is to create an instance of the Tuna class, then you can use the object to perform all desired actions. As you can see below the constructor needs a sessionID, which must come from your backend (more about sessionID further below).

Call this method to initiate Tuna before performing any actions.
Method parameters
sessionIDstringREQUIRED
The sessionID is the public key you got using your personal data through Tuna tokenizator API.
envstringOPTIONALDEFAULT:"production"
The environment name. Set env="sandbox" to use the sandbox environment of all related Tuna APIs
Returns
object
The instance of Tuna object.
HTML
1const tuna = Tuna(sessionId);

Integration methods#

You can choose between using tuna.js to generate a complete payment form with tokenization and payment in a transparent way, or you can use it to just render the form and take care of tokenization while handling the payment api calls yourself at your backend system. Optionally you can use tuna.js solely to handle tokenization(in that case you need to be carefull not to send sensitive credit card data to your backend).

When you create a sessionID on your backend, you can choose to associate this session with just customer data or customer + order. This choice will vary according to the type of integration you'll use to connect to our Payment API, which can be either through backend or using Tuna JS.

When your backend places the payment api calls#

Here you only need to send customer data when creating the sessionID.

When tuna.js places the payment api calls#

Here the sessionID must have been generated including the order indentifier. Keep in mind that since the payment is done before submitting the order to your backend, you must check that the order total matches with the total paid amout by either using a webhook or polling the payment status.

Using the default payment form#

In Tuna we believe less is more, so if you are looking for a quick and easy way to integrate with Tuna using minimum configuration then the default payment form is the best option.

This method allows you to integrate with Tuna tokenization service using the default payment fields, and it also includes the input validations configured. Look below the entire configuration of this method.

Default payment form
HTML
Javascript
1const tuna = Tuna('JfMf8kKoMkdXVtM5Df8J5LbU=',
2    (tokenizatorPromisse, creditCardData) => {
3        tknPromisse.then(response => {
4            alert(JSON.stringify(creditCardData) +"\n"+ JSON.stringify(response))
5            /// --- Send the token to your beckend checkout function
6        }).catch(e => alert("Sorry..."));
7    }
8);
9tuna.forgeDefaultForm("#root",
10    {
11        savedCardBoxTitle: "Saved cards",
12        savedCardButtonTitle: "Use saved card",
13        newCardBoxTitle: "New card",
14        newCardButtonTitle: "Use new card",
15        button: { title: "Pay with TUNA!" },
16        cardHolderName: { title: "Card holder name", placeholder: "As it’s written on the card" },
17        document: { title: "CPF", buyerDocumentFormatter: tuna.getBuyerDocumentFormatter("pt-BR"), cleanMask: true, placeholder: "000.000.000-00" },
18        cardValidity: { title: "Validity", validationMessage: "Use a valid card validity", placeholder: "mm/yyyy" },
19        cardCvv: { title: "CVV", validationMessage: "Insert a CVV", placeholder: "000" },
20        saveCard: { title: "Save card to future purchases" },
21        cardList: { title: "Saved card", cardCvv: { placeholder: "cvv" } },
22        cardNumber: { title: "Card number", placeholder: "0000 0000 0000 0000" },
23        installment: {
24            title: "Installment", options: [
25                { key: 1, value: "1x interest-free" },
26                { key: 2, value: "2x interest-free" },
27                { key: 3, value: "3x interest-free" },
28                { key: 4, value: "4x interest-free" },
29                { key: 5, value: "5x interest-free" },
30            ]
31        },
32        checkoutCallback : response => console.log(response)
33    }
34);
forgeDefaultForm (place, options)
Call this method to create the default Tuna form to acquire the user's credit card data and perform the checkout. At least one between checkoutCallback and checkoutAndPayConfig properties must to be setted.
Method parameters
placestringREQUIRED
The selector that identify the container where the form will be placed.
optionsobjectREQUIRED
The options to customize the form as well all elements used to compose then. Except the document option, none of the other pieces needs to be mandatorily configured. They will use default values when the configuration was not given.
Properties
getBuyerDocumentFormatter (locale?)
This method lookup by BuyerDocumentFormatter implementations related to the locale sent.
Method parameters
localestringOPTIONAL
The locale key related to the payment origin country.
Returns
object
An instance of BuyerDocumentFormatter object related to the locale sent or the default instance of BuyerDocumentFormatter.

Extending the BuyerDocumentFormatter class#

In order to give flexibility to the creation of document fields, the BuyerDocumentFormatter class can be extended to suport any document format and validation rules. See bellow a example of extending this class tu support Brazilian CPF (Individual Registration)

BuyerDocumentFormatter
patternstringREQUIRED
The document pattern
validationFunctionfunctionREQUIRED
Function used to validate the inputed value
documentNamestringREQUIRED
The name of the document (used as field label)
javascript
1class BrazilianDocumentFormatter extends BuyerDocumentFormatter {
2    constructor() {
3        super("999.999.99999", cpfValidationFunction, "CPF");
4    }
5}
6pieceManager.forge("#DOCUMENT", "document", {
7    title: "Document", buyerDocumentFormatter: new BrazilianDocumentFormatter()
8});

Using the Piece Manager#

The Piece Manager is the object responsible to create, treat and configure the UI elements at screen. You can use it to forge interface pieces as inputs, checkboxes and else elements that you need.

tuna.pieceManager ()
This method create the PieceManager instance which allow to create UI pieces.
Returns
object
The pieceManager instance.
javascript
1const pieceManager = tuna.pieceManager();
This method is responsible to create the UI elements.
Method parameters
placestringREQUIRED
The selector that identify the cointainer element where the piece will be placed.
pieceNamestringREQUIRED
The name that identify the type of piece that will be generated. See the piece type details.
optionsobjectOPTIONAL
The specific piece options for the choosen piece. When null, a empty options object will be used.
groupstringOPTIONALDEFAULT:"default"
The component's group name.
propertyNamestringOPTIONAL

The name of the property at the returned object.

Each piece has its own default name. Use this parameter only when the intention was override the default name or when using the following piece types: formattedInput, input.
validationFunctionfunctionOPTIONAL
Is the function used to validate if the data typed on the element is valid. The following piece types are already validated and usually no more validation are needed: cardNumber, month, year, saveCard, cardValidity, cardHolderName, cardCvv
Returns
int
The internal id of the generated piece.
pieceManager.destroy (pieceID)
Remove the UI element from the screen
Method parameters
pieceIDintREQUIRED
The id of the piece returned when the piece was forged.
pieceManager.executeOnPieces (function)
Receives a function and apply this function to each piece object created
Method parameters
functionfunctionREQUIRED
A func(piece) function to run with each created piece
pieceManager.getPiece (pieceID)
Retrieve the piece object
Method parameters
pieceIDintREQUIRED
The id of the piece returned when the piece was forged.
Returns
piece
The instance of piece with the given pieceID or null
pieceManager.getPiecesByGroup (groupName)
Retrieve an array of pieces inside the group
Method parameters
groupNamestringREQUIRED
The group name used to forge the piece
Returns
array
The array containing all pieces of the given group name
pieceManager.changeGroupEnableStatus (group, enabled)
Change the status (enabled/disabled) of all components at the given group. Once disabled, the UI elements will not be considered to the checkout proccess and the validation functions will not be triggered.
Method parameters
groupstringREQUIRED
The group name
enabledboolREQUIRED
The enable/disable status to be setted at each group element
pieceManager.destroyGroup (group, preserveRoot)
Destroy all elements of the given group.
Method parameters
groupstringREQUIRED
The group name.
preserveRootboolREQUIRED
Flag to choose if the root element should be preserved or not when destroing the element.

The Piece object#

The piece class define each type of code pieces that the Tuna js plugin can create and manage as well provide a set of functions to interact with this pieces.

piece.getId ()
Return the piece ID generated when the piece is forged
Returns
int
The piece ID
piece.getPlace ()
Return the seletor used when the piece is forged
Returns
string
The piece place selector
piece.getGroup ()
Return the group name used when the piece is forged
Returns
string
The piece group name.
piece.getPropertyName ()
Returns the property name used to the field value when the checkout is processed. This property are default in some piece types like cardCvv but can be setted or overridden at the forge moment.
Returns
string
The piece group name.
piece.getOptions ()
Returns the piece options
Returns
array
The piece options.
piece.getType ()
Returns the piece type definition.
Returns
object
This object contains a set of properties used to generate the respective piece. The properties can vary according the piece type.
Properties
piece.getOptions ()
Returns the piece options
Returns
array
The piece options passed when the piece was forged.
piece.getValidationFunction ()
Returns the piece validation function
Returns
function
The validation function passed when the piece was forged.
piece.clear ()
Clear the piece value.
piece.updateComponent ()
Update the component UI.
piece.unmountComponent (preserveRoot)
Unmount the component.
Method parameters
preserveRootboolREQUIRED
Flag to choose if the root component will be preserved or not
piece.setValue (value)
Set the value and update the component.
Method parameters
valueobjectREQUIRED
The new object value
piece.markAsInvalid ()
Mark the piece as invalid showing the validation message and giving focus to the component
piece.resetInvalidMarking ()
Resets the invalid marking.
piece.getValue ()
Gets the field value. Aditionaly, verify if the field is invalid running the respective validation function, and if positive runs the markAsInvalid() function. If the field is identified as invalid, an expection will be throwed with code ERR:07.
Returns
object
The field value

Piece Types#

There are 10 different types of UI elements that should be used to create the payment form. Each element accept a set of properties that can be used to configure aspects as: field label, validation message, css classes and so on. You can see all pieces that Tuna implemented and their configurations bellow:

input
A simple input text.
titlestring
The title of the field.
titleClassstring
The CSS class used in the field title.
inputClassstring
The CSS class used in the input.
Show object properties
javascript
HTML
1const pieceManager = tuna.pieceManager();
2pieceManager.forge("#input", "input", {
3    title: "Special wish", placeholder: "Place your special wishes here..."
4},"specialWish");
formattedInput
A customizable formatted input text.
patternstringREQUIRED
The pattern used to format the input: use "A" for letters and "9" for numbers. E.g. 999.999.999-99 for brazilian CPF (citizen identification number).
cleanMaskbool
A flag to set up if the inputted value will have the mask cleaned or not when returned.
titlestring
The title of the field.
Show object properties
javascript
HTML
1const pieceManager = tuna.pieceManager();
2pieceManager.forge("#document", "formattedInput", {
3    title: "CPF:", placeholder: "xxx.xxx.xxx-xx", cleanMask: true, pattern:"999.999.999-99"
4}, "document");
document
A customizable input text to receive and validate the buyer document data. The inputed value will be returned in the document property.
buyerDocumentFormatterobjectREQUIRED
An instance of the BuyerDocumentFormatter class
cleanMaskbool
A flag to set up if the inputted value will have the mask cleaned or not when returned.
titlestring
The title of the field.
Show object properties
javascript
HTML
1const pieceManager = tuna.pieceManager();
2pieceManager.forge("#DOCUMENT", "document", {
3    title: "Document", placeholder: "Inform your document", buyerDocumentFormatter: tuna.getBuyerDocumentFormatter("pt-BR")
4});
button
A simple button that can be used to trigger the checkout process.
titlestring
The title of the button.
buttonClassstring
The CSS class used in the button.
iconClassstring
The CSS class used in the button icon.
Show object properties
javascript
HTML
1const pieceManager = tuna.pieceManager();
2pieceManager.forge("#button", "button",
3    { title: 'Pay', onclick: _ => alert("Pay!") });
cardHolderName
An input text already setted to keep the card holder name data. The inputed value will be returned in the cardHolderName property.
titlestring
The title of the field.
titleClassstring
The CSS class used in the field title.
inputClassstring
The CSS class used in the input.
Show object properties
javascript
HTML
1const pieceManager = tuna.pieceManager();
2pieceManager.forge("#cardHolderName", "cardHolderName", {
3    title: "Name on card", placeholder: "As it’s written on the card"
4});
cardNumber
A formatted input text already setted to keep and treat the credit card number. The inputed value will be returned in the cardNumber property.
showCardBrandbool
A flag to set or not the display of the credit card brand icon.
cardBrandClassstring
The css class name to use in the card brand icon.
titlestring
The title of the field.
Show object properties
javascript
HTML
1const pieceManager = tuna.pieceManager();
2pieceManager.forge("#cardNumber", "cardNumber", {
3    title: "Card number", placeholder: "xxxx xxxx xxxx xxxx"
4});
cardCvv
A formatted input text already setted to keep and treat the credit card cvv. The inputed value will be returned in the cvv property.
showCVVImagebool
A flag to set or not the display of the cvv icon.
cvvImageClassstring
The css class name to use in the cvv icon.
titlestring
The title of the field.
Show object properties
javascript
HTML
1const pieceManager = tuna.pieceManager();
2pieceManager.forge("#cardCvv", "cardCvv", {
3    title: "cvv", placeholder: "xxx"
4});
cardValidity
A formatted input text already setted to keep and treat the credit card expiration containing the expiration month and year. The inputed value will be returned in the expirationMonth and expirationYear properties.
titlestring
The title of the field.
titleClassstring
The CSS class used in the field title.
inputClassstring
The CSS class used in the input.
Show object properties
javascript
HTML
1export const tuna = Tuna("insert a valid sessionID here");
2const pieceManager = tuna.pieceManager();
3pieceManager.forge("#cardValidity", "cardValidity", {
4    title: "Validity", placeholder: "mm/yyyy"
5});
month
A formatted select box already setted to keep the expiration month. The selected value will be returned in the expirationMonth property.
titlestring
The title of the field.
titleClassstring
The CSS class used in the field title.
inputClassstring
The CSS class used in the input.
javascript
HTML
1const pieceManager = tuna.pieceManager();
2pieceManager.forge("#month", "month", {
3    title: "Validity month"
4});
year
A formatted select box already setted to keep the validity year. The selected value will be returned in the expirationYear property.
titlestring
The title of the field.
titleClassstring
The CSS class used in the field title.
inputClassstring
The CSS class used in the input.
javascript
HTML
1const pieceManager = tuna.pieceManager();
2pieceManager.forge("#year", "year", {
3    title: "Validity year"
4});
installment
A formatted select box to render the installment options. The selected value will be returned in the selectedInstallmentKey property.
optionsarrayREQUIRED
An array of { key, value } object containing the allowed installment options.
titlestring
The title of the field.
titleClassstring
The CSS class used in the field title.
Show object properties
javascript
HTML
1pieceManager.forge("#installment", "installment", {
2    title: "Installment", options: [
3        { key: 1, value: "1x" },
4        { key: 2, value: "2x" },
5        { key: 3, value: "3x" },
6        { key: 4, value: "4x" }
7    ]
8});
saveCard
A checkbox that allows the user to save the card data for future transactions.
titlestring
The title of the field.
titleClassstring
The CSS class used in the field title.
checkedboolDEFAULT: true
The default state of the checkbox.
Show object properties
javascript
HTML
1const pieceManager = tuna.pieceManager();
2pieceManager.forge("#saveCard", "saveCard", {
3    title: "Save card"
4});

Adding saved card selector#

We strongly recomend the saveCard object to increase the conversion rate of your checkout page. By implementing it, you also need to include the Saved Card Selector, so your users can choose the card that have already been saved directly in your checkout page.

async useSavedCardSelector (place, options?, group?)
Create the saved card selector component.
Method parameters
placestringREQUIRED
The selector that identify the cointainer element where the piece will be placed.
optionsobjectOPTIONAL
The options to customize the component
Properties
groupstringOPTIONAL
The component's group name
Returns
int
The number of returned saved cards. If returns 0, then the component will not be rendered.
javascript
HTML
1tuna.useSavedCardSelector("#SAVED_CARDS", 
2    {
3        onSelectionBegins: _ => alert("selection started"), 
4        cardCvv: { placeholder: "cvv" } 
5    });
clearSavedCardSelector ()
Clean all data set in any saved card selector component. Including cvv and document numbers.
javascript
HTML
1const pieceManager = tuna.pieceManager();
2
3tuna.useSavedCardSelector(
4    "#SAVED_CARDS", 
5    tuna.getBuyerDocumentFormatter("pt-BR"),
6    _ => alert("Selection begins!")
7);
8
9pieceManager.forge("#CLEAR_SELECTOR", "button", {
10    title: "Clear saved card selector", 
11    onclick: _ => tuna.clearSavedCardSelector()
12});

Accessing the Tuna tokenization service#

Use the Tuna Tokenization Service through the Tuna.js library to create PCI Compliant credit card tokens.

HTML
1const tuna = Tuna(sessionId);
2const tokenizator = tuna.tokenizator();
async tokenizator.list ()
List saved card tokens to the given user session id.
Returns
object
Token service response object.
Properties
async tokenizator.generate (cardData)
Create a new credit card token entry
Method parameters
cardDataobjectREQUIRED
Object containing the credit card data to be tokenized.
Properties
Returns
object
Token service response object containing the generated token.
Properties
async tokenizator.delete (token)
Delete an alredy created card token.
Method parameters
tokenstringREQUIRED
The token associated to the credit card.
Returns
object
The operation response
Properties
async tokenizator.bind (token, cvv)
Binds a CVV with a token.
Method parameters
tokenstringREQUIRED
The token associated to the credit card.
cvvstringREQUIRED
The credit card CVV
Returns
object
The operation response
Properties

The details of the tokenization API request objects and responses can be access at the this link.

Using Google pay#

With Tuna you can use the Google Pay to create the credit card token.

Configure the Google Pay
Method parameters
googlePayBtnContainerSelectorstringREQUIRED
Selector to the Google Pay button container tag.
googlePaySettingsobjectREQUIRED
Google Pay API configuration properties.
Properties
checkoutCallbackFunctionfunctionREQUIRED
The function that will be called when the Google Pay proccess is done.
validationGroupstringOPTIONAL
The group of Tuna piece elements that the click at Google Pay button must validate before proceed.

Managing checkout#

async checkout (callbackFunction?)
This method triggers the field validations, and then compile the inputted data in order to generate the payment credit card token. This callback function parameter is optional, if not sent then the method will return the result as method response
Method parameters
callbackFunctionfunctionOPTIONAL
The function the will be called after the field validation proccess.
Parameters
Returns
object
An object containing the result of the credit card tokenization and all non sensible data obtained by the forged input pieces. The method will only return a value if the callbackFunction parameter wasn't sent.
Properties
javascript
1tuna.checkout((tokenizatorPromisse, creditCardData) => {
2    tokenizatorPromisse
3        .then(response => {
4            //Use the result data to post the purchase to payment
5            postToPayment(response, creditCardData);
6        })
7        .catch(result => // Handle result.error);
8});
Similar to checkout method but follows with the payment effetivation
Method parameters
paymentMethodTypestringREQUIRED
The payment method type. Avaliable: "creditCard", "pix", "crypto" and "bankInvoice"
totalPaymentAmountdecimalREQUIRED
The payment total amount
paymentMethodAmountdecimalREQUIRED
The amount that should be paid with this payment method
callbackFunctionfunctionOPTIONAL
A function that will receive the payment response promisse. The response object format is described here
Returns
object
The payment response object. The format is described here.
The function only return values if the callbackFunction is not provided.

Using QRCode Payment#

After a susccessfully call to checkoutAndPay using pix or bitcoin as payment method, you will have all necessary parameters to show the QR Code to the customers and then await for the payment confirmation.

Create an interface to show the QRCode of payments using PIX or Bitcoin as payment method. Additionally, create a long polling request responsible to check the payment status and call the callback function when the payment status changes.
Method parameters
placestringREQUIRED
The selector where the element will be mounted
optionsobjectREQUIRED
The object containing details and configurations about the payment.
Properties
paymentCallback(result, exception)functionREQUIRED
The callback function that will be called when the payment verification polling is finished or throw an error.
Parameters
groupstringOPTIONAL
The component's group name.

What is next?#

Once you have your account and your integration concluded, you can start the setup up of your services and flows in Console. For further details, please check out the Console section.