curl -X GET "https://api.tensorone.ai/v2/billing/payment-methods" \
-H "Authorization: Bearer YOUR_API_KEY" \
-G \
-d "includeUsageStats=true" \
-d "includeSecurityInfo=true"
import requests
from datetime import datetime, timedelta
import getpass
def get_payment_methods(include_usage=False, include_security=False):
params = {
'includeUsageStats': include_usage,
'includeSecurityInfo': include_security
}
response = requests.get(
"https://api.tensorone.ai/v2/billing/payment-methods",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params=params
)
return response.json()
def add_credit_card(card_details):
"""Add a new credit card payment method"""
response = requests.post(
"https://api.tensorone.ai/v2/billing/payment-methods",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=card_details
)
return response.json()
def set_default_payment_method(method_id):
"""Set default payment method"""
response = requests.post(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/set-default",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
return response.json()
# Get all payment methods with usage statistics
payment_data = get_payment_methods(include_usage=True, include_security=True)
print("💳 Payment Methods Dashboard")
print("=" * 30)
# Display default method
if payment_data.get('defaultMethod'):
default_id = payment_data['defaultMethod']
print(f"Default Payment Method: {default_id}")
print()
# List all payment methods
methods = payment_data['paymentMethods']
print(f"Payment Methods ({len(methods)}):")
print("-" * 25)
for method in methods:
method_id = method['methodId']
method_type = method['type']
status = method['status']
display_name = method['displayName']
is_default = method['isDefault']
# Status icons
status_icon = {
'active': '✅',
'expired': '⏰',
'disabled': '❌',
'failed': '🔴',
'pending_verification': '⏳'
}.get(status, '⚪')
default_icon = '⭐' if is_default else ' '
print(f"{default_icon}{status_icon} {display_name}")
print(f" Type: {method_type.title().replace('_', ' ')}")
print(f" Status: {status.title().replace('_', ' ')}")
# Show card/account details
details = method.get('details', {})
if details.get('maskedNumber'):
print(f" Number: {details['maskedNumber']}")
if details.get('brand'):
print(f" Brand: {details['brand']}")
if details.get('expiryDate'):
print(f" Expires: {details['expiryDate']}")
# Show usage statistics
if method.get('usage'):
usage = method['usage']
print(f" Usage: {usage['totalTransactions']} transactions")
print(f" Total: ${usage['totalAmount']:,.2f}")
print(f" Success Rate: {usage['successRate']:.1f}%")
if usage.get('lastUsed'):
print(f" Last Used: {usage['lastUsed'][:10]}")
# Show verification status
if method.get('verification'):
verification = method['verification']
verified_icon = '✅' if verification['verified'] else '❌'
print(f" Verified: {verified_icon}")
if verification.get('riskScore'):
risk_colors = {'low': '🟢', 'medium': '🟡', 'high': '🔴'}
risk_icon = risk_colors.get(verification['riskScore'], '⚪')
print(f" Risk: {risk_icon} {verification['riskScore'].title()}")
# Show limits
if method.get('limits'):
limits = method['limits']
if limits.get('dailyLimit'):
remaining_daily = limits.get('remainingDaily', 0)
print(f" Daily Limit: ${remaining_daily:,.2f} / ${limits['dailyLimit']:,.2f}")
print()
# Check for expiring cards
def check_expiring_cards():
"""Check for cards expiring soon"""
expiring_soon = []
for method in methods:
if method['type'] == 'credit_card' and method['status'] == 'active':
details = method.get('details', {})
expiry = details.get('expiryDate')
if expiry:
# Parse MM/YY format
month, year = expiry.split('/')
expiry_date = datetime(2000 + int(year), int(month), 1)
# Check if expiring within 60 days
if expiry_date - datetime.now() <= timedelta(days=60):
expiring_soon.append({
'method': method,
'expires': expiry_date
})
if expiring_soon:
print("⚠️ Cards Expiring Soon:")
print("-" * 22)
for item in expiring_soon:
method = item['method']
expires = item['expires']
days_left = (expires - datetime.now()).days
print(f" {method['displayName']}")
print(f" Expires in {days_left} days ({expires.strftime('%m/%y')})")
print()
check_expiring_cards()
# Payment method management functions
def update_payment_method_limits(method_id, new_limits):
"""Update spending limits for a payment method"""
response = requests.put(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/limits",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=new_limits
)
return response.json()
def disable_payment_method(method_id, reason=None):
"""Disable a payment method"""
data = {"reason": reason} if reason else {}
response = requests.post(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/disable",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=data
)
return response.json()
def verify_payment_method(method_id, verification_data):
"""Verify a payment method (for bank accounts, etc.)"""
response = requests.post(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/verify",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=verification_data
)
return response.json()
# Example: Add new credit card (requires secure input)
def add_new_credit_card():
"""Securely add a new credit card"""
print("\n💳 Add New Credit Card")
print("=" * 20)
# Note: In production, use proper secure input methods
card_number = getpass.getpass("Card Number: ")
expiry_month = input("Expiry Month (MM): ")
expiry_year = input("Expiry Year (YY): ")
cvv = getpass.getpass("CVV: ")
cardholder_name = input("Cardholder Name: ")
card_details = {
"type": "credit_card",
"cardNumber": card_number,
"expiryMonth": expiry_month,
"expiryYear": expiry_year,
"cvv": cvv,
"cardholderName": cardholder_name,
"billingAddress": {
"street": input("Billing Street: "),
"city": input("Billing City: "),
"state": input("Billing State: "),
"postalCode": input("Billing ZIP: "),
"country": input("Billing Country (US): ") or "US"
},
"setAsDefault": input("Set as default? (y/N): ").lower() == 'y'
}
result = add_credit_card(card_details)
if result.get('success'):
print(f"✅ Card added successfully: {result['methodId']}")
else:
print(f"❌ Failed to add card: {result.get('error', 'Unknown error')}")
# Uncomment to add new card interactively
# add_new_credit_card()
# Payment method security check
def security_audit():
"""Perform security audit of payment methods"""
print("\n🔒 Payment Method Security Audit")
print("=" * 35)
security_issues = []
for method in methods:
method_name = method['displayName']
# Check for unverified methods
verification = method.get('verification', {})
if not verification.get('verified', False):
security_issues.append(f"Unverified: {method_name}")
# Check for high-risk methods
if verification.get('riskScore') == 'high':
security_issues.append(f"High Risk: {method_name}")
# Check for expired methods still active
if method['status'] == 'expired' and method['type'] == 'credit_card':
security_issues.append(f"Expired Active Card: {method_name}")
# Check for methods without limits
limits = method.get('limits', {})
if not limits.get('dailyLimit') and method['status'] == 'active':
security_issues.append(f"No Spending Limits: {method_name}")
if security_issues:
print("⚠️ Security Issues Found:")
for issue in security_issues:
print(f" • {issue}")
else:
print("✅ No security issues found")
# Check security features
security_features = payment_data.get('securityFeatures', {})
print(f"\n🛡️ Security Features:")
print(f" 2FA Required: {'✅' if security_features.get('twoFactorRequired') else '❌'}")
print(f" Fraud Detection: {'✅' if security_features.get('fraudDetection') else '❌'}")
print(f" Spending Limits: {'✅' if security_features.get('spendingLimits') else '❌'}")
print(f" Approval Workflow: {'✅' if security_features.get('approvalWorkflow') else '❌'}")
security_audit()
const getPaymentMethods = async (options = {}) => {
const params = new URLSearchParams({
includeUsageStats: options.includeUsageStats || false,
includeSecurityInfo: options.includeSecurityInfo || false
});
if (options.type) {
const types = Array.isArray(options.type) ? options.type : [options.type];
types.forEach(type => params.append('type[]', type));
}
const response = await fetch(`https://api.tensorone.ai/v2/billing/payment-methods?${params}`, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
return await response.json();
};
const addPaymentMethod = async (paymentMethodData) => {
const response = await fetch('https://api.tensorone.ai/v2/billing/payment-methods', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(paymentMethodData)
});
return await response.json();
};
const setDefaultPaymentMethod = async (methodId) => {
const response = await fetch(`https://api.tensorone.ai/v2/billing/payment-methods/${methodId}/set-default`, {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
return await response.json();
};
// Get and display payment methods
getPaymentMethods({
includeUsageStats: true,
includeSecurityInfo: true
}).then(data => {
console.log('💳 Payment Methods Dashboard');
console.log('============================');
// Show default method
if (data.defaultMethod) {
console.log(`Default Method: ${data.defaultMethod}\n`);
}
// List all methods
data.paymentMethods.forEach(method => {
const statusIcon = {
'active': '✅',
'expired': '⏰',
'disabled': '❌',
'failed': '🔴',
'pending_verification': '⏳'
}[method.status] || '⚪';
const defaultIcon = method.isDefault ? '⭐' : ' ';
console.log(`${defaultIcon}${statusIcon} ${method.displayName}`);
console.log(` Type: ${method.type.replace('_', ' ')}`);
console.log(` Status: ${method.status.replace('_', ' ')}`);
if (method.details.maskedNumber) {
console.log(` Number: ${method.details.maskedNumber}`);
}
if (method.usage) {
console.log(` Usage: ${method.usage.totalTransactions} transactions`);
console.log(` Success Rate: ${method.usage.successRate.toFixed(1)}%`);
}
console.log('');
});
// Check for expiring cards
const expiringCards = data.paymentMethods.filter(method => {
if (method.type !== 'credit_card' || !method.details.expiryDate) return false;
const [month, year] = method.details.expiryDate.split('/');
const expiryDate = new Date(2000 + parseInt(year), parseInt(month) - 1);
const now = new Date();
const daysUntilExpiry = (expiryDate - now) / (1000 * 60 * 60 * 24);
return daysUntilExpiry <= 60 && daysUntilExpiry > 0;
});
if (expiringCards.length > 0) {
console.log('⚠️ Cards Expiring Soon:');
expiringCards.forEach(card => {
console.log(` ${card.displayName} - Expires ${card.details.expiryDate}`);
});
}
});
// Add new payment method
const addCreditCard = async (cardDetails) => {
const paymentMethodData = {
type: 'credit_card',
cardNumber: cardDetails.number,
expiryMonth: cardDetails.expiryMonth,
expiryYear: cardDetails.expiryYear,
cvv: cardDetails.cvv,
cardholderName: cardDetails.name,
billingAddress: cardDetails.billingAddress,
setAsDefault: cardDetails.setAsDefault || false
};
try {
const result = await addPaymentMethod(paymentMethodData);
console.log('✅ Payment method added:', result.methodId);
return result;
} catch (error) {
console.error('❌ Failed to add payment method:', error);
throw error;
}
};
// Update payment method limits
const updatePaymentLimits = async (methodId, limits) => {
const response = await fetch(`https://api.tensorone.ai/v2/billing/payment-methods/${methodId}/limits`, {
method: 'PUT',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(limits)
});
return await response.json();
};
// Security audit function
const performSecurityAudit = async () => {
const data = await getPaymentMethods({ includeSecurityInfo: true });
console.log('🔒 Payment Method Security Audit');
console.log('=================================');
const securityIssues = [];
data.paymentMethods.forEach(method => {
// Check verification status
if (!method.verification?.verified) {
securityIssues.push(`Unverified: ${method.displayName}`);
}
// Check risk score
if (method.verification?.riskScore === 'high') {
securityIssues.push(`High Risk: ${method.displayName}`);
}
// Check for spending limits
if (!method.limits?.dailyLimit && method.status === 'active') {
securityIssues.push(`No Spending Limits: ${method.displayName}`);
}
});
if (securityIssues.length > 0) {
console.log('⚠️ Security Issues:');
securityIssues.forEach(issue => console.log(` • ${issue}`));
} else {
console.log('✅ No security issues found');
}
// Display security features
const features = data.securityFeatures;
console.log('\n🛡️ Security Features:');
console.log(` 2FA Required: ${features.twoFactorRequired ? '✅' : '❌'}`);
console.log(` Fraud Detection: ${features.fraudDetection ? '✅' : '❌'}`);
console.log(` Spending Limits: ${features.spendingLimits ? '✅' : '❌'}`);
console.log(` Approval Workflow: ${features.approvalWorkflow ? '✅' : '❌'}`);
};
{
"paymentMethods": [
{
"methodId": "pm_card_1234567890",
"type": "credit_card",
"status": "active",
"isDefault": true,
"displayName": "Visa ****4242",
"details": {
"maskedNumber": "****-****-****-4242",
"brand": "Visa",
"expiryDate": "12/26",
"country": "US",
"currency": "USD"
},
"verification": {
"verified": true,
"verificationMethod": "address_verification",
"verifiedAt": "2024-01-15T10:30:00Z",
"riskScore": "low"
},
"usage": {
"totalTransactions": 24,
"totalAmount": 12847.56,
"lastUsed": "2024-01-16T14:20:00Z",
"successRate": 100.0,
"averageAmount": 535.31
},
"limits": {
"dailyLimit": 5000.00,
"monthlyLimit": 50000.00,
"transactionLimit": 10000.00,
"remainingDaily": 3200.00,
"remainingMonthly": 45680.00
},
"metadata": {
"addedAt": "2024-01-15T10:30:00Z",
"addedBy": "admin@company.com",
"tags": ["primary", "corporate"],
"notes": "Primary corporate card"
}
},
{
"methodId": "pm_bank_0987654321",
"type": "bank_account",
"status": "active",
"isDefault": false,
"displayName": "Bank Account ****1234",
"details": {
"maskedNumber": "****-****-1234",
"brand": "Chase Bank",
"expiryDate": null,
"country": "US",
"currency": "USD"
},
"verification": {
"verified": true,
"verificationMethod": "micro_deposits",
"verifiedAt": "2024-01-10T16:45:00Z",
"riskScore": "low"
},
"usage": {
"totalTransactions": 6,
"totalAmount": 8950.00,
"lastUsed": "2024-01-12T09:15:00Z",
"successRate": 83.3,
"averageAmount": 1491.67
},
"limits": {
"dailyLimit": 25000.00,
"monthlyLimit": 100000.00,
"transactionLimit": 25000.00,
"remainingDaily": 25000.00,
"remainingMonthly": 91050.00
},
"metadata": {
"addedAt": "2024-01-08T14:20:00Z",
"addedBy": "finance@company.com",
"tags": ["backup", "large-payments"],
"notes": "For large invoice payments"
}
},
{
"methodId": "pm_crypto_btc_001",
"type": "cryptocurrency",
"status": "active",
"isDefault": false,
"displayName": "Bitcoin Wallet",
"details": {
"maskedNumber": "bc1q...xyz123",
"brand": "Bitcoin",
"expiryDate": null,
"country": null,
"currency": "BTC"
},
"verification": {
"verified": true,
"verificationMethod": "wallet_signature",
"verifiedAt": "2024-01-20T11:00:00Z",
"riskScore": "medium"
},
"usage": {
"totalTransactions": 2,
"totalAmount": 3200.00,
"lastUsed": "2024-01-22T08:30:00Z",
"successRate": 100.0,
"averageAmount": 1600.00
},
"limits": {
"dailyLimit": 10000.00,
"monthlyLimit": 50000.00,
"transactionLimit": 10000.00,
"remainingDaily": 10000.00,
"remainingMonthly": 46800.00
},
"metadata": {
"addedAt": "2024-01-20T11:00:00Z",
"addedBy": "admin@company.com",
"tags": ["crypto", "experimental"],
"notes": "Testing cryptocurrency payments"
}
}
],
"defaultMethod": "pm_card_1234567890",
"supportedTypes": [
"credit_card",
"bank_account",
"digital_wallet",
"cryptocurrency",
"wire_transfer"
],
"securityFeatures": {
"twoFactorRequired": true,
"fraudDetection": true,
"spendingLimits": true,
"approvalWorkflow": true
}
}
Payment & Billing
Payment Methods
Manage payment methods, credit cards, bank accounts, and alternative payment options for your TensorOne account
curl -X GET "https://api.tensorone.ai/v2/billing/payment-methods" \
-H "Authorization: Bearer YOUR_API_KEY" \
-G \
-d "includeUsageStats=true" \
-d "includeSecurityInfo=true"
import requests
from datetime import datetime, timedelta
import getpass
def get_payment_methods(include_usage=False, include_security=False):
params = {
'includeUsageStats': include_usage,
'includeSecurityInfo': include_security
}
response = requests.get(
"https://api.tensorone.ai/v2/billing/payment-methods",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params=params
)
return response.json()
def add_credit_card(card_details):
"""Add a new credit card payment method"""
response = requests.post(
"https://api.tensorone.ai/v2/billing/payment-methods",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=card_details
)
return response.json()
def set_default_payment_method(method_id):
"""Set default payment method"""
response = requests.post(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/set-default",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
return response.json()
# Get all payment methods with usage statistics
payment_data = get_payment_methods(include_usage=True, include_security=True)
print("💳 Payment Methods Dashboard")
print("=" * 30)
# Display default method
if payment_data.get('defaultMethod'):
default_id = payment_data['defaultMethod']
print(f"Default Payment Method: {default_id}")
print()
# List all payment methods
methods = payment_data['paymentMethods']
print(f"Payment Methods ({len(methods)}):")
print("-" * 25)
for method in methods:
method_id = method['methodId']
method_type = method['type']
status = method['status']
display_name = method['displayName']
is_default = method['isDefault']
# Status icons
status_icon = {
'active': '✅',
'expired': '⏰',
'disabled': '❌',
'failed': '🔴',
'pending_verification': '⏳'
}.get(status, '⚪')
default_icon = '⭐' if is_default else ' '
print(f"{default_icon}{status_icon} {display_name}")
print(f" Type: {method_type.title().replace('_', ' ')}")
print(f" Status: {status.title().replace('_', ' ')}")
# Show card/account details
details = method.get('details', {})
if details.get('maskedNumber'):
print(f" Number: {details['maskedNumber']}")
if details.get('brand'):
print(f" Brand: {details['brand']}")
if details.get('expiryDate'):
print(f" Expires: {details['expiryDate']}")
# Show usage statistics
if method.get('usage'):
usage = method['usage']
print(f" Usage: {usage['totalTransactions']} transactions")
print(f" Total: ${usage['totalAmount']:,.2f}")
print(f" Success Rate: {usage['successRate']:.1f}%")
if usage.get('lastUsed'):
print(f" Last Used: {usage['lastUsed'][:10]}")
# Show verification status
if method.get('verification'):
verification = method['verification']
verified_icon = '✅' if verification['verified'] else '❌'
print(f" Verified: {verified_icon}")
if verification.get('riskScore'):
risk_colors = {'low': '🟢', 'medium': '🟡', 'high': '🔴'}
risk_icon = risk_colors.get(verification['riskScore'], '⚪')
print(f" Risk: {risk_icon} {verification['riskScore'].title()}")
# Show limits
if method.get('limits'):
limits = method['limits']
if limits.get('dailyLimit'):
remaining_daily = limits.get('remainingDaily', 0)
print(f" Daily Limit: ${remaining_daily:,.2f} / ${limits['dailyLimit']:,.2f}")
print()
# Check for expiring cards
def check_expiring_cards():
"""Check for cards expiring soon"""
expiring_soon = []
for method in methods:
if method['type'] == 'credit_card' and method['status'] == 'active':
details = method.get('details', {})
expiry = details.get('expiryDate')
if expiry:
# Parse MM/YY format
month, year = expiry.split('/')
expiry_date = datetime(2000 + int(year), int(month), 1)
# Check if expiring within 60 days
if expiry_date - datetime.now() <= timedelta(days=60):
expiring_soon.append({
'method': method,
'expires': expiry_date
})
if expiring_soon:
print("⚠️ Cards Expiring Soon:")
print("-" * 22)
for item in expiring_soon:
method = item['method']
expires = item['expires']
days_left = (expires - datetime.now()).days
print(f" {method['displayName']}")
print(f" Expires in {days_left} days ({expires.strftime('%m/%y')})")
print()
check_expiring_cards()
# Payment method management functions
def update_payment_method_limits(method_id, new_limits):
"""Update spending limits for a payment method"""
response = requests.put(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/limits",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=new_limits
)
return response.json()
def disable_payment_method(method_id, reason=None):
"""Disable a payment method"""
data = {"reason": reason} if reason else {}
response = requests.post(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/disable",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=data
)
return response.json()
def verify_payment_method(method_id, verification_data):
"""Verify a payment method (for bank accounts, etc.)"""
response = requests.post(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/verify",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=verification_data
)
return response.json()
# Example: Add new credit card (requires secure input)
def add_new_credit_card():
"""Securely add a new credit card"""
print("\n💳 Add New Credit Card")
print("=" * 20)
# Note: In production, use proper secure input methods
card_number = getpass.getpass("Card Number: ")
expiry_month = input("Expiry Month (MM): ")
expiry_year = input("Expiry Year (YY): ")
cvv = getpass.getpass("CVV: ")
cardholder_name = input("Cardholder Name: ")
card_details = {
"type": "credit_card",
"cardNumber": card_number,
"expiryMonth": expiry_month,
"expiryYear": expiry_year,
"cvv": cvv,
"cardholderName": cardholder_name,
"billingAddress": {
"street": input("Billing Street: "),
"city": input("Billing City: "),
"state": input("Billing State: "),
"postalCode": input("Billing ZIP: "),
"country": input("Billing Country (US): ") or "US"
},
"setAsDefault": input("Set as default? (y/N): ").lower() == 'y'
}
result = add_credit_card(card_details)
if result.get('success'):
print(f"✅ Card added successfully: {result['methodId']}")
else:
print(f"❌ Failed to add card: {result.get('error', 'Unknown error')}")
# Uncomment to add new card interactively
# add_new_credit_card()
# Payment method security check
def security_audit():
"""Perform security audit of payment methods"""
print("\n🔒 Payment Method Security Audit")
print("=" * 35)
security_issues = []
for method in methods:
method_name = method['displayName']
# Check for unverified methods
verification = method.get('verification', {})
if not verification.get('verified', False):
security_issues.append(f"Unverified: {method_name}")
# Check for high-risk methods
if verification.get('riskScore') == 'high':
security_issues.append(f"High Risk: {method_name}")
# Check for expired methods still active
if method['status'] == 'expired' and method['type'] == 'credit_card':
security_issues.append(f"Expired Active Card: {method_name}")
# Check for methods without limits
limits = method.get('limits', {})
if not limits.get('dailyLimit') and method['status'] == 'active':
security_issues.append(f"No Spending Limits: {method_name}")
if security_issues:
print("⚠️ Security Issues Found:")
for issue in security_issues:
print(f" • {issue}")
else:
print("✅ No security issues found")
# Check security features
security_features = payment_data.get('securityFeatures', {})
print(f"\n🛡️ Security Features:")
print(f" 2FA Required: {'✅' if security_features.get('twoFactorRequired') else '❌'}")
print(f" Fraud Detection: {'✅' if security_features.get('fraudDetection') else '❌'}")
print(f" Spending Limits: {'✅' if security_features.get('spendingLimits') else '❌'}")
print(f" Approval Workflow: {'✅' if security_features.get('approvalWorkflow') else '❌'}")
security_audit()
const getPaymentMethods = async (options = {}) => {
const params = new URLSearchParams({
includeUsageStats: options.includeUsageStats || false,
includeSecurityInfo: options.includeSecurityInfo || false
});
if (options.type) {
const types = Array.isArray(options.type) ? options.type : [options.type];
types.forEach(type => params.append('type[]', type));
}
const response = await fetch(`https://api.tensorone.ai/v2/billing/payment-methods?${params}`, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
return await response.json();
};
const addPaymentMethod = async (paymentMethodData) => {
const response = await fetch('https://api.tensorone.ai/v2/billing/payment-methods', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(paymentMethodData)
});
return await response.json();
};
const setDefaultPaymentMethod = async (methodId) => {
const response = await fetch(`https://api.tensorone.ai/v2/billing/payment-methods/${methodId}/set-default`, {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
return await response.json();
};
// Get and display payment methods
getPaymentMethods({
includeUsageStats: true,
includeSecurityInfo: true
}).then(data => {
console.log('💳 Payment Methods Dashboard');
console.log('============================');
// Show default method
if (data.defaultMethod) {
console.log(`Default Method: ${data.defaultMethod}\n`);
}
// List all methods
data.paymentMethods.forEach(method => {
const statusIcon = {
'active': '✅',
'expired': '⏰',
'disabled': '❌',
'failed': '🔴',
'pending_verification': '⏳'
}[method.status] || '⚪';
const defaultIcon = method.isDefault ? '⭐' : ' ';
console.log(`${defaultIcon}${statusIcon} ${method.displayName}`);
console.log(` Type: ${method.type.replace('_', ' ')}`);
console.log(` Status: ${method.status.replace('_', ' ')}`);
if (method.details.maskedNumber) {
console.log(` Number: ${method.details.maskedNumber}`);
}
if (method.usage) {
console.log(` Usage: ${method.usage.totalTransactions} transactions`);
console.log(` Success Rate: ${method.usage.successRate.toFixed(1)}%`);
}
console.log('');
});
// Check for expiring cards
const expiringCards = data.paymentMethods.filter(method => {
if (method.type !== 'credit_card' || !method.details.expiryDate) return false;
const [month, year] = method.details.expiryDate.split('/');
const expiryDate = new Date(2000 + parseInt(year), parseInt(month) - 1);
const now = new Date();
const daysUntilExpiry = (expiryDate - now) / (1000 * 60 * 60 * 24);
return daysUntilExpiry <= 60 && daysUntilExpiry > 0;
});
if (expiringCards.length > 0) {
console.log('⚠️ Cards Expiring Soon:');
expiringCards.forEach(card => {
console.log(` ${card.displayName} - Expires ${card.details.expiryDate}`);
});
}
});
// Add new payment method
const addCreditCard = async (cardDetails) => {
const paymentMethodData = {
type: 'credit_card',
cardNumber: cardDetails.number,
expiryMonth: cardDetails.expiryMonth,
expiryYear: cardDetails.expiryYear,
cvv: cardDetails.cvv,
cardholderName: cardDetails.name,
billingAddress: cardDetails.billingAddress,
setAsDefault: cardDetails.setAsDefault || false
};
try {
const result = await addPaymentMethod(paymentMethodData);
console.log('✅ Payment method added:', result.methodId);
return result;
} catch (error) {
console.error('❌ Failed to add payment method:', error);
throw error;
}
};
// Update payment method limits
const updatePaymentLimits = async (methodId, limits) => {
const response = await fetch(`https://api.tensorone.ai/v2/billing/payment-methods/${methodId}/limits`, {
method: 'PUT',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(limits)
});
return await response.json();
};
// Security audit function
const performSecurityAudit = async () => {
const data = await getPaymentMethods({ includeSecurityInfo: true });
console.log('🔒 Payment Method Security Audit');
console.log('=================================');
const securityIssues = [];
data.paymentMethods.forEach(method => {
// Check verification status
if (!method.verification?.verified) {
securityIssues.push(`Unverified: ${method.displayName}`);
}
// Check risk score
if (method.verification?.riskScore === 'high') {
securityIssues.push(`High Risk: ${method.displayName}`);
}
// Check for spending limits
if (!method.limits?.dailyLimit && method.status === 'active') {
securityIssues.push(`No Spending Limits: ${method.displayName}`);
}
});
if (securityIssues.length > 0) {
console.log('⚠️ Security Issues:');
securityIssues.forEach(issue => console.log(` • ${issue}`));
} else {
console.log('✅ No security issues found');
}
// Display security features
const features = data.securityFeatures;
console.log('\n🛡️ Security Features:');
console.log(` 2FA Required: ${features.twoFactorRequired ? '✅' : '❌'}`);
console.log(` Fraud Detection: ${features.fraudDetection ? '✅' : '❌'}`);
console.log(` Spending Limits: ${features.spendingLimits ? '✅' : '❌'}`);
console.log(` Approval Workflow: ${features.approvalWorkflow ? '✅' : '❌'}`);
};
{
"paymentMethods": [
{
"methodId": "pm_card_1234567890",
"type": "credit_card",
"status": "active",
"isDefault": true,
"displayName": "Visa ****4242",
"details": {
"maskedNumber": "****-****-****-4242",
"brand": "Visa",
"expiryDate": "12/26",
"country": "US",
"currency": "USD"
},
"verification": {
"verified": true,
"verificationMethod": "address_verification",
"verifiedAt": "2024-01-15T10:30:00Z",
"riskScore": "low"
},
"usage": {
"totalTransactions": 24,
"totalAmount": 12847.56,
"lastUsed": "2024-01-16T14:20:00Z",
"successRate": 100.0,
"averageAmount": 535.31
},
"limits": {
"dailyLimit": 5000.00,
"monthlyLimit": 50000.00,
"transactionLimit": 10000.00,
"remainingDaily": 3200.00,
"remainingMonthly": 45680.00
},
"metadata": {
"addedAt": "2024-01-15T10:30:00Z",
"addedBy": "admin@company.com",
"tags": ["primary", "corporate"],
"notes": "Primary corporate card"
}
},
{
"methodId": "pm_bank_0987654321",
"type": "bank_account",
"status": "active",
"isDefault": false,
"displayName": "Bank Account ****1234",
"details": {
"maskedNumber": "****-****-1234",
"brand": "Chase Bank",
"expiryDate": null,
"country": "US",
"currency": "USD"
},
"verification": {
"verified": true,
"verificationMethod": "micro_deposits",
"verifiedAt": "2024-01-10T16:45:00Z",
"riskScore": "low"
},
"usage": {
"totalTransactions": 6,
"totalAmount": 8950.00,
"lastUsed": "2024-01-12T09:15:00Z",
"successRate": 83.3,
"averageAmount": 1491.67
},
"limits": {
"dailyLimit": 25000.00,
"monthlyLimit": 100000.00,
"transactionLimit": 25000.00,
"remainingDaily": 25000.00,
"remainingMonthly": 91050.00
},
"metadata": {
"addedAt": "2024-01-08T14:20:00Z",
"addedBy": "finance@company.com",
"tags": ["backup", "large-payments"],
"notes": "For large invoice payments"
}
},
{
"methodId": "pm_crypto_btc_001",
"type": "cryptocurrency",
"status": "active",
"isDefault": false,
"displayName": "Bitcoin Wallet",
"details": {
"maskedNumber": "bc1q...xyz123",
"brand": "Bitcoin",
"expiryDate": null,
"country": null,
"currency": "BTC"
},
"verification": {
"verified": true,
"verificationMethod": "wallet_signature",
"verifiedAt": "2024-01-20T11:00:00Z",
"riskScore": "medium"
},
"usage": {
"totalTransactions": 2,
"totalAmount": 3200.00,
"lastUsed": "2024-01-22T08:30:00Z",
"successRate": 100.0,
"averageAmount": 1600.00
},
"limits": {
"dailyLimit": 10000.00,
"monthlyLimit": 50000.00,
"transactionLimit": 10000.00,
"remainingDaily": 10000.00,
"remainingMonthly": 46800.00
},
"metadata": {
"addedAt": "2024-01-20T11:00:00Z",
"addedBy": "admin@company.com",
"tags": ["crypto", "experimental"],
"notes": "Testing cryptocurrency payments"
}
}
],
"defaultMethod": "pm_card_1234567890",
"supportedTypes": [
"credit_card",
"bank_account",
"digital_wallet",
"cryptocurrency",
"wire_transfer"
],
"securityFeatures": {
"twoFactorRequired": true,
"fraudDetection": true,
"spendingLimits": true,
"approvalWorkflow": true
}
}
Securely manage payment methods including credit cards, bank accounts, digital wallets, and cryptocurrency payments for seamless billing automation.
Request Parameters
Filter by payment method types:
credit_card- Credit and debit cardsbank_account- Bank account/ACH transfersdigital_wallet- Digital wallets (PayPal, Apple Pay, Google Pay)cryptocurrency- Cryptocurrency paymentswire_transfer- Wire transferspurchase_order- Purchase order billing
Filter by payment method status:
active- Active and available for useexpired- Expired payment methodsdisabled- Manually disabled methodsfailed- Methods with recent failurespending_verification- Awaiting verification
Response
Array of payment method objects
Show Payment Method Object
Show Payment Method Object
Example
curl -X GET "https://api.tensorone.ai/v2/billing/payment-methods" \
-H "Authorization: Bearer YOUR_API_KEY" \
-G \
-d "includeUsageStats=true" \
-d "includeSecurityInfo=true"
import requests
from datetime import datetime, timedelta
import getpass
def get_payment_methods(include_usage=False, include_security=False):
params = {
'includeUsageStats': include_usage,
'includeSecurityInfo': include_security
}
response = requests.get(
"https://api.tensorone.ai/v2/billing/payment-methods",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params=params
)
return response.json()
def add_credit_card(card_details):
"""Add a new credit card payment method"""
response = requests.post(
"https://api.tensorone.ai/v2/billing/payment-methods",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=card_details
)
return response.json()
def set_default_payment_method(method_id):
"""Set default payment method"""
response = requests.post(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/set-default",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
return response.json()
# Get all payment methods with usage statistics
payment_data = get_payment_methods(include_usage=True, include_security=True)
print("💳 Payment Methods Dashboard")
print("=" * 30)
# Display default method
if payment_data.get('defaultMethod'):
default_id = payment_data['defaultMethod']
print(f"Default Payment Method: {default_id}")
print()
# List all payment methods
methods = payment_data['paymentMethods']
print(f"Payment Methods ({len(methods)}):")
print("-" * 25)
for method in methods:
method_id = method['methodId']
method_type = method['type']
status = method['status']
display_name = method['displayName']
is_default = method['isDefault']
# Status icons
status_icon = {
'active': '✅',
'expired': '⏰',
'disabled': '❌',
'failed': '🔴',
'pending_verification': '⏳'
}.get(status, '⚪')
default_icon = '⭐' if is_default else ' '
print(f"{default_icon}{status_icon} {display_name}")
print(f" Type: {method_type.title().replace('_', ' ')}")
print(f" Status: {status.title().replace('_', ' ')}")
# Show card/account details
details = method.get('details', {})
if details.get('maskedNumber'):
print(f" Number: {details['maskedNumber']}")
if details.get('brand'):
print(f" Brand: {details['brand']}")
if details.get('expiryDate'):
print(f" Expires: {details['expiryDate']}")
# Show usage statistics
if method.get('usage'):
usage = method['usage']
print(f" Usage: {usage['totalTransactions']} transactions")
print(f" Total: ${usage['totalAmount']:,.2f}")
print(f" Success Rate: {usage['successRate']:.1f}%")
if usage.get('lastUsed'):
print(f" Last Used: {usage['lastUsed'][:10]}")
# Show verification status
if method.get('verification'):
verification = method['verification']
verified_icon = '✅' if verification['verified'] else '❌'
print(f" Verified: {verified_icon}")
if verification.get('riskScore'):
risk_colors = {'low': '🟢', 'medium': '🟡', 'high': '🔴'}
risk_icon = risk_colors.get(verification['riskScore'], '⚪')
print(f" Risk: {risk_icon} {verification['riskScore'].title()}")
# Show limits
if method.get('limits'):
limits = method['limits']
if limits.get('dailyLimit'):
remaining_daily = limits.get('remainingDaily', 0)
print(f" Daily Limit: ${remaining_daily:,.2f} / ${limits['dailyLimit']:,.2f}")
print()
# Check for expiring cards
def check_expiring_cards():
"""Check for cards expiring soon"""
expiring_soon = []
for method in methods:
if method['type'] == 'credit_card' and method['status'] == 'active':
details = method.get('details', {})
expiry = details.get('expiryDate')
if expiry:
# Parse MM/YY format
month, year = expiry.split('/')
expiry_date = datetime(2000 + int(year), int(month), 1)
# Check if expiring within 60 days
if expiry_date - datetime.now() <= timedelta(days=60):
expiring_soon.append({
'method': method,
'expires': expiry_date
})
if expiring_soon:
print("⚠️ Cards Expiring Soon:")
print("-" * 22)
for item in expiring_soon:
method = item['method']
expires = item['expires']
days_left = (expires - datetime.now()).days
print(f" {method['displayName']}")
print(f" Expires in {days_left} days ({expires.strftime('%m/%y')})")
print()
check_expiring_cards()
# Payment method management functions
def update_payment_method_limits(method_id, new_limits):
"""Update spending limits for a payment method"""
response = requests.put(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/limits",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=new_limits
)
return response.json()
def disable_payment_method(method_id, reason=None):
"""Disable a payment method"""
data = {"reason": reason} if reason else {}
response = requests.post(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/disable",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=data
)
return response.json()
def verify_payment_method(method_id, verification_data):
"""Verify a payment method (for bank accounts, etc.)"""
response = requests.post(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/verify",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=verification_data
)
return response.json()
# Example: Add new credit card (requires secure input)
def add_new_credit_card():
"""Securely add a new credit card"""
print("\n💳 Add New Credit Card")
print("=" * 20)
# Note: In production, use proper secure input methods
card_number = getpass.getpass("Card Number: ")
expiry_month = input("Expiry Month (MM): ")
expiry_year = input("Expiry Year (YY): ")
cvv = getpass.getpass("CVV: ")
cardholder_name = input("Cardholder Name: ")
card_details = {
"type": "credit_card",
"cardNumber": card_number,
"expiryMonth": expiry_month,
"expiryYear": expiry_year,
"cvv": cvv,
"cardholderName": cardholder_name,
"billingAddress": {
"street": input("Billing Street: "),
"city": input("Billing City: "),
"state": input("Billing State: "),
"postalCode": input("Billing ZIP: "),
"country": input("Billing Country (US): ") or "US"
},
"setAsDefault": input("Set as default? (y/N): ").lower() == 'y'
}
result = add_credit_card(card_details)
if result.get('success'):
print(f"✅ Card added successfully: {result['methodId']}")
else:
print(f"❌ Failed to add card: {result.get('error', 'Unknown error')}")
# Uncomment to add new card interactively
# add_new_credit_card()
# Payment method security check
def security_audit():
"""Perform security audit of payment methods"""
print("\n🔒 Payment Method Security Audit")
print("=" * 35)
security_issues = []
for method in methods:
method_name = method['displayName']
# Check for unverified methods
verification = method.get('verification', {})
if not verification.get('verified', False):
security_issues.append(f"Unverified: {method_name}")
# Check for high-risk methods
if verification.get('riskScore') == 'high':
security_issues.append(f"High Risk: {method_name}")
# Check for expired methods still active
if method['status'] == 'expired' and method['type'] == 'credit_card':
security_issues.append(f"Expired Active Card: {method_name}")
# Check for methods without limits
limits = method.get('limits', {})
if not limits.get('dailyLimit') and method['status'] == 'active':
security_issues.append(f"No Spending Limits: {method_name}")
if security_issues:
print("⚠️ Security Issues Found:")
for issue in security_issues:
print(f" • {issue}")
else:
print("✅ No security issues found")
# Check security features
security_features = payment_data.get('securityFeatures', {})
print(f"\n🛡️ Security Features:")
print(f" 2FA Required: {'✅' if security_features.get('twoFactorRequired') else '❌'}")
print(f" Fraud Detection: {'✅' if security_features.get('fraudDetection') else '❌'}")
print(f" Spending Limits: {'✅' if security_features.get('spendingLimits') else '❌'}")
print(f" Approval Workflow: {'✅' if security_features.get('approvalWorkflow') else '❌'}")
security_audit()
const getPaymentMethods = async (options = {}) => {
const params = new URLSearchParams({
includeUsageStats: options.includeUsageStats || false,
includeSecurityInfo: options.includeSecurityInfo || false
});
if (options.type) {
const types = Array.isArray(options.type) ? options.type : [options.type];
types.forEach(type => params.append('type[]', type));
}
const response = await fetch(`https://api.tensorone.ai/v2/billing/payment-methods?${params}`, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
return await response.json();
};
const addPaymentMethod = async (paymentMethodData) => {
const response = await fetch('https://api.tensorone.ai/v2/billing/payment-methods', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(paymentMethodData)
});
return await response.json();
};
const setDefaultPaymentMethod = async (methodId) => {
const response = await fetch(`https://api.tensorone.ai/v2/billing/payment-methods/${methodId}/set-default`, {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
return await response.json();
};
// Get and display payment methods
getPaymentMethods({
includeUsageStats: true,
includeSecurityInfo: true
}).then(data => {
console.log('💳 Payment Methods Dashboard');
console.log('============================');
// Show default method
if (data.defaultMethod) {
console.log(`Default Method: ${data.defaultMethod}\n`);
}
// List all methods
data.paymentMethods.forEach(method => {
const statusIcon = {
'active': '✅',
'expired': '⏰',
'disabled': '❌',
'failed': '🔴',
'pending_verification': '⏳'
}[method.status] || '⚪';
const defaultIcon = method.isDefault ? '⭐' : ' ';
console.log(`${defaultIcon}${statusIcon} ${method.displayName}`);
console.log(` Type: ${method.type.replace('_', ' ')}`);
console.log(` Status: ${method.status.replace('_', ' ')}`);
if (method.details.maskedNumber) {
console.log(` Number: ${method.details.maskedNumber}`);
}
if (method.usage) {
console.log(` Usage: ${method.usage.totalTransactions} transactions`);
console.log(` Success Rate: ${method.usage.successRate.toFixed(1)}%`);
}
console.log('');
});
// Check for expiring cards
const expiringCards = data.paymentMethods.filter(method => {
if (method.type !== 'credit_card' || !method.details.expiryDate) return false;
const [month, year] = method.details.expiryDate.split('/');
const expiryDate = new Date(2000 + parseInt(year), parseInt(month) - 1);
const now = new Date();
const daysUntilExpiry = (expiryDate - now) / (1000 * 60 * 60 * 24);
return daysUntilExpiry <= 60 && daysUntilExpiry > 0;
});
if (expiringCards.length > 0) {
console.log('⚠️ Cards Expiring Soon:');
expiringCards.forEach(card => {
console.log(` ${card.displayName} - Expires ${card.details.expiryDate}`);
});
}
});
// Add new payment method
const addCreditCard = async (cardDetails) => {
const paymentMethodData = {
type: 'credit_card',
cardNumber: cardDetails.number,
expiryMonth: cardDetails.expiryMonth,
expiryYear: cardDetails.expiryYear,
cvv: cardDetails.cvv,
cardholderName: cardDetails.name,
billingAddress: cardDetails.billingAddress,
setAsDefault: cardDetails.setAsDefault || false
};
try {
const result = await addPaymentMethod(paymentMethodData);
console.log('✅ Payment method added:', result.methodId);
return result;
} catch (error) {
console.error('❌ Failed to add payment method:', error);
throw error;
}
};
// Update payment method limits
const updatePaymentLimits = async (methodId, limits) => {
const response = await fetch(`https://api.tensorone.ai/v2/billing/payment-methods/${methodId}/limits`, {
method: 'PUT',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify(limits)
});
return await response.json();
};
// Security audit function
const performSecurityAudit = async () => {
const data = await getPaymentMethods({ includeSecurityInfo: true });
console.log('🔒 Payment Method Security Audit');
console.log('=================================');
const securityIssues = [];
data.paymentMethods.forEach(method => {
// Check verification status
if (!method.verification?.verified) {
securityIssues.push(`Unverified: ${method.displayName}`);
}
// Check risk score
if (method.verification?.riskScore === 'high') {
securityIssues.push(`High Risk: ${method.displayName}`);
}
// Check for spending limits
if (!method.limits?.dailyLimit && method.status === 'active') {
securityIssues.push(`No Spending Limits: ${method.displayName}`);
}
});
if (securityIssues.length > 0) {
console.log('⚠️ Security Issues:');
securityIssues.forEach(issue => console.log(` • ${issue}`));
} else {
console.log('✅ No security issues found');
}
// Display security features
const features = data.securityFeatures;
console.log('\n🛡️ Security Features:');
console.log(` 2FA Required: ${features.twoFactorRequired ? '✅' : '❌'}`);
console.log(` Fraud Detection: ${features.fraudDetection ? '✅' : '❌'}`);
console.log(` Spending Limits: ${features.spendingLimits ? '✅' : '❌'}`);
console.log(` Approval Workflow: ${features.approvalWorkflow ? '✅' : '❌'}`);
};
{
"paymentMethods": [
{
"methodId": "pm_card_1234567890",
"type": "credit_card",
"status": "active",
"isDefault": true,
"displayName": "Visa ****4242",
"details": {
"maskedNumber": "****-****-****-4242",
"brand": "Visa",
"expiryDate": "12/26",
"country": "US",
"currency": "USD"
},
"verification": {
"verified": true,
"verificationMethod": "address_verification",
"verifiedAt": "2024-01-15T10:30:00Z",
"riskScore": "low"
},
"usage": {
"totalTransactions": 24,
"totalAmount": 12847.56,
"lastUsed": "2024-01-16T14:20:00Z",
"successRate": 100.0,
"averageAmount": 535.31
},
"limits": {
"dailyLimit": 5000.00,
"monthlyLimit": 50000.00,
"transactionLimit": 10000.00,
"remainingDaily": 3200.00,
"remainingMonthly": 45680.00
},
"metadata": {
"addedAt": "2024-01-15T10:30:00Z",
"addedBy": "admin@company.com",
"tags": ["primary", "corporate"],
"notes": "Primary corporate card"
}
},
{
"methodId": "pm_bank_0987654321",
"type": "bank_account",
"status": "active",
"isDefault": false,
"displayName": "Bank Account ****1234",
"details": {
"maskedNumber": "****-****-1234",
"brand": "Chase Bank",
"expiryDate": null,
"country": "US",
"currency": "USD"
},
"verification": {
"verified": true,
"verificationMethod": "micro_deposits",
"verifiedAt": "2024-01-10T16:45:00Z",
"riskScore": "low"
},
"usage": {
"totalTransactions": 6,
"totalAmount": 8950.00,
"lastUsed": "2024-01-12T09:15:00Z",
"successRate": 83.3,
"averageAmount": 1491.67
},
"limits": {
"dailyLimit": 25000.00,
"monthlyLimit": 100000.00,
"transactionLimit": 25000.00,
"remainingDaily": 25000.00,
"remainingMonthly": 91050.00
},
"metadata": {
"addedAt": "2024-01-08T14:20:00Z",
"addedBy": "finance@company.com",
"tags": ["backup", "large-payments"],
"notes": "For large invoice payments"
}
},
{
"methodId": "pm_crypto_btc_001",
"type": "cryptocurrency",
"status": "active",
"isDefault": false,
"displayName": "Bitcoin Wallet",
"details": {
"maskedNumber": "bc1q...xyz123",
"brand": "Bitcoin",
"expiryDate": null,
"country": null,
"currency": "BTC"
},
"verification": {
"verified": true,
"verificationMethod": "wallet_signature",
"verifiedAt": "2024-01-20T11:00:00Z",
"riskScore": "medium"
},
"usage": {
"totalTransactions": 2,
"totalAmount": 3200.00,
"lastUsed": "2024-01-22T08:30:00Z",
"successRate": 100.0,
"averageAmount": 1600.00
},
"limits": {
"dailyLimit": 10000.00,
"monthlyLimit": 50000.00,
"transactionLimit": 10000.00,
"remainingDaily": 10000.00,
"remainingMonthly": 46800.00
},
"metadata": {
"addedAt": "2024-01-20T11:00:00Z",
"addedBy": "admin@company.com",
"tags": ["crypto", "experimental"],
"notes": "Testing cryptocurrency payments"
}
}
],
"defaultMethod": "pm_card_1234567890",
"supportedTypes": [
"credit_card",
"bank_account",
"digital_wallet",
"cryptocurrency",
"wire_transfer"
],
"securityFeatures": {
"twoFactorRequired": true,
"fraudDetection": true,
"spendingLimits": true,
"approvalWorkflow": true
}
}
Payment Method Operations
Add New Payment Methods
Python
def add_bank_account(account_details):
"""Add a new bank account for ACH payments"""
bank_data = {
"type": "bank_account",
"accountHolderName": account_details["account_holder"],
"accountNumber": account_details["account_number"],
"routingNumber": account_details["routing_number"],
"accountType": account_details.get("account_type", "checking"), # checking or savings
"bankName": account_details.get("bank_name"),
"billingAddress": account_details["billing_address"],
"verificationMethod": "micro_deposits", # or instant_verification
"setAsDefault": account_details.get("set_default", False)
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/payment-methods",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=bank_data
)
return response.json()
def add_digital_wallet(wallet_details):
"""Add digital wallet (PayPal, Apple Pay, etc.)"""
wallet_data = {
"type": "digital_wallet",
"walletType": wallet_details["wallet_type"], # paypal, apple_pay, google_pay
"walletId": wallet_details["wallet_id"],
"displayName": wallet_details.get("display_name"),
"setAsDefault": wallet_details.get("set_default", False)
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/payment-methods",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=wallet_data
)
return response.json()
def add_cryptocurrency_wallet(crypto_details):
"""Add cryptocurrency payment method"""
crypto_data = {
"type": "cryptocurrency",
"cryptocurrency": crypto_details["currency"], # BTC, ETH, USDC, etc.
"walletAddress": crypto_details["wallet_address"],
"network": crypto_details.get("network", "mainnet"),
"displayName": crypto_details.get("display_name"),
"verificationMethod": "wallet_signature",
"setAsDefault": crypto_details.get("set_default", False)
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/payment-methods",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=crypto_data
)
return response.json()
# Example: Add bank account
bank_account_details = {
"account_holder": "Acme Corporation",
"account_number": "1234567890",
"routing_number": "021000021",
"account_type": "checking",
"bank_name": "Chase Bank",
"billing_address": {
"street": "123 Business Ave",
"city": "San Francisco",
"state": "CA",
"postalCode": "94105",
"country": "US"
},
"set_default": False
}
# bank_result = add_bank_account(bank_account_details)
# print(f"Bank account added: {bank_result.get('methodId', 'Failed')}")
# Example: Add cryptocurrency wallet
crypto_details = {
"currency": "BTC",
"wallet_address": "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh",
"network": "mainnet",
"display_name": "Bitcoin Corporate Wallet"
}
# crypto_result = add_cryptocurrency_wallet(crypto_details)
# print(f"Crypto wallet added: {crypto_result.get('methodId', 'Failed')}")
Payment Method Verification
Python
def verify_bank_account_micro_deposits(method_id, deposit_amounts):
"""Verify bank account using micro deposit amounts"""
verification_data = {
"verificationMethod": "micro_deposits",
"depositAmounts": deposit_amounts # [0.32, 0.45] - amounts in dollars
}
response = requests.post(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/verify",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=verification_data
)
return response.json()
def verify_cryptocurrency_wallet(method_id, signature):
"""Verify cryptocurrency wallet using signature"""
verification_data = {
"verificationMethod": "wallet_signature",
"signature": signature,
"message": "TensorOne Wallet Verification"
}
response = requests.post(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/verify",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=verification_data
)
return response.json()
def get_verification_status(method_id):
"""Check verification status of a payment method"""
response = requests.get(
f"https://api.tensorone.ai/v2/billing/payment-methods/{method_id}/verification",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
return response.json()
# Example verification workflow
def payment_method_verification_workflow():
"""Handle payment method verification workflow"""
unverified_methods = []
payment_data = get_payment_methods(include_security=True)
for method in payment_data['paymentMethods']:
verification = method.get('verification', {})
if not verification.get('verified', False):
unverified_methods.append(method)
if unverified_methods:
print("🔍 Unverified Payment Methods:")
print("-" * 32)
for method in unverified_methods:
method_id = method['methodId']
method_type = method['type']
display_name = method['displayName']
print(f"Method: {display_name}")
print(f"Type: {method_type}")
print(f"ID: {method_id}")
if method_type == "bank_account":
print("Action: Verify using micro deposits")
print("1. Check bank statement for two small deposits")
print("2. Call verify_bank_account_micro_deposits() with amounts")
elif method_type == "cryptocurrency":
print("Action: Verify using wallet signature")
print("1. Sign verification message with wallet")
print("2. Call verify_cryptocurrency_wallet() with signature")
print()
else:
print("✅ All payment methods are verified")
payment_method_verification_workflow()
Payment Method Security Management
Python
def enable_two_factor_auth():
"""Enable two-factor authentication for payment methods"""
response = requests.post(
"https://api.tensorone.ai/v2/billing/security/enable-2fa",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json={
"enable": True,
"methods": ["sms", "email", "authenticator"],
"requireForActions": ["add_payment_method", "set_default", "large_transactions"]
}
)
return response.json()
def set_fraud_detection_rules():
"""Configure fraud detection rules"""
rules_config = {
"enableRealTimeMonitoring": True,
"maxTransactionAmount": 10000.00,
"maxDailyAmount": 25000.00,
"unusualLocationAlert": True,
"velocityChecks": True,
"ipWhitelist": ["192.168.1.0/24"], # Office IP range
"timeRestrictions": {
"allowedHours": "06:00-22:00",
"timezone": "America/New_York",
"allowWeekends": True
},
"deviceFingerprinting": True
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/security/fraud-detection",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=rules_config
)
return response.json()
def configure_approval_workflow():
"""Set up approval workflow for large transactions"""
workflow_config = {
"enabled": True,
"thresholds": {
"requireApprovalAbove": 5000.00,
"autoApproveBelow": 1000.00
},
"approvers": [
{
"email": "cfo@company.com",
"role": "primary",
"maxAmount": 50000.00
},
{
"email": "finance-director@company.com",
"role": "secondary",
"maxAmount": 25000.00
}
],
"approvalTimeout": "24h",
"notificationChannels": ["email", "slack"],
"escalationRules": {
"escalateAfter": "12h",
"escalateTo": "ceo@company.com"
}
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/security/approval-workflow",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=workflow_config
)
return response.json()
# Configure security features
def setup_payment_security():
"""Set up comprehensive payment security"""
print("🔒 Configuring Payment Security")
print("=" * 32)
# Enable 2FA
tfa_result = enable_two_factor_auth()
print(f"Two-Factor Auth: {'✅' if tfa_result.get('success') else '❌'}")
# Set fraud detection
fraud_result = set_fraud_detection_rules()
print(f"Fraud Detection: {'✅' if fraud_result.get('success') else '❌'}")
# Configure approval workflow
approval_result = configure_approval_workflow()
print(f"Approval Workflow: {'✅' if approval_result.get('success') else '❌'}")
print("\n🛡️ Security configuration complete")
# setup_payment_security()
Payment Method Analytics
Python
def get_payment_method_analytics(time_range="last_6_months"):
"""Get analytics for payment method usage"""
response = requests.get(
"https://api.tensorone.ai/v2/billing/payment-methods/analytics",
headers={"Authorization": "Bearer YOUR_API_KEY"},
params={
"timeRange": time_range,
"includeFailureAnalysis": True,
"includeCostAnalysis": True
}
)
return response.json()
def analyze_payment_performance():
"""Analyze payment method performance and reliability"""
analytics = get_payment_method_analytics()
print("📊 Payment Method Performance Analysis")
print("=" * 42)
methods = analytics.get('methodAnalytics', [])
# Success rate analysis
print("\n✅ Success Rates:")
print("-" * 16)
success_rates = [(m['displayName'], m['successRate']) for m in methods]
success_rates.sort(key=lambda x: x[1], reverse=True)
for name, rate in success_rates:
rate_icon = "🟢" if rate >= 95 else "🟡" if rate >= 90 else "🔴"
print(f"{rate_icon} {name}: {rate:.1f}%")
# Transaction volume analysis
print(f"\n💰 Transaction Volumes:")
print("-" * 22)
volume_data = [(m['displayName'], m['totalAmount'], m['transactionCount'])
for m in methods]
volume_data.sort(key=lambda x: x[1], reverse=True)
for name, amount, count in volume_data:
avg_transaction = amount / count if count > 0 else 0
print(f"{name}:")
print(f" Total: ${amount:,.2f} ({count} transactions)")
print(f" Average: ${avg_transaction:,.2f}")
print()
# Failure analysis
if analytics.get('failureAnalysis'):
print("❌ Failure Analysis:")
print("-" * 18)
failures = analytics['failureAnalysis']
for failure_type, data in failures.items():
count = data['count']
percentage = data['percentage']
print(f" {failure_type.replace('_', ' ').title()}: {count} ({percentage:.1f}%)")
# Cost analysis
if analytics.get('costAnalysis'):
print("\n💸 Processing Costs:")
print("-" * 18)
costs = analytics['costAnalysis']
for method_name, cost_data in costs.items():
total_fees = cost_data['totalFees']
fee_rate = cost_data['averageFeeRate']
print(f" {method_name}: ${total_fees:.2f} (avg {fee_rate:.2f}%)")
# Recommendations
if analytics.get('recommendations'):
print(f"\n💡 Recommendations:")
print("-" * 17)
for rec in analytics['recommendations']:
impact_icon = {"high": "🔴", "medium": "🟡", "low": "🟢"}.get(rec['impact'], "⚪")
print(f"{impact_icon} {rec['title']}")
print(f" {rec['description']}")
print(f" Potential savings: {rec.get('potentialSavings', 'N/A')}")
print()
analyze_payment_performance()
Advanced Payment Features
Multi-Currency Support
Python
def add_multi_currency_card(card_details, supported_currencies):
"""Add a card that supports multiple currencies"""
card_data = {
"type": "credit_card",
"cardNumber": card_details["card_number"],
"expiryMonth": card_details["expiry_month"],
"expiryYear": card_details["expiry_year"],
"cvv": card_details["cvv"],
"cardholderName": card_details["cardholder_name"],
"billingAddress": card_details["billing_address"],
"supportedCurrencies": supported_currencies, # ["USD", "EUR", "GBP"]
"defaultCurrency": "USD",
"dynamicCurrencyConversion": True
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/payment-methods",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=card_data
)
return response.json()
def get_currency_exchange_rates():
"""Get current exchange rates for supported currencies"""
response = requests.get(
"https://api.tensorone.ai/v2/billing/exchange-rates",
headers={"Authorization": "Bearer YOUR_API_KEY"}
)
return response.json()
# Add international payment methods
international_card = {
"card_number": "4000000000000002", # Test card
"expiry_month": "12",
"expiry_year": "26",
"cvv": "123",
"cardholder_name": "International Corp",
"billing_address": {
"street": "123 International St",
"city": "London",
"state": "",
"postalCode": "SW1A 1AA",
"country": "GB"
}
}
# multi_currency_result = add_multi_currency_card(
# international_card,
# ["USD", "EUR", "GBP", "JPY"]
# )
Payment Method Automation
Python
def setup_payment_automation():
"""Configure automatic payment method selection and failover"""
automation_config = {
"enableSmartRouting": True,
"routingRules": [
{
"condition": "amount > 5000",
"preferredMethod": "bank_account",
"reason": "Lower fees for large amounts"
},
{
"condition": "currency != USD",
"preferredMethod": "multi_currency_card",
"reason": "Better exchange rates"
},
{
"condition": "recurring_payment == true",
"preferredMethod": "credit_card",
"reason": "Higher reliability for recurring charges"
}
],
"failoverChain": [
"primary_credit_card",
"backup_credit_card",
"bank_account",
"digital_wallet"
],
"retryPolicy": {
"maxRetries": 3,
"retryDelay": "1h",
"exponentialBackoff": True
},
"notifications": {
"onFailure": True,
"onSuccess": False,
"onFailover": True,
"channels": ["email", "webhook"]
}
}
response = requests.post(
"https://api.tensorone.ai/v2/billing/payment-automation",
headers={
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
},
json=automation_config
)
return response.json()
# Configure payment automation
automation_result = setup_payment_automation()
print(f"Payment automation configured: {automation_result.get('success', False)}")
Best Practices
Security Best Practices
- Regular Audits: Perform monthly security audits of payment methods
- Strong Authentication: Enable 2FA for all payment method changes
- Fraud Monitoring: Set up real-time fraud detection and alerts
- Access Controls: Limit who can add or modify payment methods
Payment Method Management
- Diversification: Maintain multiple payment methods for redundancy
- Expiration Tracking: Monitor and update expiring payment methods
- Cost Optimization: Use appropriate payment methods based on transaction size
- Verification: Always verify new payment methods before use
Compliance and Documentation
- PCI Compliance: Ensure all card data handling meets PCI DSS standards
- Audit Trails: Maintain detailed logs of all payment method changes
- Data Retention: Follow data retention policies for payment information
- Regular Updates: Keep payment method information current
Payment method data is encrypted at rest and in transit. Card numbers are tokenized and never stored in plain text. All payment operations are logged for security and compliance.
Set up automated alerts for expiring cards and failed payments. Use smart routing to automatically select the best payment method based on transaction characteristics and minimize processing fees.

