@tokeflow_com/bridge-js
v2.10.0
Published
Secure payment tokenization SDK by Tokeflow
Readme
Tokeflow Bridge SDK
Secure payment tokenization SDK for the browser. Collect card details using PCI-compliant secure elements powered by Evervault.
The card data never touches your servers or ours — only secure token references are returned.
Features
- PCI-compliant - Secure iframes isolate card data
- Card Elements - Pre-built, customizable card inputs
- React Components - First-class React support with hooks
- Fully Customizable - Style elements to match your brand
- Lightweight - browser bundle ~36 KB gzipped (ESM ~24 KB gzipped)
- TypeScript - Full type definitions included
Installation
npm install @tokeflow_com/bridge-js
# or
yarn add @tokeflow_com/bridge-js
# or
bun add @tokeflow_com/bridge-jsCDN
<script src="https://unpkg.com/@tokeflow_com/bridge-js/dist/tokeflow.min.js"></script>Quick Start
Vanilla JavaScript
<form id="payment-form">
<div id="card-element"></div>
<button type="submit">Pay</button>
</form>
<script src="https://unpkg.com/@tokeflow_com/bridge-js/dist/tokeflow.min.js"></script>
<script>
const tokeflow = new Tokeflow.TokeflowBridge({
publicKey: 'pk_test_your_key',
});
async function init() {
await tokeflow.init();
const cardElement = tokeflow.createCardElement();
cardElement.mount('#card-element');
document.getElementById('payment-form').addEventListener('submit', async (e) => {
e.preventDefault();
const token = await tokeflow.cards.tokenize({ card: cardElement });
// Send token.tokenId to your server
console.log('Token:', token.tokenId);
});
}
init();
</script>React
import { TokeflowProvider, CardElement, useTokeflow } from '@tokeflow_com/bridge-js/react';
import { useRef } from 'react';
function PaymentForm() {
const { tokeflow, isReady } = useTokeflow();
const cardRef = useRef(null);
const handleSubmit = async (e) => {
e.preventDefault();
const token = await tokeflow.cards.tokenize({
card: cardRef.current.element
});
console.log('Token:', token.tokenId);
};
if (!isReady) return <div>Loading...</div>;
return (
<form onSubmit={handleSubmit}>
<CardElement ref={cardRef} id="card" />
<button type="submit">Pay</button>
</form>
);
}
export default function App() {
return (
<TokeflowProvider config={{ publicKey: 'pk_test_your_key' }}>
<PaymentForm />
</TokeflowProvider>
);
}Card Elements
Create secure, isolated inputs for card data. Tokeflow supports two layouts:
Combined card element
A single iframe collecting number, expiry, and CVC together.
const cardElement = tokeflow.createCardElement();
cardElement.mount('#card-element');
cardElement.on('change', (event) => {
console.log('Complete:', event.complete, 'Empty:', event.empty, 'Error:', event.error?.message);
});Split card fields
Three independent iframes — one each for Card Number, Expiration, and CVC. Each field is isolated in its own cross-origin iframe, so a compromised page script cannot read or rewrite values across them. This layout matches the visual standard consumers see on most Brazilian and global checkouts.
const cardNumber = tokeflow.createCardNumberElement();
const expiration = tokeflow.createCardExpirationElement();
const cvc = tokeflow.createCardCvcElement();
cardNumber.mount('#card-number');
expiration.mount('#card-expiry');
cvc.mount('#card-cvc');
const token = await tokeflow.cards.tokenize({
cardNumber,
expiration,
cvc,
cardholderName: 'João Silva',
});Brand, BIN, and last4 are detected from the Card Number field's change event:
cardNumber.on('change', (event) => {
console.log(event.value?.brand, event.value?.last4, event.value?.bin);
});Additional elements
const cardholderName = tokeflow.createCardholderNameElement();
const addressLine1 = tokeflow.createAddressLine1Element();
const city = tokeflow.createCityElement();
const postalCode = tokeflow.createPostalCodeElement();Localization
Translate the card fields' labels, placeholders, and error messages without writing
your own strings. The SDK ships 39 built-in packs that match the
Evervault translations schema:
| Region | Codes |
|---|---|
| Default packs | en (default), pt-BR |
| Europe | es fr de it nl pl ru uk tr ro el cs hu sv da nb fi |
| Middle East (right to left) | ar he fa ur |
| South Asia | hi bn mr ta te |
| East and Southeast Asia | zh (Simplified) zh-TW (Traditional) ja ko th vi id ms fil |
| Africa | sw pcm (Nigerian Pidgin) |
Pass the checkout's selected language as it is. Any language tag works: the most
specific pack wins, and a tag without a pack falls back to en. es-MX uses es,
zh-Hant-HK and zh-HK use zh-TW, zh-CN uses zh, pt-PT uses pt-BR, and the
legacy iw, in, tl and no use he, id, fil and nb.
const tokeflow = new TokeflowBridge({
publicKey: 'pk_test_xxx',
locale: checkoutLanguage, // e.g. 'es-MX'; applies to every element by default
});
// Override per element if needed:
const cardNumber = tokeflow.createCardNumberElement({
locale: 'pt-BR',
translations: {
number: {
label: 'Número do cartão',
errors: { invalid: 'Verifique o número do cartão' },
},
},
});Per-element translations win over SDK-init translations, which win over the
built-in pack. Any field you don't override falls through to the built-in strings.
The cardholder-name element follows the locale too: it shows the pack's name
placeholder unless you pass placeholder, and for a right-to-left locale it gets
dir="rtl".
Right to left. For ar, he, fa and ur the SDK lays the card fields out right
to left inside their iframes: labels and errors run right to left, and the card digits
stay left to right. Your page's dir doesn't reach inside the iframes, so there's
nothing to style there, and your own style or theme rules for the same properties
still win. Set dir on your own page with isRtlLocale:
import { isRtlLocale, resolveLocale } from '@tokeflow_com/bridge-js';
document.documentElement.dir = isRtlLocale(checkoutLanguage) ? 'rtl' : 'ltr';
resolveLocale('zh-Hant-HK'); // 'zh-TW', the pack the fields will useSUPPORTED_LOCALES lists the 39 codes.
Switching language. The fields read the locale when they are created. To change
language on a live checkout, re-create the elements with the new locale. The React
elements do this themselves when their locale prop changes.
<BoletoInstructions> and <PixAutomaticInstructions> have en and pt-BR strings:
any English tag (en-US) shows English, and any other locale shows pt-BR.
Tokenization
// Basic tokenization
const token = await tokeflow.cards.tokenize({ card: cardElement });
// With cardholder name
const token = await tokeflow.cards.tokenize({
card: cardElement,
cardholderName: 'John Doe' // or pass element
});
// With billing address
const token = await tokeflow.cards.tokenize({
card: cardElement,
cardholderName: cardholderName, // element
billingAddress: {
line1: addressLine1, // element or string
city: city, // element or string
postalCode: postalCode, // element or string
country: 'US'
}
});
// Response
// {
// tokenId: 'tok_xxx',
// type: 'card',
// brand: 'visa',
// last4: '4242',
// expiryMonth: '12',
// expiryYear: '2029',
// bin: '424242',
// createdAt: '2024-01-01T00:00:00Z'
// }Custom Metadata
const token = await tokeflow.cards.tokenize(
{ card: cardElement },
{ metadata: { orderId: 'order_123' } }
);Checkout
When your backend creates a checkout session (with its secret key), pass the
session id to the SDK as checkoutSessionId. The SDK links itself to that
checkout and can read the full checkout context — the priced items, the
selected currency, the merchant's available payment methods, and the
customer's saved cards.
const tokeflow = new TokeflowBridge({
publicKey: 'pk_test_xxx',
checkoutSessionId: 'cks_xxx', // created by your backend
});
await tokeflow.init();
const context = await tokeflow.checkout.getContext();
// {
// checkout: {
// id: 'cks_xxx',
// status: 'initiated',
// selectedCurrency: 'BRL',
// customerEmail: '[email protected]',
// items: [{ offerId: 'ofr_xxx', amount: 9900, quantity: 1, installments: 1, ... }],
// ...
// },
// paymentMethods: { cards: true, pix: true, cardBrands: ['visa', ...], installmentsSupported: true, ... },
// savedInstruments: [{ id: 'pi_xxx', brand: 'visa', last4: '4242', expMonth: 12, expYear: 2030 }],
// }The context is fetched once and cached. Call tokeflow.checkout.refresh() to
re-fetch after your backend mutates the checkout (e.g. identifies the customer
or changes items). tokeflow.checkout.getCachedContext() reads the cached copy
synchronously, without a network call.
If no checkout session is linked, getContext() rejects with a
NO_CHECKOUT_SESSION error:
import { TokeflowErrorCode } from '@tokeflow_com/bridge-js';
try {
const context = await tokeflow.checkout.getContext();
} catch (error) {
if (error.code === TokeflowErrorCode.NO_CHECKOUT_SESSION) {
// The bridge was initialized without `checkoutSessionId`.
}
}React
import { useCheckout } from '@tokeflow_com/bridge-js/react';
function CheckoutSummary() {
const { context, isLoading, error, refresh } = useCheckout();
if (error) return <p>{error.message}</p>;
if (isLoading || !context) return <p>Loading…</p>;
return (
<ul>
{context.checkout.items.map((item) => (
<li key={item.id}>{item.offerId} — {item.amount}</li>
))}
</ul>
);
}Pass checkoutSessionId in the TokeflowProvider config to use useCheckout.
Styling
Customize the appearance of card elements to match your brand. Two style APIs are available:
// Tokeflow ElementStyle (mapped to Evervault's theme under the hood)
const cardElement = tokeflow.createCardElement({
style: {
base: {
fontSize: '16px',
fontWeight: 500,
color: '#333',
padding: '12px',
':focus': { color: '#0066ff' },
'::placeholder': { color: '#999' },
},
invalid: { color: '#dc3545' },
complete: { color: '#28a745' },
},
placeholder: {
cardNumber: 'Card number',
cardExpirationDate: 'MM/YY',
cardSecurityCode: 'CVC',
},
});
// Or pass a raw Evervault theme object as an escape hatch — for full control,
// or to use one of Evervault's built-in themes.
const cardElement2 = tokeflow.createCardElement({
theme: {
styles: {
'.field input': { fontSize: 16, color: '#333' },
},
},
});
// Style text elements
const nameElement = tokeflow.createCardholderNameElement({
placeholder: 'Cardholder Name',
style: {
base: {
fontSize: '16px',
padding: '12px',
color: '#333',
fontFamily: 'Arial, sans-serif'
}
}
});Error Handling
import { TokeflowError, TokeflowErrorCode } from '@tokeflow_com/bridge-js';
try {
const token = await tokeflow.cards.tokenize({ card: cardElement });
} catch (error) {
if (error instanceof TokeflowError) {
switch (error.code) {
case TokeflowErrorCode.INVALID_CARD:
console.log('Invalid card number');
break;
case TokeflowErrorCode.EXPIRED_CARD:
console.log('Card has expired');
break;
default:
console.log(error.message);
}
}
}Configuration
const tokeflow = new TokeflowBridge({
publicKey: 'pk_test_xxx', // Required
environment: 'sandbox', // 'sandbox' or 'production'
baseUrl: 'https://api.custom.com', // Custom API URL
checkoutSessionId: 'cks_xxx', // Link to a checkout session (see Checkout)
locale: 'pt-BR', // Default locale for elements (see Localization)
timeout: 30000, // Request timeout (ms)
autoRefreshSession: true, // Refresh the session before it expires (default: true)
telemetry: true, // Sentry telemetry; set false or rely on DNT to opt out (default: on)
onError: (error) => {}, // Global error handler
onSessionCreated: (session) => {},
onSessionExpired: () => {},
});
await tokeflow.init();Documentation
For complete documentation, see:
- Integration Guide - Full integration guide with examples for every feature
- API Reference - Generated reference for every exported type, class, and function
- Examples - Working code examples
- Changelog - Release history
Test Cards
| Brand | Number | Expiry | CVC | |-------|--------|--------|-----| | Visa | 4242 4242 4242 4242 | Any future | Any 3 digits | | Mastercard | 5555 5555 5555 4444 | Any future | Any 3 digits |
Security
- ✅ Card data encrypted by Evervault before transmission
- ✅ PCI DSS compliant tokenization
- ✅ Card data never reaches your servers in plaintext
- ✅ End-to-end encryption for all sensitive data
- ✅ Public keys safe to expose in client code
- ⚠️ Never use secret keys (
sk_*) in the browser
Additional Payment Methods
PIX and boleto (Brazil)
The browser registers the payer with Tokeflow and gets a single-use token
(valid 30 minutes). Your server charges it with payer_token_id, so the
payer's CPF/CNPJ and address never pass through your server. Requires a
Tokeflow API with payer tokens (POST /v1/payer-tokens).
// PIX
const cpfElement = tokeflow.createCpfElement();
const pixToken = await tokeflow.pix.tokenize({
cpf: cpfElement, // or `document` for a CPF or CNPJ
name: 'João Silva', // element or string
email: '[email protected]', // required
});
// Boleto: only when the merchant can charge one
if (tokeflow.getAvailablePaymentMethods().includes('boleto')) {
const boletoToken = await tokeflow.boleto.tokenize({
document: cpfElement, // CPF or CNPJ
name: 'João Silva',
email: '[email protected]',
address: {
street: 'Av. Paulista', number: '1000', neighborhood: 'Bela Vista',
city: 'São Paulo', state: 'SP', postalCode: '01310-100',
},
});
}Your server sends the token on the charge and returns its
payment_instructions to the browser:
// server
await fetch('https://api.tokeflow.com/api/v1/transactions', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.TOKEFLOW_SECRET_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': `order_123-${tokenId}`,
},
body: JSON.stringify({ payment_method: 'boleto', amount: 10000, currency: 'BRL', payer_token_id: tokenId, /* ... */ }),
});// browser (React)
import { BoletoInstructions } from '@tokeflow_com/bridge-js/react';
<BoletoInstructions instructions={charge.payment_instructions} />A Pix charge that starts a subscription with Pix Automático answers with
payment_instructions.type === 'pix_automatico': a QR the payer approves
once in their bank app to authorize the recurring debits.
import { PixAutomaticInstructions } from '@tokeflow_com/bridge-js/react';
<PixAutomaticInstructions instructions={charge.payment_instructions} />Apple Pay
// Configure Apple Pay
tokeflow.applePay.configure({
merchantId: 'merchant.com.yourcompany',
merchantName: 'Your Company',
countryCode: 'US',
currencyCode: 'USD'
});
// Create payment request
const request = {
total: { label: 'Total', amount: '10.00' }
};
// Begin payment
tokeflow.applePay.beginPayment(request, {
onAuthorized: async ({ payment }) => {
const token = await tokeflow.applePay.tokenize(payment);
// Send token to server
}
});Google Pay
// Configure Google Pay
tokeflow.googlePay.configure({
merchantId: 'your-merchant-id',
merchantName: 'Your Company'
});
// Check availability
const canPay = await tokeflow.googlePay.isReadyToPay();
// Create payment request and tokenize
const paymentData = await googlePayClient.loadPaymentData(request);
const token = await tokeflow.googlePay.tokenize(paymentData);Browser Support
Chrome, Firefox, Safari, Edge (latest versions)
License
MIT © Tokeflow
