Integration Guide / Hướng dẫn tích hợp

English | Tiếng Việt

English

Overview

This comprehensive integration guide will help you integrate OlymPay into your application, whether you're building a DeFi protocol, e-commerce platform, or any other application that requires stable payments.

Prerequisites

Before starting the integration:

  1. Get API Access: Sign up at app.olympay.xyz

  2. Choose Network: Decide between mainnet or testnet

  3. Select Features: Determine which OlymPay features you need

  4. Review Documentation: Familiarize yourself with the API reference

Quick Start Integration

1. Install SDK

npm install @olympay/sdk
# or
yarn add @olympay/sdk

2. Initialize SDK

import { OlymPaySDK } from '@olympay/sdk';

const olymPay = new OlymPaySDK({
  apiKey: 'your-api-key',
  network: 'mainnet', // or 'testnet'
  environment: 'production' // or 'development'
});

3. Connect Wallet

// Connect user's wallet
const wallet = await olymPay.connectWallet();

// Get wallet information
const address = wallet.getAddress();
const balance = await wallet.getBalance();

4. Implement Payment Flow

// Create payment
const payment = await olymPay.createPayment({
  amount: '100.00',
  currency: 'USD',
  recipient: '0x...',
  description: 'Payment for services'
});

// Execute payment
const result = await payment.execute();

// Handle result
if (result.success) {
  console.log('Payment successful:', result.transactionHash);
} else {
  console.error('Payment failed:', result.error);
}

Integration Patterns

E-commerce Integration

class EcommercePayment {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async processOrder(order) {
    try {
      // Create payment for order
      const payment = await this.olymPay.createPayment({
        amount: order.total.toString(),
        currency: 'USD',
        recipient: this.merchantWallet,
        description: `Order #${order.id}`,
        metadata: {
          orderId: order.id,
          customerId: order.customerId
        }
      });

      // Execute payment
      const result = await payment.execute();

      if (result.success) {
        // Update order status
        await this.updateOrderStatus(order.id, 'paid');
        return { success: true, transactionHash: result.transactionHash };
      } else {
        throw new Error(result.error.message);
      }
    } catch (error) {
      console.error('Payment processing failed:', error);
      return { success: false, error: error.message };
    }
  }

  async updateOrderStatus(orderId, status) {
    // Your order status update logic
    console.log(`Order ${orderId} status updated to ${status}`);
  }
}

DeFi Protocol Integration

class DeFiProtocol {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async createLiquidityPool(tokenA, tokenB, amountA, amountB) {
    // Create liquidity pool using OlymPay
    const pool = await this.olymPay.createLiquidityPool({
      tokenA: tokenA,
      tokenB: tokenB,
      amountA: amountA,
      amountB: amountB,
      fee: '0.3%'
    });

    return pool;
  }

  async addLiquidity(poolId, amountA, amountB) {
    const liquidity = await this.olymPay.addLiquidity({
      poolId: poolId,
      amountA: amountA,
      amountB: amountB
    });

    return liquidity;
  }

  async swapTokens(tokenIn, tokenOut, amountIn, minAmountOut) {
    const swap = await this.olymPay.swapTokens({
      tokenIn: tokenIn,
      tokenOut: tokenOut,
      amountIn: amountIn,
      minAmountOut: minAmountOut
    });

    return swap;
  }
}

Error Handling

Comprehensive Error Handling

class OlymPayErrorHandler {
  static handleError(error) {
    switch (error.code) {
      case 'INSUFFICIENT_BALANCE':
        return {
          userMessage: 'Insufficient balance for this transaction',
          action: 'Please add funds to your wallet',
          retry: false
        };
      
      case 'NETWORK_ERROR':
        return {
          userMessage: 'Network connection error',
          action: 'Please check your internet connection and try again',
          retry: true
        };
      
      case 'RATE_LIMIT_EXCEEDED':
        return {
          userMessage: 'Too many requests',
          action: 'Please wait a moment and try again',
          retry: true,
          retryAfter: 60
        };
      
      case 'UNAUTHORIZED':
        return {
          userMessage: 'Authentication failed',
          action: 'Please check your API key',
          retry: false
        };
      
      default:
        return {
          userMessage: 'An unexpected error occurred',
          action: 'Please try again or contact support',
          retry: true
        };
    }
  }
}

// Usage
try {
  const result = await olymPay.createPayment(paymentData);
} catch (error) {
  const errorInfo = OlymPayErrorHandler.handleError(error);
  console.error(errorInfo.userMessage);
  
  if (errorInfo.retry) {
    // Implement retry logic
    setTimeout(() => {
      // Retry the operation
    }, errorInfo.retryAfter * 1000);
  }
}

Testing

Unit Testing

import { OlymPaySDK } from '@olympay/sdk';

describe('OlymPay Integration', () => {
  let olymPay;

  beforeEach(() => {
    olymPay = new OlymPaySDK({
      apiKey: 'test-api-key',
      network: 'testnet',
      environment: 'development'
    });
  });

  test('should create payment successfully', async () => {
    const payment = await olymPay.createPayment({
      amount: '100.00',
      currency: 'USD',
      recipient: '0x...',
      description: 'Test payment'
    });

    expect(payment).toBeDefined();
    expect(payment.amount).toBe('100.00');
  });

  test('should handle insufficient balance error', async () => {
    await expect(
      olymPay.createPayment({
        amount: '1000000.00',
        currency: 'USD',
        recipient: '0x...',
        description: 'Test payment'
      })
    ).rejects.toThrow('INSUFFICIENT_BALANCE');
  });
});

Integration Testing

describe('E-commerce Integration', () => {
  test('should process order payment', async () => {
    const ecommerce = new EcommercePayment(olymPay);
    const order = {
      id: 'order-123',
      total: 100.00,
      customerId: 'customer-456'
    };

    const result = await ecommerce.processOrder(order);

    expect(result.success).toBe(true);
    expect(result.transactionHash).toBeDefined();
  });
});

Security Best Practices

API Key Management

// Environment variables
const config = {
  apiKey: process.env.OLYMPAY_API_KEY,
  network: process.env.NODE_ENV === 'production' ? 'mainnet' : 'testnet'
};

// Secure initialization
const olymPay = new OlymPaySDK(config);

Input Validation

class PaymentValidator {
  static validatePaymentData(data) {
    const errors = [];

    if (!data.amount || isNaN(data.amount) || data.amount <= 0) {
      errors.push('Invalid amount');
    }

    if (!data.currency || !['USD', 'EUR', 'GBP'].includes(data.currency)) {
      errors.push('Invalid currency');
    }

    if (!data.recipient || !this.isValidAddress(data.recipient)) {
      errors.push('Invalid recipient address');
    }

    return errors;
  }

  static isValidAddress(address) {
    return /^0x[a-fA-F0-9]{40}$/.test(address);
  }
}

Deployment

Production Deployment

// Production configuration
const productionConfig = {
  apiKey: process.env.OLYMPAY_API_KEY,
  network: 'mainnet',
  environment: 'production',
  timeout: 30000,
  retries: 3
};

const olymPay = new OlymPaySDK(productionConfig);

Monitoring

class OlymPayMonitor {
  constructor(olymPay) {
    this.olymPay = olymPay;
    this.setupMonitoring();
  }

  setupMonitoring() {
    // Monitor API health
    setInterval(async () => {
      try {
        await this.olymPay.healthCheck();
        console.log('OlymPay API is healthy');
      } catch (error) {
        console.error('OlymPay API health check failed:', error);
        // Alert your monitoring system
      }
    }, 60000); // Check every minute
  }

  async logTransaction(transaction) {
    // Log transaction for monitoring
    console.log('Transaction:', {
      hash: transaction.hash,
      amount: transaction.amount,
      status: transaction.status,
      timestamp: new Date().toISOString()
    });
  }
}

Tiếng Việt

Tổng quan

Hướng dẫn tích hợp toàn diện này sẽ giúp bạn tích hợp OlymPay vào ứng dụng của mình, cho dù bạn đang xây dựng giao thức DeFi, nền tảng thương mại điện tử hay bất kỳ ứng dụng nào khác yêu cầu thanh toán ổn định.

Yêu cầu trước

Trước khi bắt đầu tích hợp:

  1. Lấy quyền truy cập API: Đăng ký tại app.olympay.xyz

  2. Chọn mạng: Quyết định giữa mainnet hoặc testnet

  3. Chọn tính năng: Xác định tính năng OlymPay nào bạn cần

  4. Xem tài liệu: Làm quen với tham chiếu API

Tích hợp Bắt đầu nhanh

1. Cài đặt SDK

npm install @olympay/sdk
# hoặc
yarn add @olympay/sdk

2. Khởi tạo SDK

import { OlymPaySDK } from '@olympay/sdk';

const olymPay = new OlymPaySDK({
  apiKey: 'your-api-key',
  network: 'mainnet', // hoặc 'testnet'
  environment: 'production' // hoặc 'development'
});

3. Kết nối Ví

// Kết nối ví của người dùng
const wallet = await olymPay.connectWallet();

// Lấy thông tin ví
const address = wallet.getAddress();
const balance = await wallet.getBalance();

4. Triển khai Luồng Thanh toán

// Tạo thanh toán
const payment = await olymPay.createPayment({
  amount: '100.00',
  currency: 'USD',
  recipient: '0x...',
  description: 'Thanh toán cho dịch vụ'
});

// Thực hiện thanh toán
const result = await payment.execute();

// Xử lý kết quả
if (result.success) {
  console.log('Thanh toán thành công:', result.transactionHash);
} else {
  console.error('Thanh toán thất bại:', result.error);
}

Mẫu Tích hợp

Tích hợp Thương mại điện tử

class EcommercePayment {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async processOrder(order) {
    try {
      // Tạo thanh toán cho đơn hàng
      const payment = await this.olymPay.createPayment({
        amount: order.total.toString(),
        currency: 'USD',
        recipient: this.merchantWallet,
        description: `Đơn hàng #${order.id}`,
        metadata: {
          orderId: order.id,
          customerId: order.customerId
        }
      });

      // Thực hiện thanh toán
      const result = await payment.execute();

      if (result.success) {
        // Cập nhật trạng thái đơn hàng
        await this.updateOrderStatus(order.id, 'paid');
        return { success: true, transactionHash: result.transactionHash };
      } else {
        throw new Error(result.error.message);
      }
    } catch (error) {
      console.error('Xử lý thanh toán thất bại:', error);
      return { success: false, error: error.message };
    }
  }

  async updateOrderStatus(orderId, status) {
    // Logic cập nhật trạng thái đơn hàng của bạn
    console.log(`Trạng thái đơn hàng ${orderId} được cập nhật thành ${status}`);
  }
}

Tích hợp Giao thức DeFi

class DeFiProtocol {
  constructor(olymPay) {
    this.olymPay = olymPay;
  }

  async createLiquidityPool(tokenA, tokenB, amountA, amountB) {
    // Tạo pool thanh khoản sử dụng OlymPay
    const pool = await this.olymPay.createLiquidityPool({
      tokenA: tokenA,
      tokenB: tokenB,
      amountA: amountA,
      amountB: amountB,
      fee: '0.3%'
    });

    return pool;
  }

  async addLiquidity(poolId, amountA, amountB) {
    const liquidity = await this.olymPay.addLiquidity({
      poolId: poolId,
      amountA: amountA,
      amountB: amountB
    });

    return liquidity;
  }

  async swapTokens(tokenIn, tokenOut, amountIn, minAmountOut) {
    const swap = await this.olymPay.swapTokens({
      tokenIn: tokenIn,
      tokenOut: tokenOut,
      amountIn: amountIn,
      minAmountOut: minAmountOut
    });

    return swap;
  }
}

Xử lý Lỗi

Xử lý Lỗi Toàn diện

class OlymPayErrorHandler {
  static handleError(error) {
    switch (error.code) {
      case 'INSUFFICIENT_BALANCE':
        return {
          userMessage: 'Số dư không đủ cho giao dịch này',
          action: 'Vui lòng thêm tiền vào ví của bạn',
          retry: false
        };
      
      case 'NETWORK_ERROR':
        return {
          userMessage: 'Lỗi kết nối mạng',
          action: 'Vui lòng kiểm tra kết nối internet và thử lại',
          retry: true
        };
      
      case 'RATE_LIMIT_EXCEEDED':
        return {
          userMessage: 'Quá nhiều yêu cầu',
          action: 'Vui lòng đợi một chút và thử lại',
          retry: true,
          retryAfter: 60
        };
      
      case 'UNAUTHORIZED':
        return {
          userMessage: 'Xác thực thất bại',
          action: 'Vui lòng kiểm tra API key của bạn',
          retry: false
        };
      
      default:
        return {
          userMessage: 'Đã xảy ra lỗi không mong muốn',
          action: 'Vui lòng thử lại hoặc liên hệ hỗ trợ',
          retry: true
        };
    }
  }
}

// Sử dụng
try {
  const result = await olymPay.createPayment(paymentData);
} catch (error) {
  const errorInfo = OlymPayErrorHandler.handleError(error);
  console.error(errorInfo.userMessage);
  
  if (errorInfo.retry) {
    // Triển khai logic thử lại
    setTimeout(() => {
      // Thử lại thao tác
    }, errorInfo.retryAfter * 1000);
  }
}

Kiểm thử

Kiểm thử Đơn vị

import { OlymPaySDK } from '@olympay/sdk';

describe('Tích hợp OlymPay', () => {
  let olymPay;

  beforeEach(() => {
    olymPay = new OlymPaySDK({
      apiKey: 'test-api-key',
      network: 'testnet',
      environment: 'development'
    });
  });

  test('nên tạo thanh toán thành công', async () => {
    const payment = await olymPay.createPayment({
      amount: '100.00',
      currency: 'USD',
      recipient: '0x...',
      description: 'Thanh toán kiểm thử'
    });

    expect(payment).toBeDefined();
    expect(payment.amount).toBe('100.00');
  });

  test('nên xử lý lỗi số dư không đủ', async () => {
    await expect(
      olymPay.createPayment({
        amount: '1000000.00',
        currency: 'USD',
        recipient: '0x...',
        description: 'Thanh toán kiểm thử'
      })
    ).rejects.toThrow('INSUFFICIENT_BALANCE');
  });
});

Thực hành Bảo mật Tốt nhất

Quản lý API Key

// Biến môi trường
const config = {
  apiKey: process.env.OLYMPAY_API_KEY,
  network: process.env.NODE_ENV === 'production' ? 'mainnet' : 'testnet'
};

// Khởi tạo an toàn
const olymPay = new OlymPaySDK(config);

Xác thực Đầu vào

class PaymentValidator {
  static validatePaymentData(data) {
    const errors = [];

    if (!data.amount || isNaN(data.amount) || data.amount <= 0) {
      errors.push('Số tiền không hợp lệ');
    }

    if (!data.currency || !['USD', 'EUR', 'GBP'].includes(data.currency)) {
      errors.push('Tiền tệ không hợp lệ');
    }

    if (!data.recipient || !this.isValidAddress(data.recipient)) {
      errors.push('Địa chỉ người nhận không hợp lệ');
    }

    return errors;
  }

  static isValidAddress(address) {
    return /^0x[a-fA-F0-9]{40}$/.test(address);
  }
}

Triển khai

Triển khai Sản xuất

// Cấu hình sản xuất
const productionConfig = {
  apiKey: process.env.OLYMPAY_API_KEY,
  network: 'mainnet',
  environment: 'production',
  timeout: 30000,
  retries: 3
};

const olymPay = new OlymPaySDK(productionConfig);

Giám sát

class OlymPayMonitor {
  constructor(olymPay) {
    this.olymPay = olymPay;
    this.setupMonitoring();
  }

  setupMonitoring() {
    // Giám sát sức khỏe API
    setInterval(async () => {
      try {
        await this.olymPay.healthCheck();
        console.log('API OlymPay hoạt động tốt');
      } catch (error) {
        console.error('Kiểm tra sức khỏe API OlymPay thất bại:', error);
        // Cảnh báo hệ thống giám sát của bạn
      }
    }, 60000); // Kiểm tra mỗi phút
  }

  async logTransaction(transaction) {
    // Ghi log giao dịch để giám sát
    console.log('Giao dịch:', {
      hash: transaction.hash,
      amount: transaction.amount,
      status: transaction.status,
      timestamp: new Date().toISOString()
    });
  }
}