Advertisement
Guest User

Untitled

a guest
Jul 29th, 2014
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. function exchangeCode($authorizationCode) {
  2. try {
  3. $client = new Google_Client();
  4.  
  5. $client->setClientId(self::$clientId);
  6. $client->setClientSecret(self::$clientSacred);
  7. $client->setRedirectUri(self::getRedirectURI());
  8. $_GET['code'] = $authorizationCode;
  9. return $client->authenticate();
  10. } catch (Google_AuthException $e) {
  11. echo 'An Google_AuthException occurred: ' . $e->getMessage();
  12. throw new CodeExchangeException(null);
  13. }
  14. }
  15.  
  16. function getCredentials($authorizationCode, $state='') {
  17. $emailAddress = '';
  18. try {
  19. $credentials = self::exchangeCode($authorizationCode);
  20.  
  21. $credentialsArray = json_decode($credentials, true);
  22. if (isset($credentialsArray['refresh_token'])) {
  23. self::storeCredentials($credentials);
  24. return $credentials;
  25. } else {
  26. $credentials = self::getStoredCredentials();
  27. $credentialsArray = json_decode($credentials, true);
  28. if ($credentials != null &&
  29. isset($credentialsArray['refresh_token'])) {
  30. return $credentials;
  31. }
  32. }
  33. } catch (CodeExchangeException $e) {
  34. print 'An CodeExchangeException occurred during code exchange.';
  35. $e->setAuthorizationUrl(self::getAuthorizationUrl($emailAddress, $state));
  36. throw $e;
  37. } catch (NoUserIdException $e) {
  38. print 'No e-mail address could be retrieved.';
  39. }
  40.  
  41. $authorizationUrl = self::getAuthorizationUrl($emailAddress, $state);
  42. throw new NoRefreshTokenException($authorizationUrl);
  43. }
  44.  
  45. function buildService($credentials) {
  46. $apiClient = new Google_Client();
  47. $apiClient->setUseObjects(true);
  48. $apiClient->setAccessToken($credentials);
  49.  
  50. return new Google_DriveService($apiClient);
  51. }
  52.  
  53.  
  54. function test()
  55. {
  56. $credentials = self::getStoredCredentials();
  57. if ( empty($credentials) )
  58. {
  59. if (!isset($_GET["code"]))
  60. {
  61. header("location:".self::getAuthorizationUrl("xxx@gmail.com", ''));
  62. die();
  63. }
  64. $credentials = self::getCredentials($_GET["code"]);
  65. echo "NEW: ".$credentials;
  66. }
  67. else
  68. {
  69. echo "STORED: ".$credentials;
  70. }
  71.  
  72. $service = self::buildService($credentials);
  73.  
  74.  
  75.  
  76.  
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement