PHPackages                             serg-php/freelancer-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. serg-php/freelancer-oauth2-client

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

serg-php/freelancer-oauth2-client
=================================

Freelancer OAuth 2.0 Client Provider

02PHP

Since Mar 20Pushed 3y ago1 watchersCompare

[ Source](https://github.com/serg-php/freelancer-oauth2-client)[ Packagist](https://packagist.org/packages/serg-php/freelancer-oauth2-client)[ RSS](/packages/serg-php-freelancer-oauth2-client/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

OAuth 2.0 Client
================

[](#oauth-20-client)

This package makes it simple to integrate your application with freelancer OAuth 2.0 service providers.

Requirements
------------

[](#requirements)

The following versions of PHP are supported.

- PHP 8.0
- HHVM

Usage
-----

[](#usage)

### Initialize Freelancer OAuth2 Provider

[](#initialize-freelancer-oauth2-provider)

It is recommended to have an understanding of oauth before using this client. For an introduction to Oauth2, see , or email and ask the Freelancer Identity Team ().

Note: Create your application from [http://accounts.freelancer.com/settings/create\_app](http://accounts.freelancer.com/settings/create_app)and get it approved before you start

```
require __DIR__ . '/vendor/autoload.php';
use Sergphp\OAuth2\Client\Provider\FreelancerIdentity;
use Sergphp\OAuth2\Client\Provider\FreelancerIdentityException;

$provider = new FreelancerIdentity([
    'clientId' => '',
    'clientSecret' => '',
    'redirectUri' => '',
    'scopes' => [], // Optional only needed when retrieve access token
    'prompt' => [], // Optional only needed when retrieve access token
    'advancedScopes' => [], // Optional only needed when retrieve access token
    'sandbox' => true, // to play with https://accounts.freelancer-sandbox.com
]);
```

### Authorization Code Grant

[](#authorization-code-grant)

The authorization code grant type is the most common grant type used when authenticating users with freelancer service. This grant type utilizes a client (this library), a server (the service provider), and a resource owner (the user with credentials to a protected or owned resource) to request access to resources owned by the user. This is often referred to as 3-legged OAuth, since there are three parties involved.

```
// Check given error
if (isset($_GET['error'])) {
    exit($_GET['error']);
} elseif (!isset($_GET['code'])) {
    // If we don't have an authorization code then get one
    // Fetch the authorization URL from the provider; this returns the
    // urlAuthorize option and generates and applies any necessary parameters
    $authorizationUrl = $provider->getAuthorizationUrl();

    // Redirect the user to the authorization URL.
    header('Location: ' . $authorizationUrl);
    exit;
} else {
    try {
        // Try to get an access token using the authorization code grant.
        $accessToken = $provider->getAccessToken('authorization_code', [
            'code' => $_GET['code']
        ]);

        // Store this bearer token in your data store for future use
        // including these information
        // token_type, expires_in, scope, access_token and refresh_token
        storeAccessTokenInYourDataStore($provider->accessTokenArray);

        // We have an access token, which we may use in authenticated
        // requests against the freelancer identity and freelancer API.
        echo $accessToken->getToken() . "\n";
        echo $accessToken->getRefreshToken() . "\n";
        echo $accessToken->getExpires() . "\n";
        echo ($accessToken->hasExpired() ? 'expired' : 'not expired') . "\n";

        // Using the access token, we may look up details about the
        // resource owner.
        $resourceOwner = $provider->getResourceOwner($accessToken);
        var_export($resourceOwner);
    } catch (FreelancerIdentityException $e) {
        // Failed to get the access token or user details.
        exit($e->getMessage());
    }
}
```

### Making an authorized request to freelancer API service.

[](#making-an-authorized-request-to-freelancer-api-service)

In order to user freelancer API from you applications, your application needs to be created with certain advanced scopes then you can request user to grant these advanced scopes when retrieve access token.

Take POST Doc reference: Your application needs to have 'fln:project:create' advanced scopes on creation, and your user will need to consent on that scope so the granted access token now have the permission to call this endpoint.

```
$provider = new FreelancerIdentity();
try {
    $tokenArray = getAccessTokenFromYourDataStore();
    $provider->setAccessTokenFromArray($tokenArray);

    if (!$provider->accessToken->hasExpired()) {

        $request = $provider->getAuthenticatedRequest(
            'POST',
            $provider->apiBaseUri.'/projects/0.1/projects/',
            [
                "headers" => ["Content-Type" => "application/json"],
                "body" => '{
                    "title": "Build my Super Website!",
                    "description": "I need this website to make visual basic GUIs",
                    "currency": { "id": 1 },
                    "budget": { "minimum": 300 },
                    "jobs": [ { "id": 7 }, { "id": 3 } ]
                }'
            ]
        );
        $response = $provider->getResponse($request);
        var_export($response);
    } else {
        // refresh your token
    }
} catch (FreelancerIdentityException $e) {

    // Failed to get response
    exit($e->getMessage());
}
```

### Refreshing a Token

[](#refreshing-a-token)

Once your application is authorized, you can refresh an expired token using a refresh token rather than going through the entire process of obtaining a brand new token. To do so, simply reuse this refresh token from your data store to request a refresh.

```
$provider = new FreelancerIdentity([
    'clientId' => '',
]);
$existingAccessTokenArray = getAccessTokenFromYourDataStore();
$provider->setAccessTokenFromArray($existingAccessTokenArray);

try {
    if ($provider->accessToken->hasExpired()) {
        $newAccessToken = $provider->getAccessToken('refresh_token', [
            'refresh_token' => $provider->accessToken->getRefreshToken()
        ]);

        // Purge old access token and store new access token to your data store.
    }
} catch (FreelancerIdentityException $e) {
    // Failed to refresh token
    exit($e->getMessage());
}
```

### Client Credentials Grant

[](#client-credentials-grant)

When your application is acting on its own behalf to access resources it controls/owns in a service provider, it may use the client credentials grant type. This is best used when the credentials for your application are stored privately and never exposed (e.g. through the web browser, etc.) to end-users. This grant type functions similarly to the resource owner password credentials grant type, but it does not request a user's username or password. It uses only the client ID and secret issued to your client by the service provider.

```
try {

    // Try to get an access token using the client credentials grant.
    $accessToken = $provider->getAccessToken('client_credentials');

    // Store this bearer token in your data store for future use
    // including these information
    // token_type, expires_in, scope and access_token
    storeAccessTokenInYourDataStore($provider->accessTokenArray);

} catch (FreelancerIdentityException $e) {

    // Failed to get the access token
    exit($e->getMessage());

}
```

Install
-------

[](#install)

Via Composer

```
$ composer require serg-php/freelancer-oauth2-client -o
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/serg-php/freelancer-oauth2-client/blob/master/LICENSE) for more information.

###  Health Score

13

—

LowBetter than 1% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity2

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity22

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% 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.

### Community

Maintainers

![](https://www.gravatar.com/avatar/e61d4919408a8ca06668271270d5c2035e72ef3c99ad1aa2425f268090abc1aa?d=identicon)[serg-php](/maintainers/serg-php)

---

Top Contributors

[![serg-php](https://avatars.githubusercontent.com/u/10445674?v=4)](https://github.com/serg-php "serg-php (3 commits)")

### Embed Badge

![Health badge](/badges/serg-php-freelancer-oauth2-client/health.svg)

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

###  Alternatives

[namshi/jose

JSON Object Signing and Encryption library for PHP.

1.8k99.6M101](/packages/namshi-jose)[league/oauth1-client

OAuth 1.0 Client Library

99698.8M106](/packages/league-oauth1-client)[bezhansalleh/filament-shield

Filament support for `spatie/laravel-permission`.

2.8k2.9M88](/packages/bezhansalleh-filament-shield)[gesdinet/jwt-refresh-token-bundle

Implements a refresh token system over Json Web Tokens in Symfony

70516.4M35](/packages/gesdinet-jwt-refresh-token-bundle)[league/oauth2-google

Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client

41721.2M118](/packages/league-oauth2-google)[illuminate/auth

The Illuminate Auth package.

9327.3M1.0k](/packages/illuminate-auth)

PHPackages © 2026

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