Vite + React Donation Page Example

This guide walks through implementing a donation page using TodaQ’s micropayment system integrated into a Vite + React + TypeScript application. The page loads payment elements via npm package and handles payment success events with React Router navigation. You can find the public repo here.

Reminder:

Prerequisites

1. Install Dependencies

Install the TodaQ Micro Payment Package and other necessary dependencies. This guide needs payment-js 0.5.5 or later:

npm install @todaqmicro/payment-js
npm install react-router-dom

2. Vite Configuration

No extra configuration is needed. The vite.config.ts that the react-ts template creates works for both npm run dev and npm run build:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
})

3. Environment Variables

Create a .env file in your project root with your payment configuration:

VITE_TODAQ_PUBLIC_SECRET=your_public_secret_here
VITE_TODAQ_HASH_5=your_commodity_hash_for_5_dollars
VITE_TODAQ_HASH_05=your_commodity_hash_for_50_cents
VITE_TODAQ_HASH_005=your_commodity_hash_for_5_cents

Security Note:

4. Implementation Details

React useEffect Hook

React useEffect hook - equivalent to DOM Content Loaded in TRIE site implementation guide:

import { loadMicroPayments } from "@todaqmicro/payment-js";

useEffect(() => {
  const initialize = async () => {
    try {
      const micro = await loadMicroPayments(
        import.meta.env.VITE_TODAQ_PUBLIC_SECRET, // Merchant ID | public secret
        {
          apiVersion: "main", // API version
        }
      );
      setMicro(micro);
    } catch (error) {
      console.error("Failed to initialize payment engine:", error);
    } finally {
      setLoading(false);
    }
  };
  initialize();
}, []);

loadMicroPayments() Function

Returns promise that resolves to a micro object containing the payment engine instance:

const micro = await loadMicroPayments(
  import.meta.env.VITE_TODAQ_PUBLIC_SECRET, // Merchant ID | public secret
  {
    apiVersion: "main", // API version
  }
);

elements() Method

Returns an elements object with methods to create different payment UI components:

const elements = micro.elements();

Payment Element Initialization

The script creates three payment elements with different amounts using environment variables.

Donation Element:

const element = await elements.create('payment', {
  hash, 
  theme: 'light',
  styles: {
    colorPrimary: "#000000",
    colorBackground: "#a39f96ff",
    borderRadius: "1rem",
  },
});
const container = document.getElementById(containerId);
// create() resolves to null when the hash cannot be loaded
if (element && container) element.mount(container);

To create multiple payment elements, dynamically generate unique container IDs using a hash like this::

const containerId = `payment-element-container-${hash}`;

The donation element then repeats for $0.50 and $0.05 - each uses different hashes from environment variables, and retains identical styling for consistency.

Payment Event Handling

payment-js dispatches a payment event on document when a payment completes. One listener fires for all three buttons, so read event.detail.hash to tell which donation was paid:

const HASH_5 = import.meta.env.VITE_TODAQ_HASH_5;
const HASH_05 = import.meta.env.VITE_TODAQ_HASH_05;
const HASH_005 = import.meta.env.VITE_TODAQ_HASH_005;

const AMOUNTS: Record<string, number> = {
  [HASH_5]: 5.0,
  [HASH_05]: 0.5,
  [HASH_005]: 0.05,
};

useEffect(() => {
  const onPayment = (event: Event) => {
    // event.detail: { hash, hostname, nonce, timestamp }
    const { hash } = (event as CustomEvent<{ hash: string }>).detail;
    const amount = AMOUNTS[hash];
    if (amount !== undefined) {
      navigate(`/thank-you?amount=${amount}`); // Redirect to thank you page for the amount paid
    }
  };
  document.addEventListener("payment", onPayment);
  return () => document.removeEventListener("payment", onPayment);
}, [navigate]);

A redirect to a thank-you page is enough here because a donation delivers nothing. A site that hands over something in return for a payment must first confirm the payment on its server: see Confirm each payment on your server.

PaymentButton Component Props Usage in Donation Page

The PaymentButton component receives props from Donation.tsx with environment variables and configuration:

<PaymentButton
  amount={5.0}
  hash={HASH_5}
  engine={micro}
  title="Grand Benefactor"
  description="Depollution of the Shades of Pembereley"
  buttonClass="is-success"
/>

5. Key Implementation Patterns

  1. Environment Variables: All payment configuration uses environment variables (this is based on preference as trie.site does not use them)

    • VITE_TODAQ_PUBLIC_SECRET - for merchant/user identification
    • VITE_TODAQ_HASH_* for unique payment identifiers
  2. Initialization Flow:

    • Wait for component mount with useEffect
    • Initialize MicroPayments with merchant public secret from environment
    • Create elements with unique hashes from environment variables
    • Mount elements to specific containers
  3. Event Handling:

    • Listens for global payment events, which fire for any of the page’s buttons
    • Looks up the amount from event.detail.hash and redirects to the thank-you page with it
  4. Styling Consistency:

    • Black text on light background
    • Rounded borders (borderRadius: "1rem")
    • Light theme

6. Considerations

7. Dependencies

This implementation guide demonstrates the core concepts covered in the Getting Started guide, showing how to integrate multiple payment options with consistent styling and proper event handling in a modern Vite + React + TypeScript application.