Get mock transaction data for testing payment systems, reporting, and financial applications.
# Get all transactions (default limit: 20)
curl -X GET "https://mockly.me/transactions"
# Get transactions with filters
curl -X GET "https://mockly.me/transactions?limit=10&status=completed&method=credit_card"
// Fetch transactions with optional filters
async function getTransactions(options = {}) {
const {
limit = 20,
status = null,
method = null
} = options;
// Build query parameters
const params = new URLSearchParams();
params.append('limit', limit);
if (status) params.append('status', status);
if (method) params.append('method', method);
try {
const response = await fetch(`https://mockly.me/transactions?${params}`);
return await response.json();
} catch (error) {
console.error('Error fetching transactions:', error);
return [];
}
}
// Example: Get completed PayPal transactions
getTransactions({
limit: 5,
status: 'completed',
method: 'paypal'
}).then(transactions => {
console.log('Transactions:', transactions);
// Display transactions in a table
const tableBody = document.getElementById('transactions-table');
transactions.forEach(tx => {
const row = document.createElement('tr');
row.innerHTML = `
${tx.id.substring(0, 8)}...
${tx.date}
${tx.amount} ${tx.currency}
${tx.status}
${tx.method}
`;
tableBody.appendChild(row);
});
});
import requests
from datetime import datetime
def get_transactions(limit=20, status=None, method=None):
"""
Fetch transactions with optional filtering
Parameters:
- limit: Max number of transactions to retrieve (1-100)
- status: Filter by status (completed, pending, failed, refunded)
- method: Filter by payment method (credit_card, paypal, etc.)
"""
params = {'limit': limit}
if status:
params['status'] = status
if method:
params['method'] = method
response = requests.get('https://mockly.me/transactions', params=params)
return response.json()
# Get recent failed transactions for reporting
failed_transactions = get_transactions(limit=10, status='failed')
print(f"Found {len(failed_transactions)} failed transactions:")
for tx in failed_transactions:
# Format date for display
tx_date = datetime.strptime(tx['date'], "%Y-%m-%d %H:%M:%S")
formatted_date = tx_date.strftime("%b %d, %Y %H:%M")
print(f"ID: {tx['id'][:8]}... | {formatted_date} | " +
f"{tx['amount']} {tx['currency']} | Method: {tx['method']}")
[
{
"id": "f8b4f424-a7a8-49fa-9364-35851a7b4ba5",
"date": "2023-07-12 15:23:45",
"amount": 248.75,
"currency": "USD",
"method": "credit_card",
"status": "completed",
"description": "Monthly subscription",
"reference": "REF-5A7C1E9D"
},
{
"id": "a2b9c8d4-e5f6-47a3-b2c1-d0e9f8g7h6i5",
"date": "2023-07-10 09:14:22",
"amount": 57.99,
"currency": "EUR",
"method": "paypal",
"status": "completed",
"description": "Online purchase",
"reference": "REF-B3F7A2E1"
}
// Additional transactions...
]
# Get a specific transaction by ID
curl -X GET "https://mockly.me/transaction/f8b4f424-a7a8-49fa-9364-35851a7b4ba5"
// Fetch a specific transaction by ID
async function getTransactionDetails(id) {
try {
const response = await fetch(`https://mockly.me/transaction/${id}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching transaction:', error);
return null;
}
}
// Example: Show transaction details on page
document.addEventListener('DOMContentLoaded', () => {
// Get transaction ID from URL or use a sample ID
const txId = new URLSearchParams(window.location.search).get('tx_id') ||
'f8b4f424-a7a8-49fa-9364-35851a7b4ba5';
getTransactionDetails(txId).then(tx => {
if (!tx) return;
// Update UI with transaction details
document.getElementById('tx-id').textContent = tx.id;
document.getElementById('tx-date').textContent = tx.date;
document.getElementById('tx-amount').textContent = `${tx.amount} ${tx.currency}`;
document.getElementById('tx-status').textContent = tx.status;
document.getElementById('tx-method').textContent = tx.method;
document.getElementById('tx-description').textContent = tx.description;
document.getElementById('tx-reference').textContent = tx.reference;
// Set status indicator color
const statusElement = document.getElementById('tx-status');
if (tx.status === 'completed') {
statusElement.classList.add('text-green-600');
} else if (tx.status === 'pending') {
statusElement.classList.add('text-yellow-600');
} else if (tx.status === 'failed') {
statusElement.classList.add('text-red-600');
}
});
});
import requests
def get_transaction(transaction_id):
"""Fetch a specific transaction by ID"""
url = f'https://mockly.me/transaction/{transaction_id}'
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
return None
# Example usage
transaction_id = 'f8b4f424-a7a8-49fa-9364-35851a7b4ba5'
transaction = get_transaction(transaction_id)
if transaction:
print(f"Transaction Details for {transaction_id}")
print("-" * 50)
print(f"Date: {transaction['date']}")
print(f"Amount: {transaction['amount']} {transaction['currency']}")
print(f"Status: {transaction['status']}")
print(f"Payment Method: {transaction['method']}")
print(f"Description: {transaction['description']}")
print(f"Reference: {transaction['reference']}")
# Additional processing based on transaction status
if transaction['status'] == 'completed':
print("Transaction was successful!")
elif transaction['status'] == 'pending':
print("Transaction is still processing...")
elif transaction['status'] == 'failed':
print("Transaction failed. Please check payment details.")
elif transaction['status'] == 'refunded':
print("Transaction has been refunded.")
{
"id": "f8b4f424-a7a8-49fa-9364-35851a7b4ba5",
"date": "2023-07-12 15:23:45",
"amount": 248.75,
"currency": "USD",
"method": "credit_card",
"status": "completed",
"description": "Monthly subscription",
"reference": "REF-5A7C1E9D"
}
Work with invoices, receipts, and account balance data for financial applications.
# Get a specific invoice by ID
curl -X GET "https://mockly.me/invoice/inv-12345"
// Fetch a specific invoice by ID
async function getInvoice(invoiceId) {
try {
const response = await fetch(`https://mockly.me/invoice/${invoiceId}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching invoice:', error);
return null;
}
}
// Example: Generate an invoice preview
async function generateInvoicePreview(invoiceId) {
const invoice = await getInvoice(invoiceId);
if (!invoice) return;
// Set invoice header information
document.getElementById('invoice-number').textContent = invoice.number;
document.getElementById('invoice-date').textContent = invoice.date;
document.getElementById('invoice-due-date').textContent = invoice.due_date;
document.getElementById('invoice-status').textContent = invoice.status;
// Set customer information
const customer = invoice.customer;
document.getElementById('customer-name').textContent = customer.name;
document.getElementById('customer-email').textContent = customer.email;
document.getElementById('customer-address').textContent =
`${customer.address.line1}, ${customer.address.city}, ${customer.address.state} ${customer.address.postal_code}`;
// Generate line items
const itemsContainer = document.getElementById('invoice-items');
itemsContainer.innerHTML = ''; // Clear existing items
invoice.items.forEach(item => {
const row = document.createElement('tr');
row.className = 'border-t border-gray-200';
row.innerHTML = `
${item.description}
${item.quantity}
${item.unit_price.toFixed(2)}
${item.total.toFixed(2)}
`;
itemsContainer.appendChild(row);
});
// Set totals
document.getElementById('invoice-subtotal').textContent = invoice.subtotal.toFixed(2);
document.getElementById('invoice-tax').textContent = invoice.tax_total.toFixed(2);
document.getElementById('invoice-total').textContent =
`${invoice.total.toFixed(2)} ${invoice.currency}`;
}
import requests
import json
from datetime import datetime, timedelta
def get_invoice(invoice_id):
"""Fetch a specific invoice by ID"""
url = f'https://mockly.me/invoice/{invoice_id}'
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
return None
# Example: Generate a PDF invoice from the data
def generate_invoice_report(invoice_id):
invoice = get_invoice(invoice_id)
if not invoice:
return
# In a real app, you would use a PDF library like ReportLab
# This is a simple text representation
report = [
f"INVOICE #{invoice['number']}",
f"Status: {invoice['status'].upper()}",
"-" * 50,
f"Date: {invoice['date']}",
f"Due Date: {invoice['due_date']}",
f"Terms: {invoice['payment_terms']}",
"",
"BILL TO:",
f"{invoice['customer']['name']}",
f"{invoice['customer']['email']}",
f"{invoice['customer']['address']['line1']}",
f"{invoice['customer']['address']['city']}, {invoice['customer']['address']['state']} {invoice['customer']['address']['postal_code']}",
"",
"ITEMS:",
"-" * 50
]
# Add line items
for item in invoice['items']:
line = f"{item['description']:<30} {item['quantity']:>3} x ${item['unit_price']:<8.2f} = ${item['total']:.2f}"
report.append(line)
# Add totals
report.extend([
"-" * 50,
f"{'Subtotal:':<40} ${invoice['subtotal']:.2f}",
f"{'Tax:':<40} ${invoice['tax_total']:.2f}",
f"{'TOTAL:':<40} ${invoice['total']:.2f} {invoice['currency']}"
])
# Add notes if present
if invoice['notes']:
report.extend(["", f"Notes: {invoice['notes']}"])
return "\n".join(report)
# Generate a sample invoice report
invoice_id = 'inv-12345'
invoice_report = generate_invoice_report(invoice_id)
print(invoice_report)
{
"id": "inv-12345",
"number": "INV-202307-4875",
"date": "2023-07-12",
"due_date": "2023-07-26",
"customer": {
"id": "cust_a1b2c3d4e5f6",
"name": "Customer 5678",
"email": "[email protected]",
"address": {
"line1": "456 Main St",
"city": "Springfield",
"state": "IL",
"postal_code": "62704",
"country": "US"
}
},
"items": [
{
"id": "item_1a2b3c4d",
"description": "Item 1",
"quantity": 2,
"unit_price": 45.99,
"total": 91.98,
"tax_rate": 0.08,
"tax_amount": 7.36
},
{
"id": "item_5e6f7g8h",
"description": "Item 2",
"quantity": 1,
"unit_price": 129.99,
"total": 129.99,
"tax_rate": 0.08,
"tax_amount": 10.40
}
],
"subtotal": 221.97,
"tax_total": 17.76,
"total": 239.73,
"status": "paid",
"notes": "Thank you for your business!",
"payment_terms": "Net 15",
"currency": "USD"
}
# Get current account balance
curl -X GET "https://mockly.me/account/balance"
// Fetch current account balance
async function getAccountBalance() {
try {
const response = await fetch('https://mockly.me/account/balance');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching account balance:', error);
return null;
}
}
// Example: Update account balance dashboard
function updateBalanceDashboard() {
getAccountBalance().then(balance => {
if (!balance) return;
// Update balance amounts
document.getElementById('total-balance').textContent =
`${balance.total.toFixed(2)} ${balance.currency}`;
document.getElementById('available-balance').textContent =
`${balance.available.toFixed(2)} ${balance.currency}`;
document.getElementById('pending-balance').textContent =
`${balance.pending.toFixed(2)} ${balance.currency}`;
document.getElementById('reserved-balance').textContent =
`${balance.reserved.toFixed(2)} ${balance.currency}`;
// Update last updated timestamp
document.getElementById('last-updated').textContent =
`Last updated: ${balance.last_updated}`;
// Visualize balance distribution with a chart
const ctx = document.getElementById('balance-chart').getContext('2d');
new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['Available', 'Pending', 'Reserved'],
datasets: [{
data: [balance.available, balance.pending, balance.reserved],
backgroundColor: ['#10B981', '#F59E0B', '#6B7280']
}]
}
});
});
}
// Update balance when page loads
document.addEventListener('DOMContentLoaded', updateBalanceDashboard);
// Refresh button event listener
document.getElementById('refresh-balance').addEventListener('click', updateBalanceDashboard);
import requests
from datetime import datetime
def get_account_balance():
"""Fetch current account balance"""
response = requests.get('https://mockly.me/account/balance')
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
return None
# Example usage: Display account balance and create alerts
balance = get_account_balance()
if balance:
print(f"Account Balance ({balance['currency']})")
print("-" * 40)
print(f"Total Balance: {balance['total']:.2f}")
print(f"Available: {balance['available']:.2f}")
print(f"Pending: {balance['pending']:.2f}")
print(f"Reserved: {balance['reserved']:.2f}")
print(f"Last Updated: {balance['last_updated']}")
# Create alerts based on account status
available_ratio = balance['available'] / balance['total']
if available_ratio < 0.1:
print("\n⚠️ ALERT: Low available balance!")
print(f"Only {available_ratio*100:.1f}% of your total balance is available.")
if balance['pending'] > balance['available']:
print("\n⚠️ ALERT: High pending amount!")
print("Pending transactions exceed your available balance.")
{
"currency": "USD",
"total": 24875.50,
"available": 21320.25,
"pending": 2750.80,
"reserved": 804.45,
"last_updated": "2023-07-15 09:45:22"
}
Create payment intents, manage subscriptions, and handle recurring billing.
# Create a payment intent
curl -X POST "https://mockly.me/payment/intent" \
-H "Content-Type: application/json" \
-d '{
"amount": 49.99,
"currency": "USD",
"payment_method": "credit_card",
"description": "Premium subscription"
}'
// Create a payment intent
async function createPaymentIntent(paymentData) {
try {
const response = await fetch('https://mockly.me/payment/intent', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(paymentData)
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error creating payment intent:', error);
return null;
}
}
// Example: Process a checkout form
document.getElementById('checkout-form').addEventListener('submit', async function(e) {
e.preventDefault();
// Show loading state
const submitButton = this.querySelector('button[type="submit"]');
const originalButtonText = submitButton.textContent;
submitButton.disabled = true;
submitButton.textContent = 'Processing...';
// Get form data
const amount = parseFloat(this.querySelector('#amount').value);
const currency = this.querySelector('#currency').value;
const paymentMethod = this.querySelector('#payment-method').value;
// Create payment intent
const paymentIntent = await createPaymentIntent({
amount,
currency,
payment_method: paymentMethod,
description: 'Web store purchase',
customer_id: 'cust_current_user'
});
// Reset button state
submitButton.disabled = false;
submitButton.textContent = originalButtonText;
if (!paymentIntent) {
showError('Payment processing failed. Please try again.');
return;
}
// Store payment ID for confirmation
localStorage.setItem('paymentIntentId', paymentIntent.id);
// Redirect to confirmation page
window.location.href = `/confirmation?payment_id=${paymentIntent.id}`;
});
import requests
import json
from datetime import datetime
def create_payment_intent(amount, currency, payment_method=None, description=None, customer_id=None):
"""Create a payment intent"""
url = 'https://mockly.me/payment/intent'
# Prepare payload
payload = {
'amount': amount,
'currency': currency
}
# Add optional fields if provided
if payment_method:
payload['payment_method'] = payment_method
if description:
payload['description'] = description
if customer_id:
payload['customer_id'] = customer_id
# Send request
response = requests.post(
url,
headers={'Content-Type': 'application/json'},
data=json.dumps(payload)
)
if response.status_code == 201: # Created
return response.json()
else:
print(f"Error: {response.status_code}")
print(response.text)
return None
# Example: Create a payment intent for a product purchase
product = {
'name': 'Annual Subscription',
'amount': 99.99,
'currency': 'USD'
}
payment_intent = create_payment_intent(
amount=product['amount'],
currency=product['currency'],
payment_method='credit_card',
description=f"Purchase of {product['name']}",
customer_id='cust_12345'
)
if payment_intent:
print(f"Payment Intent Created:")
print(f"ID: {payment_intent['id']}")
print(f"Amount: {payment_intent['amount']} {payment_intent['currency']}")
print(f"Status: {payment_intent['status']}")
print(f"Created: {payment_intent['created']}")
print(f"Expires: {payment_intent['expires']}")
# In a real app, you would redirect the user to a payment page
# or use the payment_intent ID with a payment form
{
"id": "pi_a1b2c3d4e5f6g7h8",
"amount": 49.99,
"currency": "USD",
"status": "requires_payment_method",
"payment_method": "credit_card",
"description": "Premium subscription",
"customer_id": null,
"created": "2023-07-15 10:15:22",
"expires": "2023-07-16 10:15:22"
}
# Get available payment methods
curl -X GET "https://mockly.me/payment/methods"
// Fetch available payment methods
async function getPaymentMethods() {
try {
const response = await fetch('https://mockly.me/payment/methods');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching payment methods:', error);
return null;
}
}
// Example: Populate payment method dropdown
async function populatePaymentMethodsDropdown() {
const paymentMethodsData = await getPaymentMethods();
if (!paymentMethodsData || !paymentMethodsData.payment_methods) return;
const select = document.getElementById('payment-method-select');
select.innerHTML = ''; // Clear existing options
// Add a default option
const defaultOption = document.createElement('option');
defaultOption.value = '';
defaultOption.textContent = 'Select payment method';
defaultOption.disabled = true;
defaultOption.selected = true;
select.appendChild(defaultOption);
// Add each payment method as an option
paymentMethodsData.payment_methods.forEach(method => {
// Only show methods that support the selected currency
const option = document.createElement('option');
option.value = method.type;
option.textContent = method.display_name;
option.dataset.icon = method.icon;
select.appendChild(option);
});
// Optional: Add icons to the dropdown with a library like select2
$('#payment-method-select').select2({
templateResult: formatPaymentMethod,
templateSelection: formatPaymentMethod
});
}
// Format payment method with icon
function formatPaymentMethod(method) {
if (!method.id || !method.element) return method.text;
const icon = $(method.element).data('icon');
const $method = $(
`
${method.text}`
);
return $method;
}
import requests
def get_payment_methods():
"""Fetch available payment methods"""
response = requests.get('https://mockly.me/payment/methods')
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
return None
# Example: Get available payment methods for a specific currency
def get_methods_for_currency(currency):
"""Get payment methods that support a specific currency"""
methods_data = get_payment_methods()
if not methods_data or 'payment_methods' not in methods_data:
return []
# Filter methods that support the given currency
supported_methods = []
for method in methods_data['payment_methods']:
if currency in method['supported_currencies']:
supported_methods.append(method)
return supported_methods
# Find payment methods for different currencies
currencies = ['USD', 'EUR', 'BTC']
for currency in currencies:
methods = get_methods_for_currency(currency)
print(f"\nPayment methods supporting {currency}:")
if not methods:
print(f"No payment methods available for {currency}")
continue
for method in methods:
print(f"- {method['display_name']} ({method['id']})")
{
"payment_methods": [
{
"id": "pm_card",
"type": "credit_card",
"display_name": "Credit/Debit Card",
"icon": "https://mockly.me/static/icons/card.svg",
"supported_currencies": ["USD", "EUR", "GBP", "CAD", "AUD", "JPY"]
},
{
"id": "pm_paypal",
"type": "paypal",
"display_name": "PayPal",
"icon": "https://mockly.me/static/icons/paypal.svg",
"supported_currencies": ["USD", "EUR", "GBP", "CAD", "AUD"]
},
{
"id": "pm_apple_pay",
"type": "apple_pay",
"display_name": "Apple Pay",
"icon": "https://mockly.me/static/icons/apple_pay.svg",
"supported_currencies": ["USD", "EUR", "GBP", "CAD", "AUD"]
},
{
"id": "pm_bank_transfer",
"type": "bank_transfer",
"display_name": "Bank Transfer",
"icon": "https://mockly.me/static/icons/bank.svg",
"supported_currencies": ["USD", "EUR", "GBP"]
},
{
"id": "pm_crypto",
"type": "crypto",
"display_name": "Cryptocurrency",
"icon": "https://mockly.me/static/icons/crypto.svg",
"supported_currencies": ["BTC", "ETH"]
}
]
}
# Get all subscriptions (default limit: 5)
curl -X GET "https://mockly.me/subscriptions"
# Get active subscriptions only
curl -X GET "https://mockly.me/subscriptions?status=active"
# Get more subscriptions with a higher limit
curl -X GET "https://mockly.me/subscriptions?limit=10"
// Fetch subscriptions with optional status filter
async function getSubscriptions(options = {}) {
const {
limit = 5,
status = null
} = options;
// Build query parameters
const params = new URLSearchParams();
params.append('limit', limit);
if (status) params.append('status', status);
try {
const response = await fetch(`https://mockly.me/subscriptions?${params}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching subscriptions:', error);
return [];
}
}
// Example: Display active subscriptions
async function displayActiveSubscriptions() {
// Get only active subscriptions
const subscriptions = await getSubscriptions({ status: 'active' });
// Get the container element
const container = document.getElementById('subscriptions-container');
container.innerHTML = ''; // Clear existing content
// If no subscriptions, show a message
if (subscriptions.length === 0) {
container.innerHTML = 'No active subscriptions found.
';
return;
}
// Create a card for each subscription
subscriptions.forEach(sub => {
// Calculate days until next payment
const nextPaymentDate = new Date(sub.next_payment_date);
const today = new Date();
const daysRemaining = Math.ceil((nextPaymentDate - today) / (1000 * 60 * 60 * 24));
// Create the subscription card
const card = document.createElement('div');
card.className = 'bg-white p-4 rounded-lg shadow-sm border border-gray-100 mb-4';
card.innerHTML = `
${sub.name}
Active
${sub.description || 'No description'}
Amount:
${sub.amount} ${sub.currency}
Billing:
${sub.interval}
Next payment:
${sub.next_payment_date} (${daysRemaining} days)
`;
container.appendChild(card);
});
}
// Call the function when the page loads
document.addEventListener('DOMContentLoaded', displayActiveSubscriptions);
import requests
from datetime import datetime
def get_subscriptions(limit=5, status=None):
"""
Fetch subscriptions with optional filtering
Parameters:
- limit: Max number of subscriptions to retrieve (1-20)
- status: Filter by status (active, trialing, past_due, canceled)
"""
params = {'limit': limit}
if status:
params['status'] = status
response = requests.get('https://mockly.me/subscriptions', params=params)
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
return []
# Helper function to calculate days until next payment
def days_until_payment(next_payment_date):
next_date = datetime.strptime(next_payment_date, "%Y-%m-%d")
today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
return (next_date - today).days
# Example: Generate a subscription renewal report
def generate_renewal_report(days_threshold=7):
# Get all active subscriptions
active_subs = get_subscriptions(limit=20, status="active")
print(f"Subscription Renewal Report - {datetime.now().strftime('%Y-%m-%d')}")
print("-" * 50)
upcoming_renewals = []
other_subscriptions = []
for sub in active_subs:
days_left = days_until_payment(sub['next_payment_date'])
if days_left <= days_threshold:
upcoming_renewals.append((sub, days_left))
else:
other_subscriptions.append((sub, days_left))
# Display upcoming renewals
print(f"\nUpcoming Renewals (Next {days_threshold} days):")
if not upcoming_renewals:
print(" No upcoming renewals")
else:
for sub, days in sorted(upcoming_renewals, key=lambda x: x[1]):
print(f" • {sub['name']} ({sub['amount']} {sub['currency']}) - "\
f"Due in {days} days ({sub['next_payment_date']})")
# Display other active subscriptions
print("\nOther Active Subscriptions:")
for sub, days in sorted(other_subscriptions, key=lambda x: x[1]):
print(f" • {sub['name']} ({sub['amount']} {sub['currency']}) - "\
f"Due in {days} days ({sub['next_payment_date']})")
return len(upcoming_renewals)
# Generate the report for renewals in the next 7 days
upcoming_count = generate_renewal_report(7)
print(f"\nFound {upcoming_count} subscriptions renewing in the next 7 days.")
[
{
"id": "sub_a1b2c3d4e5f6",
"name": "Premium Plan",
"description": "Monthly software subscription",
"amount": 19.99,
"currency": "USD",
"interval": "monthly",
"start_date": "2023-05-15",
"next_payment_date": "2023-08-15",
"status": "active",
"customer_id": "cust_1a2b3c4d"
},
{
"id": "sub_b2c3d4e5f6g7",
"name": "Enterprise Plan",
"description": "Annual membership",
"amount": 199.99,
"currency": "USD",
"interval": "annually",
"start_date": "2023-02-01",
"next_payment_date": "2024-02-01",
"status": "active",
"customer_id": "cust_2b3c4d5e"
},
{
"id": "sub_c3d4e5f6g7h8",
"name": "Storage Add-on",
"description": null,
"amount": 4.99,
"currency": "USD",
"interval": "monthly",
"start_date": "2023-06-10",
"next_payment_date": "2023-07-10",
"status": "past_due",
"customer_id": "cust_3c4d5e6f"
}
]
Get exchange rates for different currencies to power financial tools and converters.
# Get exchange rates with USD as base currency (default)
curl -X GET "https://mockly.me/exchange-rates"
# Get exchange rates with EUR as base currency
curl -X GET "https://mockly.me/exchange-rates?base=EUR"
// Fetch exchange rates with specified base currency
async function getExchangeRates(baseCurrency = 'USD') {
try {
const response = await fetch(`https://mockly.me/exchange-rates?base=${baseCurrency}`);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('Error fetching exchange rates:', error);
return null;
}
}
// Example: Currency converter application
class CurrencyConverter {
constructor() {
this.rates = {};
this.baseCurrency = 'USD';
this.date = '';
this.initialized = false;
}
async initialize(baseCurrency = 'USD') {
// Get latest exchange rates
const data = await getExchangeRates(baseCurrency);
if (!data) return false;
// Store rates data
this.rates = data.rates;
this.baseCurrency = data.base;
this.date = data.date;
this.initialized = true;
return true;
}
convert(amount, fromCurrency, toCurrency) {
if (!this.initialized) {
throw new Error('Converter not initialized. Call initialize() first.');
}
if (fromCurrency === toCurrency) return amount;
// If converting from base currency
if (fromCurrency === this.baseCurrency) {
return amount * this.rates[toCurrency];
}
// If converting to base currency
if (toCurrency === this.baseCurrency) {
return amount / this.rates[fromCurrency];
}
// If converting between two non-base currencies
// First convert to base currency, then to target currency
const amountInBaseCurrency = amount / this.rates[fromCurrency];
return amountInBaseCurrency * this.rates[toCurrency];
}
getSupportedCurrencies() {
return Object.keys(this.rates).concat([this.baseCurrency]);
}
}
// Usage example
document.addEventListener('DOMContentLoaded', async () => {
const converter = new CurrencyConverter();
await converter.initialize('USD');
// Test conversion: 100 USD to EUR
const amountInUSD = 100;
const amountInEUR = converter.convert(amountInUSD, 'USD', 'EUR');
console.log(`${amountInUSD} USD = ${amountInEUR.toFixed(2)} EUR`);
// Update rates date info
document.getElementById('rates-date').textContent = `Exchange rates as of ${converter.date}`;
});
import requests
from datetime import datetime
def get_exchange_rates(base_currency='USD'):
"""
Get current exchange rates with specified base currency
Parameters:
- base_currency: Base currency for exchange rates (e.g. USD, EUR, GBP)
"""
params = {'base': base_currency}
response = requests.get('https://mockly.me/exchange-rates', params=params)
if response.status_code == 200:
return response.json()
else:
print(f"Error: {response.status_code}")
return None
class CurrencyConverter:
def __init__(self, base_currency='USD'):
self.rates = {}
self.base_currency = base_currency
self.date = None
self.initialized = False
def initialize(self):
"""Load the latest exchange rates"""
data = get_exchange_rates(self.base_currency)
if not data:
return False
self.rates = data['rates']
self.date = data['date']
self.initialized = True
return True
def convert(self, amount, from_currency, to_currency):
"""Convert amount from one currency to another"""
if not self.initialized:
raise Exception("Converter not initialized. Call initialize() first.")
if from_currency == to_currency:
return amount
# If converting from base currency
if from_currency == self.base_currency:
return amount * self.rates[to_currency]
# If converting to base currency
if to_currency == self.base_currency:
return amount / self.rates[from_currency]
# If converting between two non-base currencies
# First convert to base currency, then to target currency
amount_in_base = amount / self.rates[from_currency]
return amount_in_base * self.rates[to_currency]
def get_supported_currencies(self):
"""Get list of all supported currencies"""
if not self.initialized:
raise Exception("Converter not initialized. Call initialize() first.")
return list(self.rates.keys()) + [self.base_currency]
# Example usage
converter = CurrencyConverter(base_currency='USD')
if converter.initialize():
# Print available currencies
currencies = converter.get_supported_currencies()
print(f"Supported currencies: {', '.join(currencies)}")
print(f"Exchange rates as of: {converter.date}")
# Example conversions
amount = 100
from_currency = 'USD'
for to_currency in ['EUR', 'GBP', 'JPY']:
if to_currency in currencies:
converted = converter.convert(amount, from_currency, to_currency)
print(f"{amount} {from_currency} = {converted:.2f} {to_currency}")
else:
print("Failed to initialize currency converter")
{
"base": "USD",
"date": "2023-07-15",
"rates": {
"EUR": 0.90124,
"GBP": 0.76543,
"JPY": 110.45678,
"CAD": 1.31234,
"AUD": 1.35678,
"BTC": 0.000023,
"ETH": 0.000415
}
}
Interactive Finance Demo
Try out these financial utilities to test transactions, payments, and currency conversion for your applications.
Currency Converter
Conversion Result
Meet Mockly Assistant
Your AI assistant for API testing, debugging and code generation. Access the power of mockly.me directly in ChatGPT.
- Generate code examples in your preferred language
- Get guidance for request/response handling and formatting
- Supercharged by ChatGPT Plus from OpenAI
"How do I send data to a POST endpoint"
"I can show you how to structure your request with headers and JSON — here's a code example..."