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

Allegro Bundle Laravel Package

cdma-numiscorner/allegro-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require cdma-numiscorner/allegro-bundle
    

    Register the bundle in config/app.php under providers:

    Cdma\Numiscorner\AllegroBundle\AllegroServiceProvider::class,
    
  2. Configuration Publish the default config:

    php artisan vendor:publish --provider="Cdma\Numiscorner\AllegroBundle\AllegroServiceProvider" --tag="config"
    

    Update .env with your Allegro API credentials:

    ALLEGRO_CLIENT_ID=your_client_id
    ALLEGRO_CLIENT_SECRET=your_client_secret
    ALLEGRO_REDIRECT_URI=http://your-app.com/callback
    
  3. First Use Case: OAuth Authentication Use the AllegroAuth facade to initiate login:

    use Cdma\Numiscorner\AllegroBundle\Facades\AllegroAuth;
    
    $loginUrl = AllegroAuth::getLoginUrl();
    return redirect()->to($loginUrl);
    

    Handle the callback in a route:

    Route::get('/callback', function () {
        $token = AllegroAuth::handleCallback(request());
        // Store $token->access_token in session/database
    });
    

Implementation Patterns

OAuth Workflow

  1. Initiate Login Redirect users to Allegro’s OAuth endpoint:

    $loginUrl = AllegroAuth::getLoginUrl(['scope' => 'read,write']);
    
  2. Handle Callback Exchange the authorization code for an access token:

    $token = AllegroAuth::handleCallback(request());
    session(['allegro_token' => $token->access_token]);
    
  3. API Requests Use the AllegroClient facade to interact with Allegro’s API:

    use Cdma\Numiscorner\AllegroBundle\Facades\AllegroClient;
    
    $response = AllegroClient::get('/api/v1/orders', [
        'headers' => ['Authorization' => 'Bearer ' . session('allegro_token')]
    ]);
    

Data Synchronization

  • Webhooks Configure Allegro webhooks via the bundle’s AllegroWebhook class:

    AllegroWebhook::subscribe('order.created', 'https://your-app.com/webhook/allegro');
    

    Handle incoming webhooks in a Laravel route:

    Route::post('/webhook/allegro', function (Request $request) {
        $payload = $request->json()->all();
        // Validate and process $payload
    });
    
  • Scheduled Syncs Use Laravel’s schedule to periodically fetch updates:

    $schedule->command('allegro:sync-orders')->daily();
    

    Register the command in app/Console/Commands/AllegroSyncCommand.php:

    public function handle() {
        $client = AllegroClient::get('/api/v1/orders');
        // Process $client->json()
    }
    

Integration with Eloquent

  • User Model Attach Allegro user data to a Laravel User model:
    class User extends Model {
        public function allegroAccount() {
            return $this->hasOne(AllegroAccount::class);
        }
    }
    
    Sync Allegro user data post-login:
    $user->allegroAccount()->updateOrCreate(
        ['allegro_id' => $token->userId],
        ['access_token' => $token->access_token]
    );
    

Gotchas and Tips

Pitfalls

  1. Token Expiry

    • Allegro tokens expire (typically 1 hour). Implement token refresh logic:
      try {
          $token = AllegroAuth::refreshToken(session('refresh_token'));
      } catch (\Exception $e) {
          // Redirect to re-authenticate
      }
      
    • Store refresh_token securely in the database, not session.
  2. Scope Restrictions

    • Ensure requested scopes (e.g., read,write) match Allegro’s API requirements. Missing scopes cause 403 Forbidden.
  3. Webhook Verification

    • Always verify Allegro webhook signatures:
      $isValid = AllegroWebhook::verifySignature(
          $request->header('X-Allegro-Signature'),
          $request->getContent()
      );
      

Debugging

  • Enable Logging Configure the bundle’s logger in config/allegro.php:

    'log' => [
        'enabled' => true,
        'channel' => 'single',
    ],
    

    Check logs for OAuth errors or API responses:

    tail -f storage/logs/laravel.log | grep allegro
    
  • API Rate Limits Allegro enforces rate limits (e.g., 60 requests/minute). Implement exponential backoff:

    try {
        $response = AllegroClient::get('/api/v1/orders');
    } catch (\Cdma\Numiscorner\AllegroBundle\Exceptions\RateLimitExceeded $e) {
        sleep($e->retryAfter);
        retry();
    }
    

Extension Points

  1. Custom API Clients Extend the AllegroClient to add middleware:

    $client = AllegroClient::extend(function ($client) {
        $client->getMiddleware()->push(function ($request) {
            $request->headers->set('X-Custom-Header', 'value');
        });
    });
    
  2. Event Listeners Dispatch custom events for Allegro actions:

    event(new AllegroOrderCreated($orderData));
    

    Listen in EventServiceProvider:

    protected $listen = [
        AllegroOrderCreated::class => [
            HandleAllegroOrder::class,
        ],
    ];
    
  3. Testing Mock the Allegro API in tests using Http::fake():

    Http::fake([
        'api.allegro.com/*' => Http::response(['data' => 'test'], 200),
    ]);
    $this->assertEquals('test', AllegroClient::get('/api/v1/orders')->json()['data']);
    
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.
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
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours