npm package: @rajatsinha2343/secure_pay
Description: checkout SDK — lightweight, easy integration.
Latest version: 1.0.0

# @rajatsinha2343/secure_pay

Razorpay-style overlay checkout SDK — payment **same screen par overlay** mein open hota hai, new tab nahi. Secure, lightweight, aur easy integration.

## Features

- ✅ **Overlay checkout** — Same screen par, new tab nahi
- ✅ **Lightweight** — ~5KB minified
- ✅ **No dependencies** — Pure JavaScript
- ✅ **Easy integration** — 2 lines of code
- ✅ **Secure** — postMessage communication
- ✅ **Mobile responsive** — Works on all devices

## Installation

```bash
npm install @rajatsinha2343/secure_pay
```

## Quick Setup

### Step 1: Install Package

```bash
npm install @rajatsinha2343/secure_pay
```

### Step 2: Include SDK

**Option A: Script Tag (Simple HTML)**

```html
<!-- From node_modules -->
<script src="/node_modules/@rajatsinha2343/secure_pay/dist/payment-gateway.js"></script>

<!-- Or from CDN (after publish) -->
<script src="https://unpkg.com/@rajatsinha2343/secure_pay@1/dist/payment-gateway.js"></script>
```

**Option B: Bundler (Webpack/Vite/Next.js)**

```javascript
// In your component or entry file
import '@rajatsinha2343/secure_pay/dist/payment-gateway.js';

// Or if bundler supports it:
import '@rajatsinha2343/secure_pay';
```

### Step 3: Use in Your Code

```html
<button onclick="openPayment()">Pay ₹500</button>

<script>
  function openPayment() {
    // Get payment URL from your backend
    var paymentUrl = 'https://YOUR_GATEWAY_DOMAIN/pay/pay_xxx_secret_xxx';
    
    PaymentGateway.open({
      paymentUrl: paymentUrl,
      onSuccess: function(data) {
        console.log('Payment successful!', data);
        // data: { orderId, amount, currency, verifiedAt, returnUrl }
        // Handle success - redirect, show message, etc.
      },
      onFailure: function(data) {
        console.log('Payment failed/closed', data);
        // data: { orderId, message } or { reason: 'expired' }
        // Handle failure
      },
      onClose: function() {
        console.log('User closed overlay');
        // Handle close
      }
    });
  }
</script>
```

## Complete Example

### HTML + JavaScript

```html
<!DOCTYPE html>
<html>
<head>
  <title>Payment Demo</title>
</head>
<body>
  <h1>My Store</h1>
  <button id="payBtn">Pay ₹500</button>
  
  <!-- Include SDK -->
  <script src="/node_modules/@rajatsinha2343/secure_pay/dist/payment-gateway.js"></script>
  
  <script>
    document.getElementById('payBtn').onclick = function() {
      // Step 1: Get payment URL from your backend API
      fetch('/api/create-payment', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ amount: 500 })
      })
      .then(res => res.json())
      .then(data => {
        // Step 2: Open payment overlay
        PaymentGateway.open({
          paymentUrl: data.paymentUrl, // e.g. https://gateway.com/pay/pay_xxx_secret_xxx
          onSuccess: function(result) {
            alert('Payment successful! Order: ' + result.orderId);
            // Redirect or update UI
            window.location.href = '/success';
          },
          onFailure: function(error) {
            alert('Payment failed: ' + (error.message || error.reason));
          },
          onClose: function() {
            console.log('User closed payment');
          }
        });
      })
      .catch(err => {
        console.error('Error:', err);
      });
    };
  </script>
</body>
</html>
```

### React Example

```jsx
import { useEffect } from 'react';
import '@rajatsinha2343/secure_pay/dist/payment-gateway.js';

function PaymentButton() {
  const handlePayment = async () => {
    // Get payment URL from backend
    const response = await fetch('/api/create-payment', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ amount: 500 })
    });
    const data = await response.json();
    
    // Open payment overlay
    window.PaymentGateway.open({
      paymentUrl: data.paymentUrl,
      onSuccess: (result) => {
        console.log('Success:', result);
        // Handle success
      },
      onFailure: (error) => {
        console.log('Failed:', error);
        // Handle failure
      }
    });
  };
  
  return <button onClick={handlePayment}>Pay ₹500</button>;
}
```

### Next.js Example

```jsx
// pages/payment.js or app/payment/page.jsx
import { useEffect } from 'react';

export default function PaymentPage() {
  useEffect(() => {
    // Load SDK
    const script = document.createElement('script');
    script.src = '/node_modules/@rajatsinha2343/secure_pay/dist/payment-gateway.js';
    script.onload = () => {
      console.log('SDK loaded');
    };
    document.body.appendChild(script);
    
    return () => {
      document.body.removeChild(script);
    };
  }, []);
  
  const handlePayment = () => {
    window.PaymentGateway.open({
      paymentUrl: 'https://YOUR_GATEWAY/pay/pay_xxx_secret_xxx',
      onSuccess: (data) => {
        console.log('Success:', data);
      }
    });
  };
  
  return <button onClick={handlePayment}>Pay Now</button>;
}
```

## API Reference

### `PaymentGateway.open(options)` or `PaymentGateway.open(paymentUrl)`

Opens payment overlay.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `paymentUrl` | string | Yes | Full payment link from your gateway |
| `onSuccess` | function | No | Called when payment succeeds |
| `onFailure` | function | No | Called when payment fails/expires |
| `onClose` | function | No | Called when user closes overlay |

**Short form:**
```javascript
PaymentGateway.open('https://gateway.com/pay/pay_xxx_secret_xxx');
```

**Full form:**
```javascript
PaymentGateway.open({
  paymentUrl: 'https://gateway.com/pay/pay_xxx_secret_xxx',
  onSuccess: function(data) {
    // data: { orderId, amount, currency, verifiedAt, returnUrl }
  },
  onFailure: function(data) {
    // data: { orderId, message } or { reason: 'expired' }
  },
  onClose: function() {
    // User closed overlay
  }
});
```

### `PaymentGateway.close()`

Manually close the overlay.

```javascript
PaymentGateway.close();
```

## Backend Integration

Your backend needs to create payment orders and return payment URLs:

```javascript
// Example: Express.js backend
app.post('/api/create-payment', async (req, res) => {
  const { amount } = req.body;
  
  // Call your payment gateway API
  const response = await fetch('https://YOUR_GATEWAY/api/v1/payment-orders/create', {
    method: 'POST',
    headers: {
      'X-Client-Secret': 'your-client-secret',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      amount: amount,
      payerName: 'Customer Name',
      payerEmail: 'customer@example.com',
      description: 'Order #123'
    })
  });
  
  const data = await response.json();
  
  // Return payment URL to frontend
  res.json({
    paymentUrl: `https://YOUR_GATEWAY/pay/${data.data.clientSecret}`
  });
});
```

## How It Works

1. **User clicks "Pay"** → Your frontend calls backend API
2. **Backend creates payment order** → Returns payment URL
3. **Frontend calls `PaymentGateway.open()`** → Overlay opens with iframe
4. **User completes payment** → UPI/UTR submit karta hai
5. **Payment verified** → Payment page sends `postMessage` to parent
6. **SDK receives message** → Calls `onSuccess` callback
7. **Overlay closes** → User stays on same page

## Browser Support

- Chrome/Edge (latest)
- Firefox (latest)
- Safari (latest)
- Mobile browsers (iOS Safari, Chrome Mobile)

## CDN Links (After Publish)

**Unpkg:**
```html
<script src="https://unpkg.com/@rajatsinha2343/secure_pay@1/dist/payment-gateway.js"></script>
```

**JsDelivr:**
```html
<script src="https://cdn.jsdelivr.net/npm/@rajatsinha2343/secure_pay@1/dist/payment-gateway.js"></script>
```

## Troubleshooting

### SDK not loading?
- Check script path is correct
- Check browser console for errors
- Verify file exists in `node_modules/@rajatsinha2343/secure_pay/dist/`

### Overlay not opening?
- Check `paymentUrl` is valid and accessible
- Verify CORS is enabled on gateway
- Check browser console for errors

### Callbacks not firing?
- Verify payment page is sending `postMessage`
- Check `paymentUrl` origin matches gateway domain
- Open browser DevTools → Network tab to see iframe requests

## License

MIT

## Support

For issues/questions, check the main repository or contact support.