Skip to main content

Solana API Reference

This document provides a comprehensive reference for WhiskyPay’s Solana payment integration.

SDK Components

createSession

Creates a new payment session.
async function createSession(
  saasId: string,
  email: string,
  plan: string
): Promise<string>

Parameters

ParameterTypeDescription
saasIdstringYour merchant ID from the dashboard
emailstringCustomer’s email address
planstringPlan identifier for the purchase

Returns

A session ID string that you’ll use with the PaymentModal.

Example

import { createSession } from '@whisky-peak/whisky-pay-sdk';

const handleCheckout = async () => {
  try {
    const sessionId = await createSession(
      'your-saas-id',
      'customer@example.com',
      'premium-plan'
    );
    
    // Use sessionId with PaymentModal
    setSessionId(sessionId);
  } catch (error) {
    console.error('Failed to create session:', error);
  }
};

PaymentModal

React component for displaying the payment UI.
<PaymentModal
  sessionId: string;
  RPC_URL: string;
  onRedirect?: () => void;
  theme?: ThemeOptions;
  desiredToken?: string;
  showCloseButton?: boolean;
  onClose?: () => void;
/>

Props

PropTypeRequiredDefaultDescription
sessionIdstringYes-Session ID from createSession
RPC_URLstringYes-Solana RPC URL
onRedirectfunctionNoundefinedCallback when payment completes
themeobjectNoundefinedCustom styling options
desiredTokenstringNoundefinedPreferred token (USDC, SOL, etc.)
showCloseButtonbooleanNofalseAllow users to close the modal
onClosefunctionNoundefinedCallback when modal is closed

ThemeOptions

PropertyTypeDescription
colorPrimarystringPrimary color for buttons and accents
colorBackgroundstringBackground color
colorTextstringText color
borderRadiusstringBorder radius for buttons and panels
fontFamilystringFont family

Example

import { PaymentModal } from '@whisky-peak/whisky-pay-sdk';

function Checkout({ sessionId }) {
  return (
    <PaymentModal
      sessionId={sessionId}
      RPC_URL="https://api.mainnet-beta.solana.com"
      onRedirect={() => window.location.href = '/success'}
      theme={{
        colorPrimary: '#8A2BE2',
        colorBackground: '#F5F5F5',
        colorText: '#333333',
        borderRadius: '8px'
      }}
      desiredToken="USDC"
      showCloseButton={true}
      onClose={() => console.log('Modal closed')}
    />
  );
}

getSessionDetails

Retrieves details about a payment session.
async function getSessionDetails(
  sessionId: string
): Promise<SessionDetails>

Parameters

ParameterTypeDescription
sessionIdstringSession ID to retrieve

Returns: SessionDetails

PropertyTypeDescription
idstringSession ID
statusstringSession status (pending, completed, expired)
emailstringCustomer email
planIdstringPlan identifier
amountnumberPayment amount
currencystringCurrency code
createdAtstringCreation timestamp
expiresAtstringExpiration timestamp

Example

import { getSessionDetails } from '@whisky-peak/whisky-pay-sdk';

async function checkSession(sessionId) {
  try {
    const details = await getSessionDetails(sessionId);
    console.log(`Session status: ${details.status}`);
    return details;
  } catch (error) {
    console.error('Failed to get session details:', error);
  }
}

checkPaymentStatus

Checks the status of a payment.
async function checkPaymentStatus(
  sessionId: string
): Promise<PaymentStatusResponse>

Parameters

ParameterTypeDescription
sessionIdstringSession ID to check

Returns: PaymentStatusResponse

PropertyTypeDescription
statusPaymentStatusPayment status enum
messagestringStatus message
signaturestringTransaction signature (if completed)

PaymentStatus Enum

enum PaymentStatus {
  PENDING = 'pending',
  PROCESSING = 'processing',
  COMPLETED = 'completed',
  FAILED = 'failed',
  EXPIRED = 'expired'
}

Example

import { checkPaymentStatus, PaymentStatus } from '@whisky-peak/whisky-pay-sdk';

async function pollPaymentStatus(sessionId) {
  const intervalId = setInterval(async () => {
    try {
      const status = await checkPaymentStatus(sessionId);
      
      if (status.status === PaymentStatus.COMPLETED) {
        clearInterval(intervalId);
        console.log('Payment completed!', status.signature);
        // Handle successful payment
      } else if (status.status === PaymentStatus.FAILED) {
        clearInterval(intervalId);
        console.error('Payment failed:', status.message);
        // Handle failed payment
      }
    } catch (error) {
      console.error('Error checking payment status:', error);
    }
  }, 3000);
  
  // Clear interval after 10 minutes to prevent infinite polling
  setTimeout(() => clearInterval(intervalId), 10 * 60 * 1000);
}

verifyPayment

Verifies a payment on-chain.
async function verifyPayment(
  sessionId: string,
  signature: string,
  RPC_URL: string
): Promise<VerificationResult>

Parameters

ParameterTypeDescription
sessionIdstringSession ID to verify
signaturestringTransaction signature
RPC_URLstringSolana RPC URL

Returns: VerificationResult

PropertyTypeDescription
verifiedbooleanWhether payment is verified
detailsobjectTransaction details

Example

import { verifyPayment } from '@whisky-peak/whisky-pay-sdk';

async function confirmPayment(sessionId, signature) {
  try {
    const result = await verifyPayment(
      sessionId,
      signature,
      'https://api.mainnet-beta.solana.com'
    );
    
    if (result.verified) {
      console.log('Payment verified on-chain');
      return true;
    } else {
      console.error('Payment verification failed');
      return false;
    }
  } catch (error) {
    console.error('Error verifying payment:', error);
    return false;
  }
}

REST API Endpoints

These endpoints are available for server-side operations.

POST /api/v1/sessions

Creates a new payment session.

Request Body

{
  "saasId": "your-saas-id",
  "email": "customer@example.com",
  "plan": "premium-plan"
}

Headers

HeaderValueDescription
Content-Typeapplication/jsonJSON content type
AuthorizationBearer YOUR_API_KEYAPI key authentication

Response

{
  "sessionId": "sess_a1b2c3d4e5f6",
  "expiresAt": "2023-08-25T15:30:00Z"
}

GET /api/v1/sessions/:sessionId

Retrieves details about a payment session.

Parameters

ParameterTypeDescription
sessionIdstringSession ID to retrieve

Headers

HeaderValueDescription
AuthorizationBearer YOUR_API_KEYAPI key authentication

Response

{
  "id": "sess_a1b2c3d4e5f6",
  "status": "pending",
  "email": "customer@example.com",
  "planId": "premium-plan",
  "amount": 10.00,
  "currency": "USDC",
  "createdAt": "2023-08-25T14:30:00Z",
  "expiresAt": "2023-08-25T15:30:00Z"
}

GET /api/v1/payments/:sessionId/status

Checks the status of a payment.

Parameters

ParameterTypeDescription
sessionIdstringSession ID to check

Headers

HeaderValueDescription
AuthorizationBearer YOUR_API_KEYAPI key authentication

Response

{
  "status": "completed",
  "message": "Payment successful",
  "signature": "5Pz9yoyAYKuCsF7jAZJAZm9Rp5pXo43C6CK4qYJrA2UXP5qPxAvUmT7jHGYRc6H13zV3",
  "timestamp": "2023-08-25T14:45:23Z"
}

POST /api/v1/payments/verify

Verifies a payment on-chain.

Request Body

{
  "sessionId": "sess_a1b2c3d4e5f6",
  "signature": "5Pz9yoyAYKuCsF7jAZJAZm9Rp5pXo43C6CK4qYJrA2UXP5qPxAvUmT7jHGYRc6H13zV3"
}

Headers

HeaderValueDescription
Content-Typeapplication/jsonJSON content type
AuthorizationBearer YOUR_API_KEYAPI key authentication

Response

{
  "verified": true,
  "details": {
    "amount": 10.00,
    "token": "USDC",
    "sender": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",
    "recipient": "G17UmNGnMJ851x3Z1BzLFDNp2LjkTLM6A6wTGyY8xY4i",
    "blockTime": 1692969923,
    "slot": 182463921
  }
}

Webhook Events

WhiskyPay sends webhook notifications for payment status changes.

Payment Completed

{
  "event": "payment.completed",
  "sessionId": "sess_a1b2c3d4e5f6",
  "email": "customer@example.com",
  "plan": "premium-plan",
  "amount": 10.00,
  "currency": "USDC",
  "signature": "5Pz9yoyAYKuCsF7jAZJAZm9Rp5pXo43C6CK4qYJrA2UXP5qPxAvUmT7jHGYRc6H13zV3",
  "timestamp": "2023-08-25T14:45:23Z",
  "webhookSignature": "sha256=..."
}

Payment Failed

{
  "event": "payment.failed",
  "sessionId": "sess_a1b2c3d4e5f6",
  "email": "customer@example.com",
  "plan": "premium-plan",
  "reason": "Transaction rejected",
  "timestamp": "2023-08-25T14:40:12Z",
  "webhookSignature": "sha256=..."
}

Signature Verification

Verify webhook signatures to ensure authenticity:
const crypto = require('crypto');

function verifyWebhookSignature(payload, signature, secret) {
  const hmac = crypto.createHmac('sha256', secret);
  const digest = hmac.update(JSON.stringify(payload)).digest('hex');
  
  return `sha256=${digest}` === signature;
}

Error Handling

WhiskyPay API uses standard HTTP status codes and error responses.

Error Response Format

{
  "error": {
    "code": "invalid_session",
    "message": "Session not found or expired",
    "status": 404
  }
}

Common Error Codes

CodeStatusDescription
invalid_session404Session not found or expired
invalid_parameters400Invalid request parameters
authentication_error401Invalid API key
rate_limit_exceeded429Too many requests
internal_error500Server-side error

Token Support

WhiskyPay supports the following Solana tokens:
SymbolNameDecimalsToken Type
SOLSolana9Native
USDCUSD Coin6SPL
USDTTether6SPL
BONKBonk5SPL
JUPJupiter6SPL
RAYRaydium6SPL

Best Practices

Security

  1. Use HTTPS: Always use secure connections
  2. Validate Signatures: Verify webhook signatures
  3. Store API Keys Securely: Use environment variables
  4. Verify Transactions: Always verify payments on-chain

Performance

  1. Connection Pooling: Reuse HTTP connections
  2. Caching: Cache token prices and session data
  3. Background Processing: Handle webhooks asynchronously

Error Handling

  1. Retry Logic: Implement exponential backoff for failed API calls
  2. Monitoring: Set up alerts for failed payments
  3. Logging: Log all API interactions for debugging

Rate Limits

The WhiskyPay API has the following rate limits:
  • Session Creation: 60 requests per minute
  • Session Status: 120 requests per minute
  • Payment Verification: 60 requests per minute

Support and Troubleshooting

For issues with the API, contact support at support@whiskypeak.com with:
  1. Your merchant ID
  2. The session ID(s) in question
  3. Error messages received
  4. Steps to reproduce the issue
Common solutions to frequent problems:
  • “Invalid API Key”: Verify your API key in dashboard settings
  • “Session Not Found”: Check if the session has expired
  • “Payment Failed”: Verify the user has sufficient balance