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