happyr/google-api-bundle

PHP Google API 客户端库的 Symfony2 包装器

安装次数: 180,099

依赖者: 3

建议者: 0

安全性: 0

星标: 48

关注者: 6

分支: 29

开放问题: 7

类型:symfony-bundle

2.3.0 2018-09-15 04:07 UTC

This package is auto-updated.

Last update: 2024-08-25 06:27:09 UTC


README

一个用于与 Google API 通信的 symfony2 扩展包。此扩展包是 google apiclient 的 Symfony2 包装器。有一些服务尚未实现。请提交 PR,我很乐意合并。

安装

步骤 1: 使用 Composer

使用 Composer 安装它!

// composer.json
{
    // ...
    require: {
        // ...
        "happyr/google-api-bundle": "~2.1",
    }
}

然后,您可以通过在您的 composer.json 文件所在的目录中运行 Composer 的 update 命令来安装新依赖项。

$ php composer.phar update

步骤 2: 注册扩展包

为了将扩展包注册到您的内核

<?php

// in AppKernel::registerBundles()
$bundles = array(
    // ...
    new HappyR\Google\ApiBundle\HappyRGoogleApiBundle(),
    // ...
);

步骤 3: 配置扩展包

# app/config/config.yml
# you will get these parameters form https://code.google.com/apis/console/"
happy_r_google_api:
  application_name: MySite
  oauth2_client_id:
  oauth2_client_secret:
  oauth2_redirect_uri:
  developer_key:
  site_name: mysite.com

基本用法

步骤 1: 创建控制器

创建一个控制器,包含 authenticateredirect 方法。

<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;

class GoogleOAuthController extends Controller
{
  /**
   * @Route("/oauth/google/auth")
   */
  public function getAuthenticationCodeAction()
  {
  }

  /**
   * @Route("/oauth/google/redirect")
   */
  public function getAccessCodeRedirectAction(Request $request)
  {
  }
}

步骤 2: 获取访问代码

设置您应用的所需权限范围,并将用户重定向到完成 OAuth 请求的部分。

// ...

  private $accessScope = [
    \Google_Service_Calendar::CALENDAR
  ];

  /**
   * @Route("/oauth/google/auth")
   */
  public function getAuthenticationCodeAction()
  {
    $client = $this->container->get('happyr.google.api.client');

    // Determine the level of access your application needs
    $client->getGoogleClient()->setScopes($this->accessScope);

    // Send the user to complete their part of the OAuth
    return $this->redirect($client->createAuthUrl());
  }

 // ...

步骤 3: 处理重定向

确定是否返回了访问代码。如果有访问代码,则使用客户端的 authenticate 方法将其交换为访问令牌。

// ...

  private $accessScope = [
    \Google_Service_Calendar::CALENDAR
  ];

// ...

  /**
   * @Route("/oauth/google/redirect")
   */
  public function getAccessCodeRedirectAction(Request $request)
  {
    if($request->query->get('code'))
    {
      $code = $request->query->get('code');

      $client = $this->container->get('happyr.google.api.client');
      $client->getGoogleClient()->setScopes($this->accessScope);
      $client->authenticate($code);

      $accessToken = $client->getGoogleClient()->getAccessToken();

      // TODO - Store the token, etc...
    } else {
      $error = $request->query->get('error');
      // TODO - Handle the error
    }
  }

// ...

如果成功,响应应包括 access_tokenexpires_intoken_typecreated