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

Proxify Laravel Laravel Package

priyankpatel/proxify-laravel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require priyankpatel/proxify-laravel
    

    Publish the config file:

    php artisan vendor:publish --provider="Proxify\ProxifyServiceProvider"
    
  2. Configuration Edit config/proxify.php to define your OAuth2 API endpoints, client credentials, and proxy routes:

    'apis' => [
        'stripe' => [
            'client_id' => env('STRIPE_CLIENT_ID'),
            'client_secret' => env('STRIPE_CLIENT_SECRET'),
            'token_url' => 'https://api.stripe.com/v1/oauth/token',
            'api_url' => 'https://api.stripe.com/v1/',
        ],
    ],
    
  3. First Use Case Create a proxy route in routes/api.php:

    Route::get('/stripe/{endpoint}', 'ProxifyController@proxy')->name('stripe.proxy');
    

    Then call /api/stripe/customers to proxy requests to Stripe's API.


Implementation Patterns

Workflow: Proxying API Requests

  1. Route Definition Use the ProxifyController to handle proxy requests:

    Route::match(['get', 'post', 'put', 'delete'], '/{api}/{endpoint}', 'ProxifyController@proxy');
    
  2. Dynamic API Routing Leverage the api and endpoint parameters to dynamically route requests:

    // Proxifies GET /api/stripe/customers to Stripe's API
    Route::get('/{api}/{endpoint}', 'ProxifyController@proxy');
    
  3. Authentication Handling Automatically attach OAuth2 tokens to requests via middleware:

    // In ProxifyServiceProvider.php
    $router->aliasMiddleware('proxify.auth', \Proxify\Middleware\AuthenticateProxy::class);
    
  4. Custom Headers and Payloads Extend the ProxifyController to modify requests before forwarding:

    public function proxy(Request $request, $api, $endpoint)
    {
        $request->merge(['custom_param' => 'value']);
        return parent::proxy($request, $api, $endpoint);
    }
    
  5. Response Transformation Override the transformResponse method in a custom controller to modify API responses:

    protected function transformResponse($response, $api, $endpoint)
    {
        return $response->json()->all();
    }
    

Gotchas and Tips

Pitfalls

  1. Token Expiry Handling

    • The package does not auto-refresh expired tokens. Implement a middleware to handle token refreshes:
      public function handle($request, Closure $next)
      {
          if ($request->hasHeader('authorization') && $this->isTokenExpired()) {
              $newToken = $this->refreshToken();
              $request->headers->set('authorization', 'Bearer ' . $newToken);
          }
          return $next($request);
      }
      
  2. CORS Issues

    • Ensure your proxy routes include CORS headers if the API is accessed from a frontend:
      Route::middleware('cors')->group(function () {
          Route::get('/{api}/{endpoint}', 'ProxifyController@proxy');
      });
      
  3. Rate Limiting

    • The package does not enforce rate limits. Use Laravel's throttle middleware:
      Route::middleware('throttle:60,1')->group(function () {
          Route::get('/{api}/{endpoint}', 'ProxifyController@proxy');
      });
      

Tips

  1. Logging Proxy Requests Add logging to debug proxy requests/responses:

    protected function proxy(Request $request, $api, $endpoint)
    {
        \Log::info('Proxy Request', [
            'api' => $api,
            'endpoint' => $endpoint,
            'method' => $request->method(),
            'data' => $request->all(),
        ]);
        return parent::proxy($request, $api, $endpoint);
    }
    
  2. Environment-Specific Config Use Laravel's .env to manage API credentials per environment:

    STRIPE_CLIENT_ID=test_123
    STRIPE_CLIENT_SECRET=secret_456
    
  3. Testing Proxies Mock the HTTP client in tests to avoid real API calls:

    $this->app->instance(\Illuminate\Http\Client\PendingRequest::class, function () {
        return \Mockery::mock(\Illuminate\Http\Client\PendingRequest::class)
            ->shouldReceive('asForm')
            ->andReturnSelf()
            ->shouldReceive('post')
            ->andReturn(new \Illuminate\Http\Client\Response($this->mockResponse(), 200));
    });
    
  4. Extending Proxy Logic Create a custom proxy handler by extending ProxifyController:

    class CustomProxifyController extends \Proxify\ProxifyController
    {
        protected function getApiConfig($api)
        {
            // Custom logic to fetch API config
            return config("proxify.custom_apis.{$api}");
        }
    }
    
  5. Error Handling Customize error responses by overriding the handleError method:

    protected function handleError($response, $api, $endpoint)
    {
        if ($response->status() === 401) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        return parent::handleError($response, $api, $endpoint);
    }
    
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