sydefz/freelancer-oauth2-client

Freelancer OAuth 2.0 客户端提供商

2.2.1 2017-11-28 04:24 UTC

This package is not auto-updated.

Last update: 2024-09-22 10:29:17 UTC


README

此软件包使您的应用程序轻松集成到 Freelancer OAuth 2.0 服务提供商。

要求

以下版本的 PHP 受支持。

  • PHP 5.5
  • PHP 5.6
  • PHP 7.0
  • HHVM

用法

初始化 Freelancer OAuth2 提供商

建议在使用此客户端之前了解 OAuth。有关 OAuth2 的介绍,请参阅 https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2,或通过电子邮件向 Freelancer 身份团队咨询(identity@freelancer.com)。

注意:请在开始之前从 http://accounts.freelancer.com/settings/create_app 创建应用程序并获得批准

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

$provider = new FreelancerIdentity([
    'clientId' => '<your-client-id>',
    'clientSecret' => '<your-client-secret>',
    'redirectUri' => '<your-client-redirect-uri>',
    'scopes' => [<scopes-array>], // Optional only needed when retrieve access token
    'prompt' => [<prompt-step-array>], // Optional only needed when retrieve access token
    'advancedScopes' => [<advanced-scopes-array>], // Optional only needed when retrieve access token
    'sandbox' => true, // to play with https://accounts.freelancer-sandbox.com
]);

授权代码授予

授权代码授予类型是在使用 Freelancer 服务对用户进行身份验证时最常用的授权类型。此授权类型使用客户端(此库)、服务器(服务提供商)和资源所有者(拥有受保护或拥有的资源的凭证的用户)来请求访问用户拥有的资源。这通常被称为 3 方 OAuth,因为涉及三个实体。

// 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());
    }
}

向 Freelancer API 服务发出授权请求。

要从您的应用程序中调用 Freelancer API,您的应用程序需要创建具有某些高级作用域,然后在检索访问令牌时请求用户授予这些高级作用域。

例如,对于 POST https://www.freelancer.com/api/projects/0.1/projects/ 文档参考: https://www.freelancer.com/api/docs/#create-new-project 您的应用程序需要在创建时具有 'fln:project:create' 高级作用域,并且您的用户需要同意此作用域,以便授予的访问令牌现在具有调用此端点的权限。

$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());
}

刷新令牌

一旦您的应用程序获得授权,您可以使用刷新令牌而不是从头开始整个过程来刷新已过期的令牌。要这样做,只需从您的数据存储中重新使用此刷新令牌来请求刷新。

$provider = new FreelancerIdentity([
    'clientId' => '<your-client-id>',
]);
$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());
}

客户端凭据授予

当您的应用程序代表自己访问它控制/拥有的资源时,它可能使用客户端凭据授权类型。此方式最佳用于您的应用程序的凭据存储在私人位置且永远不会暴露(例如,通过网页浏览器等)给最终用户。此授权类型与资源所有者密码凭据授权类型功能类似,但它不请求用户的用户名或密码。它仅使用服务提供商向您的客户端颁发客户端 ID 和秘密。

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());

}

安装

通过 Composer

$ composer require sydefz/freelancer-oauth2-client -o

许可证

MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件