Calculate Currency Conversion
Preview currency conversion results without executing the exchange. This endpoint allows you to check current exchange rates and calculate conversion amounts.
Calculations don't perform actual conversions - they only preview what the result would be at current rates.
Endpoint​
GET /rest/v1/currency-conversion
Request Parameters​
All parameters are passed in the query string.
Required Parameters
You must provide either source amount or target amount (but not both):
View Parameter Options
Option A: Specify Source Amount
| Parameter | Type | Description |
|---|---|---|
from_currency | string | Source currency code (e.g., EUR, USD) |
to_currency | string | Target currency code |
from_amount | integer | Source amount in cents |
from_amount_decimal | string | Source amount in decimal format |
Option B: Specify Target Amount
| Parameter | Type | Description |
|---|---|---|
from_currency | string | Source currency code |
to_currency | string | Target currency code |
to_amount | integer | Desired target amount in cents |
to_amount_decimal | string | Desired target amount in decimal |
Optional Parameters
| Parameter | Type | Description |
|---|---|---|
account_number | string | Account number for account-specific rates |
Some accounts have custom exchange rates. Provide account_number to get accurate rates for that specific account.
Response​
Response Structure
{
"from_currency": "EUR",
"to_currency": "USD",
"from_amount": 10000,
"from_amount_decimal": "100.00",
"to_amount": 10850,
"to_amount_decimal": "108.50",
"account_number": "EVP1234567890"
}
View Response Fields
| Field | Type | Description |
|---|---|---|
from_currency | string | Source currency |
to_currency | string | Target currency |
from_amount | integer | Source amount in cents |
from_amount_decimal | string | Source amount (e.g., "100.00") |
to_amount | integer | Target amount in cents |
to_amount_decimal | string | Target amount (e.g., "108.50") |
account_number | string | Account number (if provided in request) |
Examples​
Example 1: Calculate Target Amount
"How much USD will I get for 100 EUR?"
Request
GET /rest/v1/currency-conversion?from_currency=EUR&to_currency=USD&from_amount_decimal=100.00
Host: wallet.paysera.com
Authorization: MAC id="wkVd93h2uS", ts="1343811600", nonce="nQnNaSNyubfPErjRO55yaaEYo9YZfKHN", mac="TjBTboV3iZkrUvu6wHxXeflNF0INZ8TZmzK/G8Utj4E="
Response
{
"from_currency": "EUR",
"to_currency": "USD",
"from_amount": 10000,
"from_amount_decimal": "100.00",
"to_amount": 10850,
"to_amount_decimal": "108.50"
}
Result: 100 EUR = 108.50 USD
Example 2: Calculate Source Amount
"How much EUR do I need to get 200 USD?"
Request
GET /rest/v1/currency-conversion?from_currency=EUR&to_currency=USD&to_amount_decimal=200.00
Host: wallet.paysera.com
Authorization: MAC id="wkVd93h2uS", ts="1343811600", nonce="nQnNaSNyubfPErjRO55yaaEYo9YZfKHN", mac="KwCRgR3O9cWGni/fkUPjVBLfl5cCURgLHIc7yppjFHw="
Response
{
"from_currency": "EUR",
"to_currency": "USD",
"from_amount": 18433,
"from_amount_decimal": "184.33",
"to_amount": 20000,
"to_amount_decimal": "200.00"
}
Result: You need 184.33 EUR to get 200 USD
Example 3: With Account Number
Calculate with account-specific rate
Request
GET /rest/v1/currency-conversion?from_currency=EUR&to_currency=GBP&from_amount_decimal=50.00&account_number=EVP1234567890
Response
{
"from_currency": "EUR",
"to_currency": "GBP",
"from_amount": 5000,
"from_amount_decimal": "50.00",
"to_amount": 4312,
"to_amount_decimal": "43.12",
"account_number": "EVP1234567890"
}
Code Examples​
JavaScript
const crypto = require('crypto');
const CLIENT_ID = 'wkVd93h2uS';
const MAC_KEY = 'your_mac_key';
function generateMacAuth(method, uri, host) {
const timestamp = Math.floor(Date.now() / 1000);
const nonce = crypto.randomBytes(16).toString('hex');
const normalizedString = [timestamp, nonce, method, uri, host, '443', ''].join('\n') + '\n';
const mac = crypto.createHmac('sha256', MAC_KEY).update(normalizedString).digest('base64');
return `MAC id="${CLIENT_ID}", ts="${timestamp}", nonce="${nonce}", mac="${mac}"`;
}
async function calculateConversion(fromCurrency, toCurrency, amount) {
const params = new URLSearchParams({
from_currency: fromCurrency,
to_currency: toCurrency,
from_amount_decimal: amount
});
const uri = `/rest/v1/currency-conversion?${params}`;
const response = await fetch(
`https://wallet.paysera.com${uri}`,
{
headers: {
'Authorization': generateMacAuth('GET', uri, 'wallet.paysera.com')
}
}
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const result = await response.json();
console.log(`${amount} ${fromCurrency} = ${result.to_amount_decimal} ${toCurrency}`);
return result;
}
// Usage
const result = await calculateConversion('EUR', 'USD', '100.00');
console.log(`Exchange rate: ${result.to_amount / result.from_amount}`);
Python
import requests
import hmac
import hashlib
import time
import secrets
CLIENT_ID = 'wkVd93h2uS'
MAC_KEY = 'your_mac_key'
def generate_mac_auth(method, uri, host):
timestamp = str(int(time.time()))
nonce = secrets.token_hex(16)
normalized = f"{timestamp}\n{nonce}\n{method}\n{uri}\n{host}\n443\n\n"
mac = hmac.new(MAC_KEY.encode(), normalized.encode(), hashlib.sha256).digest()
mac_base64 = hashlib.b64encode(mac).decode()
return f'MAC id="{CLIENT_ID}", ts="{timestamp}", nonce="{nonce}", mac="{mac_base64}"'
def calculate_conversion(from_currency, to_currency, amount):
params = {
'from_currency': from_currency,
'to_currency': to_currency,
'from_amount_decimal': amount
}
uri = '/rest/v1/currency-conversion?' + '&'.join([f"{k}={v}" for k, v in params.items()])
headers = {
'Authorization': generate_mac_auth('GET', uri, 'wallet.paysera.com')
}
response = requests.get(
'https://wallet.paysera.com/rest/v1/currency-conversion',
params=params,
headers=headers
)
response.raise_for_status()
result = response.json()
print(f"{amount} {from_currency} = {result['to_amount_decimal']} {to_currency}")
return result
# Usage
result = calculate_conversion('EUR', 'USD', '100.00')
rate = float(result['to_amount_decimal']) / float(result['from_amount_decimal'])
print(f"Exchange rate: {rate:.4f}")
PHP
<?php
define('CLIENT_ID', 'wkVd93h2uS');
define('MAC_KEY', 'your_mac_key');
function generateMacAuth($method, $uri, $host) {
$timestamp = time();
$nonce = bin2hex(random_bytes(16));
$normalized = implode("\n", [$timestamp, $nonce, $method, $uri, $host, '443', '']) . "\n";
$mac = base64_encode(hash_hmac('sha256', $normalized, MAC_KEY, true));
return sprintf('MAC id="%s", ts="%s", nonce="%s", mac="%s"', CLIENT_ID, $timestamp, $nonce, $mac);
}
function calculateConversion($fromCurrency, $toCurrency, $amount) {
$params = http_build_query([
'from_currency' => $fromCurrency,
'to_currency' => $toCurrency,
'from_amount_decimal' => $amount
]);
$uri = "/rest/v1/currency-conversion?$params";
$authorization = generateMacAuth('GET', $uri, 'wallet.paysera.com');
$ch = curl_init("https://wallet.paysera.com$uri");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: $authorization"
]);
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($statusCode !== 200) {
throw new Exception("HTTP $statusCode");
}
$result = json_decode($response, true);
echo "$amount $fromCurrency = {$result['to_amount_decimal']} $toCurrency\n";
return $result;
}
// Usage
$result = calculateConversion('EUR', 'USD', '100.00');
$rate = $result['to_amount'] / $result['from_amount'];
echo "Exchange rate: " . number_format($rate, 4) . "\n";
?>
Advanced Usage​
Compare Multiple Currencies
async function compareRates(amount, baseCurrency, targetCurrencies) {
const rates = {};
for (const targetCurrency of targetCurrencies) {
const result = await api.calculateConversion({
from_currency: baseCurrency,
to_currency: targetCurrency,
from_amount_decimal: amount
});
rates[targetCurrency] = {
amount: result.to_amount_decimal,
rate: result.to_amount / result.from_amount
};
}
return rates;
}
// Usage - compare EUR to multiple currencies
const rates = await compareRates('100.00', 'EUR', ['USD', 'GBP', 'PLN']);
console.log(rates);
// {
// USD: { amount: '108.50', rate: 1.085 },
// GBP: { amount: '86.24', rate: 0.8624 },
// PLN: { amount: '431.50', rate: 4.315 }
// }
Calculate with Rate Display
async function calculateWithRateDisplay(from, to, amount) {
const result = await api.calculateConversion({
from_currency: from,
to_currency: to,
from_amount_decimal: amount
});
const rate = parseFloat(result.to_amount_decimal) / parseFloat(result.from_amount_decimal);
console.log('Conversion Preview:');
console.log(`Amount: ${amount} ${from}`);
console.log(`Result: ${result.to_amount_decimal} ${to}`);
console.log(`Rate: 1 ${from} = ${rate.toFixed(4)} ${to}`);
console.log(`Inverse: 1 ${to} = ${(1/rate).toFixed(4)} ${from}`);
return result;
}
// Usage
await calculateWithRateDisplay('EUR', 'USD', '100.00');
// Conversion Preview:
// Amount: 100.00 EUR
// Result: 108.50 USD
// Rate: 1 EUR = 1.0850 USD
// Inverse: 1 USD = 0.9217 EUR
Bidirectional Calculator
class CurrencyCalculator {
constructor(api) {
this.api = api;
}
async calculate(currency1, currency2, amount, direction = 'forward') {
if (direction === 'forward') {
return await this.api.calculateConversion({
from_currency: currency1,
to_currency: currency2,
from_amount_decimal: amount
});
} else {
return await this.api.calculateConversion({
from_currency: currency1,
to_currency: currency2,
to_amount_decimal: amount
});
}
}
async getBothDirections(currency1, currency2, amount) {
const forward = await this.calculate(currency1, currency2, amount, 'forward');
const reverse = await this.calculate(currency2, currency1, amount, 'forward');
return {
forward: {
from: `${amount} ${currency1}`,
to: `${forward.to_amount_decimal} ${currency2}`
},
reverse: {
from: `${amount} ${currency2}`,
to: `${reverse.to_amount_decimal} ${currency1}`
}
};
}
}
// Usage
const calc = new CurrencyCalculator(api);
const both = await calc.getBothDirections('EUR', 'USD', '100.00');
console.log(both);
Best Practices
1. Cache Recent Calculations
const rateCache = new Map();
const CACHE_TTL = 60000; // 1 minute
async function cachedCalculate(params) {
const key = JSON.stringify(params);
const cached = rateCache.get(key);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.data;
}
const result = await api.calculateConversion(params);
rateCache.set(key, {
data: result,
timestamp: Date.now()
});
return result;
}
2. Validate Input
function validateCalculationParams(params) {
const { from_currency, to_currency } = params;
if (!from_currency || !to_currency) {
throw new Error('Both currencies required');
}
if (from_currency === to_currency) {
throw new Error('Cannot convert same currency');
}
const hasFromAmount = params.from_amount || params.from_amount_decimal;
const hasToAmount = params.to_amount || params.to_amount_decimal;
if (!hasFromAmount && !hasToAmount) {
throw new Error('Amount required');
}
if (hasFromAmount && hasToAmount) {
throw new Error('Provide either from_amount or to_amount, not both');
}
}
3. Handle Errors Gracefully
async function safeCalculate(params) {
try {
validateCalculationParams(params);
return await api.calculateConversion(params);
} catch (error) {
console.error('Calculation failed:', error.message);
if (error.code === 'invalid_parameters') {
throw new Error('Invalid currency or amount');
}
return null;
}
}
Common Issues
Issue: Different Results Each Time
Cause: Exchange rates change constantly
Solution: Rates update in real-time. Calculate immediately before conversion.
Issue: Account Number Not Working
Cause: Account doesn't exist or no permission
Solution: Verify account number and permissions:
// Check if account exists
const accounts = await api.getAccounts();
const validAccount = accounts.find(a => a.number === accountNumber);
if (!validAccount) {
console.error('Account not found');
}
Next Steps​
- Execute Conversion - Perform actual currency exchange
- Overview - Learn about currency conversion
- Authentication - Get access tokens