Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Php Sdk V2 Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mangopay4/php-sdk
    

    Ensure vendor/autoload.php is included in your project.

  2. 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');
    
  3. 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());
    }
    

Implementation Patterns

Core Workflows

  1. CRUD Operations:

    • Create: Instantiate an object (e.g., UserNatural), populate fields, and call Create().
      $user = new \MangoPay\UserNatural();
      $user->FirstName = 'John';
      $user->Email = 'john@example.com';
      $createdUser = $api->Users->Create($user);
      
    • Update: Fetch, modify, and call Update().
      $user->LastName = 'Doe Updated';
      $api->Users->Update($user);
      
    • Delete: Pass the ID to Delete().
      $api->Users->Delete(USER_ID);
      
  2. 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);
    
  3. Transactions:

    • Create a Transfer:
      $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);
      
  4. Webhooks:

    • Validate signatures and process events in a Laravel controller:
      public function handleWebhook(Request $request) {
          $payload = $request->getContent();
          $signature = $request->header('X-Mangopay-Signature');
          $api->Webhooks->Validate($payload, $signature);
          // Process event logic
      }
      

Integration Tips

  1. 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);
        }
    }
    
  2. 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';
    
  3. 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(),
        ]);
    }
    
  4. Testing:

    • Use the sandbox environment for tests.
    • Mock the SDK in unit tests:
      $mockApi = Mockery::mock(\MangoPay\MangoPayApi::class);
      $mockApi->shouldReceive('Users->Get')->andReturn(new \MangoPay\UserNatural());
      

Gotchas and Tips

Pitfalls

  1. Temporary Folder:

    • Issue: Forgetting to set TemporaryFolder or using a web-accessible path causes authentication failures.
    • Fix: Use a dedicated directory outside public/ (e.g., storage_path('mangopay_temp')).
    • Debug: Delete the folder and regenerate tokens if authentication fails post-update.
  2. API Version Mismatch:

    • Issue: SDK v2.1+ requires API v2.01+. Using older API endpoints may return errors.
    • Fix: Update your API calls to match the v2.01 documentation.
  3. Pagination Handling:

    • Issue: Not checking HasMoreResults in paginated responses can skip data.
    • Fix: Loop until HasMoreResults is false:
      $page = 1;
      do {
          $users = $api->Users->GetAll(new \MangoPay\Pagination($page, 20));
          $page++;
      } while ($users->HasMoreResults);
      
  4. Webhook Validation:

    • Issue: Incorrect signature validation rejects legitimate events.
    • Fix: Use the SDK’s Validate method and compare timestamps:
      $isValid = $api->Webhooks->Validate($payload, $signature, $timestamp);
      
  5. mTLS Configuration:

    • Issue: Forgetting to set BaseUrl to api-mtls.* breaks mTLS.
    • Fix: Explicitly set the mTLS URL and ensure PHP/cURL meets requirements (≥8.1, libcurl ≥7.71.0).

Debugging Tips

  1. Enable Verbose Logging: Configure the PSR-3 logger to debug SDK behavior:

    $logger = new \Monolog\Logger('mangopay');
    $api->Config->Logger = $logger;
    
  2. 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()]);
    }
    
  3. Test with Sandbox First:

  4. Handle Idempotency:

    • Mangopay supports idempotency keys for safe retries. Use the IdempotencyKey header:
      $api->Config->AddHeader('Idempotency-Key', 'unique-key-here');
      

Extension Points

  1. 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');
    
  2. 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);
                }
            }
        }
    }
    
  3. Event Subscribers: Listen to Mangopay webhooks in Laravel’s EventServiceProvider:

    protected $listen = [
        \MangoPay\WebhookReceived::class => [
            \App\Listeners\HandleMangoPayWebhook::class,
        ],
    ];
    
  4. Localization: Override error

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator