startz/oauth2-etsy

The PHP League OAuth2-Client 的 Etsy OAuth2 客户端提供程序

0.0.2 2022-09-15 04:22 UTC

This package is auto-updated.

Last update: 2024-09-16 07:13:21 UTC


README

GitHub tag GitHub license build codecov Packagist Downloads

此包为 PHP League 的 OAuth 2.0 客户端 提供Etsy OAuth 2.0 支持。

需求

以下版本的 PHP 受支持。

  • PHP 7.3
  • PHP 7.4
  • PHP 8.0

安装

要安装,请使用 composer

composer require startz/oauth2-etsy

用法

用法与 The League 的 OAuth 客户端相同,使用 \StartZ\OAuth2\Client\Provider\Etsy 作为提供程序。

请参考您的 Etsy 开发者账户 获取必要的设置。

授权码流

<?php

session_start();

require_once __DIR__ . '/vendor/autoload.php';

$provider = new Startz\OAuth2\Client\Provider\Etsy([
    'clientId'     => '{etsy-apikey-keystring}',
    'clientSecret' => '{etsy-apikey-shared-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
]);

if ( ! isset($_GET['code'])) 
{
    // If we don't have an authorization code then get one
    $preChallenge = $provider->getPreChallenge();
    $authUrl = $provider->getAuthorizationUrl([
        'code_challenge' => $provider->getPKCE($preChallenge),
        'code_challenge_method' => 'S256'
    ]);
    $_SESSION['oauth2state'] = $provider->getState();
    $_SESSION['oauth2code'] = $preChallenge;
    header('Location: ' . $authUrl);
    exit;

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

    unset($_SESSION['oauth2state']);
    unset($_SESSION['oauth2code']);
    exit('Invalid state');

} else {
    
    $preChallenge = $_SESSION['oauth2code'];
    $authParams = [
        'code' => $_GET['code'],
        'code_verifier' => $preChallenge,
    ];
    // Try to get an access token (using the authorization code grant)
    $token = $provider->getAccessToken('authorization_code', $authParams);

    // Optional: Now you have a token you can look up a users profile data
    try {

        // We got an access token, let's now get the user's details
        $user = $provider->getResourceOwner($token);
        printf('Hello %s!', $user->getName());

    } catch (Exception $e) {

        // Failed to get user details
        exit('Error...');
    }

    // Use this to interact with an API on the users behalf
    echo $token->getToken();
}

测试

单元测试

$ ./vendor/bin/phpunit

代码嗅探

$ ./vendor/bin/phpcs src --standard=psr2 -sp