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. Install the package:
    composer require mosparo/php-api-client
    
  2. Initialize the client in your Laravel controller/service:
    use Mosparo\ApiClient\Client;
    
    $client = new Client(
        config('mosparo.url'),
        config('mosparo.public_key'),
        config('mosparo.private_key'),
        ['timeout' => 10] // Optional Guzzle options
    );
    
  3. First use case: Verify form submissions in your form submission handler:
    $result = $client->verifySubmission(
        $formData, // Clean array of form fields (remove mosparo-processed fields)
        $_POST['_mosparo_submitToken'],
        $_POST['_mosparo_validationToken']
    );
    
    if ($result->isSubmittable()) {
        // Process valid submission
    }
    

Where to Look First

  • Client class: Core functionality (verification, metadata, stats, rule packages)
  • VerificationResult: Understand field validation states (isSubmittable(), getVerifiedField())
  • Configuration: Store API keys in Laravel's .env:
    MOSPARO_URL=https://your-mosparo-instance.com
    MOSPARO_PUBLIC_KEY=your_public_key
    MOSPARO_PRIVATE_KEY=your_private_key
    

Implementation Patterns

Core Workflow: Form Submission Handling

  1. Frontend Integration:
    <div id="mosparo-box"></div>
    <script src="https://[MOSPARO_URL]/build/mosparo-frontend.js" defer></script>
    <script>
        window.onload = () => {
            new mosparo('mosparo-box', '{{ config("mosparo.url") }}', '{{ $project->uuid }}', '{{ $project->public_key }}');
        };
    </script>
    
  2. Backend Validation (Laravel Controller):
    public function handleFormSubmission(Request $request)
    {
        $client = app(Client::class);
        $formData = $this->sanitizeFormData($request->all());
    
        $result = $client->verifySubmission(
            $formData,
            $request->input('_mosparo_submitToken'),
            $request->input('_mosparo_validationToken')
        );
    
        if ($result->isSubmittable()) {
            $this->processValidSubmission($formData);
            return redirect()->route('thank-you');
        }
    
        return back()->withErrors($this->formatVerificationErrors($result));
    }
    

Advanced Patterns

Metadata Storage

Link custom data to submissions:

$client->storeMetadata(
    $_POST['_mosparo_submitToken'],
    $_POST['_mosparo_validationToken'],
    [
        'user_id' => auth()->id(),
        'campaign_id' => $request->campaign_id,
        'source' => 'newsletter'
    ]
);

Rule Package Management

Update rules programmatically:

// 1. Stream hash index for incremental updates
$file = new \SplTempFileObject();
$client->streamRulePackageHashIndex(1, $file, function($progress) {
    Log::info("Progress: {$progress}MB");
});

// 2. Batch update rules
$client->batchUpdateRulePackage(1, [
    [
        'type' => 'update_rule_item',
        'rule_id' => 5,
        'rule_item_id' => 10,
        'value' => 'new_value',
        'rating' => 0.8
    ]
]);

Statistics Integration

Track submissions in Laravel:

// Daily cron job
$stats = $client->getStatisticByDate(
    range: 86400, // Last 24 hours
    startDate: now()->subDays(7)
);

$validSubmissions = $stats->getNumberOfValidSubmissions();
$spamSubmissions = $stats->getNumberOfSpamSubmissions();

Service Provider Integration

Register the client as a singleton:

// app/Providers/AppServiceProvider.php
public function register()
{
    $this->app->singleton(Client::class, function ($app) {
        return new Client(
            config('mosparo.url'),
            config('mosparo.public_key'),
            config('mosparo.private_key'),
            ['timeout' => 10]
        );
    });
}

Gotchas and Tips

Common Pitfalls

  1. Field Sanitization:

    • Issue: Mosparo processes hidden/checkbox/radio fields. Never include these in $formData.
    • Fix: Filter out mosparo-prefixed fields:
      $formData = array_filter($request->all(), fn($key) => !str_starts_with($key, '_mosparo_'), ARRAY_FILTER_USE_KEY);
      
  2. Token Validation:

    • Issue: Missing tokens throw Exception. Validate presence first:
      if (empty($_POST['_mosparo_submitToken']) || empty($_POST['_mosparo_validationToken'])) {
          throw new \RuntimeException('Mosparo tokens missing');
      }
      
  3. Pagination Handling:

    • Issue: Rule package methods paginate results. Always check getTotalPages():
      $page = 1;
      do {
          $result = $client->getRulePackageRules($packageId, $page);
          $this->processRules($result->getRules());
          $page++;
      } while ($page <= $result->getTotalPages());
      
  4. Hash Mismatches:

    • Issue: storeRulePackage fails if hashes don't match.
    • Fix: Verify hashes locally before sending:
      $hash = hash_file('sha256', $filePath);
      $client->storeRulePackage($packageId, file_get_contents($filePath), $hash);
      

Debugging Tips

  • Enable Guzzle Debugging:
    $client = new Client($url, $publicKey, $privateKey, [
        'debug' => fopen('mosparo_debug.log', 'w'),
        'headers' => ['Accept' => 'application/json']
    ]);
    
  • Inspect VerificationResult:
    if ($result->hasIssues()) {
        foreach ($result->getIssues() as $issue) {
            Log::error("Mosparo issue: {$issue['message']}");
        }
    }
    

Performance Optimization

  1. Streaming Large Responses:
    • Use streamRulePackageHashIndex for large rule packages to avoid memory issues.
  2. Batch Updates:
    • Prefer batchUpdateRulePackage over full imports for incremental changes.
  3. Caching Statistics:
    • Cache getStatisticByDate results in Laravel's cache:
      $stats = Cache::remember("mosparo_stats_{$range}", now()->addHours(1), function() use ($client, $range) {
          return $client->getStatisticByDate($range);
      });
      

Extension Points

  1. Custom Verification Logic:
    • Extend VerificationResult to add domain-specific checks:
      class CustomVerificationResult extends \Mosparo\ApiClient\VerificationResult {
          public function isBusinessValid(): bool {
              return $this->getVerifiedField('company') === self::FIELD_VALID
                  && $this->getVerifiedField('email') === self::FIELD_VALID;
          }
      }
      
  2. Middleware for API Calls:
    • Add auth/retries to the Guzzle client:
      $client = new Client($url, $publicKey, $privateKey, [
          'handler' => HandlerStack::create([
              new RetryMiddleware(),
              new AuthMiddleware($privateKey)
          ])
      ]);
      
  3. Event Dispatching:
    • Trigger Laravel events on submission results:
      if ($result->isSubmittable()) {
          event(new SubmissionVerified($formData, $result));
      }
      
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.
symfony/ai-symfony-mate-extension
aashan/pimcore-mcp-bundle
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
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