npm package: @gatevector/browser-sdk
Description: Browser extension payment SDK for GateVector - Accept payments in Chrome/Firefox extensions
Author: GateVector
Latest version: 0.2.1

# @gatevector/browser-sdk

Official Browser Extension SDK for GateVector - Accept payments in your Chrome/Firefox extensions.

## Installation

```bash
npm install @gatevector/browser-sdk
```

## Quick Start

### 1. Initialize the SDK

```typescript
import { GateVector } from '@gatevector/browser-sdk';

const gateVector = new GateVector({
  apiBaseUrl: 'https://api.gatevector.com',
  apiKey: 'your-api-key-here'
});
```

### 2. Create a One-Time Payment

```typescript
// In your extension's popup or options page
async function handleUpgrade() {
  await gateVector.openPaymentPage({
    amount: 9.99,
    currency: 'usd',
    mode: 'payment',
    description: 'Premium Upgrade'
  });
}
```

### 3. Create a Subscription

```typescript
async function handleSubscribe() {
  await gateVector.openPaymentPage({
    amount: 4.99,
    currency: 'usd',
    mode: 'subscription',
    interval: 'month',
    description: 'Premium Monthly Subscription'
  });
}
```

### 4. Check User Payment Status

```typescript
async function checkUserStatus() {
  try {
    const status = await gateVector.getUserStatus();
    
    if (status.paid) {
      console.log('User has paid!');
      enablePremiumFeatures();
    } else {
      console.log('User has not paid');
      showUpgradePrompt();
    }
  } catch (error) {
    console.error('Failed to check status:', error);
  }
}
```

### 5. Handle Payment Success

```typescript
// In your success page (success.html)
chrome.runtime.sendMessage({ type: 'payment-success' });

// In your background script
chrome.runtime.onMessage.addListener((message) => {
  if (message.type === 'payment-success') {
    extensionPay.clearCache();
    checkUserStatus();
  }
});
```

## API Reference

### Constructor

```typescript
new ExtensionPay(config: ExtensionPayConfig)
```

**Parameters:**
- `config.apiBaseUrl` (string): Base URL of your ExtensionPay instance
- `config.apiKey` (string): Your organization's API key

### Methods

#### `createPaymentSession(options: PaymentSessionOptions): Promise<PaymentSession>`

Creates a Stripe Checkout session and returns the session URL.

**Options:**
- `amount` (number, required): Payment amount (e.g., 9.99)
- `currency` (string, optional): Currency code (default: 'usd')
- `mode` ('payment' | 'subscription', optional): Payment mode (default: 'payment')
- `successUrl` (string, optional): Redirect URL after successful payment
- `cancelUrl` (string, optional): Redirect URL after cancelled payment
- `description` (string, optional): Payment description
- `locale` (string, optional): Checkout page locale (default: 'auto')
- `priceId` (string, optional): Stripe Price ID for subscriptions
- `interval` ('day' | 'week' | 'month' | 'year', optional): Subscription interval
- `intervalCount` (number, optional): Interval count (e.g., 3 for every 3 months)

**Returns:**
```typescript
{
  url: string;         // Stripe Checkout URL
  session_id?: string; // Checkout session ID
}
```

#### `openPaymentPage(options: PaymentSessionOptions): Promise<void>`

Creates a payment session and opens it in a new tab (Chrome) or window.

#### `getUserStatus(userId?: string): Promise<UserStatus>`

Checks if a user has paid. Results are cached for 60 seconds.

**Parameters:**
- `userId` (string, optional): User identifier (if not provided, uses default)

**Returns:**
```typescript
{
  paid: boolean;
  customer_id?: string;
  subscription_id?: string;
  subscription_status?: string;
  subscription_cancel_at_period_end?: boolean;
}
```

#### `confirmPayment(sessionId: string): Promise<{ status: string }>`

Confirms a payment after checkout (hybrid safety net).

#### `clearCache(userId?: string): void`

Clears the user status cache. Call this after successful payments.

#### `setApiKey(apiKey: string): void`

Updates the API key and clears cache.

#### `setApiBaseUrl(apiBaseUrl: string): void`

Updates the base URL and clears cache.

## Manifest Configuration

### Chrome Extension (Manifest V3)

```json
{
  "manifest_version": 3,
  "name": "Your Extension",
  "permissions": [
    "tabs"
  ],
  "host_permissions": [
    "https://api.extensionpay.io/*"
  ]
}
```

### Firefox Add-on (Manifest V2)

```json
{
  "manifest_version": 2,
  "name": "Your Extension",
  "permissions": [
    "tabs",
    "https://api.extensionpay.io/*"
  ]
}
```

## Complete Example

### background.js (Service Worker)

```typescript
import ExtensionPay from '@extensionpay/browser-sdk';

const extensionPay = new ExtensionPay({
  apiBaseUrl: 'https://api.extensionpay.io',
  apiKey: 'your-api-key'
});

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'check-status') {
    extensionPay.getUserStatus()
      .then(status => sendResponse({ paid: status.paid }))
      .catch(error => sendResponse({ error: error.message }));
    return true;
  }
  
  if (message.type === 'upgrade') {
    extensionPay.openPaymentPage({
      amount: 9.99,
      mode: 'payment',
      description: 'Premium Upgrade'
    }).catch(error => console.error(error));
  }
  
  if (message.type === 'payment-success') {
    extensionPay.clearCache();
    chrome.storage.local.set({ premium: true });
  }
});
```

### popup.html + popup.js

```typescript
document.getElementById('upgrade-btn').addEventListener('click', async () => {
  chrome.runtime.sendMessage({ type: 'upgrade' });
});

chrome.runtime.sendMessage({ type: 'check-status' }, (response) => {
  if (response.paid) {
    document.getElementById('status').textContent = 'Premium Active';
  }
});
```

### success.html

```html
<!DOCTYPE html>
<html>
<head>
  <title>Payment Success</title>
</head>
<body>
  <h1>Payment Successful!</h1>
  <p>Thank you for upgrading to Premium.</p>
  <script>
    chrome.runtime.sendMessage({ type: 'payment-success' });
    setTimeout(() => window.close(), 2000);
  </script>
</body>
</html>
```

## Best Practices

1. **Cache User Status**: The SDK automatically caches user status for 60 seconds. Don't call `getUserStatus()` on every page load.

2. **Clear Cache After Payment**: Always call `clearCache()` after successful payments to ensure fresh status.

3. **Handle Errors**: Wrap API calls in try-catch blocks and handle network errors gracefully.

4. **Store Premium State**: After confirming payment, store premium status in `chrome.storage` for offline access.

5. **Test in Development**: Use test API keys and test mode in Stripe during development.

## Support

- Documentation: https://docs.extensionpay.io
- Issues: https://github.com/xgame92/extensionpay-io-v2/issues

## License

MIT