---
updatedAt: 2026-04-13T15:55:27.000Z
agentTools:
  projectIndex: https://docs.nmi.com/llms.txt
---

# Payment Component Frontend

```javascript React
import { NmiPayments } from '@nmipayments/nmi-pay-react';
import { useState } from 'react';

function PaymentForm() {

  const [amount, setAmount] = useState('10.99');
  const [paymentStatus, setPaymentStatus] = useState('');
  
  return (
    <div>

      <div className="form-row">
        <label htmlFor="amount">Amount:</label>
        <input
          id="amount"
          type="text"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
        />
      </div>
      
      {paymentStatus && (
        <div className={paymentStatus === true ? 'success' : 'error'}>
          {typeof paymentStatus === 'string' ? paymentStatus : 'Payment successful!'}
        </div>
      )}
      
      <NmiPayments 
        tokenizationKey="YOUR_PUBLIC_KEY_HERE"
        onPay={async (token) => {

          try {
            // Send token to your server
            const response = await fetch('/api/process-payment', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                paymentToken: token,
                amount: parseFloat(amount)
              }),
            });
            
            // Process the response
            const data = await response.json();
            setPaymentStatus(data.success ? true : data.error || 'Payment failed');
            return data.success ? true : data.error || 'Payment failed';
          } catch (err) {
            // Handle errors
            const errorMessage = err instanceof Error ? err.message : 'An error occurred';
            setPaymentStatus(errorMessage);
            return errorMessage;
          }
        }}
      />
    </div>
  );
}
```

```javascript JavaScript
// 1. Add the HTML container
<div id="payment-container"></div>

// 2. JavaScript implementation
import { mountNmiPayments } from '@nmipayments/nmi-pay';

// 3. Initialize the payment component
document.addEventListener('DOMContentLoaded', async function() {
  try {
    // 4. Mount the payment widget
    const widget = mountNmiPayments('#payment-container', {
      tokenizationKey: 'q2U4fW-DubpT2-98Zng2-aKeqaG',
      
      // 5. Handle payment submission
      onPay: async (token) => {
        try {
          // 6. Send token to your server
          const response = await fetch('/api/process-payment', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              paymentToken: token,
              amount: 10.99 // Replace with your amount
            }),
          });
          
          // 7. Process the response
          const data = await response.json();
          if (data.success) {
            console.log('Payment successful!');
            return true;
          } else {
            console.error('Payment failed:', data.error);
            return data.error || 'Payment failed';
          }
        } catch (err) {
          // 8. Handle errors
          console.error('Payment error:', err.message);
          return err.message || 'An error occurred';
        }
      }
    });
    
    console.log('Payment widget loaded successfully');
  } catch (error) {
    console.error('Error loading payment widget:', error);
  }
});
```

```json Response Example
{"success":true}
```

# Import the npm-pay-react component

<!-- javascript@1 -->
<!-- javascript@ -->



# Create your payment form component

<!-- javascript@4 -->
<!-- javascript@ -->



# Setup state for amount and payment status

<!-- javascript@6,7 -->
<!-- javascript@ -->



# Link payment amount

<!-- javascript@12-20 -->
<!-- javascript@ -->

Set the desired payment amount.  In this example we are allowing it to be set via input field but you will want to link it to your applications logic.

# Status message display

<!-- javascript@22-26 -->
<!-- javascript@ -->

Example of how to show result of payment component.

# Add the NmiPayments component

<!-- javascript@28,29 -->
<!-- javascript@ -->

tokenizationKey must be set to your merchant's public key. 

# Process payment

<!-- javascript@30-52 -->
<!-- javascript@ -->

onPay is called once the payment data has been tokenized.   The transaction has not yet been processed.   To complete processing you will need to send the token to your backend which will need to integrate with the payment processing endpoint.