stripetest_oauthcallback.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. <?php
  2. /* Copyright (C) 2022 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2015 Frederic France <frederic.france@free.fr>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file htdocs/core/modules/oauth/stripetest_oauthcallback.php
  20. * \ingroup oauth
  21. * \brief Page to get oauth callback
  22. */
  23. // Load Dolibarr environment
  24. require '../../../main.inc.php';
  25. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  26. use OAuth\Common\Storage\DoliStorage;
  27. use OAuth\Common\Consumer\Credentials;
  28. use OAuth\OAuth2\Service\GitHub;
  29. // Define $urlwithroot
  30. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  31. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  32. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  33. $action = GETPOST('action', 'aZ09');
  34. $backtourl = GETPOST('backtourl', 'alpha');
  35. $keyforprovider = GETPOST('keyforprovider', 'aZ09');
  36. if (empty($keyforprovider) && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
  37. $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
  38. }
  39. /**
  40. * Create a new instance of the URI class with the current URI, stripping the query string
  41. */
  42. $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
  43. //$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
  44. //$currentUri->setQuery('');
  45. $currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php');
  46. /**
  47. * Load the credential for the service
  48. */
  49. /** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
  50. $serviceFactory = new \OAuth\ServiceFactory();
  51. $httpClient = new \OAuth\Common\Http\Client\CurlClient();
  52. // TODO Set options for proxy and timeout
  53. // $params=array('CURLXXX'=>value, ...)
  54. //$httpClient->setCurlParameters($params);
  55. $serviceFactory->setHttpClient($httpClient);
  56. // Dolibarr storage
  57. $storage = new DoliStorage($db, $conf, $keyforprovider);
  58. // Setup the credentials for the requests
  59. $keyforparamid = 'OAUTH_STRIPE_TEST'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
  60. $keyforparamsecret = 'OAUTH_STRIPE_TEST'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
  61. $credentials = new Credentials(
  62. getDolGlobalString($keyforparamid),
  63. getDolGlobalString($keyforparamsecret),
  64. $currentUri->getAbsoluteUri()
  65. );
  66. $requestedpermissionsarray = array();
  67. if (GETPOST('state')) {
  68. $requestedpermissionsarray = explode(',', GETPOST('state')); // Example: 'userinfo_email,userinfo_profile,cloud_print'. 'state' parameter is standard to retrieve some parameters back
  69. }
  70. /*if ($action != 'delete' && empty($requestedpermissionsarray))
  71. {
  72. print 'Error, parameter state is not defined';
  73. exit;
  74. }*/
  75. //var_dump($requestedpermissionsarray);exit;
  76. // Instantiate the Api service using the credentials, http client and storage mechanism for the token
  77. //$apiService = $serviceFactory->createService('StripeTest', $credentials, $storage, $requestedpermissionsarray);
  78. $servicesuffix = ($keyforprovider ? '-'.$keyforprovider : '');
  79. $sql = "INSERT INTO ".MAIN_DB_PREFIX."oauth_token SET service = 'StripeTest".$db->escape($servicesuffix)."', entity = ".((int) $conf->entity);
  80. $db->query($sql);
  81. // access type needed to have oauth provider refreshing token
  82. //$apiService->setAccessType('offline');
  83. $langs->load("oauth");
  84. if (!getDolGlobalString($keyforparamid)) {
  85. accessforbidden('Setup of service is not complete. Customer ID is missing');
  86. }
  87. if (!getDolGlobalString($keyforparamsecret)) {
  88. accessforbidden('Setup of service is not complete. Secret key is missing');
  89. }
  90. /*
  91. * Actions
  92. */
  93. if ($action == 'delete') {
  94. $storage->clearToken('StripeTest');
  95. setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
  96. header('Location: '.$backtourl);
  97. exit();
  98. }
  99. if (GETPOST('code')) { // We are coming from oauth provider page
  100. // We should have
  101. //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
  102. dol_syslog("We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5));
  103. // This was a callback request from service, get the token
  104. try {
  105. //var_dump($state);
  106. //var_dump($apiService); // OAuth\OAuth2\Service\Stripe
  107. //$token = $apiService->requestAccessToken(GETPOST('code'), $state);
  108. $token = $apiService->requestAccessToken(GETPOST('code'));
  109. // Stripe is a service that does not need state to be stored as second paramater of requestAccessToken
  110. setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
  111. $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
  112. unset($_SESSION["backtourlsavedbeforeoauthjump"]);
  113. header('Location: '.$backtourl);
  114. exit();
  115. } catch (Exception $e) {
  116. print $e->getMessage();
  117. }
  118. } else // If entry on page with no parameter, we arrive here
  119. {
  120. $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
  121. $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
  122. $_SESSION['oauthstateanticsrf'] = $state;
  123. // This may create record into oauth_state before the header redirect.
  124. // Creation of record with state in this tables depend on the Provider used (see its constructor).
  125. if (GETPOST('state')) {
  126. $url = $apiService->getAuthorizationUri(array('state'=>GETPOST('state')));
  127. } else {
  128. //$url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
  129. //https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_AX27ut70tJ1j6eyFCV3ObEXhNOo2jY6V&scope=read_write
  130. $url = 'https://connect.stripe.com/oauth/authorize?response_type=code&client_id='.$conf->global->$keyforparamid.'&scope=read_write';
  131. }
  132. // we go on oauth provider authorization page
  133. header('Location: '.$url);
  134. exit();
  135. }
  136. /*
  137. * View
  138. */
  139. // No view at all, just actions
  140. $db->close();