skn036/laravel-google-client 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

skn036/laravel-google-client

Composer 安装命令:

composer require skn036/laravel-google-client

包简介

Wrapper for Google API Client Library for Laravel

README 文档

README

This package only handles the authentication layer, securely saving, retrieving and revoking tokens around google api client. So it could be a good choice as authentication layer while using any api service from google.

For some common api services from google please check:

Gmail Api: skn036/laravel-gmail-api
Calendar Api: skn036/laravel-google-calendar (coming soon)

For extending your own api service please follow the guidelines below.

Installation

First install the package via composer.

composer require skn036/laravel-google-client

Then publish the config file. It will publishes google.php file in the config directory.

php artisan vendor:publish --provider="Skn036\Google\GoogleClientServiceProvider"

Configuration

Please look into config/google.php for detailed information about the configuration. First you need to enable the required api services and generate credentials in your google developers account. Please see here from detailed instructions. Available .env variables for configuration are:

GOOGLE_APPLICATION_NAME=
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_REDIRECT_URI=
GOOGLE_SCOPES=
GOOGLE_PUB_SUB_TOPIC=

Authentication Modes:

There are three authentication modes:

  • Single account in whole application ( set credentials_per_user to false in config file ).
  • Single account per user ( set credentials_per_user to true & multiple_accounts_per_user to false in config file ).
  • Multiple accounts per user ( set credentials_per_user to true & multiple_accounts_per_user to true in config file ).

Note: You need to set the scopes on .env file which google services you intended to use.

Getting Started

use Illuminate\Http\Request;
use Skn036\Google\GoogleClient;

// pass the google client to the view
Route::get('/google-dashboard', function (Request $request) {
    $googleClient = new GoogleClient();
    return view('google-dashboard', compact('googleClient'));
})->name('google-dashboard');

// redirect go google oauth2 login page
Route::post('/google-login', function (Request $request) {
    return (new GoogleClient())->redirectToAuthUrl();
})->name('google-login');

// logout from google account
Route::post('/google-logout', function (Request $request) {
    (new GoogleClient())->logout();
    return redirect()->route('google-dashboard');
})->name('google-logout');

// authenticate the account from google oauth2 login success
// this route must match the redirect uri in google console and .env file
Route::get('/google-auth-callback', function (Request $request) {
    (new GoogleClient())->authenticate();
    return redirect()->route('google-dashboard');
});

google-dashboard.blade.php:

<!-- login or logout  -->
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8 flex flex-row items-center gap-4">
    @if ($googleClient->isAuthenticated())
    <form method="POST" action="{{ route('google-logout') }}">
        @csrf
        <x-primary-button> {{ __("Logout") }} </x-primary-button>
    </form>
    @else
    <form method="POST" action="{{ route('google-login') }}">
        @csrf
        <x-primary-button> {{ __("Login with Google") }} </x-primary-button>
    </form>
    @endif
</div>

<!-- status -->
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
    {{ $googleClient->isAuthenticated() ? "Authenticated user:" . $googleClient->email : 'Not
    authenticated' }}
</div>

SPA Authentication

If you are using SPA frontend like React or Vue and entirely handle the Oauth redirect in the frontend, you should call the getAuthUrl method to get the google Oauth url.

$url = $googleClient->getAuthUrl();
return response()->json($url);

After successful login from google, it should add code route query param on redirect uri set on the google console. You need to pass this code the authenticate method or if you pass the code as route query, it will automatically capture on authentication request;

$token = $googleClient->authenticate($request->code);

Single Account Per User Mode:

By default, authenticated user is passed to GoogleClient instance using laravel's auth()->id(). If you want to pass a user manually to client instance:

$googleClient = new GoogleClient(1); // pass the user's id

Multiple Account Per User Mode:

When using multiple accounts, first account synced will be set as default account. If you want to change the default account, first get the available accounts:

$accounts = $googleClient->getSyncedAccounts();

It will give a array of synced accounts like:

[
    ['email' => 'john@gmail.com', 'profile' => ['givenName' => 'John', 'familyName' => 'Doe', ...] ],
    ['email' => 'foo@gmail.com', 'profile' => ['givenName' => 'Foo', 'familyName' => 'Bar', ...] ],
];

Then you call setDefaultAccount method to change the default account.

$googleClient = $googleClient->setDefaultAccount('foo@gmail.com');

Normally it will use the default account to interact with the services. If you want to use other account rather than the default, you should pass the email of the intended account as the second argument of the client constructor.

$googleClient = new GoogleClient(1, 'foo@gmail.com');

Extending This Package To Google Api Services

First you should make a api service class extending the GoogleClient class. Then bind it to the api services to interact with the api.

For example we will extend to the Gmail api service:

use Skn036\Google\GoogleClient;
use YourNamespace\Gmail\GmailMessage;

class Gmail extends GoogleClient
{
    public function __construct(
        string|int|null $userId = null,
        ?string $usingAccount = null,
        ?array $config = null
    ) {
        parent::__construct($userId, $usingAccount, $config);
    }

    // access the messages on gmail api
    public function messages()
    {
        return new GmailMessage($this);
    }
}

On the GmailMessage.php:

namespace YourNamespace\Gmail;

class GmailMessage
{
    protected $service;
    protected $client;
    protected $params = [];

    public function __construct(Gmail $gmail)
    {
        $this->client = $gmail;
        $this->service = new \Google_Service_Gmail($gmail); // initiate the gmail api service
    }

    public function list($params = [])
    {
        $params = array_merge($this->params, $params);

        return $this->service->users_messages->listUsersMessages('me', $params);
    }
}

Now you can get the gmail messages by

$mails = (new Gmail())->messages()->list();

Tree Shaking Unused Google Services

There are more than 200 api services shipped together on google api. For tree shaking the unnecessary services, please follow instructions on google api client.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

License

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

skn036/laravel-google-client 适用场景与选型建议

skn036/laravel-google-client 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.07k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2024 年 09 月 07 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「Muhammad Sajedul Karim」 「laravel-google-client」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 skn036/laravel-google-client 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 skn036/laravel-google-client 我们能提供哪些服务?
定制开发 / 二次开发

基于 skn036/laravel-google-client 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.07k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 16
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-09-07