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 🙏

© 2025 – Pkg Stats / Ryan Hefner

pt-card-sdk

v1.1.1

Published

SDK para embeber formulario de tarjeta via iframe y comunicar token por postMessage

Readme

CardSDK - Payment Gateway SDK

Descripción

CardSDK es un SDK de JavaScript para integrar formularios de pago de manera segura en aplicaciones web. Utiliza iframes para mantener la seguridad de los datos de tarjetas de crédito.

Instalación

Via NPM

npm install pt-card-sdk

Via Script Tag

<script src="./dist/card-sdk.js"></script>

Uso Básico

1. Importar el SDK (si usas bundlers)

// ES6 Modules
import CardSDK from 'pt-card-sdk';

// CommonJS
const CardSDK = require('pt-card-sdk');

// AMD
define(['pt-card-sdk'], function(CardSDK) {
    // usar CardSDK
});

2. Inicializar el SDK

const sdk = new CardSDK({
    mountId: 'card-form',
    frameUrl: 'https://tu-servidor.com/sdk/demo-events',
    
    // Eventos automáticamente registrados
    onSuccess: function(data) {
        console.log('Pago exitoso:', data);
    },
    
    onError: function(error) {
        console.error('Error en el pago:', error);
    },
    
    onReady: function() {
        console.log('SDK listo');
    },
    
    onValidation: function(validation) {
        console.log('Validación:', validation);
    }
});

// Inicializar
sdk.init();

3. HTML Requerido

<div id="card-form"></div>

API del SDK

Constructor

new CardSDK(options)

Opciones

| Opción | Tipo | Requerido | Descripción | |--------|------|-----------|-------------| | mountId | string | ✅ | ID del elemento donde se montará el iframe | | frameUrl | string | ✅ | URL del iframe de pago | | onSuccess | function | ❌ | Callback para pagos exitosos | | onError | function | ❌ | Callback para errores | | onReady | function | ❌ | Callback cuando el SDK está listo | | onValidation | function | ❌ | Callback para validaciones | | onCancel | function | ❌ | Callback cuando el usuario cancela | | onTimeout | function | ❌ | Callback para timeouts | | onLoad | function | ❌ | Callback cuando el iframe se carga | | onResize | function | ❌ | Callback cuando el iframe cambia de tamaño | | * | any | ❌ | Cualquier otra propiedad se inyectará como query parameter en la URL |

Métodos

init()

Inicializa el SDK y monta el iframe en el contenedor especificado.

sdk.init();

on(eventType, callback)

Registra un listener para un evento específico.

sdk.on('customEvent', function(data) {
    console.log('Evento personalizado:', data);
});

emit(eventType, payload)

Emite un evento (principalmente para uso interno).

sdk.emit('customEvent', { message: 'Hola' });

Eventos Disponibles

Eventos Estándar

  • onSuccess: Se dispara cuando el pago se procesa exitosamente
  • onError: Se dispara cuando ocurre un error
  • onReady: Se dispara cuando el SDK está completamente inicializado
  • onValidation: Se dispara durante validaciones de formulario

Eventos Personalizados

Puedes escuchar eventos personalizados usando el método on():

sdk.on('customEvent', function(data) {
    // Manejar evento personalizado
});

Ejemplos

Ejemplo Completo

Ver examples/complete-example.html para un ejemplo completo con:

  • Inicialización del SDK
  • Manejo de eventos
  • Sistema de logs
  • Controles de destrucción

Ejemplo con AngularJS

Ver examples/angularjs-example.html para integración con AngularJS.

Ejemplo con Parámetros

const sdk = new CardSDK({
    mountId: 'card-form',
    frameUrl: 'https://tu-servidor.com/sdk/demo-events',
    
    // Parámetros que se inyectarán automáticamente en la URL
    userId: '12345',
    sessionId: 'abc-def-ghi-jkl',
    theme: 'dark',
    language: 'es',
    customData: 'valor-personalizado',
    
    onSuccess: function(data) {
        console.log('Pago exitoso:', data);
    },
    
    onError: function(error) {
        console.error('Error:', error);
    }
});

sdk.init();
// La URL final será: https://tu-servidor.com/sdk/demo-events?userId=12345&sessionId=abc-def-ghi-jkl&theme=dark&language=es&customData=valor-personalizado

Ejemplo con Webpack

import CardSDK from 'pt-card-sdk';

class PaymentComponent {
    constructor() {
        this.sdk = null;
    }
    
    initPayment() {
        this.sdk = new CardSDK({
            mountId: 'payment-container',
            frameUrl: process.env.PAYMENT_IFRAME_URL,
            onSuccess: (data) => this.handleSuccess(data),
            onError: (error) => this.handleError(error)
        });
        
        this.sdk.init();
    }
    
    handleSuccess(data) {
        // Redirigir o mostrar mensaje de éxito
    }
    
    handleError(error) {
        // Mostrar mensaje de error
    }
}

Desarrollo

Estructura del Proyecto

sdk/
├── src/
│   └── index.js          # Código fuente principal
├── dist/
│   └── card-sdk.js       # Build compilado
├── examples/
│   ├── complete-example.html
│   └── angularjs-example.html
├── package.json
├── webpack.config.js
└── README.md

Comandos de Desarrollo

# Instalar dependencias
npm install

# Compilar el SDK
npm run build

# Publicar a NPM
npm publish

Build

El SDK se compila usando Webpack con configuración UMD, lo que permite su uso en:

  • Navegadores (script tag)
  • Node.js (CommonJS)
  • Bundlers (ES6 modules)
  • AMD (RequireJS)

Seguridad

  • El SDK utiliza iframes para mantener los datos de pago aislados
  • Toda comunicación se realiza via postMessage
  • Los datos sensibles nunca tocan el DOM principal
  • Validación de origen en todos los mensajes

Compatibilidad

  • ✅ Chrome 60+
  • ✅ Firefox 55+
  • ✅ Safari 12+
  • ✅ Edge 79+
  • ✅ IE 11 (con polyfills)

Troubleshooting

Error: "No se encontró el contenedor"

Asegúrate de que el elemento con el mountId especificado existe en el DOM antes de llamar init().

Error: "CardSDK is not a constructor"

Si usas bundlers, asegúrate de importar correctamente:

// ✅ Correcto
import CardSDK from 'pt-card-sdk';

// ❌ Incorrecto
import { CardSDK } from 'pt-card-sdk';

El iframe no se carga

Verifica que:

  1. La frameUrl sea correcta y accesible
  2. No haya problemas de CORS
  3. El servidor esté ejecutándose

Changelog

v0.1.2

  • ✅ Corregido problema de exportación con bundlers
  • ✅ Mejorado sistema de eventos
  • ✅ Agregado soporte para eventos automáticos en constructor
  • ✅ Documentación actualizada

v0.1.1

  • ✅ Versión inicial
  • ✅ Soporte básico para iframes
  • ✅ Sistema de eventos simple

Licencia

MIT License

Soporte

Para reportar bugs o solicitar features, por favor crea un issue en el repositorio del proyecto.