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

Spatie Price Api Laravel Package

spatie/spatie-price-api

Fetch pricing information from Spatie’s spatie.be API, used internally on Spatie product promotional sites. Includes a simple method to retrieve a price for a purchasable item. Open source but not intended for third-party use.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/spatie-price-api
    

    Publish the config file (if needed for customization):

    php artisan vendor:publish --provider="Spatie\PriceApi\PriceApiServiceProvider" --tag="config"
    
  2. First Use Case: Fetch a product price via its ID:

    use Spatie\PriceApi\Facades\PriceApi;
    
    $price = PriceApi::getPrice('product-id-123');
    

    Output will be a Spatie\PriceApi\Price object with attributes like amount, currency, and validFrom.

  3. Where to Look First:

    • Config: config/price-api.php (if published) for API base URL, timeout, and retry logic.
    • Facade: Spatie\PriceApi\Facades\PriceApi for direct method calls.
    • Models: Check if Spatie provides Eloquent models (unlikely here, but verify via PriceApi::getPrice() return type).

Implementation Patterns

Core Workflows

  1. Price Retrieval:

    • Basic Fetch:
      $price = PriceApi::getPrice('product-slug');
      
    • With Fallback:
      $price = PriceApi::getPrice('product-slug', fallback: 99.99); // Fallback to $99.99 if API fails
      
    • Bulk Fetch (if supported; check docs):
      $prices = PriceApi::getPrices(['slug1', 'slug2']);
      
  2. Integration with Eloquent:

    • Attach price to a product model via an accessor:
      // In Product.php
      public function getPriceAttribute()
      {
          return PriceApi::getPrice($this->slug);
      }
      
    • Cache results to avoid repeated API calls:
      $price = Cache::remember("price_{$product->slug}", now()->addHours(1), function() use ($product) {
          return PriceApi::getPrice($product->slug);
      });
      
  3. Real-Time Updates:

    • Use Laravel Events to trigger price updates:
      // In a controller or job
      event(new \Spatie\PriceApi\Events\PriceUpdated($product->slug));
      
  4. API Response Handling:

    • Customize response parsing (if API returns non-standard data):
      PriceApi::extend(function ($response) {
          return new Price(
              amount: $response['custom_amount_field'],
              currency: $response['currency']
          );
      });
      

Gotchas and Tips

Pitfalls

  1. Rate Limiting:

    • The API may throttle requests. Implement exponential backoff:
      PriceApi::setRetryOptions([
          'max_retries' => 3,
          'delay' => 1000, // 1 second
      ]);
      
  2. Caching Quirks:

    • Avoid caching prices for too long (e.g., >1 hour) if promotions change frequently.
    • Use Cache::tags(['prices']) for bulk invalidation:
      Cache::tags(['prices'])->flush();
      
  3. Error Handling:

    • The API might return null or throw exceptions. Handle gracefully:
      try {
          $price = PriceApi::getPrice('invalid-slug');
      } catch (\Spatie\PriceApi\Exceptions\PriceNotFound $e) {
          abort(404, 'Product not found or price unavailable.');
      }
      
  4. Currency Mismatches:

    • Ensure your app’s default currency matches the API’s response. Convert if needed:
      use Money\Money;
      $money = Money::USD($price->amount);
      
  5. Testing:

    • Mock the API in tests using Laravel’s HTTP testing:
      $response = Http::fake([
          'api.spatie.be/*' => Http::response(['amount' => 19.99, 'currency' => 'EUR']),
      ]);
      

Tips

  1. Logging:

    • Log failed requests for debugging:
      PriceApi::setLogger(function ($message) {
          \Log::debug($message);
      });
      
  2. Environment-Specific Config:

    • Override the API URL per environment:
      // config/price-api.php
      'url' => env('PRICE_API_URL', 'https://api.spatie.be'),
      
  3. Performance:

    • Batch requests for multiple products if the API supports it (check docs).
    • Use Laravel’s queue to defer price fetches for non-critical paths.
  4. Extensions:

    • Extend the Price model to add custom logic:
      namespace App\Extensions;
      
      use Spatie\PriceApi\Price;
      
      class ExtendedPrice extends Price {
          public function isOnSale()
          {
              return $this->amount < 50; // Example condition
          }
      }
      
      Then override the facade binding:
      PriceApi::setPriceClass(ExtendedPrice::class);
      
  5. Documentation:

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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport