npm package: @royaltics/pay-reactjs
Description: Official React SDK for Royaltics Pay integration
Author: Royaltics
Latest version: 0.1.3

# @royaltics/pay-reactjs

Official React SDK for Royaltics Pay integration. Easily accept payments in your React applications with a complete, secure, and customizable checkout experience.

## Installation

```bash
pnpm add @royaltics/pay-reactjs
# or
npm install @royaltics/pay-reactjs
# or
yarn add @royaltics/pay-reactjs
```

## Quick Start

Import the `RoyalticsPay` component and the CSS styles.

```tsx
import { RoyalticsPay } from '@royaltics/pay-reactjs';
import '@royaltics/pay-reactjs/dist/index.css'; // Make sure to import styles

function App() {
  return (
    <div className="App">
       <RoyalticsPay
          workspaceId="YOUR_WORKSPACE_ID"
          applicationId="YOUR_APPLICATION_ID"
          authToken="YOUR_AUTH_TOKEN"
          baseUrl="http://localhost/v2" 
          orderData={{
            subtotal: 100.00,
            tax_percent: 15,
            currency: 'USD',
            resolved_url: "http://localhost/checkout/rpay/", //Optional
            reject_url: "http://localhost/checkout/rpay/", //Optional
            intent: 'BUY',
            description: 'Order #1234',
            customer: {
              names: 'John Doe',
              email: 'john@example.com',
              cardid: '1234567890',
              country_id: 1,
              city_id: 1,
              province_id: 1,
              address: '123 Main St',
              mobile: '555-0123'
            }
          }}
          onSuccess={(data) => console.log('Success:', data)}
          onError={(error) => console.error('Error:', error)}
        />
    </div>
  );
}
```

## Configuration (Props)

| Prop | Type | Required | Description |
|------|------|----------|-------------|
| `workspaceId` | string | Yes | Your Royaltics Workspace ID. |
| `applicationId` | string | Yes | Your Application ID. |
| `authToken` | string | Yes | Authentication token for the session. |
| `baseUrl` | string | Yes | Base URL for the Royaltics API (e.g., `https://api.royaltics.com/v2`). |
| `orderData` | object | Yes | Details of the order (amount, customer, description, etc.). |
| `onSuccess` | function | Yes | Callback fired when payment is completed successfully. |
| `onError` | function | Yes | Callback fired when an error occurs. |
| `onCancel` | function | No | Callback fired when the user closes the modal without paying. |
| `theme` | object | No | Custom styling ({ `primaryColor`, `borderRadius`, `fontFamily` }). |
| `locale` | string | No | Language for the UI ('en' or 'es'). |

### OrderData Structure

```typescript
interface OrderData {
  subtotal: number;
  tax_percent: number; // e.g., 12 for 12%
  currency: string;    // 'USD', etc.
  intent: 'REGISTER' | 'BUY' | 'RENEWAL' | ...;
  description: string;
  customer: {
    names: string;
    email: string;
    cardid: string; // ID document number
    // ... address fields
  };
  // ...
}
```

## Handling Redirect Callbacks

Some payment methods (like Credit Cards via 3D Secure or specialized gateways) require redirecting the user to a secure page. @royaltics/pay-reactjs handles this by opening a popup.

**You must create a route in your application to handle the callback from this popup.**

1. **Callback Route**: Create a route (e.g., `/checkout/callback`) in your app.
2. **Logic**: This route should capture the URL parameters and send them back to the main window using `window.postMessage`.

### Example `CallbackPage` Implementation

```tsx
import React, { useEffect } from 'react';

export const CallbackPage = () => {
  useEffect(() => {
    // 1. Get query parameters
    const params = new URLSearchParams(window.location.search);
    const data: Record<string, string> = {};
    params.forEach((value, key) => {
      data[key] = value;
    });

    // 2. Construct message
    const message = {
      type: 'PAYMENT_CALLBACK',
      params: data
    };

    // 3. Send to opener (the main checkout window)
    if (window.opener) {
      window.opener.postMessage(message, '*');
      window.close(); // Close the popup
    }
  }, []);

  return (
    <div style={{ textAlign: 'center', marginTop: '50px' }}>
      <h2>Verifying Payment...</h2>
      <p>Please wait a moment.</p>
    </div>
  );
};
```

## Security & Server Verification

> [!WARNING]
> **Never trust the client-side `onSuccess` callback alone.**

When `onSuccess` is triggered:
1. It receives a payload with `payment_id`, `gateway_status`, etc.
2. **Send this `payment_id` to your backend.**
3. Your backend should verify the transaction status with the Royaltics API to confirm the payment is actually **APPROVED** and the amount matches.

This prevents users from manipulating client-side code to fake a successful payment.

## License

MIT