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

Xenopay Laravel Package

laraditz/xenopay

Laravel SDK for Xenopay payments. Authenticate via facade/container, create and view bills with access tokens, optional default credentials via .env, plus included migration. Returns XenopayResponse with helpers for status, message, data, and errors.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require laraditz/xenopay
    

    (Auto-discovery works for Laravel 5.5+; otherwise, manually register Laraditz\Xenopay\XenopayServiceProvider in config/app.php.)

  2. Environment Configuration Add Xenopay credentials to .env:

    XENOPAY_EMAIL=your_email@example.com
    XENOPAY_PASSWORD=your_secure_password
    
  3. Run Migrations

    php artisan migrate
    

    (Note: Verify if migrations are required for your use case—check the package’s database/migrations for dependencies.)

  4. First API Call

    // Facade (preferred for simplicity)
    $response = \Xenopay::auth()->login();
    
    // Or via container
    $response = app('xenopay')->auth()->login();
    

    (The facade abstracts the container call, reducing boilerplate.)


First Use Case: Authentication Flow

  • Login: Use auth()->login() to authenticate and retrieve a session token.
  • Verify Response: Check $response->success() or inspect $response->data for errors.
  • Store Token: Save the returned token (e.g., in the user’s session or database) for subsequent API calls:
    session(['xenopay_token' => $response->data->token]);
    

Implementation Patterns

Common Workflows

1. Authentication & Session Management

  • Login: Always pass credentials via login(['email' => ..., 'password' => ...]).
  • Logout: Use auth()->logout() to end the session.
  • Token-Based Calls: Attach the token to requests:
    $response = \Xenopay::withToken($storedToken)->api()->get('endpoint');
    

2. API Requests

  • GET/POST/PUT/DELETE: Use the api() method with HTTP verbs:
    $response = \Xenopay::api()->post('transactions', ['amount' => 100]);
    
  • Query Parameters: Pass as an associative array:
    $response = \Xenopay::api()->get('transactions', ['status' => 'pending']);
    

3. Webhook Handling

  • Verify Signatures: Xenopay may require signature validation for webhooks. Implement middleware:
    public function handle($request, Closure $next) {
        $valid = \Xenopay::validateWebhook($request->getContent(), $request->header('X-Signature'));
        if (!$valid) abort(403);
        return $next($request);
    }
    
  • Route Webhooks: Define a route to handle incoming payloads:
    Route::post('/xenopay/webhook', [XenopayWebhookController::class, 'handle']);
    

4. Error Handling

  • Global Exception Handling: Catch Laraditz\Xenopay\Exceptions\XenopayException in App\Exceptions\Handler:
    public function render($request, Throwable $exception) {
        if ($exception instanceof XenopayException) {
            return response()->json(['error' => $exception->getMessage()], 400);
        }
        return parent::render($request, $exception);
    }
    
  • Per-Request Validation: Check $response->success() before processing:
    if (!$response->success()) {
        throw new \RuntimeException($response->message);
    }
    

Integration Tips

Laravel Ecosystem Synergy

  • Queues: Offload Xenopay API calls to queues for long-running tasks:
    dispatch(new ProcessXenopayPayment($paymentId));
    
  • Events: Trigger custom events after successful API calls:
    event(new XenopayTransactionCreated($transactionData));
    
  • Notifications: Notify users of payment status changes via Laravel Notifications:
    Notification::send($user, new PaymentStatusUpdated($response->data));
    

Testing

  • Mocking the SDK: Use Laravel’s Mockery to stub responses:
    $mock = Mockery::mock('\Laraditz\Xenopay\Xenopay');
    $mock->shouldReceive('api()->post')->andReturn((object) ['success' => true]);
    $this->app->instance('xenopay', $mock);
    
  • Environment Variables: Use laravel/env package to manage test credentials:
    XENOPAY_EMAIL=test@example.com
    XENOPAY_PASSWORD=test123
    

Configuration

  • Dynamic Credentials: Override default credentials per request:
    $response = \Xenopay::withCredentials(['email' => 'alt@example.com', 'password' => 'altpass'])
                        ->auth()->login();
    
  • API Endpoint: Configure custom endpoints in config/xenopay.php (if supported):
    'api_url' => env('XENOPAY_API_URL', 'https://api.xenopay.example.com'),
    

Gotchas and Tips

Pitfalls

1. Missing Migrations

  • Issue: The package mentions running migrations, but the README lacks details on required tables.
  • Fix: Inspect vendor/laraditz/xenopay/database/migrations to understand schema dependencies. If unused, skip migrations or create your own tables.

2. Token Expiry

  • Issue: Xenopay tokens may expire silently, causing 401 Unauthorized errors.
  • Fix: Implement token refresh logic or retry failed requests:
    try {
        $response = \Xenopay::withToken($token)->api()->get('data');
    } catch (\Laraditz\Xenopay\Exceptions\UnauthorizedException $e) {
        $token = \Xenopay::auth()->refreshToken();
        return $this->withToken($token)->api()->get('data');
    }
    

3. Facade vs. Container

  • Issue: Overusing the facade can make tests harder to mock.
  • Fix: Prefer dependency injection in controllers/services:
    public function __construct(private Xenopay $xenopay) {}
    

4. Webhook Signature Validation

  • Issue: Webhook signatures may fail due to timing or payload mismatches.
  • Fix: Log raw requests and signatures for debugging:
    \Log::debug('Webhook payload:', $request->getContent());
    \Log::debug('Signature header:', $request->header('X-Signature'));
    

5. Rate Limiting

  • Issue: Xenopay may throttle requests, especially during testing.
  • Fix: Implement exponential backoff in retries:
    use Symfony\Component\HttpClient\RetryStrategy;
    
    $client = \Xenopay::getClient()->withOptions([
        'timeout' => 30,
        'retry' => RetryStrategy::create(3, 1000, true),
    ]);
    

Debugging Tips

1. Enable Debug Mode

  • Set XENOPAY_DEBUG=true in .env to log raw API responses:
    XENOPAY_DEBUG=true
    

2. Inspect HTTP Clients

  • Use Laravel’s tap to debug the underlying HTTP client:
    \Xenopay::getClient()->tap(function ($client) {
        \Log::info('Client config:', $client->getConfig());
    });
    

3. Validate Payloads

  • Xenopay may reject malformed requests. Validate data before sending:
    $validator = Validator::make($request->all(), [
        'amount' => 'required|numeric|min:0.01',
        'currency' => 'required|string|size:3',
    ]);
    

4. Check for Deprecations


Extension Points

1. Custom HTTP Client

  • Extend the default Guzzle client by binding a custom instance:
    $this->app->bind('xenopay.http_client', function () {
        return new \GuzzleHttp\Client([
            'timeout' => 60,
            'headers' => ['User-Agent' => 'MyApp/1.0'],
        ]);
    });
    

2. Middleware for API Calls

  • Add middleware to modify requests/responses globally:
    \Xenopay::getClient()->getEmitter()->
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony