美文网首页
PHP+google

PHP+google

作者: 泽_0b48 | 来源:发表于2020-05-22 10:07 被阅读0次

    1、获取ID+秘钥 https://console.developers.google.com/

    image.png
    image.png
    image.png
    创建凭据获取客户端ID+秘钥
    image.png
    2、下载SDK
    https://github.com/googleapis/google-api-php-client/releases

    3、跳转登录

            require APP_ROOT_PATH."google-api-php-client-2.4.1/vendor/autoload.php";
            $clientID = '你的clientID';
            $clientSecret = '你的clientSecret';
            $aUrl = 回调地址;
            $redirectUri = $aUrl;
    
        // create Client Request to access Google API
            $client = new Google_Client();
            $client->setClientId($clientID);
            $client->setClientSecret($clientSecret);
            $client->setRedirectUri($redirectUri);
            $client->addScope("email");
            $client->addScope("profile");
    
            // authenticate code from Google OAuth Flow
            if (isset($_GET['code'])) {
                $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
                $client->setAccessToken($token['access_token']);
    
                // get profile info
                $google_oauth = new Google_Service_Oauth2($client);
                $google_account_info = $google_oauth->userinfo->get();
                $email =  $google_account_info->email;
                $name =  $google_account_info->name;
    
                // now you can use this profile info to create account in your website and make user logged in.
            } else {
                $loginUrl = $client->createAuthUrl();
                app_redirect($loginUrl);
            }
    

    4、回调

                require APP_ROOT_PATH."google-api-php-client-2.4.1/vendor/autoload.php";
                $clientID = '你的clientID';
                $clientSecret = '你的clientSecret';
                $aUrl = 回调地址;
                $redirectUri = $aUrl;
    
                // create Client Request to access Google API
                $client = new Google_Client();
                $client->setClientId($clientID);
                $client->setClientSecret($clientSecret);
                $client->setRedirectUri($redirectUri);
                $client->addScope("email");
                $client->addScope("profile");
                // authenticate code from Google OAuth Flow
                if (isset($_GET['code'])) {
                    $token = $client->authenticate($_GET['code']);
                    $client->setAccessToken($token['access_token']);
                    $q = 'https://www.googleapis.com/oauth2/v1/userinfo?access_token='.$token['access_token'];
                    $json = file_get_contents($q);
                    $userInfoArray = json_decode($json,true);
                  //var_dump($userInfoArray);die;  //接收的数据
                  //处理
                }
                
    

    相关文章

      网友评论

          本文标题:PHP+google

          本文链接:https://www.haomeiwen.com/subject/xpwfahtx.html