OhGoo 是一个简单的 OAuth 库,用于在您的应用程序中验证 Google 用户。

1.0.1 2019-11-17 08:34 UTC

This package is auto-updated.

Last update: 2024-09-17 19:52:36 UTC


README

OhGoo 是一个简单的 OAuth 库,用于在您的应用程序中验证 Google 用户。

配置

配置是一个单例。最终,您需要在一个 Google Cloud Console 项目中设置一个 'Web 应用' 凭证,以便获取配置对象所需的详细信息。

<?php
\OhGoo\OhGooConfig::getInstance()->setClientId(
    'xxxx-xxxx.apps.googleusercontent.com'
)->setClientSecret(
    'xxxxxxxx'
)->setRedirectUri(
    'http://mydomain.tld/my-path'
);

身份验证

<?php
if ($_GET['code']) {
    try {
        $data = \OhGoo\OhGooService::getAccessTokenFromCode($_GET['code']);
        // If you have a refresh token already for a user, call the line below instead:
        // $data = \OhGoo\OhGooService::getAccessTokenFromRefreshToken($theRefreshToken)
        if ($data instanceof \OhGoo\Dto\OauthCredentialsDto) {
            $userDto = \OhGoo\OhGooService::getGoogleUser($data);
            var_dump($userDto);
            exit;
        }
        echo 'Logging in via Google failed.';
        exit;

    } catch(Exception $e) {
        echo sprintf(
            'We experienced an error authenticating you via Google. Message: %s',
            $e->getMessage()
        );
        exit;
    }
}

header("Location: " . \OhGoo\OhGooService::getLoginUrl(
    \OhGoo\OhGooService::ACCESS_TYPE_OFFLINE // OR \OhGoo\OhGooService::ACCESS_TYPE_ONLINE
));