dolibarr 21.0.0-alpha
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 *
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';
29use OAuth\Common\Storage\DoliStorage;
30use OAuth\Common\Consumer\Credentials;
31
32// Define $urlwithroot
33$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
34$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
35//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
36
37
38$action = GETPOST('action', 'aZ09');
39$backtourl = GETPOST('backtourl', 'alpha');
40$keyforprovider = GETPOST('keyforprovider', 'aZ09');
41if (empty($keyforprovider) && !empty($_SESSION["oauthkeyforproviderbeforeoauthjump"]) && (GETPOST('code') || $action == 'delete')) {
42 $keyforprovider = $_SESSION["oauthkeyforproviderbeforeoauthjump"];
43}
44
45
49$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
50//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
51//$currentUri->setQuery('');
52$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php');
53
54
60$serviceFactory = new \OAuth\ServiceFactory();
61$httpClient = new \OAuth\Common\Http\Client\CurlClient();
62// TODO Set options for proxy and timeout
63// $params=array('CURLXXX'=>value, ...)
64//$httpClient->setCurlParameters($params);
65$serviceFactory->setHttpClient($httpClient);
66
67// Dolibarr storage
68$storage = new DoliStorage($db, $conf, $keyforprovider);
69
70// Setup the credentials for the requests
71$keyforparamid = 'OAUTH_STRIPE_LIVE'.($keyforprovider ? '-'.$keyforprovider : '').'_ID';
72$keyforparamsecret = 'OAUTH_STRIPE_LIVE'.($keyforprovider ? '-'.$keyforprovider : '').'_SECRET';
73$credentials = new Credentials(
74 getDolGlobalString($keyforparamid),
75 getDolGlobalString($keyforparamsecret),
76 $currentUri->getAbsoluteUri()
77);
78
79$requestedpermissionsarray = array();
80if (GETPOST('state')) {
81 $requestedpermissionsarray = explode(',', GETPOST('state')); // Example: 'userinfo_email,userinfo_profile,cloud_print'. 'state' parameter is standard to retrieve some parameters back
82}
83/*if ($action != 'delete' && empty($requestedpermissionsarray))
84{
85 print 'Error, parameter state is not defined';
86 exit;
87}*/
88//var_dump($requestedpermissionsarray);exit;
89
90$apiService = null;
91$state = null;
92// Instantiate the Api service using the credentials, http client and storage mechanism for the token
93//$apiService = $serviceFactory->createService('StripeTest', $credentials, $storage, $requestedpermissionsarray);
94
95$servicesuffix = ($keyforprovider ? '-'.$keyforprovider : '');
96$sql = "INSERT INTO ".MAIN_DB_PREFIX."oauth_token SET service = 'StripeLive".$db->escape($servicesuffix)."', entity = ".((int) $conf->entity);
97$db->query($sql);
98
99// access type needed to have oauth provider refreshing token
100//$apiService->setAccessType('offline');
101
102$langs->load("oauth");
103
104if (!getDolGlobalString($keyforparamid)) {
105 accessforbidden('Setup of service is not complete. Customer ID is missing');
106}
107if (!getDolGlobalString($keyforparamsecret)) {
108 accessforbidden('Setup of service is not complete. Secret key is missing');
109}
110
111
112/*
113 * Actions
114 */
115
116if ($action == 'delete' && (!empty($user->admin) || $user->id == GETPOSTINT('userid'))) {
117 $storage->userid = GETPOSTINT('userid');
118 $storage->clearToken('StripeLive');
119
120 setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
121
122 if (empty($backtourl)) {
123 $backtourl = DOL_URL_ROOT.'/';
124 }
125
126 header('Location: '.$backtourl);
127 exit();
128}
129
130if (GETPOST('code')) { // We are coming from oauth provider page
131 // We should have
132 //$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
133
134 dol_syslog("We are coming from the oauth provider page code=".dol_trunc(GETPOST('code'), 5));
135
136 // This was a callback request from service, get the token
137 if ($apiService === null) {
138 dol_syslog("No API Service", LOG_ERR);
139 } else {
140 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
141 try {
142 //var_dump($state);
143 //var_dump($apiService); // OAuth\OAuth2\Service\Stripe
144
145 //$token = $apiService->requestAccessToken(GETPOST('code'), $state);
146 $token = $apiService->requestAccessToken(GETPOST('code'));
147 // Stripe is a service that does not need state to be stored as second parameter of requestAccessToken
148
149 setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
150
151 $backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
152 unset($_SESSION["backtourlsavedbeforeoauthjump"]);
153
154 header('Location: '.$backtourl);
155 exit();
156 } catch (Exception $e) {
157 print $e->getMessage();
158 }
159 }
160} else { // If entry on page with no parameter, we arrive here
161 $_SESSION["backtourlsavedbeforeoauthjump"] = $backtourl;
162 $_SESSION["oauthkeyforproviderbeforeoauthjump"] = $keyforprovider;
163 $_SESSION['oauthstateanticsrf'] = $state;
164
165 // This may create record into oauth_state before the header redirect.
166 // Creation of record with state in this tables depend on the Provider used (see its constructor).
167 if (GETPOST('state')) {
168 if ($apiService === null) {
169 dol_syslog("No API Service", LOG_ERR);
170 } else {
171 $url = $apiService->getAuthorizationUri(array('state' => GETPOST('state')));
172 }
173 } else {
174 //$url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
175 //https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_AX27ut70tJ1j6eyFCV3ObEXhNOo2jY6V&scope=read_write
176 $url = 'https://connect.stripe.com/oauth/authorize?response_type=code&client_id=' . getDolGlobalString($keyforparamid).'&scope=read_write';
177 }
178
179 if (empty($url)) {
180 $url = DOL_URL_ROOT.'/';
181 }
182
183 // we go on oauth provider authorization page
184 header('Location: '.$url);
185 exit();
186}
187
188
189/*
190 * View
191 */
192
193// No view at all, just actions
194
195$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.
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.