npm package: @payloqa/auth-widget
Description: React-based authentication widget for Payloqa
Author: Payloqa Team
Latest version: 1.4.0

# 🔐 Payloqa Auth Widget

A React authentication widget for phone number verification with OTP. Easily integrate secure authentication into your React applications.

## ✨ Features

- 📱 Phone number verification with OTP
- 🔐 4-digit OTP with auto-submit
- 🤖 Cloudflare Turnstile bot protection
- 📱 Fully responsive design
- ⚡ Easy integration with React

## 🚀 Getting Started

### 1. Get Your API Credentials

Visit [https://developer.payloqa.com/](https://developer.payloqa.com/) to:

- Login with your phone number (simple phone number authentication)
- Go to the **API Keys** page
- Create your **API Key** and get your **Platform ID**

### 2. Install the Package

```bash
npm install @payloqa/auth-widget
```

### 3. Import and Use

```jsx
import { AuthWidget } from "@payloqa/auth-widget";
import "@payloqa/auth-widget/styles";

function App() {
  const config = {
    apiKey: "your-api-key",
    platformId: "your-platform-id",
    apiUrl: "https://auth.payloqa.com/api/v1/auth",
    turnstileSiteKey: "your-turnstile-site-key", // Get from Cloudflare
  };

  const handleSuccess = (user, token, refreshToken, isNewUser) => {
    console.log("Authentication successful!");
    console.log("User:", user);
    console.log("Access Token:", token);
    console.log("Is New User:", isNewUser);

    // Store tokens and redirect user
    localStorage.setItem("accessToken", token);
    localStorage.setItem("refreshToken", refreshToken);
  };

  const handleError = (error) => {
    console.error("Authentication failed:", error.message);
    alert(`Error: ${error.message}`);
  };

  return (
    <AuthWidget
      config={config}
      onSuccess={handleSuccess}
      onError={handleError}
    />
  );
}
```

## ⚙️ Configuration

### Required Configuration

```typescript
interface AuthWidgetConfig {
  apiKey: string; // Your Payloqa API key
  platformId: string; // Your platform ID
  apiUrl: string; // API endpoint (use: https://auth.payloqa.com/api/v1/auth)
  turnstileSiteKey: string; // Cloudflare Turnstile site key
}
```

### Callbacks

```typescript
// Success callback - called when authentication succeeds
onSuccess: (
  user: AuthUser,        // User object
  token: string,         // JWT access token (valid for 24 hours)
  refreshToken: string,  // Refresh token (valid for 7 days)
  isNewUser: boolean     // true if user was just created
) => void

// Error callback - called when authentication fails
onError: (error: AuthError) => void

// Optional: State change callback
onStateChange: (state: "phone-input" | "otp-verification" | "loading" | "success" | "error") => void
```

## 📝 Sample Responses

### Success Response

When authentication succeeds, the `onSuccess` callback receives:

```typescript
// User object
{
  id: "user-uuid",
  phone: "+233XXXXXXXXX",
  email: null,
  platformId: "your-platform-id",
  platformName: "Your Platform Name",
  userData: {},
  isPhoneVerified: true,
  isEmailVerified: false,
  lastLoginAt: "2024-01-01T12:00:00Z",
  createdAt: "2024-01-01T11:00:00Z"
}

// Token (JWT string)
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

// Refresh Token
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

// isNewUser (boolean)
false // or true for newly created users
```

### Error Response

When authentication fails, the `onError` callback receives:

```typescript
{
  message: "Invalid OTP code", // or other error message
  code: "INVALID_OTP" // optional error code
}
```

## 🔑 Cloudflare Turnstile Setup

1. Go to [Cloudflare Dashboard](https://dash.cloudflare.com/)
2. Navigate to **Turnstile**
3. Create a new site
4. Copy your **Site Key**
5. Add it to your widget configuration

**For localhost testing**, use the test key: `1x00000000000000000000AA`

## 📱 Complete Example

```jsx
import React from "react";
import { AuthWidget } from "@payloqa/auth-widget";
import "@payloqa/auth-widget/styles";

function LoginPage() {
  const config = {
    apiKey: "pk_live_your_api_key",
    platformId: "plat_your_platform_id",
    apiUrl: "https://auth.payloqa.com/api/v1/auth",
    turnstileSiteKey: "your-turnstile-site-key",
  };

  const handleSuccess = (user, token, refreshToken, isNewUser) => {
    // Store authentication tokens
    localStorage.setItem("accessToken", token);
    localStorage.setItem("refreshToken", refreshToken);

    // Redirect to dashboard
    window.location.href = "/dashboard";
  };

  const handleError = (error) => {
    // Handle error (show toast, alert, etc.)
    console.error("Auth error:", error);
  };

  return (
    <div className="min-h-screen flex items-center justify-center">
      <AuthWidget
        config={config}
        onSuccess={handleSuccess}
        onError={handleError}
      />
    </div>
  );
}

export default LoginPage;
```

## 🎨 Styling

The widget includes default styles. Import them:

```jsx
import "@payloqa/auth-widget/styles";
```

You can customize the appearance by overriding CSS classes in your application.

## 🔒 Security Notes

- **Access Token**: Valid for 24 hours
- **Refresh Token**: Valid for 7 days
- Store tokens securely (consider using httpOnly cookies for production)
- Never expose your API key in client-side code (use environment variables)

## 🐛 Troubleshooting

### Widget doesn't load

- Ensure React and ReactDOM are installed
- Check browser console for errors
- Verify all required props are provided

### Turnstile not appearing

- Verify your Turnstile site key is correct
- For localhost, use test key: `1x00000000000000000000AA`
- Ensure you're using HTTP/HTTPS (not `file://`)

### OTP not working

- Check API configuration (apiKey, platformId, apiUrl)
- Verify phone number format (10 digits, will be converted to E.164)
- Check network connectivity

## 📚 TypeScript Support

Full TypeScript definitions are included:

```typescript
import {
  AuthWidget,
  AuthWidgetConfig,
  AuthUser,
  AuthError,
} from "@payloqa/auth-widget";
```

## 📄 License

MIT License

## 🆘 Support

- 📖 Documentation: [https://developer.payloqa.com/](https://developer.payloqa.com/)
- 📧 Email: support@payloqa.com
- 🐛 Issues: [GitHub Issues](https://github.com/payloqa/payloqa-widgets/issues)

---

Built with ❤️ by the Payloqa Team