dolibarr  13.0.2
stripetest_oauthcallback.php
Go to the documentation of this file.
1 <?php
2 /*
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 
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 
38 $action = GETPOST('action', 'aZ09');
39 $backtourl = GETPOST('backtourl', 'alpha');
40 
41 
45 $uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
46 //$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
47 //$currentUri->setQuery('');
48 $currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php');
49 
50 
56 $serviceFactory = new \OAuth\ServiceFactory();
57 $httpClient = new \OAuth\Common\Http\Client\CurlClient();
58 // TODO Set options for proxy and timeout
59 // $params=array('CURLXXX'=>value, ...)
60 //$httpClient->setCurlParameters($params);
61 $serviceFactory->setHttpClient($httpClient);
62 
63 // Dolibarr storage
64 $storage = new DoliStorage($db, $conf);
65 
66 // Setup the credentials for the requests
67 $credentials = new Credentials(
68  $conf->global->OAUTH_STRIPE_TEST_ID,
69  $conf->global->STRIPE_TEST_SECRET_KEY,
70  $currentUri->getAbsoluteUri()
71 );
72 
73 $requestedpermissionsarray = array();
74 if (GETPOST('state')) $requestedpermissionsarray = explode(',', GETPOST('state')); // Example: 'userinfo_email,userinfo_profile,cloud_print'. 'state' parameter is standard to retrieve some parameters back
75 /*if ($action != 'delete' && empty($requestedpermissionsarray))
76 {
77  print 'Error, parameter state is not defined';
78  exit;
79 }*/
80 //var_dump($requestedpermissionsarray);exit;
81 
82 // Instantiate the Api service using the credentials, http client and storage mechanism for the token
83 //$apiService = $serviceFactory->createService('StripeTest', $credentials, $storage, $requestedpermissionsarray);
84 
85 $sql = "INSERT INTO ".MAIN_DB_PREFIX."oauth_token set service='StripeTest', entity=".$conf->entity;
86 $db->query($sql);
87 
88 // access type needed to have oauth provider refreshing token
89 //$apiService->setAccessType('offline');
90 
91 $langs->load("oauth");
92 
93 
94 /*
95  * Actions
96  */
97 
98 
99 if ($action == 'delete')
100 {
101  $storage->clearToken('StripeTest');
102 
103  setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
104 
105  header('Location: '.$backtourl);
106  exit();
107 }
108 
109 if (!empty($_GET['code'])) // We are coming from oauth provider page
110 {
111  // We should have
112  //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
113 
114  dol_syslog("We are coming from the oauth provider page");
115  //llxHeader('',$langs->trans("OAuthSetup"));
116 
117  //$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
118  //print load_fiche_titre($langs->trans("OAuthSetup"),$linkback,'title_setup');
119 
120  //print dol_get_fiche_head();
121  // retrieve the CSRF state parameter
122  $state = isset($_GET['state']) ? $_GET['state'] : null;
123  //print '<table>';
124 
125  // This was a callback request from service, get the token
126  try {
127  //var_dump($_GET['code']);
128  //var_dump($state);
129  //var_dump($apiService); // OAuth\OAuth2\Service\GitHub
130 
131  //$token = $apiService->requestAccessToken($_GET['code'], $state);
132  $token = $apiService->requestAccessToken($_GET['code']);
133  // Github is a service that does not need state to be stored.
134  // Into constructor of GitHub, the call
135  // parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri)
136  // has not the ending parameter to true like the Google class constructor.
137 
138  setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
139 
140  $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
141  unset($_SESSION["backtourlsavedbeforeoauthjump"]);
142 
143  header('Location: '.$backtourl);
144  exit();
145  } catch (Exception $e) {
146  print $e->getMessage();
147  }
148 } else // If entry on page with no parameter, we arrive here
149 {
150  $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
151 
152  // This may create record into oauth_state before the header redirect.
153  // Creation of record with state in this tables depend on the Provider used (see its constructor).
154  if (GETPOST('state'))
155  {
156  $url = $apiService->getAuthorizationUri(array('state'=>GETPOST('state')));
157  } else {
158  //$url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
159  //https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_AX27ut70tJ1j6eyFCV3ObEXhNOo2jY6V&scope=read_write
160  $url = 'https://connect.stripe.com/oauth/authorize?response_type=code&client_id='.$conf->global->OAUTH_STRIPE_TEST_ID.'&scope=read_write';
161  }
162 
163  // we go on oauth provider authorization page
164  header('Location: '.$url);
165  exit();
166 }
167 
168 
169 /*
170  * View
171  */
172 
173 // No view at all, just actions
174 
175 $db->close();
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
$uriFactory
Create a new instance of the URI class with the current URI, stripping the query string.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
print
Draft customers invoices.
Definition: index.php:89