PHP Library Guide
Official PHP library for integrating Paysera Wallet API into your PHP applications.
Repository
paysera/lib-wallet-php-client on GitHub
Installation​
Requirements:
- PHP 7.4 or higher
- Composer
- HTTPS support (cURL with SSL)
Via Composer:
composer require paysera/lib-wallet-php-client
Quick Start​
1. Initialize Client
<?php
require_once 'vendor/autoload.php';
use Paysera\WalletApi\ClientFactory;
$clientFactory = ClientFactory::create([
'auth' => [
'mac' => [
'mac_id' => 'wkVd93h2uS',
'mac_secret' => 'IrdTc8uQodU7PRpLzzLTW6wqZAO6tAMU',
],
],
'base_url' => 'https://wallet.paysera.com/rest/v1/',
]);
$client = $clientFactory->getWalletClient();
2. Create Payment
$transaction = $client->createTransaction([
'payments' => [[
'description' => 'Order #1234',
'price' => 2999,
'currency' => 'EUR',
]],
'redirect_uri' => 'https://yoursite.com/payment-return',
]);
echo $transaction->getKey();
3. Get Confirmation URL
$confirmUrl = sprintf(
'https://www.paysera.com/wallet/confirm/%s',
$transaction->getKey()
);
header('Location: ' . $confirmUrl);
Authentication Methods​
MAC Authentication (Recommended)
Most common method using shared secret:
$clientFactory = ClientFactory::create([
'auth' => [
'mac' => [
'mac_id' => 'YOUR_CLIENT_ID',
'mac_secret' => 'YOUR_MAC_SECRET',
],
],
]);
SSL Certificate Authentication
More secure, using client certificate:
$clientFactory = ClientFactory::create([
'auth' => [
'certificate' => [
'cert_path' => '/path/to/certificate.pem',
'key_path' => '/path/to/private.key',
],
],
]);
Production Environment
$clientFactory = ClientFactory::create([
'auth' => [
'mac' => [
'mac_id' => 'YOUR_CLIENT_ID',
'mac_secret' => 'YOUR_MAC_SECRET',
],
],
'base_url' => 'https://wallet.paysera.com/rest/v1/',
]);
Production Only
Wallet API operates in production environment only. Test carefully with small amounts.
Creating Payments​
Simple Payment
$transaction = $client->createTransaction([
'payments' => [[
'description' => 'Product purchase',
'price' => 1999,
'currency' => 'EUR',
]],
'redirect_uri' => 'https://yoursite.com/return',
]);
Payment with Items
$transaction = $client->createTransaction([
'payments' => [[
'description' => 'Shopping cart',
'items' => [
[
'title' => 'Product A',
'price' => 1499,
'quantity' => 2,
],
[
'title' => 'Product B',
'price' => 999,
'quantity' => 1,
],
],
]],
'redirect_uri' => 'https://yoursite.com/return',
]);
Payment with Callback
$transaction = $client->createTransaction([
'payments' => [[
'description' => 'Order #5678',
'price' => 4999,
'currency' => 'EUR',
]],
'redirect_uri' => 'https://yoursite.com/return',
'callback_uri' => 'https://yoursite.com/payment-callback',
]);
Managing Transactions​
Get Transaction
$transaction = $client->getTransaction('pDAlAZ3z');
echo $transaction->getStatus();
echo $transaction->getCreatedAt()->format('Y-m-d H:i:s');
Confirm Transaction
$client->confirmTransaction('pDAlAZ3z');
// Or with reduced amount
$client->confirmTransaction('pDAlAZ3z', [
'payments' => [[
'id' => 2988,
'price' => 2500,
]],
]);
Revoke Transaction
$client->revokeTransaction('pDAlAZ3z');
Working with Allowances​
Create Allowance
$transaction = $client->createTransaction([
'allowance' => [
'description' => 'Monthly Subscription',
'max_price' => 999,
'currency' => 'EUR',
'valid' => ['for' => 31536000],
'limits' => [[
'max_price' => 999,
'period' => 2592000,
]],
],
'redirect_uri' => 'https://yoursite.com/subscription-setup',
]);
Use Allowance for Payment
// Create transaction with allowance
$transaction = $client->createTransaction([
'payments' => [[
'description' => 'Monthly charge',
'price' => 999,
]],
'allowance_id' => 12345,
]);
// Reserve using allowance
$client->reserveTransaction($transaction->getKey(), 14471);
// Confirm
$client->confirmTransaction($transaction->getKey());
User Information​
Get User Data
// Requires OAuth access token
$user = $client->getUser('me', $accessToken);
echo $user->getEmail();
echo $user->getDisplayName();
Get Wallet Balance
$walletBalance = $client->getWalletBalance(14471);
foreach ($walletBalance->getBalances() as $balance) {
echo sprintf(
'%s: %s %s',
$balance->getCurrency(),
$balance->getAtDisposal() / 100,
PHP_EOL
);
}
Handling Callbacks​
Basic Callback Handler
<?php
// payment-callback.php
require_once 'vendor/autoload.php';
$input = file_get_contents('php://input');
$data = json_decode($input, true);
$transactionKey = $data['transaction_key'];
$status = $data['status'];
// Verify with API
$transaction = $client->getTransaction($transactionKey);
if ($transaction->getStatus() === 'waiting') {
$client->confirmTransaction($transactionKey);
updateOrder($transactionKey, 'paid');
sendConfirmation($transactionKey);
}
http_response_code(200);
echo 'OK';
Production Callback Handler
<?php
class PaymentCallbackHandler
{
private $client;
private $db;
public function handle()
{
try {
$input = file_get_contents('php://input');
$data = json_decode($input, true);
if ($this->isProcessed($data['transaction_key'])) {
$this->respond200();
return;
}
$transaction = $this->client->getTransaction($data['transaction_key']);
if ($transaction->getStatus() !== $data['status']) {
$this->logSuspicious($data);
$this->respond200();
return;
}
switch ($transaction->getStatus()) {
case 'waiting':
$this->handleWaiting($transaction);
break;
case 'confirmed':
$this->handleConfirmed($transaction);
break;
case 'failed':
$this->handleFailed($transaction);
break;
}
$this->markProcessed($data['transaction_key']);
$this->respond200();
} catch (\Exception $e) {
error_log('Callback error: ' . $e->getMessage());
$this->respond200();
}
}
private function handleWaiting($transaction)
{
$this->client->confirmTransaction($transaction->getKey());
}
private function handleConfirmed($transaction)
{
$this->db->updateOrder($transaction->getKey(), [
'status' => 'paid',
'paid_at' => new DateTime(),
]);
$this->queue->add('send-confirmation', [
'transaction_key' => $transaction->getKey(),
]);
}
private function respond200()
{
http_response_code(200);
echo 'OK';
}
}
Error Handling​
Try-Catch Pattern
use Paysera\WalletApi\Exception\ApiException;
try {
$transaction = $client->createTransaction([
'payments' => [[
'description' => 'Test',
'price' => 1000,
]],
]);
} catch (ApiException $e) {
$errorCode = $e->getErrorCode();
$errorDescription = $e->getMessage();
switch ($errorCode) {
case 'insufficient_funds':
echo 'Insufficient balance';
break;
case 'invalid_parameters':
echo 'Invalid data provided';
break;
default:
echo 'Payment failed: ' . $errorDescription;
}
}
Logging Errors
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('payments');
$logger->pushHandler(new StreamHandler('var/log/payments.log', Logger::WARNING));
try {
$transaction = $client->createTransaction($data);
} catch (ApiException $e) {
$logger->error('Payment creation failed', [
'error_code' => $e->getErrorCode(),
'error' => $e->getMessage(),
'data' => $data,
]);
throw $e;
}
Complete Examples​
E-Commerce Checkout
<?php
session_start();
require_once 'vendor/autoload.php';
use Paysera\WalletApi\ClientFactory;
$client = ClientFactory::create([...])->getWalletClient();
$cart = $_SESSION['cart'];
try {
$transaction = $client->createTransaction([
'payments' => [[
'description' => sprintf('Order #%d', $_SESSION['order_id']),
'items' => array_map(function($item) {
return [
'title' => $item['name'],
'price' => $item['price'],
'quantity' => $item['quantity'],
];
}, $cart['items']),
]],
'redirect_uri' => 'https://yoursite.com/payment-return',
'callback_uri' => 'https://yoursite.com/payment-callback',
]);
$_SESSION['transaction_key'] = $transaction->getKey();
$confirmUrl = sprintf(
'https://www.paysera.com/wallet/confirm/%s',
$transaction->getKey()
);
header('Location: ' . $confirmUrl);
} catch (\Exception $e) {
$_SESSION['error'] = 'Payment creation failed';
header('Location: /checkout?error=1');
}
Subscription Service
<?php
function chargeMonthlySubscription($userId)
{
global $client, $db;
$subscription = $db->getSubscription($userId);
try {
$transaction = $client->createTransaction([
'payments' => [[
'description' => 'Monthly Subscription',
'price' => $subscription['price'],
]],
'allowance_id' => $subscription['allowance_id'],
]);
$client->reserveTransaction(
$transaction->getKey(),
$subscription['wallet_id']
);
$client->confirmTransaction($transaction->getKey());
$db->updateSubscription($userId, [
'last_charge' => new DateTime(),
'next_charge' => (new DateTime())->modify('+1 month'),
]);
return true;
} catch (ApiException $e) {
if ($e->getErrorCode() === 'invalid_allowance') {
notifyRenewalNeeded($userId);
}
error_log('Subscription charge failed: ' . $e->getMessage());
return false;
}
}
Advanced Topics​
Testing
use PHPUnit\Framework\TestCase;
class PaymentTest extends TestCase
{
private $client;
protected function setUp(): void
{
$this->client = ClientFactory::create([
'base_url' => 'https://wallet.paysera.com/rest/v1/',
'auth' => [
'mac' => [
'mac_id' => getenv('TEST_CLIENT_ID'),
'mac_secret' => getenv('TEST_MAC_SECRET'),
],
],
])->getWalletClient();
}
public function testCreateTransaction()
{
$transaction = $this->client->createTransaction([
'payments' => [[
'description' => 'Test payment',
'price' => 100,
]],
]);
$this->assertNotNull($transaction->getKey());
$this->assertEquals('new', $transaction->getStatus());
}
}
Production Testing
All tests run in production environment. Use small amounts and clean up test data.
Troubleshooting
Authentication failed
- Check MAC credentials
- Verify base URL
- Check system time sync
Transaction creation fails
- Validate all required fields
- Check amount format (cents)
- Verify permissions
Callbacks not received
- Check callback URL is public
- Verify HTTPS certificate
- Check firewall rules
Resources​
- GitHub Repository - Source code
- Library Documentation - Detailed docs
- GitHub Issues - Bug reports
- Support - Technical support
What's Next?​
- JavaScript SDK - Add client-side dialogs
- Use Cases - Real-world examples
- API Reference - Complete API docs
- Getting Started - Initial setup
tip
The PHP library handles all authentication, request signing, and error handling automatically. Focus on your business logic!