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

Boxnow Bundle Laravel Package

answear/boxnow-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require answear/boxnow-bundle
    

    The bundle auto-registers in config/bundles.php.

  2. Configure API credentials in config/packages/answear_boxnow.yaml:

    answear_box_now:
        client_id: your_client_id
        client_secret: your_client_secret
        api_url: https://locationapi-stage.boxnow.gr  # Optional (defaults to stage)
    
  3. First Use Case: Fetch pickup points for a region (e.g., Cyprus) without authentication:

    use Answear\BoxNowBundle\Service\PickupPointService;
    use Answear\BoxNowBundle\Enum\RegionEnum;
    
    $pickupPoints = $this->container->get(PickupPointService::class);
    $cyprusPoints = $pickupPoints->getAllByRegion(RegionEnum::Cyprus);
    

Implementation Patterns

Core Workflows

  1. Authentication Flow:

    • Use AuthorizationService for OAuth2 token retrieval:
      $auth = $this->authorizationService->authorize();
      $token = $auth->getAccessToken(); // Cache this token (e.g., in Redis)
      
    • Caching: Store tokens in a cache layer (e.g., Symfony Cache) with a TTL of expires_in - 300 seconds.
  2. Pickup Point Integration:

    • By Region (Recommended for static data):
      $pickupPoints = $this->pickupPointService->getAllByRegion(RegionEnum::Greece);
      
    • By API Token (For dynamic filtering):
      $pickupPoints = $this->pickupPointService->getAll(token: $cachedToken);
      
    • Filtering: Use PickupPointDTO properties (e.g., isActive, region) to filter results in your application logic.
  3. Event-Driven Updates:

    • Poll pickup points periodically (e.g., via Symfony Messenger or Cron) and store results in a database table (e.g., pickup_points):
      $points = $pickupPoints->getAllByRegion(RegionEnum::Croatia);
      foreach ($points as $point) {
          PickupPoint::updateOrCreate(
              ['boxnow_id' => $point->getId()],
              $point->toArray()
          );
      }
      

Integration Tips

  • Database Schema: Normalize PickupPointDTO into a table with fields like:
    // Example migration
    Schema::create('pickup_points', function (Blueprint $table) {
        $table->id();
        $table->string('boxnow_id')->unique();
        $table->string('name');
        $table->string('address');
        $table->decimal('latitude', 10, 8);
        $table->decimal('longitude', 11, 8);
        $table->enum('region', ['Greece', 'Cyprus', 'Croatia', 'Bulgaria']);
        $table->boolean('is_active');
        $table->timestamps();
    });
    
  • API Rate Limiting: Implement a decorator around PickupPointService to throttle requests (e.g., 1 request/minute per region).
  • Fallback Logic: Cache API responses locally (e.g., with Symfony Cache) to handle API downtime:
    $cacheKey = 'boxnow_pickup_points_' . RegionEnum::Cyprus->value;
    $points = $this->cache->get($cacheKey, function () use ($pickupPoints) {
        return $pickupPoints->getAllByRegion(RegionEnum::Cyprus);
    });
    

Gotchas and Tips

Pitfalls

  1. Authentication Scope:

    • The getAllByRegion method does not require authentication (since it uses the public locationapi endpoint). Avoid passing tokens unnecessarily.
    • Error: Passing a token to getAllByRegion may trigger API errors. Validate the response structure:
      if ($pickupPoints->getAllByRegion(RegionEnum::Cyprus)->isEmpty()) {
          throw new \RuntimeException("Invalid API response for Cyprus");
      }
      
  2. Region Coverage:

    • Only 4 regions are supported (Greece, Cyprus, Croatia, Bulgaria). Attempting to use unsupported regions (e.g., RegionEnum::Spain) will return an empty array.
  3. Token Expiry:

    • Tokens expire after expires_in seconds (typically 3600). Implement a refresh mechanism:
      if ($auth->isExpired()) {
          $auth = $this->authorizationService->authorize(); // Auto-refresh
      }
      
  4. Guzzle Timeouts:

    • The bundle defaults to a 5-second timeout. For slow networks, increase it in the service configuration:
      answear_box_now:
          guzzle_timeout: 10 # seconds
      

Debugging

  • Enable Logging: Inject a custom logger to debug API responses:

    answear_box_now:
        logger: app.logger.boxnow
    
    // In a controller/service
    $this->logger->debug('BoxNow API Response', [
        'data' => $pickupPoints->getAllByRegion(RegionEnum::Cyprus)
    ]);
    
  • HTTP Client Errors: Wrap API calls in a try-catch to handle Guzzle exceptions:

    try {
        $points = $pickupPoints->getAll(token: $token);
    } catch (\GuzzleHttp\Exception\RequestException $e) {
        $response = $e->getResponse();
        $this->logger->error('BoxNow API Error', [
            'status' => $response->getStatusCode(),
            'body' => $response->getBody()->getContents()
        ]);
        throw new \RuntimeException("BoxNow API failed: " . $e->getMessage());
    }
    

Extension Points

  1. Custom DTO Mapping: Extend PickupPointDTO to add business logic:

    class ExtendedPickupPointDTO extends PickupPointDTO {
        public function isOpenNow(): bool {
            $hours = $this->getOpeningHours();
            $now = new \DateTime();
            return $hours->isOpenAt($now);
        }
    }
    
  2. Service Decorator: Decorate PickupPointService to add pre/post-processing:

    class CachedPickupPointService implements PickupPointServiceInterface {
        public function __construct(
            private PickupPointService $decorated,
            private CacheInterface $cache
        ) {}
    
        public function getAllByRegion(RegionEnum $region): array {
            $key = "boxnow_{$region->value}";
            return $this->cache->get($key, fn() => $this->decorated->getAllByRegion($region));
        }
    }
    
  3. Webhook Integration: Use the AuthorizationResponse to validate webhook signatures (if BoxNow supports them). Example:

    $auth = $this->authorizationService->authorize();
    $signature = $auth->getTokenType() . $auth->getAccessToken();
    if (!hash_equals($expectedSignature, $signature)) {
        throw new \RuntimeException("Invalid BoxNow webhook signature");
    }
    

Configuration Quirks

  • Default API URL: The bundle defaults to https://locationapi-stage.boxnow.gr. For production, override it:
    answear_box_now:
        api_url: https://locationapi.boxnow.gr  # Production endpoint
    
  • Logger Injection: If logger is not set, the bundle uses Symfony’s default logger. For silent failures, set:
    answear_box_now:
        logger: null
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware