npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@vindibr/wallets-sdk

v1.0.1

Published

SDK JavaScript da Vindi para Apple Pay no browser e cobranças Visa/Mastercard com o subadquirente Vindi Pagamentos.

Readme

@vindibr/wallets-sdk

SDK JavaScript da Vindi para pagamentos com Apple Pay no browser e criação de cobranças via cartão de crédito Visa e Mastercard com o subadquirente Vindi Pagamentos.

Importante para lojistas com checkout próprio:

O cadastro dos certificados de Payment Processing e Merchant Identity, além da URL da loja necessários para transações com Apple Pay, deve ser feito diretamente na área de plugins da Plataforma da Vindi. Procure seu gerente de contas para obter apoio e mais informações.

Verificação do domínio da loja

O Apple Pay verifica se o domínio em que o método de pagamento será oferecido pertence à loja. Para um domínio próprio, o lojista deve cadastrá-lo na conta Apple Developer. Se a loja usar um canal oficial de vendas da Vindi, como Shopify ou links de pagamento, entre em contato com a Vindi para receber orientação.

Para concluir a verificação do domínio:

  • Arquivo de validação: hospede no servidor o arquivo fornecido pela Apple no caminho exato .well-known/apple-developer-merchantid-domain-association.
  • HTTPS: o site deve usar uma conexão HTTPS segura, com certificado válido para o domínio.
  • Validação: os servidores da Apple acessam o arquivo no domínio para confirmar que ele pertence à loja.

Consulte Configure Apple Pay on the web na documentação da Apple.

Validade e manutenção: a verificação do domínio expira com o certificado SSL ou após 25 meses, conforme a configuração do ambiente. Para domínio próprio, cabe ao time interno manter a validação atualizada junto à Apple.

Instalação

npm install @vindibr/wallets-sdk

Esse comando instala o pacote pelo registry configurado no npm (por padrão, o registry público do npm). A instalação é a mesma para browser e servidor; /server é um subpath de import, não um pacote npm separado.

Requer Node.js 20 ou superior.

Apple Pay no browser

ApplePay.init() carrega o SDK Apple Pay, renderiza o botão e inicia o pagamento. O callback onToken recebe o token para enviar ao seu backend:

import { ApplePay, FingerPrint } from '@vindibr/wallets-sdk';

await ApplePay.init({
  button: '#apple-pay-button',
  accessKey: 'SUA_CHAVE_PUBLICA',
  environment: 'production',
  paymentMethodCode: 'credit_card_apple_pay',
  paymentForm: '#checkout-form',
  amount: { value: '99.90', currency: 'BRL' },
  holderName: 'Nome do titular',
  onToken: async ({ gatewayToken }) => {
    const fingerprint = await FingerPrint.getValue();
    const response = await fetch('/api/billing', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        paymentMethodCode: 'credit_card_apple_pay',
        customer: getCustomer(),
        billItems: getBillItems(),
        paymentProfile: { gatewayToken },
        fingerprint,
      }),
    });

    if (!response.ok) throw new Error(`Billing error: ${response.status}`);
  },
  onError: (error) => console.error('Falha no pagamento:', error),
});

getCustomer() e getBillItems() representam os dados do checkout da sua aplicação. Valide-os e recalcule os valores no backend antes de criar a cobrança. A rota /api/billing pertence à sua aplicação e deve encaminhar a requisição ao serviço de Billing no backend.

Billing no servidor

Depois da instalação acima, para usar a API de servidor sem importar a entrada de browser, importe pelo subpath /server. Use a chave privada somente no backend. VindiBillingServer oferece um endpoint HTTP simples que recebe POST /billing com paymentMethodCode, customer, billItems e paymentProfile.gatewayToken:

import { VindiBillingServer } from '@vindibr/wallets-sdk/server';

const server = new VindiBillingServer({
  accessKey: process.env.VINDI_PRIVATE_KEY,
  environment: process.env.VINDI_ENVIRONMENT ?? 'production',
});

server.listen(Number(process.env.PORT ?? 3001), '0.0.0.0');

O cliente envia a requisição ao seu backend; não exponha a chave privada nem chame esse endpoint diretamente de uma página pública sem autenticação e validação dos dados.

Ambientes

| Ambiente | Valor de environment | URL base da API | Referência | | -------- | ---------------------- | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------- | | Produção | production | https://app.vindi.com.br/api/v1/ | Swagger de produção | | Sandbox | development | https://sandbox-app.vindi.com.br/api/v1/ | Swagger de sandbox |

Essas URLs são usadas por VindiBilling no backend. Elas não são as URLs públicas /public usadas diretamente pelo Apple Pay no browser.

Guia completo de Apple Pay e Billing

Arquitetura

O Apple Pay usa a chave pública diretamente no browser. Somente a criação da cobrança usa servidor e a chave privada:

Browser
  ApplePay.init()
    -> carrega o fingerprint da Vindi (quando `paymentForm` é informado)
    -> merchant validation na API pública Vindi
    -> tokenização na API pública Vindi
    -> onToken({ gatewayToken })
    -> POST /api/billing (inclui `fingerprint`)

Servidor
  VindiBillingServer
    -> VindiBilling
    -> API privada Vindi
    -> VindiBill

Não envie a chave privada para o browser. O servidor Apple Pay (VindiApplePay) continua disponível para integrações que precisam de um proxy server-side, mas não é necessário neste fluxo.

Apple Pay no browser

O entrypoint recomendado é ApplePay.init(). Ele carrega o SDK Apple Pay, renderiza o botão e inicia a sessão quando o usuário clicar.

import { ApplePay, FingerPrint } from '@vindibr/wallets-sdk';

await ApplePay.init({
  button: '#apple-pay-button',
  accessKey: 'SUA_CHAVE_PUBLICA',
  environment: 'production',
  paymentMethodCode: 'credit_card_apple_pay',
  paymentForm: '#checkout-form',
  amount: { value: '99.90', currency: 'BRL' },
  holderName: () => document.querySelector('#holder-name').value,
  onToken: async ({ gatewayToken }) => {
    const fingerprint = await FingerPrint.getValue();

    const response = await fetch('/api/billing', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        paymentMethodCode: 'credit_card_apple_pay',
        customer: getCustomer(),
        billItems: getBillItems(),
        paymentProfile: { gatewayToken },
        fingerprint,
      }),
    });

    if (!response.ok) {
      throw new Error(`Billing error: ${response.status}`);
    }

    const bill = await response.json();
    console.log('Cobrança criada:', bill.id);
  },
  onError: (error) => {
    console.error('Falha no pagamento:', error);
  },
  onUserCancelled: () => {
    console.log('Pagamento cancelado.');
  },
  buttonOptions: {
    locale: 'pt-BR',
    type: 'buy',
    style: 'black',
  },
});

O callback onToken aceita uma Promise. A sessão Apple Pay só é concluída depois que essa Promise termina. Isso permite executar o Billing antes de informar sucesso ao Apple Pay.

Fingerprint (antifraude)

O SDK carrega o script de fingerprint da Vindi (finger_print.js), marca o formulário com o atributo técnico data-yapay="payment-form" e aciona window.yapay.FingerPrint(). Em ambientes que não são production, o SDK informa env: 'sandbox'.

Use paymentForm no ApplePay.init() ou inicialize manualmente:

import { FingerPrint } from '@vindibr/wallets-sdk';

await FingerPrint.init({
  paymentForm: '#checkout-form',
  environment: 'development',
});

const fingerprint = await FingerPrint.getValue();

Envie fingerprint na raiz do corpo do Billing; o servidor repassa o campo para a API Vindi.

Configuração

| Campo | Obrigatório | Descrição | | ------------------- | ----------- | ------------------------------------------------------------ | | button | Sim | Seletor ou elemento onde o botão será renderizado. | | accessKey | Condicional | Chave pública para chamar a API Vindi diretamente. | | backendUrl | Condicional | Use somente quando optar pelo proxy server-side Apple Pay. | | paymentMethodCode | Sim | Código do método de pagamento na Vindi. | | amount | Sim | Valor e moeda exibidos na sessão Apple Pay. | | holderName | Sim | Nome do titular, ou função que o retorna. | | paymentForm | Recomendado | Formulário de checkout para coleta antifraude (fingerprint). | | baseUrl | Não | URL pública da Vindi. Usa o ambiente padrão quando omitida. | | environment | Não | production ou development (sandbox). | | onToken | Não | Recebe o gatewayToken; pode ser assíncrono. | | onError | Não | Recebe falhas da sessão, tokenização ou callback onToken. | | onUserCancelled | Não | Chamado quando o usuário cancela o pagamento. |

Ambientes disponíveis e URLs públicas padrão:

  • production: https://app.vindi.com.br/api/v1/public
  • Sandbox (environment: 'development'): https://sandbox-app.vindi.com.br/api/v1/public

Inicialização manual

Para controlar cada etapa separadamente, use uma instância:

import { ApplePay } from '@vindibr/wallets-sdk';

const applePay = new ApplePay();

await applePay.init({
  accessKey: 'SUA_CHAVE_PUBLICA',
  paymentMethodCode: 'credit_card_apple_pay',
  onToken: ({ gatewayToken }) => {
    console.log('Token recebido:', gatewayToken);
  },
});

const button = applePay.createButton();
button.render('#apple-pay-button', {
  type: 'buy',
  style: 'black',
});

applePay.startPayment({
  amount: { value: '99.90', currency: 'BRL' },
  holderName: 'João Silva',
});

ApplePay.checkout() permanece disponível como alias deprecated de ApplePay.init() para compatibilidade.

Botão e capabilities

applePay.capabilities.isSupported();
applePay.capabilities.canMakePayments();
applePay.capabilities.canCheckout();

O botão oficial aceita type, style, width, height, borderRadius e locale.

Billing no servidor

O Billing deve rodar no backend com a chave privada:

import { VindiBilling } from '@vindibr/wallets-sdk/server';

const billing = new VindiBilling({
  accessKey: process.env.VINDI_PRIVATE_KEY,
  environment: process.env.VINDI_ENVIRONMENT,
});

const bill = await billing.createBilling({
  paymentMethodCode: 'credit_card_apple_pay',
  customer: {
    name: 'João Silva',
    email: '[email protected]',
    registryCode: '25291797002',
    phonesAttributes: [{ phoneType: 'mobile', number: '5511999999999' }],
    addressAttributes: {
      street: 'Rua A',
      number: '100',
      zipcode: '01000-000',
      neighborhood: 'Centro',
      city: 'São Paulo',
      state: 'SP',
      country: 'BR',
    },
  },
  billItems: [{ code: 'PROD001', name: 'Produto', amount: 99.9, quantity: 1 }],
  paymentProfile: { gatewayToken: 'token-recebido-do-browser' },
});

console.log(bill.id, bill.status);

O pacote também oferece VindiBillingServer para subir uma API HTTP simples de Billing:

import { VindiBillingServer } from '@vindibr/wallets-sdk/server';

const server = new VindiBillingServer({
  accessKey: process.env.VINDI_PRIVATE_KEY,
  environment: process.env.VINDI_ENVIRONMENT,
});

server.listen(Number(process.env.PORT ?? 3001), '0.0.0.0');

Ele atende POST /billing. O corpo deve conter customer, billItems, paymentMethodCode, o paymentProfile.gatewayToken recebido do provider e, quando disponível, fingerprint para antifraude.

O cliente escolhe VINDI_ENVIRONMENT como production ou development (sandbox). Não é necessário informar baseUrl em uma configuração normal.

Erros

Erros HTTP da Vindi preservam status, código, categoria, mensagem e indicação de retry:

{
  "error": {
    "name": "SDKError",
    "code": "BAD_REQUEST",
    "category": "validation",
    "message": "customer.email: formato inválido",
    "retryable": false,
    "httpStatus": 422
  }
}

No browser, trate onError. No VindiBillingServer, erros são retornados como JSON com status HTTP correspondente.

Segurança e requisitos

  • Use HTTPS para páginas que exibem Apple Pay.
  • A chave pública pode ser usada no browser.
  • A chave privada deve existir somente no backend.
  • Recalcule e valide preços e itens no backend em aplicações reais.
  • Não confie em valores enviados pelo browser como fonte final da cobrança.
  • Para produção, trate idempotência e confirmação definitiva da cobrança no backend.