dolibarr  16.0.5
stripelive_oauthcallback.php
Go to the documentation of this file.
1 <?php
2 /*
3  * Copyright (C) 2019 Thibault FOUCART <support@ptibogxiv.net>
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 
25 require '../../../main.inc.php';
26 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
27 use OAuth\Common\Storage\DoliStorage;
28 use OAuth\Common\Consumer\Credentials;
29 use OAuth\OAuth2\Service\GitHub;
30 
31 // Define $urlwithroot
32 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
33 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
34 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
35 
36 
37 $action = GETPOST('action', 'aZ09');
38 $backtourl = GETPOST('backtourl', 'alpha');
39 $keyforprovider = GETPOST('keyforprovider', 'aZ09');
40 if (empty($keyforprovider) && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
41  $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
42 }
43 
44 
48 $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
49 //$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
50 //$currentUri->setQuery('');
51 $currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php');
52 
53 
59 $serviceFactory = new \OAuth\ServiceFactory();
60 $httpClient = new \OAuth\Common\Http\Client\CurlClient();
61 // TODO Set options for proxy and timeout
62 // $params=array('CURLXXX'=>value, ...)
63 //$httpClient->setCurlParameters($params);
64 $serviceFactory->setHttpClient($httpClient);
65 
66 // Dolibarr storage
67 $storage = new DoliStorage($db, $conf);
68 
69 // Setup the credentials for the requests
70 $keyforparamid = 'OAUTH_STRIPE_LIVE'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
71 $keyforparamsecret = 'OAUTH_STRIPE_LIVE'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
72 $credentials = new Credentials(
73  getDolGlobalString($keyforparamid),
74  getDolGlobalString($keyforparamsecret),
75  $currentUri->getAbsoluteUri()
76 );
77 
78 $requestedpermissionsarray = array();
79 if (GETPOST('state')) {
80  $requestedpermissionsarray = explode(',', GETPOST('state')); // Example: 'userinfo_email,userinfo_profile,cloud_print'. 'state' parameter is standard to retrieve some parameters back
81 }
82 /*if ($action != 'delete' && empty($requestedpermissionsarray))
83 {
84  print 'Error, parameter state is not defined';
85  exit;
86 }*/
87 //var_dump($requestedpermissionsarray);exit;
88 
89 // Instantiate the Api service using the credentials, http client and storage mechanism for the token
90 //$apiService = $serviceFactory->createService('StripeTest', $credentials, $storage, $requestedpermissionsarray);
91 
92 $servicesuffix = ($keyforprovider ? '-'.$keyforprovider : '');
93 $sql = "INSERT INTO ".MAIN_DB_PREFIX."oauth_token SET service = 'StripeLive".$db->escape($servicesuffix)."', entity = ".((int) $conf->entity);
94 $db->query($sql);
95 
96 // access type needed to have oauth provider refreshing token
97 //$apiService->setAccessType('offline');
98 
99 $langs->load("oauth");
100 
101 if (!getDolGlobalString($keyforparamid)) {
102  accessforbidden('Setup of service is not complete. Customer ID is missing');
103 }
104 if (!getDolGlobalString($keyforparamsecret)) {
105  accessforbidden('Setup of service is not complete. Secret key is missing');
106 }
107 
108 
109 /*
110  * Actions
111  */
112 
113 
114 if ($action == 'delete') {
115  $storage->clearToken('StripeLive');
116 
117  setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
118 
119  header('Location: '.$backtourl);
120  exit();
121 }
122 
123 if (!empty($_GET['code'])) { // We are coming from oauth provider page
124  // We should have
125  //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
126 
127  dol_syslog("We are coming from the oauth provider page");
128  //llxHeader('',$langs->trans("OAuthSetup"));
129 
130  //$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
131  //print load_fiche_titre($langs->trans("OAuthSetup"),$linkback,'title_setup');
132 
133  //print dol_get_fiche_head();
134  // retrieve the CSRF state parameter
135  $state = isset($_GET['state']) ? $_GET['state'] : null;
136  //print '<table>';
137 
138  // This was a callback request from service, get the token
139  try {
140  //var_dump($_GET['code']);
141  //var_dump($state);
142  //var_dump($apiService); // OAuth\OAuth2\Service\GitHub
143 
144  //$token = $apiService->requestAccessToken($_GET['code'], $state);
145  $token = $apiService->requestAccessToken($_GET['code']);
146  // Github is a service that does not need state to be stored.
147  // Into constructor of GitHub, the call
148  // parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri)
149  // has not the ending parameter to true like the Google class constructor.
150 
151  setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
152 
153  $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
154  unset($_SESSION["backtourlsavedbeforeoauthjump"]);
155 
156  header('Location: '.$backtourl);
157  exit();
158  } catch (Exception $e) {
159  print $e->getMessage();
160  }
161 } else // If entry on page with no parameter, we arrive here
162 {
163  $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
164  $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
165  $_SESSION['oauthstateanticsrf'] = $state;
166 
167  // This may create record into oauth_state before the header redirect.
168  // Creation of record with state in this tables depend on the Provider used (see its constructor).
169  if (GETPOST('state')) {
170  $url = $apiService->getAuthorizationUri(array('state'=>GETPOST('state')));
171  } else {
172  //$url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
173  //https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_AX27ut70tJ1j6eyFCV3ObEXhNOo2jY6V&scope=read_write
174  $url = 'https://connect.stripe.com/oauth/authorize?response_type=code&client_id='.$conf->global->$keyforparamid.'&scope=read_write';
175  }
176 
177  // we go on oauth provider authorization page
178  header('Location: '.$url);
179  exit();
180 }
181 
182 
183 /*
184  * View
185  */
186 
187 // No view at all, just actions
188 
189 $db->close();
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:484
$uriFactory
if(empty($keyforprovider) &&!empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) &&(GETPOST('code')|| $action=='delete')) $uriFactory
Create a new instance of the URI class with the current URI, stripping the query string.
Definition: stripelive_oauthcallback.php:48
Exception
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
getDolGlobalString
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:80
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
accessforbidden
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
Definition: security.lib.php:933