dolibarr 21.0.0-beta
stripelive_oauthcallback.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2022 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2019 Thibault FOUCART <support@ptibogxiv.net>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
27// Load Dolibarr environment
28require '../../../main.inc.php';
29require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
39use OAuth\Common\Storage\DoliStorage;
40use OAuth\Common\Consumer\Credentials;
41
42// Define $urlwithroot
43$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
44$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
45//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
46
47
48$action = GETPOST('action', 'aZ09');
49$backtourl = GETPOST('backtourl', 'alpha');
50$keyforprovider = GETPOST('keyforprovider', 'aZ09');
51if (empty($keyforprovider) && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
52 $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
53}
54
55
59$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
60//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
61//$currentUri->setQuery('');
62$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php');
63
64
70$serviceFactory = new \OAuth\ServiceFactory();
71$httpClient = new \OAuth\Common\Http\Client\CurlClient();
72// TODO Set options for proxy and timeout
73// $params=array('CURLXXX'=>value, ...)
74//$httpClient->setCurlParameters($params);
75$serviceFactory->setHttpClient($httpClient);
76
77// Dolibarr storage
78$storage = new DoliStorage($db, $conf, $keyforprovider);
79
80// Setup the credentials for the requests
81$keyforparamid = 'OAUTH_STRIPELIVE'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
82$keyforparamsecret = 'OAUTH_STRIPELIVE'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
83$credentials = new Credentials(
84 getDolGlobalString($keyforparamid),
85 getDolGlobalString($keyforparamsecret),
86 $currentUri->getAbsoluteUri()
87);
88
89$requestedpermissionsarray = array();
90if (GETPOST('state')) {
91 $requestedpermissionsarray = explode(',', GETPOST('state')); // Example: 'userinfo_email,userinfo_profile,cloud_print'. 'state' parameter is standard to retrieve some parameters back
92}
93/*if ($action != 'delete' && empty($requestedpermissionsarray))
94{
95 print 'Error, parameter state is not defined';
96 exit;
97}*/
98//var_dump($requestedpermissionsarray);exit;
99
100$apiService = null;
101$state = null;
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 = 'StripeLive".$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('StripeLive');
129
130 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
131
132 if (empty($backtourl)) {
133 $backtourl = DOL_URL_ROOT.'/';
134 }
135
136 header('Location: '.$backtourl);
137 exit();
138}
139
140if (GETPOST('code')) { // We are coming from oauth provider page
141 // We should have
142 //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
143
144 dol_syslog(basename(__FILE__)." We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5));
145
146 // This was a callback request from service, get the token
147 if ($apiService === null) {
148 dol_syslog("No API Service", LOG_ERR);
149 } else {
150 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
151 try {
152 //var_dump($state);
153 //var_dump($apiService); // OAuth\OAuth2\Service\Stripe
154
155 //$token = $apiService->requestAccessToken(GETPOST('code'), $state);
156 $token = $apiService->requestAccessToken(GETPOST('code'));
157 // Stripe is a service that does not need state to be stored as second parameter of requestAccessToken
158
159 setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
160
161 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
162 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
163
164 header('Location: '.$backtourl);
165 exit();
166 } catch (Exception $e) {
167 print $e->getMessage();
168 }
169 }
170} else { // If entry on page with no parameter, we arrive here
171 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
172 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
173 $_SESSION['oauthstateanticsrf'] = $state;
174
175 // This may create record into oauth_state before the header redirect.
176 // Creation of record with state in this tables depend on the Provider used (see its constructor).
177 if (GETPOST('state')) {
178 if ($apiService === null) {
179 dol_syslog("No API Service", LOG_ERR);
180 } else {
181 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
182 $url = $apiService->getAuthorizationUri(array('state' => GETPOST('state')));
183 }
184 } else {
185 //$url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
186 //https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_AX27ut70tJ1j6eyFCV3ObEXhNOo2jY6V&scope=read_write
187 $url = 'https://connect.stripe.com/oauth/authorize?response_type=code&client_id=' . getDolGlobalString($keyforparamid).'&scope=read_write';
188 }
189
190 if (empty($url)) {
191 $url = DOL_URL_ROOT.'/';
192 }
193
194 // we go on oauth provider authorization page
195 header('Location: '.$url);
196 exit();
197}
198
199
200/*
201 * View
202 */
203
204// No view at all, just actions
205
206$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.