天天看點

PHP之常用第三方類庫彙總

彙總項目中經常使用到的第三方類庫, 友善日後查找與使用

1.Oauth授權認證

​​  https://github.com/jumbojett/OpenID-Connect-PHP​​

     使用:

[安裝]
composer require jumbojett/openid-connect-php      

示例:

<?php
namespace backend\controllers;

use Jumbojett\OpenIDConnectClient;

class LoginController extends Controller
{
    function getOidc()
    {
        $clientID = config('oauth.clientID');
        $clientSecret = config('oauth.clientSecret');
        $issuer = config('oauth.issuer');
        $redirectUrl = config('oauth.redirectUrl');

        $oidc = new OpenIDConnectClient($issuer,
            $clientID,
            $clientSecret);
        $oidc->setResponseTypes(['code']);
        $oidc->setRedirectURL($redirectUrl);
        $oidc->addScope(["profile email"]);
        return $oidc;
    }

    public function login(Request $request)
    {
        $oidc = $this->getOidc();
        $oidc->authenticate();
    }


    // 回調位址
    public function callback(Request $request)
    {
        $oidc = $this->getOidc();
        try {
            if (!$oidc->authenticate()) {
                throw new \Exception("登入失敗");
            }

            // 擷取使用者資訊成功
            $userInfo = $oidc->requestUserInfo();
            if ($userInfo == null) {
                throw new \Exception("擷取使用者資訊失敗");
            }

            // todo 後續步驟: 實作業務登入邏輯
            return response(json_encode($userInfo), 200);

        } catch (\Exception $e) {
            return response($e->getMessage(), 500);
        }
    }
}      

  

  ​​https://github.com/thephpleague/oauth2-client​​

  說明: 在接入公司内部系統的時候出現問題,沒有接入成功, 改用上面的類庫

[安裝]
composer require league/oauth2-client


[使用]
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
    'clientId'                => 'XXXXXX',    // The client ID assigned to you by the provider
    'clientSecret'            => 'XXXXXX',    // The client password assigned to you by the provider
    'redirectUri'             => 'https://my.example.com/your-redirect-url/',
    'urlAuthorize'            => 'https://service.example.com/authorize',
    'urlAccessToken'          => 'https://service.example.com/token',
    'urlResourceOwnerDetails' => 'https://service.example.com/resource'
]);

// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {

    // Fetch the authorization URL from the provider; this returns the
    // urlAuthorize option and generates and applies any necessary parameters
    // (e.g. state).
    $authorizationUrl = $provider->getAuthorizationUrl();

    // Get the state generated for you and store it to the session.
    $_SESSION['oauth2state'] = $provider->getState();

    // Redirect the user to the authorization URL.
    header('Location: ' . $authorizationUrl);
    exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || (isset($_SESSION['oauth2state']) && $_GET['state'] !== $_SESSION['oauth2state'])) {

    if (isset($_SESSION['oauth2state'])) {
        unset($_SESSION['oauth2state']);
    }

    exit('Invalid state');

} else {

    try {

        // Try to get an access token using the authorization code grant.
        $accessToken = $provider->getAccessToken('authorization_code', [
            'code' => $_GET['code']
        ]);

        // We have an access token, which we may use in authenticated
        // requests against the service provider's API.
        echo 'Access Token: ' . $accessToken->getToken() . "<br>";
        echo 'Refresh Token: ' . $accessToken->getRefreshToken() . "<br>";
        echo 'Expired in: ' . $accessToken->getExpires() . "<br>";
        echo 'Already expired? ' . ($accessToken->hasExpired() ? 'expired' : 'not expired') . "<br>";

        // Using the access token, we may look up details about the
        // resource owner.
        $resourceOwner = $provider->getResourceOwner($accessToken);

        var_export($resourceOwner->toArray());

        // The provider provides a way to get an authenticated API request for
        // the service, using the access token; it returns an object conforming
        // to Psr\Http\Message\RequestInterface.
        $request = $provider->getAuthenticatedRequest(
            'GET',
            'https://service.example.com/resource',
            $accessToken
        );

    } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {

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

    }

}      

  

 2.時間日期處理

  • ​​https://github.com/briannesbitt/Carbon​​