dolibarr 21.0.0-beta
stripetest_oauthcallback.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2022 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2015-2024 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
26// Load Dolibarr environment
27require '../../../main.inc.php';
28require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
38use OAuth\Common\Storage\DoliStorage;
39use OAuth\Common\Consumer\Credentials;
40
41// Define $urlwithroot
42$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
43$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
44//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
45
46
47$action = GETPOST('action', 'aZ09');
48$backtourl = GETPOST('backtourl', 'alpha');
49$keyforprovider = GETPOST('keyforprovider', 'aZ09');
50if (empty($keyforprovider) && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
51 $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
52}
53
54
58$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
59//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
60//$currentUri->setQuery('');
61$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php');
62
63$state = null;
64$apiService = null;
65
66
72$serviceFactory = new \OAuth\ServiceFactory();
73$httpClient = new \OAuth\Common\Http\Client\CurlClient();
74// TODO Set options for proxy and timeout
75// $params=array('CURLXXX'=>value, ...)
76//$httpClient->setCurlParameters($params);
77$serviceFactory->setHttpClient($httpClient);
78
79// Dolibarr storage
80$storage = new DoliStorage($db, $conf, $keyforprovider);
81
82// Setup the credentials for the requests
83$keyforparamid = 'OAUTH_STRIPETEST'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
84$keyforparamsecret = 'OAUTH_STRIPETEST'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
85$credentials = new Credentials(
86 getDolGlobalString($keyforparamid),
87 getDolGlobalString($keyforparamsecret),
88 $currentUri->getAbsoluteUri()
89);
90
91$requestedpermissionsarray = array();
92if (GETPOST('state')) {
93 $requestedpermissionsarray = explode(',', GETPOST('state')); // Example: 'userinfo_email,userinfo_profile,cloud_print'. 'state' parameter is standard to retrieve some parameters back
94}
95/*if ($action != 'delete' && empty($requestedpermissionsarray))
96{
97 print 'Error, parameter state is not defined';
98 exit;
99}*/
100//var_dump($requestedpermissionsarray);exit;
101
102// Instantiate the Api service using the credentials, http client and storage mechanism for the token
103//$apiService = $serviceFactory->createService('StripeTest', $credentials, $storage, $requestedpermissionsarray);
104
105$servicesuffix = ($keyforprovider ? '-'.$keyforprovider : '');
106$sql = "INSERT INTO ".MAIN_DB_PREFIX."oauth_token SET service = 'StripeTest".$db->escape($servicesuffix)."', entity = ".((int) $conf->entity);
107$db->query($sql);
108
109// access type needed to have oauth provider refreshing token
110//$apiService->setAccessType('offline');
111
112$langs->load("oauth");
113
114if (!getDolGlobalString($keyforparamid)) {
115 accessforbidden('Setup of service is not complete. Customer ID is missing');
116}
117if (!getDolGlobalString($keyforparamsecret)) {
118 accessforbidden('Setup of service is not complete. Secret key is missing');
119}
120
121
122/*
123 * Actions
124 */
125
126if ($action == 'delete' && (!empty($user->admin) || $user->id == GETPOSTINT('userid'))) {
127 $storage->userid = GETPOSTINT('userid');
128 $storage->clearToken('StripeTest');
129
130 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
131
132 header('Location: '.$backtourl);
133 exit();
134}
135
136if (GETPOST('code')) { // We are coming from oauth provider page
137 // We should have
138 //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
139
140 dol_syslog(basename(__FILE__)." We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5));
141
142 // This was a callback request from service, get the token
143 try {
144 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
145 //var_dump($state);
146 //var_dump($apiService); // OAuth\OAuth2\Service\Stripe
147
148 //$token = $apiService->requestAccessToken(GETPOST('code'), $state);
149 $token = $apiService->requestAccessToken(GETPOST('code'));
150 // Stripe is a service that does not need state to be stored as second parameter of requestAccessToken
151
152 setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
153
154 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
155 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
156
157 if (empty($backtourl)) {
158 $backtourl = DOL_URL_ROOT.'/';
159 }
160
161 header('Location: '.$backtourl);
162 exit();
163 } catch (Exception $e) {
164 print $e->getMessage();
165 }
166} else { // If entry on page with no parameter, we arrive here
167 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
168 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
169 $_SESSION['oauthstateanticsrf'] = $state;
170
171 // This may create record into oauth_state before the header redirect.
172 // Creation of record with state in this tables depend on the Provider used (see its constructor).
173 if (GETPOST('state')) {
174 if (is_object($apiService)) { // @phpstan-ignore-line
175 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
176 $url = $apiService->getAuthorizationUri(array('state' => GETPOST('state')));
177 } else {
178 $url = null;
179 }
180 } else {
181 //$url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
182 //https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_AX27ut70tJ1j6eyFCV3ObEXhNOo2jY6V&scope=read_write
183 $url = 'https://connect.stripe.com/oauth/authorize?response_type=code&client_id=' . getDolGlobalString($keyforparamid).'&scope=read_write';
184 }
185
186 if (empty($url)) {
187 $url = DOL_URL_ROOT.'/';
188 }
189
190 // we go on oauth provider authorization page
191 header('Location: '.$url);
192 exit();
193}
194
195
196/*
197 * View
198 */
199
200// No view at all, just actions
201
202$db->close();
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
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.