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 Api Client Laravel Package

mosparo/php-api-client

PHP API client for mosparo spam protection. Connect to a mosparo instance, send verification requests for form submissions, handle validation results, and integrate bot protection into your PHP/Laravel apps with a simple, lightweight client.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require mosparo/php-api-client
    

    Ensure your project meets PHP 8.0+ requirements.

  2. First API Call Initialize the client with your API key (replace YOUR_API_KEY):

    use Mosparo\ApiClient\Client;
    
    $client = new Client('YOUR_API_KEY');
    
  3. Basic Request Fetch a simple endpoint (e.g., /v1/health):

    $response = $client->get('/v1/health');
    $data = json_decode($response->getBody(), true);
    
  4. Key Files

    • src/Client.php: Core client logic.
    • src/Exception/ApiException.php: Error handling.
    • src/Request.php: Request builder.

Implementation Patterns

Workflows

  1. Authenticated Requests Use the client instance for all requests (automatically includes auth headers):

    $response = $client->post('/v1/campaigns', ['name' => 'Test']);
    
  2. Pagination Handle paginated responses with getNextPage():

    $response = $client->get('/v1/campaigns');
    $campaigns = json_decode($response->getBody(), true);
    
    while ($nextPage = $client->getNextPage($response)) {
        $campaigns = array_merge($campaigns, json_decode($nextPage->getBody(), true));
    }
    
  3. Webhook Verification Verify incoming webhooks (e.g., from Mosparo):

    $verifier = $client->getWebhookVerifier($_SERVER['HTTP_SIGNATURE']);
    if ($verifier->isValid()) {
        // Process webhook
    }
    
  4. Rate Limiting Check rate limits before making requests:

    $limits = $client->getRateLimit();
    if ($limits['remaining'] <= 0) {
        sleep($limits['reset'] - time());
    }
    

Integration Tips

  • Laravel Service Provider Bind the client to the container for dependency injection:

    $this->app->singleton(Client::class, function ($app) {
        return new Client(config('services.mosparo.key'));
    });
    
  • API Resource Classes Extend Mosparo\ApiClient\Resource to model API responses:

    class Campaign extends Resource {
        public function getName() { return $this->name; }
    }
    
  • Async Requests Use Guzzle’s async features for batch operations:

    $promises = [];
    foreach ($campaigns as $campaign) {
        $promises[] = $client->postAsync('/v1/campaigns/send', ['id' => $campaign['id']]);
    }
    GuzzleHttp\Promise\Utils::settle($promises)->wait();
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Never hardcode API keys in version control. Use Laravel’s .env or a secrets manager.
    • Fix: Validate keys via config('services.mosparo.key') in Laravel.
  2. Rate Limit Headers

    • The library doesn’t auto-retry on rate limits. Always check X-RateLimit-Remaining.
    • Fix: Implement exponential backoff in your service layer.
  3. Webhook Signatures

    • Mosparo’s webhook signatures are case-sensitive. Ensure HTTP_SIGNATURE matches the header name.
    • Fix: Normalize headers:
      $signature = $_SERVER['HTTP_X_MOSPARO_SIGNATURE'] ?? '';
      
  4. Deprecated Endpoints

    • Mosparo’s API evolves. Check the official docs for breaking changes.
    • Fix: Use Client::setBaseUrl() to override endpoints during testing.

Debugging

  • Enable Guzzle Debugging Attach a middleware to log requests:

    $client->getClient()->getEmitter()->attach(
        new \GuzzleHttp\Middleware::tap(function ($request) {
            error_log($request->getUri());
        })
    );
    
  • Handle Exceptions Catch Mosparo\ApiClient\Exception\ApiException for HTTP errors:

    try {
        $response = $client->get('/v1/invalid');
    } catch (ApiException $e) {
        logger()->error($e->getMessage(), ['status' => $e->getCode()]);
    }
    

Extension Points

  1. Custom Headers Add headers globally:

    $client->getClient()->getConfig()->set('headers', [
        'X-Custom-Header' => 'value',
    ]);
    
  2. Middleware Inject middleware (e.g., for logging or auth):

    $client->getClient()->getMiddleware()->unshift(
        new \GuzzleHttp\Middleware()
    );
    
  3. Response Transformers Override response handling:

    $client->setResponseTransformer(function ($response) {
        return json_decode($response->getBody(), true)['data'];
    });
    
  4. Testing Mock the client in PHPUnit:

    $mock = $this->getMockBuilder(Client::class)
        ->disableOriginalConstructor()
        ->onlyMethods(['get'])
        ->getMock();
    $mock->method('get')->willReturn(new \GuzzleHttp\Psr7\Response(200, [], '{}'));
    
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle