@mycloudclaw/paygate-sdk
v1.0.0
Published
TypeScript SDK for PayGate - Universal Pay-Per-Use Gateway
Maintainers
Readme
PayGate SDK
TypeScript SDK for integrating PayGate - the universal pay-per-use gateway platform.
PayGate enables any business to monetize APIs and services with multiple payment protocols through a single integration.
Features
- Multi-Protocol Support: x402, L402, Stripe, AP2, Solana Pay
- Type-Safe: Full TypeScript support with comprehensive type definitions
- Automatic Retry: Built-in exponential backoff for network resilience
- Webhook Verification: Secure webhook signature validation
- Protocol Detection: Automatic payment protocol detection
- Easy Integration: Simple, intuitive API
Installation
npm install @paygate/sdkQuick Start
import { PayGateClient } from '@paygate/sdk';
// Initialize client
const paygate = new PayGateClient('your-api-key', {
baseUrl: 'https://pay.searchx402.com',
maxRetries: 3,
timeout: 30000,
debug: true,
});
// Create a payment
const payment = await paygate.createPayment({
amount: 1000, // cents
currency: 'usd',
protocol: 'stripe',
metadata: {
userId: 'user_123',
orderId: 'order_456',
},
});
console.log('Payment created:', payment.id);Payment Methods
Create Payment
const payment = await paygate.createPayment({
amount: 1000, // Amount in cents
currency: 'usd',
protocol: 'x402', // or 'l402', 'stripe', 'ap2', 'solana-pay'
serviceId: 'svc_abc123',
callerId: 'user_xyz',
metadata: {
custom_field: 'value',
},
});Get Payment
const payment = await paygate.getPayment('pay_123');
console.log(payment.status); // 'created', 'pending', 'succeeded', 'failed'List Payments
const { payments, total } = await paygate.listPayments({
status: 'succeeded',
protocol: 'x402',
limit: 50,
offset: 0,
startDate: '2024-01-01T00:00:00Z',
endDate: '2024-12-31T23:59:59Z',
});
payments.forEach((payment) => {
console.log(`${payment.id}: ${payment.amount} ${payment.currency}`);
});Cancel Payment
const canceled = await paygate.cancelPayment('pay_123');Service Management
Create Service
const service = await paygate.createService({
name: 'My API Service',
description: 'AI-powered data analysis',
baseUrl: 'https://api.example.com',
pricing: {
perCall: {
amountCents: 50,
currency: 'usd',
},
},
enabledProtocols: ['x402', 'stripe', 'l402'],
metadata: {
apiVersion: 'v1',
},
});Update Service
const updated = await paygate.updateService('svc_123', {
pricing: {
perCall: {
amountCents: 75, // Increase price
currency: 'usd',
},
},
});Get Service
const service = await paygate.getService('svc_123');Protocol-Specific Usage
x402 (Crypto - USDC on Base L2)
import { X402Handler } from '@paygate/sdk';
const x402 = new X402Handler({
walletAddress: '0x1234...5678',
chainId: 8453, // Base mainnet
});
// Generate payment headers
const headers = x402.generateHeaders(
'0xabc...def', // Transaction hash
'0x9876...5432' // Caller wallet (optional)
);
// Make paid request
const response = await fetch('https://api.example.com/data', {
headers,
});L402 (Bitcoin Lightning)
import { L402Handler } from '@paygate/sdk';
const l402 = new L402Handler();
// Create payment proof
const proof = l402.createPaymentProof(
'macaroon_hex_string',
'preimage_hex_string'
);
// Generate headers
const headers = l402.generateHeaders('macaroon', 'preimage');Stripe
import { StripeHandler } from '@paygate/sdk';
const stripe = new StripeHandler({
publishableKey: 'pk_test_...',
});
// Create payment intent
const payment = await paygate.createStripePaymentIntent(
'svc_123',
5000, // $50.00
'usd',
10, // 10% platform fee
{
orderId: 'order_789',
}
);
console.log('Client secret:', payment.clientSecret);Stripe Connect
// Create Connect account for a service
const account = await paygate.createConnectAccount('svc_123', '[email protected]');
// Get onboarding link
const { url } = await paygate.getConnectAccountOnboardingLink(
account.id,
'https://example.com/onboarding/complete',
'https://example.com/onboarding/refresh'
);
console.log('Send vendor to:', url);
// Check account status
const status = await paygate.getConnectAccount(account.id);
console.log('Charges enabled:', status.chargesEnabled);AP2 (Agent Payments Protocol)
import { AP2Handler } from '@paygate/sdk';
const ap2 = new AP2Handler({
provider: 'stripe', // or 'paypal'
accountId: 'acct_123',
});
// Generate headers
const headers = ap2.generateHeaders('bearer_token_here');Solana Pay
import { SolanaPayHandler } from '@paygate/sdk';
const solanaPay = new SolanaPayHandler({
walletAddress: 'So11111111111111111111111111111111111111112',
network: 'mainnet-beta',
});
// Verify transaction
const tx = await solanaPay.verifyTransaction('signature_base58');
console.log('Amount:', solanaPay.lamportsToSol(tx!.amountLamports));Webhooks
Verify Webhook Signature
// In your webhook handler
app.post('/webhooks/paygate', async (req, res) => {
const signature = req.headers['x-paygate-signature'];
const payload = req.body;
const result = await paygate.verifyWebhook({
payload,
signature,
secret: 'your_webhook_secret',
});
if (!result.valid) {
return res.status(401).json({ error: result.error });
}
// Process webhook event
const event = result.event!;
switch (event.type) {
case 'payment.succeeded':
console.log('Payment succeeded:', event.data);
break;
case 'payment.failed':
console.log('Payment failed:', event.data);
break;
}
res.json({ received: true });
});Analytics
Get Revenue Analytics
const analytics = await paygate.getRevenueAnalytics('30d', 'svc_123');
console.log('Total revenue:', analytics.overall.totalRevenue);
console.log('Transactions:', analytics.overall.totalTransactions);
analytics.byProtocol.forEach((protocol) => {
console.log(`${protocol.protocol}: $${protocol.revenue / 100}`);
});Get Protocol Usage Stats
const stats = await paygate.getProtocolUsageStats('7d');
console.log('Total requests:', stats.overall.totalRequests);
console.log('Avg latency:', stats.overall.avgLatency, 'ms');
stats.byProtocol.forEach((protocol) => {
console.log(`${protocol.protocol}: ${protocol.request_count} requests`);
});Making Paid Requests
Using PayGateClient
const response = await paygate.makePaidRequest(
'https://api.example.com/data',
'x402',
'tx_hash=0xabc...def',
{
method: 'POST',
body: JSON.stringify({ query: 'search term' }),
}
);
const data = await response.json();Manual Headers
const headers = paygate.generatePaymentHeaders('x402', 'tx_hash=0x123...');
const response = await fetch('https://api.example.com/data', {
headers: {
...headers,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query: 'search' }),
});Error Handling
import {
PayGateAPIError,
PayGateNetworkError,
PayGateValidationError,
} from '@paygate/sdk';
try {
const payment = await paygate.createPayment({
amount: 1000,
currency: 'usd',
});
} catch (error) {
if (error instanceof PayGateAPIError) {
console.error('API error:', error.code, error.message);
console.error('Status:', error.status);
console.error('Details:', error.details);
} else if (error instanceof PayGateNetworkError) {
console.error('Network error after', error.retries, 'retries');
} else if (error instanceof PayGateValidationError) {
console.error('Validation error:', error.message);
}
}Configuration
Client Options
const paygate = new PayGateClient('api-key', {
baseUrl: 'https://pay.searchx402.com',
timeout: 30000, // 30 seconds
maxRetries: 3, // Retry up to 3 times
retryDelay: 1000, // Start with 1 second delay
debug: true, // Enable debug logging
});Request Options
const payment = await paygate.getPayment('pay_123', {
timeout: 10000, // Override default timeout
retryable: false, // Disable retries for this request
idempotencyKey: 'unique-key-123', // Custom idempotency key
});TypeScript Support
The SDK is fully typed. Import types as needed:
import type {
Payment,
Service,
PaymentProtocol,
PaymentStatus,
CreatePaymentParams,
WebhookPayload,
} from '@paygate/sdk';
function processPayment(payment: Payment) {
if (payment.status === 'succeeded') {
console.log('Payment successful!');
}
}Protocol Detection
import { detectProtocolFromProof } from '@paygate/sdk';
const protocol = detectProtocolFromProof('tx_hash=0xabc...');
console.log(protocol); // 'x402'
const protocol2 = detectProtocolFromProof('L402 macaroon:preimage');
console.log(protocol2); // 'l402'Best Practices
- Always use idempotency keys for payment creation to prevent duplicate charges
- Verify webhooks before processing to ensure authenticity
- Handle errors gracefully with proper retry logic
- Store payment IDs in your database for reconciliation
- Test thoroughly with each protocol before going live
- Use HTTPS for all webhook endpoints
- Monitor analytics to track payment success rates
License
MIT
Support
- Documentation: https://docs.useyouragents.com/paygate
- GitHub: https://github.com/mkc909/agents
- Email: [email protected]
