Code Monkey home page Code Monkey logo

oauth2-wechat's Introduction

Wechat Provider for OAuth 2.0 Client

Latest Version Software License Build Status Coverage Status Quality Score Total Downloads

This package provides Wechat OAuth 2.0 support for the PHP League's OAuth 2.0 Client.

  • DONE:

    Website SDK, Mini Programs

  • TODO:

    Mobile App SDK

Installation

To install, use composer:

composer require oakhope/oauth2-wechat

Usage

Usage is the same as The League's OAuth client, using \Oakhope\OAuth2\Client\Provider\{WebProvider} as the provider.

Authorization Code Flow

$provider = new \Oakhope\OAuth2\Client\Provider\WebProvider([
        'appid' => '{wechat-client-id}',
        'secret' => '{wechat-client-secret}',
        'redirect_uri' => 'https://example.com/callback-url'
    ]);

// 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']) || ($_GET['state'] !== rtrim($_SESSION['oauth2state'], '#wechat_redirect'))) {

    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 "token: ".$accessToken->getToken()."<br/>";
        echo "refreshToken: ".$accessToken->getRefreshToken()."<br/>";
        echo "Expires: ".$accessToken->getExpires()."<br/>";
        echo ($accessToken->hasExpired() ? 'expired' : 'not expired')."<br/><br/>";

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

        var_export($resourceOwner->toArray());
        
    } catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {

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

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.

This example uses Brent Shaffer's demo OAuth 2.0 application named Lock'd In. See authorization code example above, for more details.

$provider = new \Oakhope\OAuth2\Client\Provider\WebProvider([
        'appid' => '{wechat-client-id}',
        'secret' => '{wechat-client-secret}',
        'redirect_uri' => 'https://example.com/callback-url'
    ]);

$existingAccessToken = getAccessTokenFromYourDataStore();

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

    // Purge old access token and store new access token to your data store.
}

Testing

$ ./vendor/bin/phpunit --colors tests

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

oauth2-wechat's People

Contributors

oakhope avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.