Skip to content

Commit 721a936

Browse files
author
Jordan Hall
committedFeb 19, 2018
Initial commit
1 parent da70cfb commit 721a936

File tree

4 files changed

+88
-1
lines changed

4 files changed

+88
-1
lines changed
 

‎.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/vendor/
2+
composer.lock

‎README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1-
# php-google-oauth-2-handler
1+
# PHP Google OAuth 2 Handler
2+
23
This package provides a handler to ease authentication with Google's OAuth 2 APIs.

‎composer.json

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"name": "rapidwebltd/php-google-oauth-2-handler",
3+
"description": "This package provides a handler to ease authentication with Google's OAuth 2 APIs.",
4+
"type": "library",
5+
"license": "LGPL-3.0-only",
6+
"authors": [
7+
{
8+
"name": "Jordan Hall",
9+
"email": "jordan.hall@rapidweb.biz"
10+
}
11+
],
12+
"require": {
13+
"google/apiclient": "^2.2",
14+
"guzzlehttp/guzzle": "^6.3"
15+
},
16+
"autoload": {
17+
"psr-4": {
18+
"RapidWeb\\GoogleOAuth2Handler\\": "./src/"
19+
}
20+
}
21+
}

‎src/GoogleOAuth2Handler.php

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
<?php
2+
3+
namespace RapidWeb\GoogleOAuth2Handler;
4+
5+
use GuzzleHttp\Psr7\Request;
6+
7+
class GoogleOAuth2Handler
8+
{
9+
private $clientId;
10+
private $clientSecret;
11+
private $scopes;
12+
private $refreshToken;
13+
private $client;
14+
15+
public $authUrl;
16+
17+
public function __construct($clientId, $clientSecret, $scopes, $refreshToken = '')
18+
{
19+
$this->clientId = $clientId;
20+
$this->clientSecret = $clientSecret;
21+
$this->scopes = $scopes;
22+
$this->refreshToken = $refreshToken;
23+
24+
$this->setupClient();
25+
}
26+
27+
private function setupClient()
28+
{
29+
$this->client = new \Google_Client();
30+
31+
$this->client->setClientId($this->clientId);
32+
$this->client->setClientSecret($this->clientSecret);
33+
$this->client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
34+
$this->client->setAccessType('offline');
35+
$this->client->setApprovalPrompt('force');
36+
37+
foreach($this->scopes as $scope) {
38+
$this->client->addScope($scope);
39+
}
40+
41+
if ($this->refreshToken) {
42+
$this->client->refreshToken($this->refreshToken);
43+
} else {
44+
$this->authUrl = $this->client->createAuthUrl();
45+
}
46+
}
47+
48+
public function getRefreshToken($authCode)
49+
{
50+
$this->client->authenticate($authCode);
51+
$accessToken = $this->client->getAccessToken();
52+
return $accessToken['refresh_token'];
53+
}
54+
55+
public function performRequest($method, $url, $body = null)
56+
{
57+
$httpClient = $this->client->authorize();
58+
$request = new Request($method, $url, [], $body);
59+
$response = $httpClient->send($request);
60+
return $response;
61+
}
62+
63+
}

0 commit comments

Comments
 (0)
Please sign in to comment.