mangopay/php-sdk-v2
PHP SDK for the MANGOPAY REST API v2.01+. Provides a client to authenticate and interact with MANGOPAY endpoints (payments, users, wallets, transfers, etc.). Install via Composer (mangopay4/php-sdk). Requires PHP 5.6+, cURL, OpenSSL.
Installation:
composer require mangopay4/php-sdk
Ensure vendor/autoload.php is included in your project.
Basic Configuration (Sandbox):
$api = new \MangoPay\MangoPayApi();
$api->Config->ClientId = env('MANGOPAY_CLIENT_ID');
$api->Config->ClientPassword = env('MANGOPAY_CLIENT_PASSWORD');
$api->Config->TemporaryFolder = storage_path('mangopay_temp');
First Use Case:
Fetch a user by ID (replace USER_ID):
try {
$user = $api->Users->Get(USER_ID);
return $user->Email; // Example: Access a property
} catch (\MangoPay\Libraries\ResponseException $e) {
log::error('MangoPay Error: ' . $e->GetMessage());
}
CRUD Operations:
UserNatural), populate fields, and call Create().
$user = new \MangoPay\UserNatural();
$user->FirstName = 'John';
$user->Email = 'john@example.com';
$createdUser = $api->Users->Create($user);
Update().
$user->LastName = 'Doe Updated';
$api->Users->Update($user);
Delete().
$api->Users->Delete(USER_ID);
Pagination:
Use MangoPay\Pagination for paginated endpoints (e.g., GetAll):
$pagination = new \MangoPay\Pagination(1, 20); // Page 1, 20 items
$users = $api->Users->GetAll($pagination);
Transactions:
$transfer = new \MangoPay\Transfer();
$transfer->SenderId = 'SENDER_USER_ID';
$transfer->ReceiverId = 'RECEIVER_USER_ID';
$transfer->Amount = 1000; // Cents
$transfer->Currency = 'EUR';
$transfer->FundedAccountId = 'FUNDING_ACCOUNT_ID';
$transfer->DebitedFundsAccountId = 'DEBIT_ACCOUNT_ID';
$transfer->CreditedFundsAccountId = 'CREDIT_ACCOUNT_ID';
$api->Transfers->Create($transfer);
Webhooks:
public function handleWebhook(Request $request) {
$payload = $request->getContent();
$signature = $request->header('X-Mangopay-Signature');
$api->Webhooks->Validate($payload, $signature);
// Process event logic
}
Service Layer:
Encapsulate SDK calls in a service class (e.g., MangoPayService) for reusability:
class MangoPayService {
protected $api;
public function __construct() {
$this->api = new \MangoPay\MangoPayApi();
$this->api->Config->ClientId = config('mangopay.client_id');
// ... other config
}
public function createUser(array $data) {
$user = new \MangoPay\UserNatural();
$user->FirstName = $data['first_name'];
// ... map other fields
return $this->api->Users->Create($user);
}
}
Environment Separation:
Use Laravel’s .env for credentials and toggle BaseUrl:
$api->Config->BaseUrl = env('MANGOPAY_ENVIRONMENT') === 'production'
? 'https://api.mangopay.com'
: 'https://api.sandbox.mangopay.com';
Logging: Integrate with Laravel’s logging:
try {
$result = $api->Users->Get(USER_ID);
} catch (\MangoPay\Libraries\ResponseException $e) {
\Log::error('MangoPay Error', [
'code' => $e->GetCode(),
'message' => $e->GetMessage(),
'errors' => $e->GetErrorDetails(),
]);
}
Testing:
$mockApi = Mockery::mock(\MangoPay\MangoPayApi::class);
$mockApi->shouldReceive('Users->Get')->andReturn(new \MangoPay\UserNatural());
Temporary Folder:
TemporaryFolder or using a web-accessible path causes authentication failures.public/ (e.g., storage_path('mangopay_temp')).API Version Mismatch:
Pagination Handling:
HasMoreResults in paginated responses can skip data.HasMoreResults is false:
$page = 1;
do {
$users = $api->Users->GetAll(new \MangoPay\Pagination($page, 20));
$page++;
} while ($users->HasMoreResults);
Webhook Validation:
Validate method and compare timestamps:
$isValid = $api->Webhooks->Validate($payload, $signature, $timestamp);
mTLS Configuration:
BaseUrl to api-mtls.* breaks mTLS.Enable Verbose Logging: Configure the PSR-3 logger to debug SDK behavior:
$logger = new \Monolog\Logger('mangopay');
$api->Config->Logger = $logger;
Check Response Headers: Inspect raw responses for HTTP errors (e.g., 401 Unauthorized):
try {
$result = $api->Users->Get(USER_ID);
} catch (\MangoPay\Libraries\ResponseException $e) {
\Log::debug('Raw Response:', ['headers' => $e->GetHeaders()]);
}
Test with Sandbox First:
Handle Idempotency:
IdempotencyKey header:
$api->Config->AddHeader('Idempotency-Key', 'unique-key-here');
Custom Headers: Add headers globally or per request:
$api->Config->AddHeader('X-Custom-Header', 'value');
// Or per request:
$api->Config->AddHeader('Idempotency-Key', 'unique-key');
Override API Calls: Extend the SDK for custom logic (e.g., retry logic):
class CustomMangoPayApi extends \MangoPay\MangoPayApi {
public function GetWithRetry($method, $endpoint, $params = []) {
$retries = 3;
while ($retries--) {
try {
return parent::$method($endpoint, $params);
} catch (\Exception $e) {
if ($retries === 0) throw $e;
sleep(1);
}
}
}
}
Event Subscribers:
Listen to Mangopay webhooks in Laravel’s EventServiceProvider:
protected $listen = [
\MangoPay\WebhookReceived::class => [
\App\Listeners\HandleMangoPayWebhook::class,
],
];
Localization: Override error
How can I help you explore Laravel packages today?