npm package: @polkapay/sdk
Description: Official PolkaPay SDK for Node.js and Browser
Author: Chizihn
Latest version: 0.1.1

# @polkapay/sdk

Official SDK for accepting cryptocurrency payments on Polkadot (Westend Testnet).

## Installation

```bash
npm install @polkapay/sdk
# or
yarn add @polkapay/sdk
```

## Quick Start

### 1. Get Your API Key

Sign up at [polkapay.xyz](https://polkapay.xyz) and get your API key from the dashboard.

### 2. Server-Side Integration (Node.js/Express/Next.js)

```typescript
import { PolkaPay } from '@polkapay/sdk';

const polkapay = new PolkaPay({
  apiKey: process.env.POLKAPAY_API_KEY!
});

// Create a payment link
const paymentLink = await polkapay.createPaymentLink({
  title: 'Premium Subscription',
  description: 'Monthly subscription',
  amount: 29.99,
  currency: 'USD',
  acceptedTokens: ['DOT', 'USDT'],
  webhookUrl: 'https://yourapp.com/webhooks/polkapay',
  metadata: {
    userId: 'user_123',
    plan: 'premium'
  }
});

console.log('Payment URL:', paymentLink.url);
```

### 3. Client-Side Integration (React/Next.js)

```typescript
'use client';

import { PolkaPayClient } from '@polkapay/sdk';
import { useEffect, useState } from 'react';

export function PaymentButton({ paymentLinkSlug }: { paymentLinkSlug: string }) {
  const [client, setClient] = useState<PolkaPayClient | null>(null);

  useEffect(() => {
    const initClient = async () => {
      const polkaClient = new PolkaPayClient({
        network: 'westend',
        autoDiscoverTokens: true,
      });
      
      await polkaClient.initialize();
      setClient(polkaClient);
    };

    initClient();
  }, []);

  const handlePayment = async () => {
    if (!client) return;

    const accounts = await client.getAccounts();
    if (accounts.length === 0) {
      alert('Please install a Polkadot wallet and switch to Westend Testnet');
      return;
    }

    // Send payment
    const result = await client.sendPayment({
      paymentLinkId: paymentLinkSlug,
      token: 'DOT',
      amount: '10'
    });

    if (result.success) {
      alert('Payment successful!');
    }
  };

  return (
    <button onClick={handlePayment}>
      Pay with Polkadot
    </button>
  );
}
```

## Use Cases

### E-commerce (Next.js)

```typescript
// app/api/checkout/route.ts
import { PolkaPay } from '@polkapay/sdk';

export async function POST(req: Request) {
  const { items, total } = await req.json();
  
  const polkapay = new PolkaPay({
    apiKey: process.env.POLKAPAY_API_KEY!
  });

  const payment = await polkapay.createPaymentLink({
    title: 'Order #12345',
    amount: total,
    currency: 'USD',
    acceptedTokens: ['DOT', 'USDT', 'USDC'],
    metadata: { items, orderId: '12345' }
  });

  return Response.json({ paymentUrl: payment.url });
}
```

### SaaS Subscriptions (Express)

```typescript
import express from 'express';
import { PolkaPay } from '@polkapay/sdk/server';

const app = express();
const polkapay = new PolkaPay({
  apiKey: process.env.POLKAPAY_API_KEY!
});

app.post('/subscribe', async (req, res) => {
  const { plan, userId } = req.body;
  
  const payment = await polkapay.createPaymentLink({
    title: `${plan} Subscription`,
    amount: plan === 'premium' ? 29.99 : 9.99,
    currency: 'USD',
    acceptedTokens: ['DOT', 'USDT'],
    webhookUrl: 'https://yourapi.com/webhooks/polkapay',
    metadata: { userId, plan }
  });

  res.json({ paymentUrl: payment.url });
});

// Webhook handler
app.post('/webhooks/polkapay', express.raw({ type: 'application/json' }), (req, res) => {
  const { WebhookVerifier } = require('@polkapay/sdk');
  const verifier = new WebhookVerifier(process.env.POLKAPAY_WEBHOOK_SECRET!);
  
  const signature = req.headers['x-polkapay-signature'];
  const timestamp = req.headers['x-polkapay-timestamp'] || Math.floor(Date.now() / 1000).toString();
  const payload = req.body.toString();
  
  const event = verifier.parseEvent(payload, signature, timestamp);
  
  if (!event) {
    return res.status(401).send('Invalid signature');
  }
  
  if (event.type === 'payment.completed') {
    const transaction = event.data.object;
    // Activate user subscription
    await activateSubscription(transaction.metadata?.userId);
  }

  res.json({ received: true });
});
```

### Donations (React)

```typescript
import { PolkaPayClient } from '@polkapay/sdk';

function DonateButton() {
  const donate = async (amount: string) => {
    const client = new PolkaPayClient({
      network: 'polkadot'
    });
    
    await client.initialize();
    
    const result = await client.sendPayment({
      paymentLinkId: 'donate-slug',
      token: 'DOT',
      amount
    });

    if (result.success) {
      alert('Thank you for your donation!');
    }
  };

  return (
    <div>
      <button onClick={() => donate('10')}>Donate 10 DOT</button>
      <button onClick={() => donate('50')}>Donate 50 DOT</button>
    </div>
  );
}
```

## API Reference

See full documentation at [polkapay.xyz/docs](https://polkapay.xyz/docs)

## Support

- Documentation: https://polkapay.xyz/docs
- Discord: https://discord.gg/polkapay
- Email: support@polkapay.xyz

## License

MIT
*/

// ============================================================================
// EXAMPLE: Merchant's Express Server
// ============================================================================
/*
// merchant-backend/index.js
import express from 'express';
import { PolkaPay } from '@polkapay/sdk';

const app = express();
app.use(express.json());

const polkapay = new PolkaPay({
  apiKey: process.env.POLKAPAY_API_KEY // They get this from YOUR dashboard
});

// Merchant creates payment
app.post('/create-payment', async (req, res) => {
  const payment = await polkapay.createPaymentLink({
    title: 'Product Purchase',
    amount: 99.99,
    currency: 'USD',
    acceptedTokens: ['DOT', 'USDT'],
    webhookUrl: 'https://merchant-site.com/webhook'
  });
  
  // payment.url points to YOUR hosted payment page
  // e.g., https://pay.polkapay.xyz/abc123
  res.json({ paymentUrl: payment.url });
});

// Merchant receives webhook from YOUR API
app.post('/webhook', (req, res) => {
  const event = req.body;
  
  if (event.type === 'payment.completed') {
    // Fulfill order
    console.log('Payment received!', event.data.object);
  }
  
  res.json({ received: true });
});

app.listen(3000);
*/

// ============================================================================
// EXAMPLE: Merchant's React App
// ============================================================================
/*
// merchant-frontend/src/Checkout.tsx
import { PolkaPayClient } from '@polkapay/sdk';

function Checkout() {
  const handlePay = async () => {
    // Client connects to blockchain directly
    const client = new PolkaPayClient({ network: 'polkadot' });
    await client.initialize();
    
    // Send payment to YOUR merchant's payment link
    const result = await client.sendPayment({
      paymentLinkId: 'merchant-payment-123',
      token: 'DOT',
      amount: '10'
    });
    
    // Transaction gets verified by YOUR backend via blockchain
    // Webhook gets sent to merchant
  };
  
  return <button onClick={handlePay}>Pay with PolkaPay</button>;
}
*/