Integration Guide / Hướng dẫn tích hợp
English
Overview
Prerequisites
Quick Start Integration
1. Install SDK
npm install @olympay/sdk
# or
yarn add @olympay/sdknpm install @olympay/sdk
# or
yarn add @olympay/sdkimport { OlymPaySDK } from '@olympay/sdk';
const olymPay = new OlymPaySDK({
apiKey: 'your-api-key',
network: 'mainnet', // or 'testnet'
environment: 'production' // or 'development'
});// Connect user's wallet
const wallet = await olymPay.connectWallet();
// Get wallet information
const address = wallet.getAddress();
const balance = await wallet.getBalance();// 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);
}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}`);
}
}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;
}
}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);
}
}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');
});
});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();
});
});// 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);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);
}
}// Production configuration
const productionConfig = {
apiKey: process.env.OLYMPAY_API_KEY,
network: 'mainnet',
environment: 'production',
timeout: 30000,
retries: 3
};
const olymPay = new OlymPaySDK(productionConfig);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()
});
}
}npm install @olympay/sdk
# hoặc
yarn add @olympay/sdkimport { OlymPaySDK } from '@olympay/sdk';
const olymPay = new OlymPaySDK({
apiKey: 'your-api-key',
network: 'mainnet', // hoặc 'testnet'
environment: 'production' // hoặc 'development'
});// 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();// 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);
}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}`);
}
}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;
}
}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);
}
}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');
});
});// 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);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);
}
}// 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);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()
});
}
}