API Request Examples
Implementation examples for Wallet API using MAC Authentication.
MAC Authentication Setup​
All Wallet API requests use MAC (Message Authentication Code) authentication.
JavaScript Helper
const crypto = require('crypto');
const CLIENT_ID = 'wkVd93h2uS';
const MAC_KEY = 'IrdTc8uQodU7PRpLzzLTW6wqZAO6tAMU';
function generateMacAuth(method, uri, host, body = '') {
const timestamp = Math.floor(Date.now() / 1000);
const nonce = crypto.randomBytes(16).toString('hex');
let ext = '';
if (body) {
const bodyHash = crypto.createHash('sha256').update(body).digest('base64');
ext = `body_hash=${encodeURIComponent(bodyHash)}`;
}
const normalizedString = [timestamp, nonce, method, uri, host, '443', ext].join('\n') + '\n';
const mac = crypto.createHmac('sha256', MAC_KEY).update(normalizedString).digest('base64');
let authHeader = `MAC id="${CLIENT_ID}", ts="${timestamp}", nonce="${nonce}", mac="${mac}"`;
if (ext) {
authHeader += `, ext="${ext}"`;
}
return authHeader;
}
Get User Information​
Python Example
import requests
import hmac
import hashlib
import time
import secrets
CLIENT_ID = 'wkVd93h2uS'
MAC_KEY = 'IrdTc8uQodU7PRpLzzLTW6wqZAO6tAMU'
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 get_user_info():
uri = '/rest/v1/user/me'
headers = {
'Authorization': generate_mac_auth('GET', uri, 'wallet.paysera.com')
}
response = requests.get(
f'https://wallet.paysera.com{uri}',
headers=headers
)
if response.status_code == 200:
data = response.json()
print(f"User ID: {data['id']}")
print(f"Email: {data['email']}")
print(f"Name: {data['display_name']}")
return data
else:
print(f"Error: {response.status_code}")
return None
# Usage
user = get_user_info()
Get Account Information​
cURL Example
curl -X GET 'https://wallet.paysera.com/rest/v1/account/EVP1234567890' \
-H 'Authorization: MAC id="wkVd93h2uS", ts="1343811600", nonce="nQnNaSNyubfPErjRO55yaaEYo9YZfKHN", mac="Bp22nWw9qFsz7ux5xOYkCIYJjXAz8mhxTSfJsoOKV3A="'
Response​
{
"number": "EVP1234567890",
"owner": 123456,
"owner_display_name": "John Doe",
"activated_at": 1391686980,
"ibans": [
{
"iban": "LT123456789012345678",
"display": "LT12 3456 7890 1234 5678"
}
],
"balances": [
{
"at_disposal": "15000",
"at_disposal_decimal": "150.00",
"currency": "EUR"
}
]
}
Create Payment​
JavaScript Example
const crypto = require('crypto');
const axios = require('axios');
const CLIENT_ID = 'wkVd93h2uS';
const MAC_KEY = 'IrdTc8uQodU7PRpLzzLTW6wqZAO6tAMU';
function generateMacAuth(method, uri, host, body = '') {
const timestamp = Math.floor(Date.now() / 1000);
const nonce = crypto.randomBytes(16).toString('hex');
let ext = '';
if (body) {
const bodyHash = crypto.createHash('sha256').update(body).digest('base64');
ext = `body_hash=${encodeURIComponent(bodyHash)}`;
}
const normalizedString = [timestamp, nonce, method, uri, host, '443', ext].join('\n') + '\n';
const mac = crypto.createHmac('sha256', MAC_KEY).update(normalizedString).digest('base64');
let authHeader = `MAC id="${CLIENT_ID}", ts="${timestamp}", nonce="${nonce}", mac="${mac}"`;
if (ext) {
authHeader += `, ext="${ext}"`;
}
return authHeader;
}
async function createPayment(amount, beneficiary, description) {
const uri = '/rest/v1/payment';
const body = JSON.stringify({
amount_decimal: amount,
currency: 'EUR',
beneficiary: beneficiary,
description: description
});
try {
const response = await axios.post(
`https://wallet.paysera.com${uri}`,
body,
{
headers: {
'Content-Type': 'application/json',
'Authorization': generateMacAuth('POST', uri, 'wallet.paysera.com', body)
}
}
);
const payment = response.data;
console.log(`Payment created: ${payment.id}`);
console.log(`Status: ${payment.status}`);
console.log(`Amount: ${payment.amount_decimal} ${payment.currency}`);
return payment;
} catch (error) {
console.error('Payment failed:', error.response?.data);
throw error;
}
}
// Usage
createPayment('100.00', 'EVP1234567890', 'Invoice payment');
Get Payment Details​
PHP Example
<?php
define('CLIENT_ID', 'wkVd93h2uS');
define('MAC_KEY', 'IrdTc8uQodU7PRpLzzLTW6wqZAO6tAMU');
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 getPayment($paymentId) {
$uri = "/rest/v1/payment/$paymentId";
$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) {
$data = json_decode($response, true);
echo "Payment ID: {$data['id']}\n";
echo "Status: {$data['status']}\n";
echo "Amount: {$data['amount_decimal']} {$data['currency']}\n";
return $data;
} else {
echo "Error fetching payment\n";
return null;
}
}
// Usage
$payment = getPayment('10145');
?>
Confirm Payment​
Python Example
import requests
import hmac
import hashlib
import time
import secrets
import json
from urllib.parse import quote
CLIENT_ID = 'wkVd93h2uS'
MAC_KEY = 'IrdTc8uQodU7PRpLzzLTW6wqZAO6tAMU'
def generate_mac_auth(method, uri, host, body=''):
timestamp = str(int(time.time()))
nonce = secrets.token_hex(16)
ext = ''
if body:
body_hash = hashlib.sha256(body.encode()).digest()
body_hash_b64 = hashlib.b64encode(body_hash).decode()
ext = f'body_hash={quote(body_hash_b64)}'
normalized = f"{timestamp}\n{nonce}\n{method}\n{uri}\n{host}\n443\n{ext}\n"
mac = hmac.new(MAC_KEY.encode(), normalized.encode(), hashlib.sha256).digest()
mac_base64 = hashlib.b64encode(mac).decode()
auth_header = f'MAC id="{CLIENT_ID}", ts="{timestamp}", nonce="{nonce}", mac="{mac_base64}"'
if ext:
auth_header += f', ext="{ext}"'
return auth_header
def confirm_payment(payment_id):
uri = f'/rest/v1/payment/{payment_id}/confirm'
body = json.dumps({})
headers = {
'Content-Type': 'application/json',
'Authorization': generate_mac_auth('PUT', uri, 'wallet.paysera.com', body)
}
response = requests.put(
f'https://wallet.paysera.com{uri}',
data=body,
headers=headers
)
if response.status_code == 200:
data = response.json()
print(f"Payment {payment_id} confirmed")
print(f"Status: {data['status']}")
return data
else:
print(f"Error: {response.status_code}")
return None
# Usage
confirm_payment('10145')
Webhook Handler​
Express.js Example
const express = require('express');
const crypto = require('crypto');
const app = express();
app.use(express.json());
const WEBHOOK_SECRET = 'your_webhook_secret';
function verifySignature(payload, signature) {
const expectedSig = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(JSON.stringify(payload))
.digest('hex');
return signature === expectedSig;
}
app.post('/webhooks/wallet', (req, res) => {
const signature = req.headers['x-paysera-signature'];
if (!verifySignature(req.body, signature)) {
return res.status(401).send('Invalid signature');
}
const event = req.body;
switch (event.type) {
case 'payment.confirmed':
console.log(`Payment ${event.data.id} confirmed`);
handlePaymentConfirmed(event.data);
break;
case 'payment.reserved':
console.log(`Payment ${event.data.id} reserved`);
handlePaymentReserved(event.data);
break;
case 'payment.failed':
console.log(`Payment ${event.data.id} failed`);
handlePaymentFailed(event.data);
break;
}
res.status(200).send('OK');
});
app.listen(3000, () => {
console.log('Webhook server running on port 3000');
});
Error Handling​
JavaScript Example
async function safeApiCall(operation) {
try {
return await operation();
} catch (error) {
if (error.response) {
const { status, data } = error.response;
switch (status) {
case 401:
console.error('Authentication failed - check MAC credentials');
throw new Error('Invalid MAC authentication');
case 403:
console.error('Forbidden - check permissions');
throw new Error('Insufficient permissions');
case 429:
console.error('Rate limit exceeded, waiting...');
await new Promise(resolve => setTimeout(resolve, 60000));
return await operation();
case 400:
console.error('Invalid request:', data);
throw new Error(`API Error: ${data.error || data.message}`);
default:
console.error('API error:', status, data);
throw error;
}
}
throw error;
}
}
Rate Limits​
- 100 requests per minute
- Monitor rate limits in response headers
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1697197260
Next Steps​
- Review Authentication for MAC authentication details
- Check API Reference for complete endpoint documentation
- Read Security best practices