PHPackages                             antogkou/laravel-oauth2-client - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. antogkou/laravel-oauth2-client

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

antogkou/laravel-oauth2-client
==============================

A Laravel package for OAuth2 integration

v1.0.0(1y ago)146.1k↓74.1%[1 issues](https://github.com/antogkou/laravel-oauth2-client/issues)[1 PRs](https://github.com/antogkou/laravel-oauth2-client/pulls)MITPHPPHP ^8.2|^8.3|^8.4CI failing

Since Feb 3Pushed 8mo ago1 watchersCompare

[ Source](https://github.com/antogkou/laravel-oauth2-client)[ Packagist](https://packagist.org/packages/antogkou/laravel-oauth2-client)[ RSS](/packages/antogkou-laravel-oauth2-client/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (10)Dependencies (11)Versions (18)Used By (0)

Laravel OAuth2 Client
=====================

[](#laravel-oauth2-client)

[![Tests](https://github.com/antogkou/laravel-oauth2-client/actions/workflows/tests.yml/badge.svg)](https://github.com/antogkou/laravel-oauth2-client/actions)[![License](https://camo.githubusercontent.com/75ba4e30cc581ef94c22bb06b96655f4ea1d553098ddcdd15696be22064dd9ac/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f616e746f676b6f752f6c61726176656c2d6f61757468322d636c69656e74)](LICENSE)[![Packagist](https://camo.githubusercontent.com/d3d5f126619ad820cd447568ee4f4aabfe50bf0729ed94db4b3cc32eb0911483/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616e746f676b6f752f6c61726176656c2d6f61757468322d636c69656e74)](https://packagist.org/packages/antogkou/laravel-oauth2-client)

A robust Laravel package for OAuth2 Client Credentials flow integration with automatic token management.

Features
--------

[](#features)

- 🚀 **Automatic Token Management** - Handles token acquisition and refresh
- 🔧 **Multiple Service Support** - Configure multiple OAuth2 providers
- 📦 **Caching** - Stores tokens securely using Laravel Cache
- 📝 **Structured Logging** - Detailed error logging for failed requests
- 🛡️ **Security** - Sensitive data redaction in logs
- ✅ **Laravel 11+ Ready** - Full support for latest Laravel versions

Installation
------------

[](#installation)

```
composer require antogkou/laravel-oauth2-client
php artisan oauth2:generate-types
```

Publish configuration file:

```
php artisan vendor:publish --tag=oauth2-client-config
```

Configuration
-------------

[](#configuration)

### Config File (`config/oauth2-client.php`)

[](#config-file-configoauth2-clientphp)

```
return [
    'services' => [
        'service1' => [
            'client_id' => env('SERVICE1_CLIENT_ID'),
            'client_secret' => env('SERVICE1_CLIENT_SECRET'),
            'token_url' => env('SERVICE1_TOKEN_URL'),
            'scope' => env('SERVICE1_SCOPE', ''),
            'verify' => env('SERVICE1_VERIFY', true),
        ],
    ],
    'cache_prefix' => 'oauth2_',
    'expiration_buffer' => 60, // Seconds before expiration to renew token
    'logging' => [
        'enabled' => true,
        'level' => 'error',
        'redact' => [
            'headers.authorization',
            'body.password',
            'response.access_token'
        ]
    ]
];
```

### Environment Variables

[](#environment-variables)

```
# Service 1 Configuration
SERVICE1_CLIENT_ID = your_client_id
SERVICE1_CLIENT_SECRET = your_client_secret
SERVICE1_TOKEN_URL = https://auth.service.com/token
SERVICE1_SCOPE = api
SERVICE1_VERIFY = true # Set to false to disable SSL verification
```

Enabling IDE Autocompletion for Services
----------------------------------------

[](#enabling-ide-autocompletion-for-services)

To enable IDE autocompletion for your OAuth2 service names in `OAuth2::for('...')`, this package provides a type generation command:

```
php artisan oauth2:generate-types
```

This command scans your `config/oauth2-client.php` and generates a PHP interface listing all configured service names. IDEs like PHPStorm and VSCode (with PHP Intelephense) will then offer autocompletion and static analysis for the available services.

**Workflow:**

1. Add or update your services in `config/oauth2-client.php` under the `services` key.
2. Run `php artisan oauth2:generate-types` to regenerate the types.
3. Enjoy autocompletion in your IDE for `OAuth2::for('your_service')`.

**Example:**

```
// config/oauth2-client.php
'services' => [
    'service1' => [...],
    'service2' => [...],
],
```

After running the command, your IDE will suggest 'service1' and 'service2' in:

```
OAuth2::for('service1')->get(...);
```

Usage
-----

[](#usage)

### Basic API Calls

[](#basic-api-calls)

```
use Antogkou\LaravelOAuth2Client\Facades\OAuth2;

// GET request
$response = OAuth2::for('service1')->get('https://api.service.com/data');

// POST request with JSON payload
$response = OAuth2::for('service1')->post('https://api.service.com/data', [
    'json' => [
        'name' => 'John Doe',
        'email' => 'john@example.com'
    ]
]);

// POST form data
$response = OAuth2::for('service1')->post('https://api.service.com/data', [
    'form_params' => [
        'name' => 'John Doe',
        'email' => 'john@example.com'
    ]
]);

// PUT request with JSON payload
$response = OAuth2::for('service1')->put('https://api.service.com/data/1', [
    'json' => [
        'name' => 'Updated Name'
    ]
]);

// PATCH request with JSON payload
$response = OAuth2::for('service1')->patch('https://api.service.com/data/1', [
    'json' => [
        'status' => 'active'
    ]
]);

// Request with custom headers
$response = OAuth2::for('service1')->post('https://api.service.com/data', [
    'json' => [
        'name' => 'John Doe'
    ],
    'headers' => [
        'X-Custom-Header' => 'value',
        'Accept' => 'application/json'
    ]
]);

// Get JSON response
$data = $response->json();
```

### Request Options

[](#request-options)

The package supports various request options that can be passed as an array:

#### JSON Payload

[](#json-payload)

```
$options = [
    'json' => [
        'key' => 'value',
        'nested' => ['data' => 'value']
    ]
];
```

#### Form Data

[](#form-data)

```
$options = [
    'form_params' => [
        'field1' => 'value1',
        'field2' => 'value2'
    ]
];
```

#### Multipart/Form-Data (File Uploads)

[](#multipartform-data-file-uploads)

```
$options = [
    'multipart' => [
        [
            'name' => 'file',
            'contents' => fopen('path/to/file.pdf', 'r')
        ],
        [
            'name' => 'field',
            'contents' => 'value'
        ]
    ]
];
```

#### Custom Headers

[](#custom-headers)

```
$options = [
    'headers' => [
        'Accept' => 'application/json',
        'X-Custom-Header' => 'value'
    ],
    'json' => [
        'data' => 'value'
    ]
];
```

### Available Methods

[](#available-methods)

```
OAuth2::for('service1')->get($url, $options = []);
OAuth2::for('service1')->post($url, $options = []);
OAuth2::for('service1')->put($url, $options = []);
OAuth2::for('service1')->patch($url, $options = []);
OAuth2::for('service1')->delete($url, $options = []);
OAuth2::for('service1')->request($method, $url, $options = []);
```

### Response Handling

[](#response-handling)

```
$response = OAuth2::for('service1')->post('https://api.service.com/data', [
    'json' => ['name' => 'John']
]);

if ($response->successful()) {
    $data = $response->json();
    $status = $response->status(); // 200, 201, etc.
    $headers = $response->headers();
} else {
    $errorData = $response->json();
    $statusCode = $response->status();
}
```

Error Handling
--------------

[](#error-handling)

The package throws `Antogkou\LaravelOAuth2Client\Exceptions\OAuth2Exception` for errors:

```
try {
    OAuth2::for('service1')->get('https://api.service.com/data');
} catch (OAuth2Exception $e) {
    // Handle exception
    $errorContext = $e->getContext();
}
```

Automatic JSON Error Responses
------------------------------

[](#automatic-json-error-responses)

To make error handling seamless, you can configure your Laravel application's global exception handler to automatically return JSON responses for OAuth2 errors. This way, users of your API will always receive a structured JSON error response, and you don't need to manually catch exceptions in your controllers.

**How to set up:**

1. Open (or create) `app/Exceptions/Handler.php` in your Laravel application.
2. Add the following to your `render` method:

```
use Antogkou\LaravelOAuth2Client\Exceptions\OAuth2Exception;

public function render($request, Throwable $exception)
{
    if ($exception instanceof OAuth2Exception) {
        return $exception->toResponse($request);
    }
    return parent::render($request, $exception);
}
```

**Debug Mode:**

- If you include an `X-Debug: 1` header or a `?debug=1` query parameter in your request, the error response will include additional debug information (stack trace, exception class).
- This is useful for development and debugging, but should be used with care in production.

**Example error response (with debug):**

```
{
  "message": "Invalid token response format for service: myservice",
  "code": 500,
  "context": { ... },
  "exception": "Antogkou\\LaravelOAuth2Client\\Exceptions\\OAuth2Exception",
  "trace": [
    { "file": "/path/to/file.php", "line": 123, "function": "...", "class": "..." },
    ...
  ]
}
```

This setup is optional but highly recommended for API projects using this package.

Testing
-------

[](#testing)

The package uses [Pest PHP](https://pestphp.com/) for testing. To run all tests:

```
composer test
```

To run only unit tests:

```
composer test:unit
```

To run static analysis:

```
composer test:types
```

To check code style:

```
composer lint
```

To test the artisan type generation command:

```
php artisan oauth2:generate-types
# Or run the dedicated test
pest tests/Feature/GenerateOAuth2TypesCommandTest.php
```

**Adding New Services for Testing:**

- Add your service to the `services` array in `config/oauth2-client.php`.
- Run the type generation command to update IDE support.

Troubleshooting &amp; FAQ
-------------------------

[](#troubleshooting--faq)

**Q: I added a new service but it doesn't autocomplete in my IDE.**

- Run `php artisan oauth2:generate-types` after updating your config.
- Restart your IDE if needed.

**Q: I get an exception about missing or invalid service configuration.**

- Ensure your service is correctly defined in `config/oauth2-client.php`.
- Check for typos in the service name.

**Q: How do I test error handling or simulate network/cache failures?**

- See the feature tests for examples of simulating HTTP and cache errors using Laravel's testing tools.

**Q: How do I contribute tests or features?**

- See the 'Contributing' section below. All new features should include tests.

Contributing
------------

[](#contributing)

Contributions welcome! Please follow:

1. Fork the repository
2. Create a feature branch
3. Submit a pull request

License
-------

[](#license)

MIT License - See [LICENSE](LICENSE) for details.

Support
-------

[](#support)

For issues and feature requests, please [create a GitHub issue](https://github.com/antogkou/laravel-oauth2-client/issues).

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance34

Infrequent updates — may be unmaintained

Popularity30

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 96.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~12 days

Recently: every ~0 days

Total

11

Last Release

391d ago

Major Versions

v0.09 → v1.0.02025-06-08

PHP version history (2 changes)0.0.1PHP ^8.2

v0.0.4PHP ^8.2|^8.3|^8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/fdbdc9ea38ded68b1272a7a1b50f517ef856cb7014c760dc092acbc78a151ecd?d=identicon)[antogkou](/maintainers/antogkou)

---

Top Contributors

[![antogkou](https://avatars.githubusercontent.com/u/15363511?v=4)](https://github.com/antogkou "antogkou (25 commits)")[![Copilot](https://avatars.githubusercontent.com/in/1143301?v=4)](https://github.com/Copilot "Copilot (1 commits)")

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/antogkou-laravel-oauth2-client/health.svg)

```
[![Health](https://phpackages.com/badges/antogkou-laravel-oauth2-client/health.svg)](https://phpackages.com/packages/antogkou-laravel-oauth2-client)
```

###  Alternatives

[backpack/crud

Quickly build admin interfaces using Laravel, Bootstrap and JavaScript.

3.4k3.7M222](/packages/backpack-crud)[statamic/cms

The Statamic CMS Core Package

4.8k3.6M985](/packages/statamic-cms)[unopim/unopim

UnoPim Laravel PIM

10.5k2.4k](/packages/unopim-unopim)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

273.0k](/packages/eslazarev-wildberries-sdk)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
