Referência da API do SDK
A classe TokeflowBridge, opções de configuração, módulos, fábricas de elementos e tipos TypeScript exportados do Bridge SDK.
Esta página é a referência de nível superficial para @tokeflow_com/bridge-js. Para guias orientados a tarefas, consulte
Início rápido, Elements, Tokenização e
Métodos de pagamento.
O SDK inclui definições TypeScript completas — cada tipo abaixo é importável.
TokeflowBridge
O ponto de entrada principal. Crie uma instância por checkout, chame init(), crie elementos e então tokenize.
class TokeflowBridge {
constructor(config: TokeflowBridgeConfig);
init(): Promise<void>; // creates a session and loads the secure elements runtime
destroy(): void; // tears down the bridge and releases all resources
// Session & capabilities (synchronous getters; valid after init())
getSession(): Session | null;
getCapabilities(): Capabilities | null;
getSessionSettings(): SessionSettings | null;
getAvailablePaymentMethods(): AvailablePaymentMethod[];
// Element factories
createCardElement(options?: CardElementOptions): TokeflowCardElement;
createCardNumberElement(options?): TokeflowCardNumberElement;
createCardExpirationElement(options?): TokeflowCardExpirationElement;
createCardCvcElement(options?): TokeflowCardCvcElement;
createCardholderNameElement(options?): TokeflowCardholderNameElement;
createTextElement(options?): TokeflowTextElement;
createCpfElement(options?): TokeflowCpfElement;
createAddressLine1Element(options?): TokeflowAddressLine1Element;
createAddressLine2Element(options?): TokeflowAddressLine2Element;
createCityElement(options?): TokeflowCityElement;
createStateElement(options?): TokeflowStateElement;
createPostalCodeElement(options?): TokeflowPostalCodeElement;
createCountryElement(options?): TokeflowCountryElement;
createApplePayButton(options?): TokeflowApplePayButton;
createGooglePayButton(options?): TokeflowGooglePayButton;
// Modules
cards: Cards;
pix: Pix;
boleto: Boleto;
applePay: ApplePay;
googlePay: GooglePay;
checkout: Checkout;
sessionManager: SessionManager;
}Ciclo de vida
import { TokeflowBridge } from '@tokeflow_com/bridge-js';
const tokeflow = new TokeflowBridge({ publicKey: 'pk_live_mer_xxxxxxxx' });
await tokeflow.init(); // 1. initialize
const card = tokeflow.createCardElement(); // 2. create
card.mount('#card-element'); // 3. mount
const token = await tokeflow.cards.tokenize({ card }); // 4. tokenize
// 5. send token.tokenId to your backend to charge
tokeflow.destroy(); // 6. clean up when doneTokeflowBridgeConfig
| Opção | Type | Obrigatório | Padrão | Descrição |
|---|---|---|---|---|
publicKey | string | Sim | — | Sua chave pública Tokeflow (pk_test_* ou pk_live_*). Seguro para expor no navegador. |
environment | 'sandbox' | 'production' | Não | Auto | Detectado automaticamente a partir da chave (pk_test_* → sandbox, pk_live_* → production). |
brandName | string | Não | — | Nome da marca do Merchant exibido em algumas telas de UI hospedadas. |
checkoutSessionId | string | Não | — | Vincula o bridge a uma sessão de checkout criada no backend. |
locale | TokeflowLocale | Não | 'en' | Locale padrão para todos os elementos. Consulte Localização. |
translations | Partial<TokeflowTranslations> | Não | — | Sobrescreve as strings de tradução integradas. |
elementOptions | { style?: ElementStyle; fonts?: string[] } | Não | — | Estilização/fontes padrão aplicadas a cada elemento. |
sessionTTL | number | Não | Definido pelo servidor | Tempo de vida solicitado da sessão em segundos. |
autoRefreshSession | boolean | Não | true | Renova a sessão automaticamente antes de ela expirar. |
timeout | number | Não | 30000 | Tempo limite da requisição em milissegundos. |
telemetry | boolean | TelemetryOptions | Não | true | Telemetria anônima de erros. Defina false para desativar; também é desativada automaticamente quando o navegador envia Do-Not-Track. |
onSessionCreated | (session: Session) => void | Não | — | Chamado quando uma sessão é criada. |
onSessionExpired | () => void | Não | — | Chamado quando a sessão expira. |
onError | (error: TokeflowError) => void | Não | — | Manipulador global de erros. |
const tokeflow = new TokeflowBridge({
publicKey: 'pk_live_mer_xxxxxxxx',
locale: 'pt-BR',
timeout: 15000,
onError: (error) => console.error(error.code, error.message),
onSessionCreated: (session) => console.log('Session:', session.id),
});A telemetria é anônima e higienizada. Quando ativada, o SDK reporta seus próprios erros internos para ajudar
a Tokeflow a melhorar a confiabilidade. Um higienizador com política de falha segura (fail-closed) remove quaisquer identificadores relevantes para pagamento (número do cartão,
validade, CVC, nome do titular do cartão, e-mail, CPF, endereço de cobrança) antes de qualquer coisa ser enviada, e ele nunca interfere em uma configuração
de monitoramento de erros ou de analytics que você execute no seu próprio app. Desative-a por completo com telemetry: false.
interface TelemetryOptions {
enabled?: boolean;
sampleRate?: number; // 0..1
environment?: string; // defaults from the key
release?: string; // defaults to the SDK version
}Módulos
| Módulo | Acessor | Propósito |
|---|---|---|
Cards | tokeflow.cards | Tokeniza dados de cartão. Consulte Tokenização. |
Pix | tokeflow.pix | Registra um pagador de PIX e obtém um token de pagador (Brasil). Veja PIX. |
Boleto | tokeflow.boleto | Registra um pagador de boleto e o endereço de cobrança e obtém um token de pagador (Brasil, SDK 2.8.0+). Veja Boleto. |
ApplePay | tokeflow.applePay | Configuração, verificações de suporte e tokenização do Apple Pay. |
GooglePay | tokeflow.googlePay | Configuração, verificações de prontidão e tokenização do Google Pay. |
Checkout | tokeflow.checkout | Lê o contexto de checkout vinculado. Consulte Contexto de checkout. |
SessionManager | tokeflow.sessionManager | Inspeciona e renova a sessão subjacente. |
Módulo Cards
class Cards {
tokenize(
input:
| TokeflowCardElement
| { card: TokeflowCardElement; cardholderName?: TokeflowCardholderNameElement | string; billingAddress?: BillingAddressInput }
| { cardNumber: TokeflowCardNumberElement; expiration: TokeflowCardExpirationElement; cvc: TokeflowCardCvcElement; cardholderName?: TokeflowCardholderNameElement | string; billingAddress?: BillingAddressInput },
options?: TokenizeOptions
): Promise<CardToken>;
}Interface de elemento (todos os elementos)
interface TokeflowElement<TOptions = unknown> {
mount(target: string | HTMLElement): void;
unmount(): void;
update(options: TOptions): void;
focus(): void;
blur(): void;
clear(): void;
setValue(value: string): void; // text-style elements only
getState(): ElementState;
on(event: ElementEvent, handler: EventHandler): void;
off(event: ElementEvent, handler?: EventHandler): void;
}Consulte Elements para o catálogo completo, opções e eventos.
Tipos exportados
import {
TokeflowBridge,
TokeflowError,
TokeflowErrorCode,
TokeflowCardElement,
} from '@tokeflow_com/bridge-js';
import type {
TokeflowBridgeConfig,
Session,
CardToken,
PixToken,
BoletoToken,
PixTokenizeParams,
BoletoTokenizeParams,
PaymentInstructions,
PixInstructions,
BoletoInstructions,
AvailablePaymentMethod,
TokenizeOptions,
TokenPurpose,
ElementStyle,
ElementState,
ElementChangeEvent,
CardElementOptions,
CheckoutContext,
TelemetryOptions,
} from '@tokeflow_com/bridge-js';
// React types
import type {
CardElementRef,
CardNumberElementRef,
CardExpirationElementRef,
CardCvcElementRef,
} from '@tokeflow_com/bridge-js/react';Suporte a navegadores
O SDK tem como alvo as versões atuais do Chrome, Firefox, Safari e Edge.
Relacionados
- Tratamento de erros —
TokeflowErrore a tabela completa de códigos de erro - Integração com React — provider, hooks e componentes
- Tokenização — entrada/saída de
cards.tokenize()