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

payment-checkout-sdk-another-implementation

v0.1.0

Published

A seamless checkout library built with React and Vite.

Readme

Building a library like react-stripe-js requires abstracting complex native SDK interactions into simple, reusable React components and hooks, while ensuring a seamless user experience. This involves creating a Provider to initialize the library, hooks (useElements, useClient) to access the initialized instance, and components (CardElement, PaymentRequestButtonElement) to securely render payment fields via iframes. Below is a conceptual outline and an example of how you might structure the core components of such a library.

Library Architecture

The library revolves around a central PaymentGatewayProvider that initializes the underlying non-React SDK and a custom React context to expose that instance to all child components and hooks. This mimics the architecture of most professional payment gateway SDKs.

1. Core Hooks and Context (src/context.js)

This manages the React context for sharing the initialized gateway instance (clientInstance) and element management utilities.

import React, { createContext, useContext, useState, useEffect } from 'react';

const PaymentGatewayContext = createContext(null);

export const PaymentGatewayProvider = ({ children, clientKey }) => {
  const [clientInstance, setClientInstance] = useState(null);
  const [elements, setElements] = useState(null);

  useEffect(() => {
    // In a real library, you would load an external JS SDK here
    // e.g., const gatewaySDK = loadExternalSDK(clientKey);
    // setClientInstance(gatewaySDK);
    // setElements(gatewaySDK.elements());

    // Mock implementation for demonstration:
    const mockGateway = {
        elements: () => ({
            create: (type, options) => ({
                mount: (domElement) => console.log(`Mounting ${type} to ${domElement.id}`),
                on: (event, handler) => console.log(`Listening for ${event}`),
                // Mock methods for confirm calls
                confirmCardPayment: async (clientSecret, paymentMethod) => ({
                    paymentIntent: { status: 'succeeded' }
                })
            })
        }),
        confirmCardPayment: async (clientSecret, options) => ({
            paymentIntent: { status: 'succeeded' }
        })
    };
    setClientInstance(mockGateway);
    setElements(mockGateway.elements());
  }, [clientKey]);

  return (
    <PaymentGatewayContext.Provider value={{ clientInstance, elements }}>
      {children}
    </PaymentGatewayContext.Provider>
  );
};

export const useClient = () => useContext(PaymentGatewayContext).clientInstance;
export const useElements = () => useContext(PaymentGatewayContext).elements;

2. Generic Element Component (src/Element.js)

This reusable component renders a generic payment field securely within an iframe and manages its lifecycle.

import React, { useRef, useEffect, useState } from 'react';
import { useElements } from './context';

export const Element = ({ id, type, options, onChange }) => {
  const elements = useElements();
  const elementRef = useRef(null);
  const [elementInstance, setElementInstance] = useState(null);

  useEffect(() => {
    if (elements && elementRef.current) {
      const element = elements.create(type, options);
      element.mount(elementRef.current);
      if (onChange) {
        element.on('change', onChange);
      }
      setElementInstance(element);
    }
  }, [elements, options, type, onChange]);

  // Clean up element on unmount
  useEffect(() => {
    return () => {
        if (elementInstance) {
            elementInstance.destroy();
        }
    };
  }, [elementInstance]);

  return <div id={id} ref={elementRef} />;
};

3. Specific Payment Method Components (src/CardElement.js)

You create specific components for different payment methods as simple wrappers around the generic Element.

import React from 'react';
import { Element } from './Element';

export const CardElement = (props) => (
  <Element id="card-element" type="card" {...props} />
);

Usage Example (src/App.js or Merchant App)

The merchant using your library would integrate it like this:

import React, { useState } from 'react';
import { PaymentGatewayProvider, CardElement, useClient, useElements } from './context'; // from 'your-gateway-library'

const CheckoutForm = () => {
  const client = useClient();
  const elements = useElements();
  const [loading, setLoading] = useState(false);
  const [status, setStatus] = useState('');

  const handleSubmit = async (event) => {
    event.preventDefault();
    setLoading(true);

    if (!client || !elements) {
      return;
    }
    
    // Get a reference to a mounted element
    const cardElement = elements.create('card'); // In a real app, you'd use the instance from the ref/state

    // Use the client library to confirm the payment
    const result = await client.confirmCardPayment('MOCK_CLIENT_SECRET_FROM_BACKEND', {
      payment_method: {
        card: cardElement,
        billing_details: { name: 'John Doe' },
      },
    });

    if (result.error) {
      setStatus(`Error: ${result.error.message}`);
    } else {
      setStatus(`Payment status: ${result.paymentIntent.status}`);
    }
    setLoading(false);
  };

  return (
    <form onSubmit={handleSubmit} style={{ padding: '20px', border: '1px solid #ccc' }}>
      <label>
        Card Details
        {/* The CardElement securely renders the iframe */}
        <CardElement onChange={(event) => console.log('Element changed:', event.complete)} />
      </label>
      <button type="submit" disabled={loading} style={{ marginTop: '15px' }}>
        {loading ? 'Processing...' : 'Pay'}
      </button>
      <p>{status}</p>
    </form>
  );
};


const MerchantApp = () => {
  return (
    // Initialize the provider with the merchant's key
    <PaymentGatewayProvider clientKey="pk_test_MERCHANT_KEY">
      <h1>My Store Checkout</h1>
      <CheckoutForm />
    </PaymentGatewayProvider>
  );
};

// export default MerchantApp;