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

Leapi Laravel Package

milestone/leapi

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require milestone/leapi
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Milestone\LeAPI\LeAPIServiceProvider"
    
  2. Configuration Update .env with your ePlus API credentials:

    LEAPI_CLIENT_ID=your_client_id
    LEAPI_CLIENT_SECRET=your_client_secret
    LEAPI_BASE_URL=https://api.epus.com
    
  3. First Use Case: Authentication Fetch an access token and initialize the client:

    use Milestone\LeAPI\Facades\LeAPI;
    
    $token = LeAPI::auth()->getToken();
    $client = LeAPI::client($token);
    
  4. Quick API Call Example: Fetch a customer list:

    $customers = $client->get('/customers');
    

Implementation Patterns

Common Workflows

  1. Authentication Handling

    • Use LeAPI::auth() to manage tokens (refresh, store, retrieve).
    • Cache tokens for performance (Laravel cache driver recommended):
      $token = LeAPI::auth()->getToken(true); // Force refresh if expired
      
  2. API Resource Management

    • CRUD Operations:
      // Create
      $response = $client->post('/customers', $data);
      
      // Read
      $customer = $client->get('/customers/123');
      
      // Update
      $client->put('/customers/123', $data);
      
      // Delete
      $client->delete('/customers/123');
      
    • Pagination: Handle paginated responses with ->paginate() helper:
      $customers = $client->get('/customers')->paginate();
      
  3. Webhook Integration

    • Subscribe to ePlus webhooks via the LeAPI::webhooks() facade:
      $webhook = LeAPI::webhooks()->subscribe('customer.created', route('webhook.handle'));
      
  4. Middleware for API Calls

    • Attach middleware to the client for logging, retries, or transformations:
      $client = LeAPI::client($token)
          ->withMiddleware(new \Milestone\LeAPI\Middleware\LogRequests);
      

Integration Tips

  • Laravel Services: Bind the client to the container for dependency injection:
    $this->app->singleton(\Milestone\LeAPI\Client::class, function ($app) {
        $token = LeAPI::auth()->getToken();
        return LeAPI::client($token);
    });
    
  • Event Dispatching: Trigger Laravel events on API responses:
    $client->onResponse(function ($response) {
        event(new \App\Events\EPlusApiResponse($response));
    });
    
  • Testing: Use the LeAPI::fake() helper for mocking API calls in tests:
    LeAPI::fake()->shouldReceive('get')->once()->andReturn(['data' => []]);
    

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • Always handle TokenExpiredException when calling authenticated endpoints.
    • Use LeAPI::auth()->refreshToken() in a try-catch block:
      try {
          $client->get('/customers');
      } catch (\Milestone\LeAPI\Exceptions\TokenExpiredException $e) {
          LeAPI::auth()->refreshToken();
          retry();
      }
      
  2. Rate Limiting

    • The package does not auto-retry on rate limits. Implement middleware or handle HttpException manually:
      $client->withMiddleware(new \Milestone\LeAPI\Middleware\RetryOnRateLimit);
      
  3. Endpoint Changes

    • The ePlus API may change endpoints. Validate responses with:
      if (!$response->successful()) {
          throw new \RuntimeException('API Error: ' . $response->getBody());
      }
      
  4. Config Overrides

    • Avoid hardcoding API URLs. Use the config file (config/leapi.php) for environment-specific overrides.

Debugging

  • Enable Debug Mode: Set LEAPI_DEBUG=true in .env to log raw API responses.
  • Logging Middleware: Attach \Milestone\LeAPI\Middleware\LogRequests to inspect requests/responses:
    $client->withMiddleware(new \Milestone\LeAPI\Middleware\LogRequests);
    
  • Common Errors:
    • 401 Unauthorized: Token expired or invalid. Refresh the token.
    • 404 Not Found: Verify the endpoint URL in the ePlus API docs.
    • 500 Server Error: Check the response body for details; contact ePlus support.

Extension Points

  1. Custom Responses Extend the Milestone\LeAPI\Response class to add domain-specific logic:

    class CustomResponse extends \Milestone\LeAPI\Response {
        public function asCustomer() {
            return $this->data['customer'];
        }
    }
    

    Register the binding in a service provider:

    $this->app->bind(
        \Milestone\LeAPI\Response::class,
        \App\Extensions\CustomResponse::class
    );
    
  2. New API Methods Add custom methods to the Client class via traits or decorators:

    use Milestone\LeAPI\Traits\ApiMethods;
    
    class CustomClient extends \Milestone\LeAPI\Client {
        use ApiMethods;
    
        public function getCustomerOrders($customerId) {
            return $this->get("/customers/{$customerId}/orders");
        }
    }
    
  3. Webhook Verification Extend the Webhook class to validate payloads:

    class CustomWebhook extends \Milestone\LeAPI\Webhook {
        public function verifyPayload(array $payload) {
            // Custom validation logic
            return true;
        }
    }
    
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.
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
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver