@skywu/buy-tax
v1.1.3
Published
A referral purchase marketplace with Bitcoin/USDT payment integration
Downloads
2
Maintainers
Readme
Referral Trading Marketplace
A comprehensive npm package for creating a referral purchase marketplace with Bitcoin and USDT payment integration. This package provides a complete trading interface where users can purchase referrals from virtual sellers using cryptocurrency payments.
Features
- 🏪 Virtual Marketplace: Complete trading interface with simulated sellers
- 💰 Crypto Payments: Bitcoin (BTC) and USDT payment support
- 📊 Smart Pricing: Bulk discount algorithm with decreasing per-unit costs
- 🌍 Internationalization: Multi-language support using @skywu/translator
- 🔒 Security: Comprehensive validation and security measures
- 📱 Responsive UI: Embeddable or modal interface
- ⚡ Real-time: Payment status monitoring and updates
Installation
npm install @skywu/buy-taxQuick Start (one‑liner modal)
import { openMarketplaceModal } from '@skywu/buy-tax';
// In your button click handler
document.getElementById('open-market-btn').addEventListener('click', async () => {
await openMarketplaceModal({
// apiBaseUrl is optional and defaults to same-origin proxy '/api/paybtc-usdt'
width: 480, // optional, default ~480
onClose: () => console.log('Marketplace closed')
});
});Backend setup: provide a reverse proxy at '/api/paybtc-usdt' that forwards to your real PAY API base, adding Authorization header from server-side .env (e.g., PAY_API_BASE, PAY_API_KEY).
The modal renders the Telegram‑style marketplace UI with the header, info banner ("This marketplace enables peer‑to‑peer trading between users." + sell), single‑column seller list, Buy buttons, standard crypto URIs for QR (bitcoin:/tron:), and auto‑polling.
Configuration
MarketplaceConfig
interface MarketplaceConfig {
apiBaseUrl?: string; // Optional; defaults to same-origin proxy '/api/paybtc-usdt'
apiKey?: string; // Optional API key (handled server-side via proxy is recommended)
theme?: 'light' | 'dark'; // UI theme
language?: string; // Language code (e.g., 'en', 'es')
onPurchaseComplete?: (order: PurchaseOrder) => void;
onError?: (error: Error) => void;
}MarketplaceOptions
interface MarketplaceOptions {
containerId?: string; // Container element ID for embedded mode
modal?: boolean; // Show as modal (default: true)
width?: number; // Width in pixels (default: 800)
height?: number; // Height in pixels (default: 600)
}Pricing Algorithm
The package implements a sophisticated bulk discount pricing system:
- Minimum: 20 referrals for $10 USD ($0.50 per referral)
- Maximum: 200 referrals for $60 USD ($0.30 per referral)
- Algorithm: Logarithmic scaling for smooth bulk discounts
import { PricingCalculator } from '@skywu/buy-tax';
// Calculate price for 100 referrals
const price = PricingCalculator.calculatePrice(100);
const unitPrice = PricingCalculator.calculateUnitPrice(100);
const discount = PricingCalculator.calculateDiscount(100);
console.log(`100 referrals: $${price} ($${unitPrice} each, ${discount}% discount)`);Payment Integration
The package integrates with your payment API using the following endpoints:
Get Payment Address
POST /api/v1/receive-address
Content-Type: application/json
{
"user_id": "string",
"currency": "BTC|USDT",
"amount_usd": number
}Check Payment Status
GET /api/v1/receive-address/{address}/status
Content-Type: application/jsonUsage Examples
Basic Integration
import ReferralMarketplace from '@skywu/buy-tax';
const marketplace = new ReferralMarketplace({
// apiBaseUrl omitted; defaults to '/api/paybtc-usdt'
language: 'en'
});
// Show in modal
await marketplace.show({ modal: true });Embedded Integration
<div id="marketplace-container"></div>
<script>
import { createMarketplace } from '@skywu/buy-tax';
const marketplace = createMarketplace({
// apiBaseUrl omitted; defaults to '/api/paybtc-usdt'
});
marketplace.show({
containerId: 'marketplace-container',
modal: false,
width: 1000,
height: 700
});
</script>Event Handling
const marketplace = createMarketplace({
// apiBaseUrl omitted; defaults to '/api/paybtc-usdt'
});
// Listen to events
marketplace.on('onSellerSelect', (seller) => {
console.log('Selected seller:', seller.name);
});
marketplace.on('onPackageSelect', (package) => {
console.log('Selected package:', package.referralCount, 'referrals');
});
marketplace.on('onPaymentInitiated', (order) => {
console.log('Payment initiated:', order.id);
});
marketplace.on('onPurchaseComplete', (order) => {
console.log('Purchase completed:', order);
// Credit referrals to user account
creditReferrals(order.userId, order.referralCount);
});Custom Language Support
import { TranslationService } from '@skywu/buy-tax';
const translationService = new TranslationService('es');
await translationService.initialize();
// Add custom translations
translationService.addTranslations('es', {
marketplace: {
customMessage: 'Mensaje personalizado'
}
});
const marketplace = new ReferralMarketplace({
apiBaseUrl: 'https://api.example.com',
language: 'es'
});API Reference
ReferralMarketplace
Main marketplace class that orchestrates all components.
Methods
show(options?: MarketplaceOptions): Promise<void>- Show the marketplacehide(): void- Hide the marketplacepurchaseReferrals(sellerId, packageId, currency, userId): Promise<PurchaseOrder>- Purchase referralsgetOrder(orderId): PurchaseOrder | undefined- Get order by IDgetUserOrders(userId): PurchaseOrder[]- Get user's orderson(event, callback): void- Add event listeneroff(event, callback): void- Remove event listenergetStats()- Get marketplace statistics
PricingCalculator
Utility class for pricing calculations.
Static Methods
calculatePrice(referralCount): number- Calculate total pricecalculateUnitPrice(referralCount): number- Calculate per-referral pricecalculateDiscount(referralCount): number- Calculate discount percentagegeneratePackages(): ReferralPackage[]- Generate predefined packagesisValidQuantity(referralCount): boolean- Validate quantitygetClosestValidQuantity(referralCount): number- Get closest valid quantity
PaymentService
Service for handling payment API integration.
Methods
getPaymentAddress(request): Promise<PaymentResponse>- Get payment addresscheckPaymentStatus(address): Promise<PaymentStatusResponse>- Check payment statuspollPaymentStatus(address, callback?, interval?, maxAttempts?): Promise<PaymentStatusResponse>- Poll payment status
Error Handling
The package includes comprehensive error handling:
import { ErrorHandler, ErrorCode, MarketplaceError } from '@skywu/buy-tax';
const errorHandler = ErrorHandler.getInstance();
// Handle specific error types
errorHandler.onError(ErrorCode.PAYMENT_FAILED, (error) => {
console.log('Payment failed:', error.message);
// Show retry option to user
});
errorHandler.onError(ErrorCode.NETWORK_ERROR, (error) => {
console.log('Network error:', error.message);
// Show offline message
});
// Global error handler
errorHandler.onGlobalError((error) => {
console.log('Global error:', error.toJSON());
// Log to external service
});Security Features
- Input validation and sanitization
- Cryptocurrency address validation
- Rate limiting
- Suspicious activity detection
- API timeout handling
- XSS protection
TypeScript Support
The package is written in TypeScript and includes full type definitions:
import {
ReferralMarketplace,
MarketplaceConfig,
PurchaseOrder,
Currency
} from '@skywu/buy-tax';
const config: MarketplaceConfig = {
// apiBaseUrl optional; defaults to '/api/paybtc-usdt'
theme: 'dark',
language: 'en'
};
const marketplace = new ReferralMarketplace(config);Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For support, email [email protected] or create an issue on GitHub.
