PHP SDK
Official PHP SDK for Moneybag Payment API
PHP SDK
The Moneybag PHP SDK provides a simple and elegant way to integrate Moneybag payments into your PHP applications. Currently in beta release (v1.0.0-beta.1).
Requirements
- PHP 7.4 or higher
- Composer
- Guzzle HTTP client
Installation
Install the beta SDK using Composer:
composer require moneybag/moneybag-sdk-php:^1.0@beta
Note: This is a beta release and is not recommended for production use yet.
Configuration
Basic Setup
<?php
require_once 'vendor/autoload.php';
use Moneybag\MoneybagClient;
// Initialize with your API key
$client = new MoneybagClient('your_merchant_api_key', [
'base_url' => $ENV['MONEYBAG_API_URL'] ?? 'https://staging.api.moneybag.com.bd/api/v2'
]);
Laravel Configuration
Add your credentials to .env
:
MONEYBAG_MERCHANT_API_KEY=your_merchant_api_key_here
MONEYBAG_API_URL=https://staging.api.moneybag.com.bd/api/v2
Configure the client in your Laravel service:
<?php
// In a service class or controller
$client = new MoneybagClient(
env('MONEYBAG_MERCHANT_API_KEY'),
['base_url' => env('MONEYBAG_API_URL')]
);
Creating a Checkout
Basic Checkout
<?php
use Moneybag\MoneybagClient;
use Moneybag\Request\CheckoutRequest;
$client = new MoneybagClient('your_merchant_api_key', [
'base_url' => 'https://staging.api.moneybag.com.bd/api/v2'
]);
$checkoutData = [
'order_id' => 'order123',
'currency' => 'BDT',
'order_amount' => '1280.00',
'customer' => [
'name' => 'John Doe',
'email' => 'john@example.com'
]
];
$request = new CheckoutRequest($checkoutData);
$response = $client->createCheckout($request);
// Redirect customer to checkout
header('Location: ' . $response->getCheckoutUrl());
exit;
Advanced Checkout with Items
<?php
$checkout = $client->checkout->create([
'order_id' => 'ORDER_' . uniqid(),
'currency' => 'BDT',
'order_amount' => 3280.00,
'order_description' => 'Electronics Purchase',
'success_url' => 'https://yoursite.com/payment/success',
'cancel_url' => 'https://yoursite.com/payment/cancel',
'fail_url' => 'https://yoursite.com/payment/fail',
'ipn_url' => 'https://yoursite.com/webhook/moneybag',
'customer' => [
'name' => 'Jane Smith',
'email' => 'jane@example.com',
'phone' => '+8801700000001',
'address' => '456 Park Avenue',
'city' => 'Chittagong',
'postcode' => '4000',
'country' => 'Bangladesh'
],
'order_items' => [
[
'sku' => 'LAPTOP001',
'product_name' => 'Gaming Laptop',
'quantity' => 1,
'unit_price' => 2500.00,
'net_amount' => 2500.00
],
[
'sku' => 'MOUSE001',
'product_name' => 'Wireless Mouse',
'quantity' => 2,
'unit_price' => 390.00,
'net_amount' => 780.00
]
],
'shipping' => [
'name' => 'Jane Smith',
'address' => '456 Park Avenue',
'city' => 'Chittagong',
'postcode' => '4000',
'country' => 'Bangladesh'
]
]);
Verifying Payments
Basic Verification
<?php
// After customer is redirected back to your site
$transactionId = $_GET['transaction_id'];
$response = $client->verifyPayment($transactionId);
if ($response->isSuccessful()) {
echo 'Payment completed for order: ' . $response->getOrderId();
// Update your order status
} else {
echo 'Payment verification failed';
}
Laravel Controller Example
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Moneybag\MoneybagClient;
use Moneybag\Request\CheckoutRequest;
use App\Models\Order;
use App\Models\MoneybagTransaction;
class CheckoutController extends Controller
{
private $client;
public function __construct()
{
$this->client = new MoneybagClient(
env('MONEYBAG_MERCHANT_API_KEY'),
['base_url' => env('MONEYBAG_API_URL')]
);
}
public function createCheckout(Request $request)
{
$validated = $request->validate([
'order_id' => 'required|string',
'amount' => 'required|numeric|min:10',
'customer_name' => 'required|string',
'customer_email' => 'required|email',
]);
$checkoutData = [
'order_id' => $validated['order_id'],
'currency' => 'BDT',
'order_amount' => (string) $validated['amount'],
'customer' => [
'name' => $validated['customer_name'],
'email' => $validated['customer_email']
]
];
$request = new CheckoutRequest($checkoutData);
$response = $this->client->createCheckout($request);
// Save transaction record
MoneybagTransaction::create([
'order_id' => $validated['order_id'],
'session_id' => $response->getSessionId(),
'status' => 'pending'
]);
return redirect($response->getCheckoutUrl());
}
public function verifyPayment(Request $request)
{
$transactionId = $request->query('transaction_id');
if (!$transactionId) {
return redirect()->route('orders.index')
->with('error', 'Transaction ID required');
}
$response = $this->client->verifyPayment($transactionId);
if ($response->isSuccessful()) {
// Update order and transaction status
$order = Order::where('id', $response->getOrderId())->first();
if ($order) {
$order->update(['status' => 'paid']);
}
MoneybagTransaction::where('order_id', $response->getOrderId())
->update(['status' => 'paid']);
return view('checkout.success', compact('response'));
}
return view('checkout.failed', compact('response'));
}
}
Webhook Handling
Setting Up Webhooks
<?php
// webhook.php
use Moneybag\Webhook\WebhookHandler;
$client = new MoneybagClient('YOUR_API_KEY');
$handler = new WebhookHandler($client);
// Get raw POST data
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_MONEYBAG_SIGNATURE'] ?? '';
try {
// Verify and parse webhook
$event = $handler->handle($payload, $signature);
switch ($event->type) {
case 'payment.success':
// Handle successful payment
$transactionId = $event->data['transaction_id'];
$orderId = $event->data['order_id'];
// Update your database
break;
case 'payment.failed':
// Handle failed payment
break;
case 'payment.cancelled':
// Handle cancelled payment
break;
}
// Return 200 OK
http_response_code(200);
echo json_encode(['status' => 'received']);
} catch (\Moneybag\Exception\WebhookException $e) {
// Invalid signature or payload
http_response_code(400);
echo json_encode(['error' => $e->getMessage()]);
}
Error Handling
The SDK throws specific exceptions for different error scenarios:
<?php
use Moneybag\Exception\ApiException;
use Moneybag\Exception\ValidationException;
use Moneybag\Exception\AuthenticationException;
use Moneybag\Exception\NetworkException;
try {
$checkout = $client->checkout->create([/* ... */]);
} catch (ValidationException $e) {
// Handle validation errors
$errors = $e->getErrors();
foreach ($errors as $field => $message) {
echo "Field $field: $message\n";
}
} catch (AuthenticationException $e) {
// Handle authentication errors
echo "Authentication failed: Check your API key";
} catch (NetworkException $e) {
// Handle network errors
echo "Network error: " . $e->getMessage();
} catch (ApiException $e) {
// Handle other API errors
echo "API Error: " . $e->getMessage();
echo "Error Code: " . $e->getCode();
}
Testing
Running Tests
composer test
Writing Tests
<?php
use PHPUnit\Framework\TestCase;
use Moneybag\MoneybagClient;
class PaymentTest extends TestCase
{
private $client;
protected function setUp(): void
{
$this->client = new MoneybagClient('test_api_key', [
'environment' => 'sandbox'
]);
}
public function testCreateCheckout()
{
$checkout = $this->client->checkout->create([
'order_id' => 'TEST_' . uniqid(),
'currency' => 'BDT',
'order_amount' => 100.00,
// ... other required fields
]);
$this->assertNotNull($checkout->checkout_url);
$this->assertNotNull($checkout->session_id);
}
}
Configuration Options
<?php
$client = new MoneybagClient('YOUR_API_KEY', [
'environment' => 'production', // or 'sandbox'
'timeout' => 30, // Request timeout in seconds
'retry_count' => 3, // Number of retries for failed requests
'retry_delay' => 1000, // Delay between retries in milliseconds
'debug' => false, // Enable debug logging
'logger' => $psrLogger, // PSR-3 compatible logger
]);
API Reference
Methods
Checkout Methods
$client->checkout->create($params)
- Create a new checkout session$client->checkout->get($sessionId)
- Get checkout session details
Payment Methods
$client->payments->verify($transactionId)
- Verify a payment$client->payments->list($filters)
- List payments with filters$client->payments->get($transactionId)
- Get payment details
Webhook Methods
$client->webhooks->create($params)
- Register a webhook endpoint$client->webhooks->list()
- List webhook endpoints$client->webhooks->delete($webhookId)
- Delete a webhook endpoint
Laravel Example Application
A complete Laravel example application is available that demonstrates:
- Order management with customer details
- Order items tracking
- Payment processing workflow
- Transaction status monitoring
- BDT currency support
Repository: Laravel Example App
The example includes models for Order
, OrderItem
, and MoneybagTransaction
to handle the complete e-commerce payment flow.
Support
- GitHub: moneybag/moneybag-sdk-php
- Laravel Example: laravel-example-app-php-sdk
- Issues: Report Issues
- Email: developer@fitl.com.bd
- Documentation: https://docs.moneybag.com.bd
License
The Moneybag PHP SDK is open-source software licensed under the MIT license.