@tonder.io/ionic-full-sdk
v0.0.56
Published
Tonder ionic full SDK
Keywords
Readme
Tonder Ionic Full SDK
Tonder SDK helps to integrate the services Tonder offers in your own mobile app
Table of Contents
- Installation
- Usage
- Configuration Options
- Styling InlineCheckout
- Mobile Settings
- Payment Data Structure
- API Reference
- Events
- Examples
- Deprecated Functions
- License
Installation
You can install using NPM
npm i @tonder.io/ionic-full-sdkAdd dependencies to the root of the app (index.html) only if you are going to use Openpay as the payment processor.
<script src="https://openpay.s3.amazonaws.com/openpay.v1.min.js"></script>
<script src="https://openpay.s3.amazonaws.com/openpay-data.v1.min.js"></script>Usage
InlineCheckout provides a pre-built, customizable checkout interface.
HTML Setup
<div>
<h1>Checkout</h1>
<!-- You have to add an entry point with the ID 'tonder-checkout' -->
<div id="tonder-checkout"></div>
</div>Import InlineCheckout class
import { InlineCheckout } from "@tonder.io/ionic-full-sdk";Create instance
const inlineCheckout = new InlineCheckout({
apiKey,
returnUrl,
renderPaymentButton: false // true, if you need render default button of tonder
});
// The configureCheckout function allows you to set initial information,
// such as the customer's email, which is used to retrieve a list of saved cards or the secure token required to save a card.
// You can refer to the Customer interface for the complete object structure that can be passed.
inlineCheckout.configureCheckout({
customer: {
email: "[email protected]"
},
secureToken: "e89eb18.."
});
// Inject the checkout into the DOM
inlineCheckout.injectCheckout();
// To verify a 3ds transaction you can use the following method
// It should be called after the injectCheckout method
// The response status will be one of the following
// ['Declined', 'Cancelled', 'Failed', 'Success', 'Pending', 'Authorized']
inlineCheckout.verify3dsTransaction().then((response) => {
console.log("Verify 3ds response", response);
});// Process a payment
const response = await inlineCheckout.payment(checkoutData);Configuration Options
| Property | Type | Required | Description |
|--------------------------------------------|----------|:--------:|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| mode | string | | Environment mode. Options: 'stage', 'production', 'sandbox'. Default: 'stage' |
| apiKey | string | X | You can take this from you Tonder Dashboard |
| returnUrl | string | | url where the checkout form is mounted (3ds) |
| styles | object | | Custom styles for the checkout interface |
| containerId | string | | If require a custom checkout container id, default value "tonder-checkout" |
| collectorIds | object | | If require a custom div containers ids, default value {"cardsListContainer": "cardsListContainer", "holderName": "collectCardholderName", "cardNumber": "collectCardNumber", "expirationMonth": "collectExpirationMonth", "expirationYear": "collectExpirationYear", "cvv": "collectCvv", "tonderPayButton": "tonderPayButton", "msgError": "msgError", "msgNotification": "msgNotification"} |
| callBack | function | | Callback function invoqued after the payment process end successfully |
| isOpenpaySandbox | boolean | | Define if openpay work on sandbox, default value true |
| isEnrollmentCard | boolean | | Use the SDK as an enrollment card. |
| customization | object | | Object to customize the checkout behavior and UI. Default value {saveCards: {showSaved: true, showSaveCardOption: true, autoSave: false}, paymentButton: {show: false, showAmount: true, text: 'Pagar'}} |
| customization.saveCards.showSaved | boolean | | Show saved cards in the checkout UI. Default value: true |
| customization.saveCards.showSaveCardOption | object | | Show the option to save the card for future payments. Default value: true |
| customization.saveCards.autoSave | object | | Automatically save the card without showing the option to the user. Default value: false |
| customization.paymentButton.show | boolean | | Show or hide the payment button. Default value: false |
| customization.paymentButton.text | string | | Custom text for the payment button. Default value: Pagar |
| customization.paymentButton.showAmount | boolean | | Show or hide the amount in the payment button. Default value: true |
| events | IEvents | No | Event handlers for card form input fields (onChange, onFocus, onBlur) |
Important Note about SaveCard functionality: To properly implement the SaveCard feature, you must use a SecureToken. For detailed implementation instructions and best practices, please refer to our official documentation on How to use SecureToken for secure card saving.
Styling InlineCheckout
You can customize the appearance of InlineCheckout by passing a styles object:
const customStyles = {
inputStyles: {
base: {
border: "1px solid #e0e0e0",
padding: "10px 7px",
borderRadius: "5px",
color: "#1d1d1d",
marginTop: "2px",
backgroundColor: "white",
fontFamily: '"Inter", sans-serif',
fontSize: "16px",
"&::placeholder": {
color: "#ccc",
},
},
cardIcon: {
position: "absolute",
left: "6px",
bottom: "calc(50% - 12px)",
},
complete: {
color: "#4caf50",
},
empty: {},
focus: {},
invalid: {
border: "1px solid #f44336",
},
global: {
"@import":
'url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap")',
},
},
labelStyles: {
base: {
fontSize: "12px",
fontWeight: "500",
fontFamily: '"Inter", sans-serif',
},
},
errorTextStyles: {
base: {
fontSize: "12px",
fontWeight: "500",
color: "#f44336",
fontFamily: '"Inter", sans-serif',
},
},
labels: {
nameLabel: "Card Holder Name",
cardLabel: "Card Number",
cvvLabel: "CVC/CVV",
expiryDateLabel: "Expiration Date",
},
placeholders: {
namePlaceholder: "Name as it appears on the card",
cardPlaceholder: "1234 1234 1234 1234",
cvvPlaceholder: "3-4 digits",
expiryMonthPlaceholder: "MM",
expiryYearPlaceholder: "YY",
},
};The styles param is related to the style of the inputs inside the checkout form, to customize the checkout container and the cards list you can use global styles on base to this classes
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;700&display=swap");
.container-tonder {
background-color: #f9f9f9;
margin: 0 auto;
padding: 30px 10px 30px 10px;
overflow: hidden;
transition: max-height 0.5s ease-out;
max-width: 600px;
border: solid 1px #e3e3e3;
}
.collect-row {
display: flex;
justify-content: space-between;
width: 100%;
}
.collect-row > :first-child {
min-width: 120px;
}
.expiration-year {
padding-top: 25px;
}
.empty-div {
height: 80px;
margin-top: 2px;
margin-bottom: 4px;
margin-left: 10px;
margin-right: 10px;
}
.error-container {
color: red;
background-color: #ffdbdb;
margin-bottom: 13px;
font-size: 80%;
padding: 8px 10px;
border-radius: 10px;
text-align: left;
}
.message-container {
color: green;
background-color: #90ee90;
margin-bottom: 13px;
font-size: 80%;
padding: 8px 10px;
border-radius: 10px;
text-align: left;
}
.pay-button {
font-size: 16px;
font-weight: bold;
min-height: 2.3rem;
border-radius: 0.5rem;
cursor: pointer;
width: 100%;
padding: 1rem;
text-align: center;
border: none;
background-color: #000;
color: #fff;
margin-bottom: 10px;
display: none;
}
.pay-button:disabled,
pay-button[disabled] {
background-color: #b9b9b9;
}
.lds-dual-ring {
display: inline-block;
width: 14px;
height: 14px;
}
.lds-dual-ring:after {
content: " ";
display: block;
width: 14px;
height: 14px;
border-radius: 50%;
border: 6px solid #fff;
border-color: #fff transparent #fff transparent;
animation: lds-dual-ring 1.2s linear infinite;
}
@keyframes lds-dual-ring {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@media screen and (max-width: 600px) {
.payment_method_zplit {
font-size: 16px;
width: 100%;
}
.payment_method_zplit label img {
display: none;
}
}
.cards-list-container {
display: flex;
flex-direction: column;
padding: 0px 10px 0px 10px;
gap: 33% 20px;
}
.checkbox label {
margin-left: 10px;
font-size: 12px;
font-weight: 500;
color: #1d1d1d;
font-family: "Inter", sans-serif;
}
.checkbox {
margin-top: 10px;
margin-bottom: 10px;
width: 100%;
text-align: left;
}
.pay-new-card {
display: flex;
justify-content: start;
align-items: center;
color: #1d1d1d;
gap: 33% 20px;
margin-top: 10px;
margin-bottom: 10px;
padding-left: 10px;
padding-right: 10px;
width: 90%;
}
.pay-new-card .card-number {
font-size: 16px;
font-family: "Inter", sans-serif;
}
.card-image {
width: 27px;
height: 20px;
text-align: left;
}
.card-item-label {
display: flex;
justify-content: start;
align-items: center;
color: #1d1d1d;
gap: 33% 20px;
margin-top: 10px;
margin-bottom: 10px;
padding-left: 10px;
padding-right: 10px;
width: 90%;
}
.card_selected {
width: 10%;
}
.card-item {
display: flex;
justify-content: start;
align-items: center;
gap: 33% 20px;
}
.card-item .card-number {
font-size: 16px;
font-family: "Inter", sans-serif;
}
.card-item .card-expiration {
font-size: 16px;
font-family: "Inter", sans-serif;
}Mobile settings
If you are deploying to Android, edit your AndroidManifest.xml file to add the Internet permission.
<!-- Required to fetch data from the internet. -->
<uses-permission android:name="android.permission.INTERNET" />Payment Data Structure
When calling the payment method, use the following data structure:
Field Descriptions
customer: Object containing the customer's personal information to be registered in the transaction.
cart: Object containing the total amount and an array of items to be registered in the Tonder order.
- total: The total amount of the transaction.
- items: An array of objects, each representing a product or service in the order.
- name: name of the product
- price_unit: valid float string with the price of the product
- quantity: valid integer string with the quantity of this product
currency: String representing the currency code for the transaction (e.g., "MXN" for Mexican Peso).
metadata: Object for including any additional information about the transaction. This can be used for internal references or tracking.
apm_config: (Optional) Configuration object for APM-specific options. Only applicable when using alternative payment methods like Mercado Pago.
| Field | Type | Description |
|-------------------------------------|--------------------------------------------|---------------------------------------------------------------------------|
| binary_mode | boolean | If true, payment must be approved or rejected immediately (no pending). |
| additional_info | string | Extra info shown during checkout and in payment details. |
| back_urls | object | URLs to redirect the user after payment. |
| └─ success | string | Redirect URL after successful payment. |
| └─ pending | string | Redirect URL after pending payment. |
| └─ failure | string | Redirect URL after failed/canceled payment. |
| auto_return | "approved" | "all" | Enables auto redirection after payment completion. |
| payment_methods | object | Payment method restrictions and preferences. |
| └─ excluded_payment_methods[] | array | List of payment methods to exclude. |
| └─ excluded_payment_methods[].id | string | ID of payment method to exclude (e.g., "visa"). |
| └─ excluded_payment_types[] | array | List of payment types to exclude. |
| └─ excluded_payment_types[].id | string | ID of payment type to exclude (e.g., "ticket"). |
| └─ default_payment_method_id | string | Default payment method (e.g., "master"). |
| └─ installments | number | Max number of installments allowed. |
| └─ default_installments | number | Default number of installments suggested. |
| expires | boolean | Whether the preference has expiration. |
| expiration_date_from | string (ISO 8601) | Start of validity period (e.g. "2025-01-01T12:00:00-05:00"). |
| expiration_date_to | string (ISO 8601) | End of validity period. |
| differential_pricing | object | Configuration for differential pricing. |
| └─ id | number | ID of the differential pricing strategy. |
| marketplace | string | Marketplace identifier (default: "NONE"). |
| marketplace_fee | number | Fee to collect as marketplace commission. |
| tracks[] | array | Ad tracking configurations. |
| └─ type | "google_ad" | "facebook_ad" | Type of tracker. |
| └─ values.conversion_id | string | Google Ads conversion ID. |
| └─ values.conversion_label | string | Google Ads label. |
| └─ values.pixel_id | string | Facebook Pixel ID. |
| statement_descriptor | string | Text on payer’s card statement (max 16 characters). |
| shipments | object | Shipping configuration. |
| └─ mode | "custom" | "me2" | "not_specified" | Type of shipping mode. |
| └─ local_pickup | boolean | Enable pickup at local branch (for me2). |
| └─ dimensions | string | Package dimensions (e.g. 10x10x10,500). |
| └─ default_shipping_method | number | Default shipping method (for me2). |
| └─ free_methods[] | array | Shipping methods offered for free (for me2). |
| └─ free_methods[].id | number | ID of free shipping method. |
| └─ cost | number | Shipping cost (only for custom mode). |
| └─ free_shipping | boolean | If true, shipping is free (custom only). |
| └─ receiver_address | object | Shipping address. |
| └─ receiver_address.zip_code | string | ZIP or postal code. |
| └─ receiver_address.street_name | string | Street name. |
| └─ receiver_address.street_number | number | Street number. |
| └─ receiver_address.city_name | string | City name. |
| └─ receiver_address.state_name | string | State name. |
| └─ receiver_address.country_name | string | Country name. |
| └─ receiver_address.floor | string | Floor (optional). |
| └─ receiver_address.apartment | string | Apartment or unit (optional). |
const paymentData = {
customer: {
firstName: "John",
lastName: "Doe",
country: "USA",
address: "123 Main St",
city: "Anytown",
state: "CA",
postCode: "12345",
email: "[email protected]",
phone: "1234567890",
identification:{
type: "CPF",
number: "19119119100"
}
},
cart: {
total: "100.00",
items: [
{
description: "Product description",
quantity: 1,
price_unit: "100.00",
discount: "0.00",
taxes: "0.00",
product_reference: "PROD123",
name: "Product Name",
amount_total: "100.00",
},
],
},
currency: "MXN",
metadata: {
order_id: "ORDER123",
},
// apm_config: {} // Optional, only for APMs like Mercado Pago, Oxxo Pay
};API Reference
configureCheckout(data): Set initial checkout datainjectCheckout(): Initialize the checkoutpayment(data): Process a paymentverify3dsTransaction(): Verify a 3DS transactionsaveCard(): Save a new card. This is useful when using sdk as an enrollment cardisEnrollmentCardremoveCheckout(): Removes the checkout from the DOM and cleans up associated resources.setPaymentData(data): Set the payment data, such as customer, cart, and metadata. This is useful when using the default Tonder payment buttonrenderPaymentButton.
Events
The SDK provides event handling capabilities for card form input fields, supporting both Full/Enrollment SDK implementations.
Event Types
Each event object supports:
onChange: Called when input value changesonFocus: Called when input receives focusonBlur: Called when input loses focus
export interface IEvents {
onChange?: (event: IEventSecureInput) => void;
onFocus?: (event: IEventSecureInput) => void;
onBlur?: (event: IEventSecureInput) => void;
}Input event properties
| Property | Type | Description | |-------------|---------|-------------------------------------------------------------------------------------------------------------| | elementType | string | Type of input element (e.g. 'CARDHOLDER_NAME', 'CARD_NUMBER', 'EXPIRATION_YEAR', 'EXPIRATION_MONTH', 'CVV') | | isEmpty | boolean | Whether the input field has a value | | isFocused | boolean | Whether the input field currently has focus | | isValid | boolean | Whether the input value passes validation rules |
export interface IEventSecureInput {
elementType: string;
isEmpty: boolean;
isFocused: boolean;
isValid: boolean;
}Full/Enrollment SDK Events
Events are configured during SDK initialization.
Available Events
| Event Object | Description | |------------------|-----------------------------------| | cardHolderEvents | Events for cardholder name input | | cardNumberEvents | Events for card number input | | cvvEvents | Events for CVV input | | monthEvents | Events for expiration month input | | yearEvents | Events for expiration year input |
export interface IEvents {
cardHolderEvents?: IEvents;
cardNumberEvents?: IEvents;
cvvEvents?: IEvents;
monthEvents?: IEvents;
yearEvents?: IEvents;
}Example
const inlineCheckout = new InlineCheckout({
events: {
cardHolderEvents: {
onChange: (event) => {
console.log('Card holder change event', event);
},
onFocus: (event) => {
console.log('Card holder focus event', event);
},
onBlur: (event) => {
console.log('Card holder blur event', event);
}
},
cvvEvents: {
onChange: (event) => {
console.log('Cvv change event', event);
},
onFocus: (event) => {
console.log('Cvv focus event', event);
},
onBlur: (event) => {
console.log('Cvv blur event', event);
}
}
}
});Examples
Here are examples of how to implement Tonder SDK:
Ionic Angular - Checkout
For Angular, we recommend using a service to manage the Tonder instance:
// tonder.service.ts
import { Injectable } from "@angular/core";
import { InlineCheckout } from "@tonder.io/ionic-full-sdk";
import {IInlineCheckout} from "@tonder.io/ionic-full-sdk/dist/types/inlineCheckout";
@Injectable({
providedIn: "root",
})
export class TonderService {
private inlineCheckout: IInlineCheckout;
constructor(@Inject(Object) private sdkParameters: IInlineCheckoutOptions) {
this.initializeInlineCheckout();
}
private initializeInlineCheckout(): void {
this.inlineCheckout = new InlineCheckout({ ...this.sdkParameters });
}
configureCheckout(customerData: IConfigureCheckout): void {
return this.inlineCheckout.configureCheckout({ ...customerData });
}
async injectCheckout(): Promise<void> {
return await this.inlineCheckout.injectCheckout();
}
verify3dsTransaction(): Promise<ITransaction | IStartCheckoutResponse | void> {
return this.inlineCheckout.verify3dsTransaction();
}
payment(
checkoutData: IProcessPaymentRequest
): Promise<IStartCheckoutResponse> {
return this.inlineCheckout.payment(checkoutData);
}
removeCheckout(): void {
return this.inlineCheckout.removeCheckout();
}
}// checkout.component.ts
import { Component, OnInit, OnDestroy } from "@angular/core";
import { TonderService } from "./tonder.service";
@Component({
selector: "app-tonder-checkout",
template: `
<div id="tonder-checkout"></div>
<button (click)="pay()" [disabled]="loading">
{{ loading ? "Processing..." : "Pay" }}
</button>
`,
providers: [
{
provide: TonderInlineService,
// Initialization of the Tonder Inline SDK.
// Note: Replace these credentials with your own in development/production.
useFactory: () =>
new TonderInlineService({
apiKey: "11e3d3c3e95e0eaabbcae61ebad34ee5f93c3d27",
returnUrl: "http://localhost:8100/tabs/tab1",
mode: "stage",
}),
},
],
})
export class TonderCheckoutComponent implements OnInit, OnDestroy {
loading = false;
checkoutData: IProcessPaymentRequest;
constructor(private tonderService: TonderService) {
this.checkoutData = {
customer: {
firstName: "Jhon",
lastName: "Doe",
email: "[email protected]",
phone: "+58452258525"
},
cart: {
total: 25,
items: [
{
description: "Test product description",
quantity: 1,
price_unit: 25,
discount: 1,
taxes: 12,
product_reference: 89456123,
name: "Test product",
amount_total: 25
}
]
},
metadata: {},
currency: "MXN"
}
}
ngOnInit() {
this.initCheckout();
}
ngOnDestroy() {
// Clear the checkout upon destroying the component.
this.tonderService.removeCheckout();
}
async initCheckout() {
this.tonderService.configureCheckout({
customer: { email: "[email protected]" },
});
await this.tonderService.injectCheckout();
this.tonderService.verify3dsTransaction().then((response) => {
console.log("Verify 3ds response", response);
});
}
async pay() {
this.loading = true;
try {
const response = await this.tonderService.payment(this.checkoutData);
console.log("Payment successful:", response);
alert("Payment successful");
} catch (error) {
console.error("Payment failed:", error);
alert("Payment failed");
} finally {
this.loading = false;
}
}
}Ionic Angular - Enrollment Card
For Angular, we recommend using a service to manage the Tonder instance:
// tonder.service.ts
import { Injectable } from "@angular/core";
import { InlineCheckout } from "@tonder.io/ionic-full-sdk";
import {IInlineCheckout} from "@tonder.io/ionic-full-sdk/dist/types/inlineCheckout";
@Injectable({
providedIn: "root",
})
export class TonderService {
private inlineCheckout: IInlineCheckout;
constructor(@Inject(Object) private sdkParameters: IInlineCheckoutOptions) {
this.initializeInlineCheckout();
}
private initializeInlineCheckout(): void {
this.inlineCheckout = new InlineCheckout({ ...this.sdkParameters });
}
configureCheckout(customerData: IConfigureCheckout): void {
return this.inlineCheckout.configureCheckout({ ...customerData });
}
async injectCheckout(): Promise<void> {
return await this.inlineCheckout.injectCheckout();
}
async saveCard(): Promise<string> {
return await this.inlineCheckout.saveCard();
}
removeCheckout(): void {
return this.inlineCheckout.removeCheckout();
}
}// enrollment.component.ts
import { Component, OnInit, OnDestroy } from "@angular/core";
import { TonderService } from "./tonder.service";
@Component({
selector: "app-tonder-enrollment",
template: `
<div id="container">
<form id="payment-form">
<div id="tonder-checkout-enrollment"></div>
</form>
<button class="external-payment-button" (click)="onSave($event)">Guardar</button>
</div>
`,
providers: [
{
provide: TonderInlineService,
// Initialization of the Tonder Inline SDK.
// Note: Replace these credentials with your own in development/production.
useFactory: () =>
new TonderInlineService({
apiKey: "11e3d3c3e95e0eaabbcae61ebad34ee5f93c3d27",
returnUrl: "http://localhost:8100/tabs/tab1",
mode: "stage",
}),
},
],
})
export class TonderCheckoutComponent implements OnInit, OnDestroy {
loading = false;
customerData: IProcessPaymentRequest;
constructor(private tonderService: TonderService) {
this.customerData = {
customer: {
firstName: "Pedro",
lastName: "Perez",
country: "Finlandia",
street: "The street",
city: "The city",
state: "The state",
postCode: "98746",
email: "[email protected]",
phone: "+58 4169855522"
}
}
}
ngOnInit() {
this.initCheckout();
}
ngOnDestroy() {
// Clear the checkout upon destroying the component.
this.tonderService.removeCheckout();
}
async initCheckout() {
this.tonderService.configureCheckout({
customer: { email: "[email protected]" },
});
await this.tonderService.injectCheckout();
}
async onSave(event: any) {
await this.tonderService.saveCard()
}
}Deprecated Functions
The following functions have been deprecated and should no longer be used. Consider using the recommended alternatives:
setCustomerEmail
- Deprecated Reason: This function have been replaced by the
configureCheckoutfunction. - Alternative: Use the
configureCheckoutfunction.
setCartTotal
- Deprecated Reason: It is no longer necessary to use this method is now automatically handled during the payment process.
Notes
General
- Replace
apiKey,mode,returnUrlwith your actual values. - Remember to use the
configureCheckoutfunction after creating an instance ofInlineCheckout. This ensures that functions such as payment processing, saving cards, deleting cards, and others work correctly.
