# HivePay - Full Documentation for LLMs > Payment gateway for the Hive blockchain. Stripe-like API for accepting HIVE and HBD payments. HivePay lets developers accept Hive blockchain payments via a simple REST API and TypeScript SDK. It handles checkout flows, webhook notifications, fee calculations, and x402 HTTP-native micropayments. ## Key links - Docs: https://docs.hivepay.me - OpenAPI spec: https://hivepay.me/openapi.json - SDK (npm): https://www.npmjs.com/package/@hivepay/client - Dashboard: https://dashboard.hivepay.me - Status: https://status.hivepay.me - x402 facilitator: https://hivepay.me/api/public/x402/ --- # Dashboard The HivePay Dashboard is a web-based interface for merchants to manage payments, configure settings, and monitor their account. ## Features ### Payment Management - View all payment sessions - Filter by status, date, and amount - View detailed payment information - Track payment history ### Merchant Settings - Update business information - Configure webhook URL - Change Hive account for receiving payments - Update logo/icon ### Analytics (Coming Soon) - Payment volume trends - Success rate metrics - Revenue reports ## Quick Actions | Action | How To | |--------|--------| | Create payment | Click "New Payment" or use the API | | View payment details | Click on any payment in the list | | Update webhook URL | Go to Settings > Webhooks | | Change Hive account | Go to Settings > Profile | --- # Admin Panel The Admin Panel provides administrative features for managing the HivePay platform. The Admin Panel is only available to users with admin privileges. Contact the HivePay team if you need admin access for your deployment. ## Merchant Management ### List All Merchants View all registered merchants: | Column | Description | |--------|-------------| | ID | Merchant identifier | | Name | Business name | | Hive Account | Payment destination | | Status | Active/Inactive | | Created | Registration date | ### Search Merchants Use the search box to find merchants by: - Merchant ID - Business name - Hive account ### Filter by Status - **All** - Show all merchants - **Active** - Active merchants only - **Inactive** - Deactivated merchants ## Bulk Operations ### Export Merchants Export merchant list to CSV: 1. Apply filters if needed 2. Click **Export** 3. Choose format (CSV or JSON) 4. Download file ### Pagination Navigate large merchant lists: - Items per page: 20, 50, 100 - Previous/Next navigation - Jump to specific page ## API Access Admin endpoints require an API key with admin privileges: ### List Merchants ```typescript // Get paginated list const result = await hivepay.admin.listMerchants({ page: 1, limit: 50, query: 'store' // Optional search }); console.log(result.data); // Array of merchants console.log(result.pagination.total); // Total count ``` ### Iterate All Merchants ```typescript // Async iteration for await (const merchant of hivepay.admin.iterateMerchants()) { console.log(merchant.id, merchant.name, merchant.isActive); } // With filters for await (const merchant of hivepay.admin.iterateMerchants({ query: 'store', pageSize: 50 })) { // Process merchant } ``` ## Self-Hosted Deployments If you're running your own HivePay instance: 1. Admin privileges are configured during deployment 2. See the deployment documentation for setup 3. Admin users are defined in the database seed --- # Managing Payments View, filter, and manage your payment sessions in the dashboard. ## Filtering Payments ### By Status Use the status filter dropdown to show only payments with a specific status: - **All** - Show all payments - **Pending** - Awaiting customer action - **Processing** - Payment in progress - **Completed** - Successfully completed - **Failed** - Payment failed - **Cancelled** - User or system cancelled ### By Date Click the date filter to show payments from a specific time range: - Today - Last 7 days - Last 30 days - Custom range ### Search Use the search box to find payments by: - Payment ID - Description - Metadata values ## Creating Payments While payments are typically created via API, you can create test payments from the dashboard: 1. Click **New Payment** button 2. Fill in the payment details: - Amount (in HIVE or HBD) - Currency - Description - Optional redirect URLs 3. Click **Create** 4. Copy the checkout URL or redirect immediately ## Status Badges Payments are color-coded by status for quick identification: | Status | Color | Meaning | |--------|-------|---------| | Pending | Yellow | Awaiting action | | Processing | Blue | In progress | | Completed | Green | Successful | | Failed | Red | Failed | | Cancelled | Gray | Cancelled | ## Tips Use the browser's back button to return to your filtered list without losing your filter settings. The payment list doesn't auto-refresh. Click the refresh button or reload the page to see the latest payments. --- # Dashboard Settings Configure your merchant account settings in the dashboard. ## Profile Settings ### Business Name Your business name is displayed to customers during checkout. | Field | Description | |-------|-------------| | Name | Your business or store name | | | Displayed on checkout page | | | Max 100 characters | ### Hive Account The Hive account where payments are sent. | Field | Description | |-------|-------------| | Hive Account | Your Hive username | | | Receives all payments (minus fees) | | | Must be a valid Hive account | Changing your Hive account affects all future payments. Pending payments will still be sent to the previously configured account. ### Icon/Logo Add a logo to display on checkout pages: | Field | Description | |-------|-------------| | Icon URL | HTTPS URL to your logo image | | | Recommended: 256x256px or larger | | | Supported: PNG, JPG, SVG | ## API Key Management ### View API Key Info The settings page shows: - Partial API key (last 4 characters) - Creation date - Last used timestamp ### Regenerate API Key If you need a new API key: 1. Contact [support](/support/) 2. Your old key will be immediately deactivated 3. You'll receive a new API key 4. Update your applications with the new key Regenerating an API key immediately invalidates the old key. Any applications using the old key will stop working. ## Notification Preferences Coming soon: - Email notifications for large payments - Daily/weekly summary emails - Alert thresholds --- # Getting Started Welcome to HivePay! This guide will help you get started with accepting Hive blockchain payments in your application. ## Prerequisites Before you begin, you'll need: - A Hive blockchain account (to receive payments) - A web application or service where you want to accept payments - Basic knowledge of REST APIs or one of our SDKs ## Next Steps - [Creating Payments](/payments/creating/) - Learn about payment options - [Handling Webhooks](/payments/webhooks/) - Get notified of payment status changes - [SDK Reference](/sdk/) - Explore the full TypeScript SDK --- # Authentication Learn how to authenticate your API requests to HivePay. ## Using Your API Key Include your API key in the `Authorization` header of every API request: ```typescript import { HivePay } from '@hivepay/client'; const hivepay = new HivePay({ apiKey: 'sk_live_xxxxxxxxxxxxx' }); // All subsequent requests are authenticated const payment = await hivepay.payments.create({ amount: '10000', currency: 'HIVE', description: 'Order #123' }); ``` ```bash curl https://hivepay.me/api/public/payments \ -H "Authorization: Bearer sk_live_xxxxxxxxxxxxx" ``` ```javascript const response = await fetch('https://hivepay.me/api/public/payments', { headers: { 'Authorization': 'Bearer sk_live_xxxxxxxxxxxxx', 'Content-Type': 'application/json' } }); ``` ## Security Best Practices ### Do - Store API keys in environment variables, not in code - Use secrets management systems in production - Rotate keys if you suspect they've been compromised - Use separate keys for development and production (when available) ### Don't - Commit API keys to version control - Share API keys in public forums or code snippets - Include API keys in client-side JavaScript - Log API keys or include them in error messages ## Lost API Key If you lose your API key, you cannot retrieve it. Contact [support](/support/) to: 1. Deactivate your existing key 2. Generate a new API key When a new key is generated, your old key becomes invalid immediately. Update your application with the new key before deactivating the old one. --- # Merchant Registration Register as a HivePay merchant to start accepting HIVE and HBD payments. ## Programmatic Registration You can also register programmatically using the API or SDK: ```typescript import { HivePay } from '@hivepay/client'; // No API key needed for registration const publicClient = new HivePay(); const result = await publicClient.merchants.register({ name: 'My Store', hiveAccount: 'mystore', iconUrl: 'https://example.com/logo.png' // optional }); // IMPORTANT: Save these credentials securely! console.log('API Key:', result.apiKey); console.log('Webhook Secret:', result.webhookSecret); console.log('Merchant ID:', result.merchant.id); // Create authenticated client for future requests const hivepay = publicClient.withApiKey(result.apiKey); ``` ```bash curl -X POST https://hivepay.me/api/public/merchants/register \ -H "Content-Type: application/json" \ -d '{ "name": "My Store", "hiveAccount": "mystore", "iconUrl": "https://example.com/logo.png" }' ``` Response: ```json { "apiKey": "sk_live_xxxxxxxxxxxxx", "webhookSecret": "whsec_xxxxxxxxxxxxx", "merchant": { "id": "cmkfgjmim00008rcxp81upef9", "name": "My Store", "hiveAccount": "mystore", "isActive": true, "createdAt": "2024-01-15T10:30:00.000Z" } } ``` ## After Registration Once registered, you can: 1. [Configure authentication](/getting-started/authentication/) for API access 2. [Set up webhooks](/payments/webhooks/) to receive payment notifications 3. [Create your first payment](/payments/creating/) --- # Payments Learn how to create, track, and manage payments with HivePay. ## Payment Lifecycle ```mermaid stateDiagram-v2 [*] --> pending: Payment Created pending --> processing: Payment Initiated processing --> completed: Payment Confirmed processing --> failed: Payment Failed pending --> user_cancelled: User Cancelled pending --> system_cancelled: Timeout/Expired completed --> [*] failed --> [*] user_cancelled --> [*] system_cancelled --> [*] ``` ## Supported Currencies | Currency | Description | Precision | |----------|-------------|-----------| | `HIVE` | Hive native token | 3 decimals | | `HBD` | Hive Backed Dollars | 3 decimals | --- # Creating Payments Learn how to create payment sessions and redirect customers to checkout. ## Amount Format Amounts are specified as strings in the smallest unit (satoshis): | Input | Actual Amount | |-------|---------------| | `"1000"` | 1.000 HIVE/HBD | | `"10500"` | 10.500 HIVE/HBD | | `"100000"` | 100.000 HIVE/HBD | Both HIVE and HBD use 3 decimal precision. ## Payment Response A successful payment creation returns: ```json { "id": "cmj7b2rg10004d2rimvum8kaz", "status": "pending", "checkoutUrl": "https://hivepay.me/checkout/cmj7b2rg10004d2rimvum8kaz", "amount": { "value": "10500", "formatted": "10.500 HBD", "currency": "HBD", "usdCents": 1050 }, "fee": "158", "net": "10342", "description": "Order #123", "expiresAt": "2024-01-15T11:30:00.000Z", "createdAt": "2024-01-15T10:30:00.000Z" } ``` | Field | Description | |-------|-------------| | `id` | Unique payment identifier | | `status` | Current payment status | | `checkoutUrl` | URL to redirect customer to | | `amount` | Amount details including USD equivalent | | `fee` | HivePay fee (in satoshis) | | `net` | Amount you receive after fees | | `expiresAt` | When the payment expires | ## After Payment When the payment is completed or cancelled: 1. Customer is redirected to your `redirectUrl` or `cancelUrl` 2. A [webhook](/payments/webhooks/) is sent to your configured endpoint 3. You can [check the status](/payments/tracking/) using the payment ID Always verify payment status via webhook or API before fulfilling orders. Don't rely solely on the redirect. --- # Fee Calculations Understand HivePay fees and how to calculate them in your application. ## Get Current Fee Rate Retrieve the current fee percentage from the API: ```typescript const feePercent = await hivepay.payments.getFeeRate(); console.log(`Current fee: ${feePercent}%`); // e.g., "1.5%" ``` ```bash curl https://hivepay.me/api/public/payments/fee-rate \ -H "Authorization: Bearer sk_live_xxx" ``` ## Format Satoshis Convert satoshi values to readable strings: ```typescript import { formatSatoshis } from '@hivepay/client'; const satoshis = 10500n; console.log(formatSatoshis(satoshis)); // "10.500" console.log(formatSatoshis(satoshis, 2)); // "10.50" console.log(formatSatoshis(158n)); // "0.158" ``` ## Fee Calculation Formula ``` fee = floor(amount * feePercent / 100) net = amount - fee ``` The SDK uses BigInt for precise calculations without floating-point errors. ## Pricing Your Products If you want customers to pay a specific amount and you want to receive a fixed net amount, calculate the gross amount: ```typescript function calculateGrossAmount(desiredNet: bigint, feePercent: number): bigint { // gross = net / (1 - feePercent/100) const multiplier = 100 - feePercent; return (desiredNet * 100n) / BigInt(Math.floor(multiplier)); } // You want to receive exactly 10.000 HIVE const desiredNet = 10000n; const feePercent = 1.5; const grossAmount = calculateGrossAmount(desiredNet, feePercent); console.log('Charge customer:', formatSatoshis(grossAmount)); // ~10.153 HIVE ``` --- # Tracking Payments Learn how to check payment status and monitor payment progress. ## Check Status Only For quick status checks, use the status endpoint: ```typescript const status = await hivepay.payments.getStatus('cmj7b2rg10004d2rimvum8kaz'); if (status === 'completed') { // Fulfill the order } else if (status === 'pending') { // Still waiting for payment } ``` ```bash curl https://hivepay.me/api/public/payments/cmj7b2rg10004d2rimvum8kaz/status \ -H "Authorization: Bearer sk_live_xxx" ``` ## List All Payments Retrieve a paginated list of your payments: ```typescript // Get first page (default: 20 items) const result = await hivepay.payments.list(); console.log(result.data); // Array of payments console.log(result.pagination.page); // Current page: 1 console.log(result.pagination.limit); // Items per page: 20 console.log(result.pagination.total); // Total items console.log(result.pagination.totalPages); // Total pages // Get specific page with custom size const page3 = await hivepay.payments.list({ page: 3, limit: 50 // Max: 100 }); ``` ```bash # First page curl "https://hivepay.me/api/public/payments" \ -H "Authorization: Bearer sk_live_xxx" # Page 3 with 50 items curl "https://hivepay.me/api/public/payments?page=3&limit=50" \ -H "Authorization: Bearer sk_live_xxx" ``` ## Payment Response Structure ```json { "id": "cmj7b2rg10004d2rimvum8kaz", "merchantId": "cmkfgjmim00008rcxp81upef9", "status": "completed", "checkoutUrl": "https://hivepay.me/checkout/cmj7b2rg10004d2rimvum8kaz", "amount": { "value": "10500", "formatted": "10.500 HBD", "currency": "HBD", "usdCents": 1050 }, "fee": "158", "net": "10342", "description": "Order #123", "metadata": { "orderId": "12345" }, "redirectUrl": "https://yourstore.com/success", "cancelUrl": "https://yourstore.com/cancel", "expiresAt": "2024-01-15T11:30:00.000Z", "completedAt": "2024-01-15T10:45:00.000Z", "createdAt": "2024-01-15T10:30:00.000Z" } ``` --- # Webhooks Receive real-time notifications when payment statuses change. ## Configuration Configure your webhook URL in the [Dashboard](/dashboard/settings/) or via API: ```typescript await hivepay.merchants.update('merchant_id', { webhookUrl: 'https://yoursite.com/webhooks/hivepay' }); ``` ```bash curl -X PUT https://hivepay.me/api/public/merchants/your_merchant_id \ -H "Authorization: Bearer sk_live_xxx" \ -H "Content-Type: application/json" \ -d '{ "webhookUrl": "https://yoursite.com/webhooks/hivepay" }' ``` ## Event Types | Event | Description | |-------|-------------| | `payment.status_changed` | Payment status changed (most common) | ## Webhook Secret Each merchant receives a dedicated webhook signing secret (`whsec_xxx`) at registration. This secret is separate from your API key and is used exclusively for webhook signature verification. - The webhook secret is returned **once** during registration. Store it securely alongside your API key. - You can regenerate it in the [Dashboard settings](/dashboard/settings/) or via `POST /api/public/merchants/{id}/webhook-secret` (requires API key authentication). - Regenerating the secret **immediately invalidates** the previous one. The webhook secret is shown only once — during registration or after regeneration. If you lose it, you'll need to regenerate a new one (which invalidates the old one). ## Example Handlers ### Express.js ```typescript import express from 'express'; import { HivePay } from '@hivepay/client'; const app = express(); const hivepay = new HivePay({ apiKey: process.env.HIVEPAY_API_KEY, webhookSecret: process.env.HIVEPAY_WEBHOOK_SECRET }); app.post('/webhooks/hivepay', express.raw({ type: 'application/json' }), async (req, res) => { const result = await hivepay.verifyWebhook({ payload: req.body.toString(), signature: req.header('X-HivePay-Signature')!, timestamp: req.header('X-HivePay-Timestamp')! }); if (!result.valid) { return res.status(401).json({ error: result.error }); } const { event } = result; switch (event.data.status) { case 'completed': await handlePaymentCompleted(event.data.id); break; case 'failed': await handlePaymentFailed(event.data.id); break; } res.json({ received: true }); }); ``` ### Hono ```typescript import { Hono } from 'hono'; import { HivePay } from '@hivepay/client'; const app = new Hono(); const hivepay = new HivePay({ apiKey: process.env.HIVEPAY_API_KEY, webhookSecret: process.env.HIVEPAY_WEBHOOK_SECRET }); app.post('/webhooks/hivepay', async (c) => { const result = await hivepay.verifyWebhook({ payload: await c.req.text(), signature: c.req.header('X-HivePay-Signature')!, timestamp: c.req.header('X-HivePay-Timestamp')! }); if (!result.valid) { return c.json({ error: result.error }, 401); } // Handle event... return c.json({ received: true }); }); ``` ## Security Best Practices 1. **Always verify signatures** - Never process unverified webhooks 2. **Check timestamps** - Reject webhooks older than 5 minutes 3. **Use HTTPS** - Always use HTTPS in production 4. **Respond quickly** - Return 2xx within 5 seconds; process async 5. **Handle duplicates** - Implement idempotency for webhook handling --- # SDK Reference Official client libraries for integrating HivePay into your applications. ## TypeScript SDK The official TypeScript SDK provides a fully typed, promise-based API for interacting with HivePay. ### Features - Full TypeScript support with comprehensive type definitions - Promise-based API with async/await - Native async iterators for pagination - Built-in webhook verification - Custom error types for easy error handling - Zero dependencies (uses native fetch) - Tree-shakeable ESM module - Works in Node.js 18+ and modern browsers ### Quick Start ```typescript import { HivePay } from '@hivepay/client'; const hivepay = new HivePay({ apiKey: 'sk_live_xxx' }); // Create a payment const payment = await hivepay.payments.create({ amount: '10500', currency: 'HBD', description: 'Order #123' }); // Redirect to checkout window.location.href = payment.checkoutUrl; ``` ```javascript const { HivePay } = require('@hivepay/client'); const hivepay = new HivePay({ apiKey: 'sk_live_xxx' }); const payment = await hivepay.payments.create({ amount: '10500', currency: 'HBD', description: 'Order #123' }); ``` ## Requirements ### TypeScript SDK | Requirement | Version | |-------------|---------| | Node.js | 18.0.0+ | | TypeScript | 5.6+ (for development) | | Runtime | Node.js or modern browser | ### Secure Context (Webhooks) Webhook verification requires a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts) (HTTPS or localhost). --- # Error Handling Handle errors gracefully with HivePay's typed error system. ## Error Codes | Code | Status | Description | |------|--------|-------------| | `NETWORK_ERROR` | - | Network request failed or timed out | | `API_ERROR` | varies | General API error | | `AUTHENTICATION_ERROR` | 401 | Invalid or missing API key | | `FORBIDDEN_ERROR` | 403 | Insufficient permissions | | `NOT_FOUND_ERROR` | 404 | Resource not found | | `VALIDATION_ERROR` | 400 | Invalid request parameters | | `RATE_LIMIT_ERROR` | 429 | Too many requests | | `SERVER_ERROR` | 5xx | Server-side error | ## Error Type Methods `HivePayError` provides methods to check error type: ```typescript if (isHivePayError(error)) { if (error.isNotFound()) { // 404 - Resource not found console.log('Payment not found'); } else if (error.isAuthError()) { // 401 - Authentication failed console.log('Invalid API key'); } else if (error.isValidation()) { // 400 - Validation error console.log('Invalid data:', error.message); } else if (error.isRateLimited()) { // 429 - Rate limited console.log('Too many requests, retry later'); } else if (error.isForbidden()) { // 403 - Forbidden console.log('Access denied'); } else if (error.isServerError()) { // 5xx - Server error console.log('Server error, retry later'); } } ``` ### Available Methods | Method | Returns `true` for | |--------|-------------------| | `isNotFound()` | `NOT_FOUND_ERROR` (404) | | `isAuthError()` | `AUTHENTICATION_ERROR` (401) | | `isValidation()` | `VALIDATION_ERROR` (400) | | `isRateLimited()` | `RATE_LIMIT_ERROR` (429) | | `isForbidden()` | `FORBIDDEN_ERROR` (403) | | `isServerError()` | `SERVER_ERROR` (5xx) | | `isNetworkError()` | `NETWORK_ERROR` | ## Complete Example ```typescript import { HivePay, isHivePayError, type CreatePaymentOptions } from '@hivepay/client'; const hivepay = new HivePay({ apiKey: process.env.HIVEPAY_API_KEY! }); async function createPayment(options: CreatePaymentOptions) { try { const payment = await hivepay.payments.create(options); return { success: true, payment }; } catch (error) { if (!isHivePayError(error)) { // Unknown error - rethrow throw error; } // Handle specific error types if (error.isAuthError()) { return { success: false, error: 'Authentication failed. Check your API key.' }; } if (error.isValidation()) { return { success: false, error: `Invalid data: ${error.message}` }; } if (error.isRateLimited()) { return { success: false, error: 'Too many requests. Please wait and try again.' }; } if (error.isServerError()) { return { success: false, error: 'Server error. Please try again later.' }; } if (error.isNetworkError()) { return { success: false, error: 'Network error. Check your connection.' }; } // Fallback for unhandled error codes return { success: false, error: error.message }; } } ``` --- # Installation Install and configure the HivePay SDK for your project. ## ESM Import The SDK is distributed as an ESM module: ```typescript import { HivePay } from '@hivepay/client'; ``` ```javascript import { HivePay } from '@hivepay/client'; ``` ```javascript const { HivePay } = require('@hivepay/client'); ``` ## Configuration Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `apiKey` | `string` | - | Your HivePay API key | | `webhookSecret` | `string` | - | Webhook signing secret (`whsec_xxx`) for signature verification | | `endpoint` | `string` | `https://hivepay.me` | API endpoint URL | | `timeout` | `number` | `30000` | Request timeout in ms | ### Full Configuration ```typescript const hivepay = new HivePay({ apiKey: 'sk_live_xxxxxxxxxxxxx', webhookSecret: 'whsec_xxxxxxxxxxxxx', // For webhook verification endpoint: 'https://hivepay.me', // Default timeout: 30000 // 30 seconds }); ``` ### Custom Endpoint For self-hosted deployments: ```typescript const hivepay = new HivePay({ apiKey: 'sk_live_xxxxxxxxxxxxx', endpoint: 'https://your-hivepay-instance.com' }); ``` ## TypeScript Configuration The SDK includes TypeScript definitions. No additional `@types` package is needed. Recommended `tsconfig.json` settings: ```json { "compilerOptions": { "target": "ES2022", "module": "ESNext", "moduleResolution": "bundler", "esModuleInterop": true, "strict": true } } ``` ## Verifying Installation Test your installation: ```typescript import { HivePay } from '@hivepay/client'; const hivepay = new HivePay({ apiKey: process.env.HIVEPAY_API_KEY! }); async function testConnection() { try { const feeRate = await hivepay.payments.getFeeRate(); console.log('Connected! Current fee rate:', feeRate); } catch (error) { console.error('Connection failed:', error); } } testConnection(); ``` --- # Merchants API Register and manage merchant accounts using the SDK. ## Get Current Merchant Get the merchant associated with the current API key: ```typescript const merchant = await hivepay.merchants.getCurrent(); console.log(merchant.id); // Merchant ID console.log(merchant.name); // Business name console.log(merchant.hiveAccount); // Hive username console.log(merchant.iconUrl); // Logo URL console.log(merchant.webhookUrl); // Webhook endpoint console.log(merchant.isActive); // Active status console.log(merchant.createdAt); // Registration date ``` ## Update Merchant Update merchant settings: ```typescript const updated = await hivepay.merchants.update('merchant_id', { iconUrl: 'https://example.com/new-logo.png', webhookUrl: 'https://example.com/webhooks/hivepay', hiveAccount: 'newaccount' }); console.log('Updated:', updated.name); ``` ### Updatable Fields | Field | Type | Description | |-------|------|-------------| | `iconUrl` | `string` | Logo/icon URL | | `webhookUrl` | `string` | Webhook endpoint URL | | `hiveAccount` | `string` | Hive account for payments | You can only update merchants you own (matching API key). ## Admin Operations Admin endpoints require elevated privileges: ### List All Merchants ```typescript // Paginated list const result = await hivepay.admin.listMerchants({ page: 1, limit: 50, query: 'store' // Optional search }); console.log(result.data); // Merchant[] console.log(result.pagination); // Pagination info ``` ### Iterate All Merchants ```typescript // Iterate through all merchants for await (const merchant of hivepay.admin.iterateMerchants()) { console.log(merchant.id, merchant.name, merchant.isActive); } // With search and custom page size for await (const merchant of hivepay.admin.iterateMerchants({ query: 'store', pageSize: 50 })) { // Process merchant } ``` ### Activate/Deactivate Merchant ```typescript // Activate a merchant await hivepay.admin.setActive('merchant_id', true); // Deactivate a merchant await hivepay.admin.setActive('merchant_id', false); ``` ## Examples ### Complete Registration Flow ```typescript import { HivePay, isHivePayError } from '@hivepay/client'; async function registerMerchant(data: { name: string; hiveAccount: string; iconUrl?: string; }) { const publicClient = new HivePay(); try { const result = await publicClient.merchants.register(data); // Store credentials securely (e.g., in database) await saveCredentialsToDatabase(result.merchant.id, result.apiKey, result.webhookSecret); // Return client for immediate use return { merchant: result.merchant, client: publicClient.withApiKey(result.apiKey) }; } catch (error) { if (isHivePayError(error) && error.isValidation()) { throw new Error(`Invalid data: ${error.message}`); } throw error; } } ``` ### Configure Webhooks After Registration ```typescript async function setupMerchant(apiKey: string, webhookUrl: string) { const hivepay = new HivePay({ apiKey }); // Get current merchant const merchant = await hivepay.merchants.getCurrent(); // Configure webhook await hivepay.merchants.update(merchant.id, { webhookUrl }); console.log('Webhook configured for', merchant.name); } ``` --- # Payments API Create, retrieve, and manage payment sessions using the SDK. ## Get Payment Retrieve full payment details: ```typescript const payment = await hivepay.payments.get('payment_id'); console.log(payment.status); // Current status console.log(payment.amount.formatted); // '10.500 HBD' console.log(payment.amount.usdCents); // USD equivalent console.log(payment.completedAt); // Date or null console.log(payment.metadata); // Your custom data ``` ## Wait for Completion Poll until payment reaches terminal status: ```typescript try { const status = await hivepay.payments.waitFor('payment_id', { timeout: 300000, // 5 minutes interval: 3000 // Check every 3 seconds }); switch (status) { case 'completed': console.log('Payment successful!'); break; case 'failed': console.log('Payment failed'); break; case 'user_cancelled': case 'system_cancelled': console.log('Payment cancelled'); break; } } catch (error) { // Timeout exceeded console.error('Polling timed out'); } ``` ### Options | Option | Type | Default | Description | |--------|------|---------|-------------| | `timeout` | `number` | `300000` | Max wait time (ms) | | `interval` | `number` | `3000` | Poll interval (ms) | ## Iterate Payments Async iterator for processing all payments: ```typescript // Direct iteration for await (const payment of hivepay.payments) { console.log(payment.id, payment.status); } // With custom page size for await (const payment of hivepay.payments.iterate({ pageSize: 50 })) { await processPayment(payment); } // Early exit for await (const payment of hivepay.payments) { if (payment.id === 'target_id') { console.log('Found!'); break; } } ``` ## Type Definitions ### Payment ```typescript interface Payment { id: string; merchantId: string; status: PaymentStatus; checkoutUrl: string; amount: { value: string; formatted: string; currency: 'HIVE' | 'HBD'; usdCents: number; }; fee: string; net: string; description: string; metadata?: Record; redirectUrl?: string; cancelUrl?: string; expiresAt: Date; completedAt: Date | null; createdAt: Date; } type PaymentStatus = | 'pending' | 'processing' | 'completed' | 'failed' | 'user_cancelled' | 'system_cancelled'; ``` ### PaginatedResult ```typescript interface PaginatedResult { data: T[]; pagination: { page: number; limit: number; total: number; totalPages: number; }; } ``` --- # Utilities Helper functions for common operations like fee calculations and webhook verification. ### getSplitAmountFromFormatted Calculate from decimal string: ```typescript import { getSplitAmountFromFormatted } from '@hivepay/client'; const grossAmount = '10.500'; // Decimal format const feePercent = 1.5; const { fee, net } = getSplitAmountFromFormatted(grossAmount, feePercent); console.log('Fee:', fee); // 158n console.log('Net:', net); // 10342n ``` ## Webhook Verification ### verifyWebhook Verify webhook signature and parse payload: ```typescript import { HivePay } from '@hivepay/client'; const hivepay = new HivePay({ apiKey: 'sk_live_xxx', webhookSecret: 'whsec_xxx' }); async function handleWebhook(req: Request) { const result = await hivepay.verifyWebhook({ payload: await req.text(), signature: req.headers.get('X-HivePay-Signature')!, timestamp: req.headers.get('X-HivePay-Timestamp')!, maxAge: 300000 // 5 minutes (optional) }); if (!result.valid) { console.error('Invalid webhook:', result.error); return new Response('Unauthorized', { status: 401 }); } // Access verified event const { event } = result; console.log('Event type:', event.type); console.log('Payment ID:', event.data.paymentId); console.log('Status:', event.data.status); return new Response('OK'); } ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `payload` | `string` | Yes | Raw request body | | `signature` | `string` | Yes | `X-HivePay-Signature` header | | `timestamp` | `string` | Yes | `X-HivePay-Timestamp` header | | `maxAge` | `number` | No | Max age in ms (default: 300000) | ### Returns ```typescript // Success { valid: true, event: WebhookEvent } // Failure { valid: false, error: string } ``` ## Type Guards ### isHivePayError Check if an error is a HivePay error: ```typescript import { isHivePayError } from '@hivepay/client'; try { await hivepay.payments.get('invalid-id'); } catch (error) { if (isHivePayError(error)) { // TypeScript knows this is HivePayError console.log(error.code); console.log(error.statusCode); // Use type guards if (error.isNotFound()) { // Handle 404 } } } ``` --- # Support Get help with HivePay integration and troubleshooting. ### Email Support For private inquiries, security issues, or account-related questions: **support@hivepay.me** We aim to respond within 24-48 hours on business days. Replace with your actual support email address. ## Common Issues ### Authentication Errors **Symptom:** `401 Unauthorized` or `AUTHENTICATION_ERROR` **Solutions:** 1. Verify your API key is correct 2. Check the API key hasn't been regenerated 3. Ensure the `Authorization` header is formatted correctly: `Bearer sk_live_xxx` ### Webhook Not Received **Symptom:** Your webhook endpoint isn't receiving notifications **Solutions:** 1. Verify webhook URL is configured in [Settings](/dashboard/settings/) 2. Ensure URL is HTTPS and publicly accessible 3. Check your server logs for incoming requests 4. Test with local webhook server: `pnpm test:webhook` ### Payment Not Completing **Symptom:** Payment stuck in `pending` or `processing` **Solutions:** 1. Verify the Hive transaction was submitted 2. Check blockchain explorers for transaction status 3. Wait for blockchain confirmation (typically 3 seconds) 4. Contact support if issue persists ### SDK Installation Issues **Symptom:** Cannot import `@hivepay/client` **Solutions:** 1. Verify Node.js version is 18+ 2. Run `pnpm install` to ensure dependencies are installed 3. Check for conflicting package versions ## Feature Requests Have an idea for HivePay? We'd love to hear it: [!button icon="light-bulb" text="Request Feature"](https://github.com/hivepayment/hivepay/issues/new?labels=enhancement) ## Business Inquiries For partnerships, enterprise pricing, or custom integrations: **business@hivepay.me** Replace with your actual business email address. --- # System Status Check the current operational status of HivePay services. ## Services Monitored | Service | Description | |---------|-------------| | **API** | Payment API endpoints | | **Dashboard** | Merchant dashboard | | **Checkout** | Customer checkout pages | | **Webhooks** | Webhook delivery system | | **Documentation** | This documentation site | ## Maintenance Windows Planned maintenance is announced on: - Status page - Discord server - Email to affected merchants (for major maintenance) ### Typical Maintenance | Maintenance Type | Frequency | Duration | Impact | |-----------------|-----------|----------|--------| | Security updates | Weekly | < 5 min | None | | Feature releases | Bi-weekly | < 10 min | Minimal | | Major upgrades | Monthly | < 30 min | May affect API | ## API Health Check Programmatically check API status: ```typescript async function checkApiHealth(): Promise { try { const response = await fetch('https://hivepay.me/api/health'); return response.ok; } catch { return false; } } ``` ```bash curl -s -o /dev/null -w "%{http_code}" https://hivepay.me/api/health # Returns 200 if healthy ``` --- # x402 Protocol Accept automated HBD payments from AI agents and x402-aware clients through your existing HivePay checkout URLs. ## Why Hive + HBD? Hive is a natural fit for x402 micropayments: | Property | Benefit | |----------|---------| | **Zero transaction fees** | Every micropayment arrives in full — no gas eating into small amounts | | **3-second finality** | Near-instant settlement, no waiting for confirmations | | **HBD stablecoin** | Pegged to $1 USD — no volatility risk for service providers | | **Human-readable accounts** | `alice` pays `your-service`, not `0x742d35Cc...` | | **Battle-tested** | Billions of transactions processed since 2016 | ## Client Detection HivePay automatically detects x402-aware clients (AI agents, `HiveX402Client`, CLI tools) by inspecting the request: - If the `x-payment` header is present — it's an x402 payment retry - If the `Accept` header does not include `text/html` — it's not a browser Browser users see the normal checkout page. x402 clients get a `402` response with payment requirements. ## Merchant Control x402 is **enabled by default** for all merchants. Merchants can disable it in the [Dashboard settings](/dashboard/settings/) or via API. When disabled, x402 clients receive a `403` error on the checkout URL. --- # Client Integration Build apps and AI agents that can pay for HivePay checkout URLs automatically. ## Automated Client (Server-side) The `HiveX402Client` wraps the native `fetch()` API and transparently handles the `402 -> sign -> retry` flow. ```typescript import { HiveX402Client } from '@hiveio/x402/client'; const client = new HiveX402Client({ account: 'alice', activeKey: '5K...', // Hive active private key (WIF format) maxPayment: 15.0 // Max HBD per request (default: 1.0) }); // Pay for a HivePay checkout URL const response = await client.fetch('https://hivepay.me/for/order-abc123'); const data = await response.json(); console.log(data.txId); // On-chain transaction ID console.log(data.payer); // "alice" console.log(data.sessionId); // HivePay session ID ``` ### Configuration | Option | Type | Default | Description | |--------|------|---------|-------------| | `account` | `string` | Required | Hive account name | | `activeKey` | `string` | Required | Active private key in WIF format | | `maxPayment` | `number` | `1.0` | Maximum HBD per single request | The `activeKey` has full transfer authority over your account. Only use this in secure server-side environments. Never expose it in client-side JavaScript. ## Browser Client For browser-based apps, you cannot embed private keys. Instead, use the library's building blocks with an external wallet signer. ### With Hive Keychain ```typescript import { parseRequirements } from '@hiveio/x402/client'; async function payForCheckout(checkoutUrl: string, account: string) { // Step 1: Request the checkout URL, get 402 requirements const initialResponse = await fetch(checkoutUrl); if (initialResponse.status !== 402) return initialResponse; // Not a 402 or already paid // Step 2: Parse payment requirements from the response const body = await initialResponse.json(); const requirements = body.accepts[0]; const { feeAccount, feeAmount, netAmount } = requirements.extra; // Step 3: Build the two-operation transaction using Hive Keychain const ops = [ ['transfer', { from: account, to: requirements.payTo, amount: netAmount, memo: `pos-${requirements.extra.sessionId}` }], ['transfer', { from: account, to: feeAccount, amount: feeAmount, memo: `Fee for ${requirements.extra.sessionId}` }] ]; // Step 4: Sign with Hive Keychain const signResult = await new Promise((resolve, reject) => { window.hive_keychain.requestBroadcast( account, ops, 'Active', (response) => { if (response.success) resolve(response); else reject(new Error(response.message)); } ); }); // Payment is broadcast — HivePay detects it via block scanning return signResult; } ``` When using Hive Keychain, the transaction is broadcast directly by the wallet extension. HivePay's block scanner will detect the transfers and mark the session as completed, just like a normal Hive checkout payment. ## Programmatic Verify & Settle (SDK) If you build your own x402 transaction signing and don't use `HiveX402Client`, you can call the HivePay verify and settle endpoints directly through the `@hivepay/client` SDK. This is useful when you want full control over transaction construction, or when integrating x402 into an existing backend pipeline. ```typescript import { HivePay } from '@hivepay/client'; const hivepay = new HivePay({ apiKey: 'sk_live_xxx' }); // After constructing and signing the transaction yourself: const payload = { x402Version: 1 as const, scheme: 'exact' as const, network: 'hive:mainnet', payload: { signedTransaction: mySignedTx, nonce: crypto.randomUUID() } }; // Optional: verify first (does NOT broadcast) const check = await hivepay.payments.x402Verify('session_id', payload); if (!check.isValid) { throw new Error(check.invalidReason); } // Settle: verify + broadcast + mark session completed const result = await hivepay.payments.x402Settle('session_id', payload); if (result.success) { console.log(`Paid! TX: ${result.txId}, Payer: ${result.payer}`); } ``` ```php use HivePay\HivePay; $hivepay = new HivePay(['apiKey' => 'sk_live_xxx']); $payload = [ 'x402Version' => 1, 'scheme' => 'exact', 'network' => 'hive:mainnet', 'payload' => [ 'signedTransaction' => $mySignedTx, 'nonce' => bin2hex(random_bytes(16)), ], ]; // Optional: verify first (does NOT broadcast) $check = $hivepay->payments->x402Verify('session_id', $payload); if (!$check['isValid']) { throw new RuntimeException($check['invalidReason']); } // Settle: verify + broadcast + mark session completed $result = $hivepay->payments->x402Settle('session_id', $payload); if ($result['success']) { echo "Paid! TX: {$result['txId']}, Payer: {$result['payer']}"; } ``` ## External Resources - [x402 Protocol Specification](https://github.com/coinbase/x402) — the open standard by Coinbase - [@hiveio/x402 on npm](https://www.npmjs.com/package/@hiveio/x402) — the Hive implementation by Ecency - [hive-x402 on GitHub](https://github.com/ecency/hive-x402) — source code and documentation - [Hive CAIP-2 Namespace](https://github.com/ChainAgnostic/namespaces/pull/174) — Hive's registration in the cross-chain standard --- # Merchant Configuration Control x402 payment support for your HivePay merchant account. ## Toggle x402 Support ### Via API ```typescript import { HivePay } from '@hivepay/client'; const hivepay = new HivePay({ apiKey: 'sk_live_xxx' }); // Disable x402 payments await hivepay.merchants.update('your_merchant_id', { x402Enabled: false }); // Re-enable x402 payments await hivepay.merchants.update('your_merchant_id', { x402Enabled: true }); ``` ```php use HivePay\HivePay; $hivepay = new HivePay(['apiKey' => 'sk_live_xxx']); // Disable x402 payments $hivepay->merchants->update('your_merchant_id', [ 'x402Enabled' => false, ]); // Re-enable x402 payments $hivepay->merchants->update('your_merchant_id', [ 'x402Enabled' => true, ]); ``` ```bash # Disable x402 payments curl -X POST https://hivepay.me/api/public/merchants/your_merchant_id \ -H "x-api-key: sk_live_xxx" \ -H "Content-Type: application/json" \ -d '{ "x402Enabled": false }' # Re-enable x402 payments curl -X POST https://hivepay.me/api/public/merchants/your_merchant_id \ -H "x-api-key: sk_live_xxx" \ -H "Content-Type: application/json" \ -d '{ "x402Enabled": true }' ``` ### Via Dashboard Toggle the **x402 Payments** switch in your [Dashboard Settings](/dashboard/settings/). ## Fee Structure x402 payments use the **same fee structure** as standard HivePay checkout payments. The [percentage-based fee](/payments/fees/) is included in the `402` response and enforced at settlement time. The `402` response includes a fee breakdown in the `extra` field: ```json { "extra": { "sessionId": "cmj7b2rg10004d2rimvum8kaz", "feeAccount": "hivepay", "feeAmount": "0.158 HBD", "netAmount": "10.342 HBD" } } ``` The x402 client must sign a transaction with **two transfer operations**: | Transfer | Recipient | Amount | |----------|-----------|--------| | Net payment | Merchant's Hive account | `netAmount` | | Fee | HivePay's fee account (`feeAccount`) | `feeAmount` | Both transfers must be from the same sender and in the same currency as the payment session. ## API Endpoints HivePay also exposes session-aware x402 endpoints for programmatic use: | Endpoint | Method | Description | |----------|--------|-------------| | `/api/public/x402/health` | GET | Health check | | `/api/public/x402/supported-networks` | GET | Returns `["hive:mainnet"]` | | `/api/public/x402/verify` | POST | Verify a payment payload for a session | | `/api/public/x402/settle` | POST | Verify, broadcast, and complete a session | ### Using the SDK The `@hivepay/client` (TypeScript) and `hivepay/client` (PHP) SDKs provide built-in methods for the verify and settle endpoints: ```typescript import { HivePay } from '@hivepay/client'; const hivepay = new HivePay({ apiKey: 'sk_live_xxx' }); // Verify without broadcasting const verify = await hivepay.payments.x402Verify('session_id', { x402Version: 1, scheme: 'exact', network: 'hive:mainnet', payload: { signedTransaction: tx, nonce: 'unique-nonce' } }); if (verify.isValid) { // Settle — broadcasts and completes the session const settle = await hivepay.payments.x402Settle('session_id', { x402Version: 1, scheme: 'exact', network: 'hive:mainnet', payload: { signedTransaction: tx, nonce: 'unique-nonce' } }); console.log(settle.txId, settle.payer); } ``` ```php use HivePay\HivePay; $hivepay = new HivePay(['apiKey' => 'sk_live_xxx']); $payload = [ 'x402Version' => 1, 'scheme' => 'exact', 'network' => 'hive:mainnet', 'payload' => ['signedTransaction' => $tx, 'nonce' => 'unique-nonce'], ]; // Verify without broadcasting $verify = $hivepay->payments->x402Verify('session_id', $payload); if ($verify['isValid']) { // Settle — broadcasts and completes the session $settle = $hivepay->payments->x402Settle('session_id', $payload); echo $settle['txId'] . ' ' . $settle['payer']; } ``` ```bash # Verify curl -X POST https://hivepay.me/api/public/x402/verify \ -H "Content-Type: application/json" \ -d '{ "sessionId": "cmj7b2rg10004d2rimvum8kaz", "paymentPayload": { "x402Version": 1, "scheme": "exact", "network": "hive:mainnet", "payload": { "signedTransaction": { ... }, "nonce": "a1b2c3d4e5f6..." } } }' # Settle curl -X POST https://hivepay.me/api/public/x402/settle \ -H "Content-Type: application/json" \ -d '{ "sessionId": "cmj7b2rg10004d2rimvum8kaz", "paymentPayload": { "x402Version": 1, "scheme": "exact", "network": "hive:mainnet", "payload": { "signedTransaction": { ... }, "nonce": "a1b2c3d4e5f6..." } } }' ``` ### Settle Response ```json { "success": true, "txId": "abc123def456...", "payer": "alice" } ``` For most use cases, the `/for/[slug]` middleware flow (described in the [Quick Start](/x402/quick-start/)) is simpler — the client just fetches the checkout URL and everything is handled automatically. The API endpoints and SDK methods above are for advanced integrations that need to separate verification from settlement. --- # Quick Start Accept automated x402 payments from AI agents through your existing HivePay integration — no additional server-side setup needed. ## Merchant Side (No Changes Needed) Your existing payment creation code already works with x402: ```typescript import { HivePay } from '@hivepay/client'; const hivepay = new HivePay({ apiKey: 'sk_live_xxx' }); const payment = await hivepay.payments.create({ amount: '10500', // 10.500 HBD currency: 'HBD', description: 'API access' }); // This URL works for BOTH browsers and x402 clients const checkoutUrl = payment.checkoutUrl; // e.g., "https://hivepay.me/for/api-access-a1b2c3" ``` ```php use HivePay\HivePay; $hivepay = new HivePay(['apiKey' => 'sk_live_xxx']); $payment = $hivepay->payments->create([ 'amount' => '10500', // 10.500 HBD 'currency' => 'HBD', 'description' => 'API access', ]); // This URL works for BOTH browsers and x402 clients $checkoutUrl = $payment['checkoutUrl']; // e.g., "https://hivepay.me/for/api-access-a1b2c3" ``` ```bash curl -X POST https://hivepay.me/api/public/payments/create \ -H "x-api-key: sk_live_xxx" \ -H "Content-Type: application/json" \ -d '{ "amount": "10500", "currency": "HBD", "description": "API access" }' ``` When a browser visits the checkout URL, they see the normal payment page. When an x402 client visits the same URL, they receive a `402` response and can pay automatically. ## What the 402 Response Looks Like When an x402 client hits a checkout URL without a payment header: ``` HTTP/1.1 402 Payment Required x-payment: Content-Type: application/json ``` ```json { "x402Version": 1, "accepts": [{ "x402Version": 1, "scheme": "exact", "network": "hive:mainnet", "maxAmountRequired": "10.500 HBD", "resource": "/for/api-access-a1b2c3", "payTo": "merchant-account", "validBefore": "2025-01-15T11:30:00.000Z", "description": "API access", "extra": { "sessionId": "cmj7b2rg10004d2rimvum8kaz", "feeAccount": "hivepay", "feeAmount": "0.158 HBD", "netAmount": "10.342 HBD" } }] } ``` The `extra` field tells the client the fee breakdown. The signed transaction must include two transfers matching the `netAmount` and `feeAmount`. ## Next Steps - [Configure x402 settings for your merchant account](/x402/configuration/) - [Build custom x402 clients for browsers and AI agents](/x402/client/) - [Learn about fee calculations](/payments/fees/)