Enhance OAuth module to store the stripe account in llx_oauth_token

This commit is contained in:
Laurent Destailleur 2018-03-08 19:50:41 +01:00
parent 88e47e11a4
commit 235db1f405
13 changed files with 728 additions and 465 deletions

View File

@ -95,6 +95,7 @@ print '<table class="noborder" width="100%">';
$i=0;
// $list is defined into oauth.lib.php
foreach ($list as $key)
{
$supported=0;

View File

@ -141,13 +141,27 @@ if ($mode == 'setup' && $user->admin)
$urltodelete=$urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
$urltocheckperms='https://github.com/settings/applications/';
}
if ($key[0] == 'OAUTH_GOOGLE_NAME')
elseif ($key[0] == 'OAUTH_GOOGLE_NAME')
{
$OAUTH_SERVICENAME='Google';
$urltorenew=$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?state=userinfo_email,userinfo_profile,cloud_print&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
$urltodelete=$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
$urltocheckperms='https://security.google.com/settings/security/permissions';
}
elseif ($key[0] == 'OAUTH_STRIPE_TEST_NAME')
{
$OAUTH_SERVICENAME='StripeTest';
$urltorenew=$urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php');
$urltodelete='';
$urltocheckperms='';
}
else
{
$urltorenew='';
$urltodelete='';
$urltocheckperms='';
}
// Show value of token
$tokenobj=null;
@ -204,7 +218,6 @@ if ($mode == 'setup' && $user->admin)
print '<table class="noborder" width="100%">'."\n";
$var=false;
print '<tr class="liste_titre">';
print '<th class="titlefieldcreate">'.$langs->trans($key[0]).'</th>';
print '<th></th>';
@ -222,7 +235,6 @@ if ($mode == 'setup' && $user->admin)
print '</td>';
print '</tr>'."\n";
$var = ! $var;
print '<tr class="oddeven">';
print '<td'.($key['required']?' class="required"':'').'>';
//var_dump($key);
@ -237,19 +249,21 @@ if ($mode == 'setup' && $user->admin)
if (is_object($tokenobj))
{
//test on $storage->hasAccessToken($OAUTH_SERVICENAME) ?
print '<a class="button" href="'.$urltodelete.'">'.$langs->trans('DeleteAccess').'</a><br><br>';
print '<a class="button" href="'.$urltodelete.'">'.$langs->trans('DeleteAccess').'</a><br>';
}
// Request remote token
print '<a class="button" href="'.$urltorenew.'">'.$langs->trans('RequestAccess').'</a><br><br>';
if ($urltorenew)
{
print '<a class="button" href="'.$urltorenew.'">'.$langs->trans('RequestAccess').'</a><br>';
}
// Check remote access
if ($urltocheckperms)
{
print $langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': <a href="'.$urltocheckperms.'" target="_'.strtolower($OAUTH_SERVICENAME).'">'.$urltocheckperms.'</a>';
print '<br>'.$langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': <a href="'.$urltocheckperms.'" target="_'.strtolower($OAUTH_SERVICENAME).'">'.$urltocheckperms.'</a>';
}
print '</td>';
print '</tr>';
$var = ! $var;
print '<tr class="oddeven">';
print '<td'.($key['required']?' class="required"':'').'>';
//var_dump($key);
@ -272,7 +286,6 @@ if ($mode == 'setup' && $user->admin)
if (is_object($tokenobj))
{
// Token refresh
$var = ! $var;
print '<tr class="oddeven">';
print '<td'.($key['required']?' class="required"':'').'>';
//var_dump($key);
@ -283,7 +296,6 @@ if ($mode == 'setup' && $user->admin)
print '</tr>';
// Token expired
$var = ! $var;
print '<tr class="oddeven">';
print '<td'.($key['required']?' class="required"':'').'>';
//var_dump($key);
@ -294,7 +306,6 @@ if ($mode == 'setup' && $user->admin)
print '</tr>';
// Token expired at
$var = ! $var;
print '<tr class="oddeven">';
print '<td'.($key['required']?' class="required"':'').'>';
//var_dump($key);
@ -354,7 +365,6 @@ if ($mode == 'userconf' && $user->admin)
print $langs->trans('PrintUserConfDesc'.$driver)."<br><br>\n";
print '<table class="noborder" width="100%">';
$var=true;
print '<tr class="liste_titre">';
print '<th>'.$langs->trans("User").'</th>';
print '<th>'.$langs->trans("PrintModule").'</th>';

View File

@ -27,12 +27,15 @@
$supportedoauth2array=array(
'OAUTH_GOOGLE_NAME'=>'google',
);
if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
{
$supportedoauth2array['OAUTH_GITHUB_NAME']='github';
$supportedoauth2array['OAUTH_STRIPE_TEST_NAME']='stripetest';
$supportedoauth2array['OAUTH_STRIPE_LIVE_NAME']='stripelive';
}
$supportedoauth2array['OAUTH_GITHUB_NAME']='github';
// API access parameters OAUTH
$list = array (
array(
@ -217,7 +220,17 @@ $list = array (
'OAUTH_STRAVA_ID',
'OAUTH_STRAVA_SECRET',
),
array(
array(
'OAUTH_STRIPE_TEST_NAME',
'OAUTH_STRIPE_TEST_ID',
'STRIPE_TEST_SECRET_KEY',
),
array(
'OAUTH_STRIPE_LIVE_NAME',
'OAUTH_STRIPE_LIVE_ID',
'STRIPE_LIVE_SECRET_KEY',
),
array(
'OAUTH_TUMBLR_NAME',
'OAUTH_TUMBLR_ID',
'OAUTH_TUMBLR_SECRET',
@ -266,12 +279,12 @@ function oauthadmin_prepare_head()
$head[$h][1] = $langs->trans("OAuthServices");
$head[$h][2] = 'services';
$h++;
$head[$h][0] = dol_buildpath('/admin/oauthlogintokens.php', 1);
$head[$h][1] = $langs->trans("TokenManager");
$head[$h][2] = 'tokengeneration';
$h++;
complete_head_from_modules($conf, $langs, null, $head, $h, 'oauthadmin');
complete_head_from_modules($conf, $langs, null, $head, $h, 'oauthadmin', 'remove');

View File

@ -109,7 +109,7 @@ if (! empty($_GET['code'])) // We are coming from oauth provider page
// We should have
//$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
dol_syslog("We are coming fr mthe oauth provider page");
dol_syslog("We are coming from the oauth provider page");
//llxHeader('',$langs->trans("OAuthSetup"));
//$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
@ -125,14 +125,14 @@ if (! empty($_GET['code'])) // We are coming from oauth provider page
//var_dump($_GET['code']);
//var_dump($state);
//var_dump($apiService); // OAuth\OAuth2\Service\GitHub
//$token = $apiService->requestAccessToken($_GET['code'], $state);
$token = $apiService->requestAccessToken($_GET['code']);
// Github is a service that does not need state to be stored.
// Into constructor of GitHub, the call
// parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri)
// has not the ending parameter to true like the Google class constructor.
setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
$backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];

View File

@ -109,7 +109,7 @@ if ($action == 'delete')
if (! empty($_GET['code'])) // We are coming from oauth provider page
{
dol_syslog("We are coming fr mthe oauth provider page");
dol_syslog("We are coming from the oauth provider page");
//llxHeader('',$langs->trans("OAuthSetup"));
//$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';

View File

@ -0,0 +1,180 @@
<?php
/*
* Copyright (C) 2015 Frederic France <frederic.france@free.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/core/modules/oauth/stripe_oauthcallback.php
* \ingroup oauth
* \brief Page to get oauth callback
*/
require '../../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
use OAuth\Common\Storage\DoliStorage;
use OAuth\Common\Consumer\Credentials;
use OAuth\OAuth2\Service\GitHub;
// Define $urlwithroot
$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
//$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
$action = GETPOST('action', 'alpha');
$backtourl = GETPOST('backtourl', 'alpha');
/**
* Create a new instance of the URI class with the current URI, stripping the query string
*/
$uriFactory = new \OAuth\Common\Http\Uri\UriFactory();
//$currentUri = $uriFactory->createFromSuperGlobalArray($_SERVER);
//$currentUri->setQuery('');
$currentUri = $uriFactory->createFromAbsolute($urlwithroot.'/core/modules/oauth/stripe_oauthcallback.php');
/**
* Load the credential for the service
*/
/** @var $serviceFactory \OAuth\ServiceFactory An OAuth service factory. */
$serviceFactory = new \OAuth\ServiceFactory();
$httpClient = new \OAuth\Common\Http\Client\CurlClient();
// TODO Set options for proxy and timeout
// $params=array('CURLXXX'=>value, ...)
//$httpClient->setCurlParameters($params);
$serviceFactory->setHttpClient($httpClient);
// Dolibarr storage
$storage = new DoliStorage($db, $conf);
// Setup the credentials for the requests
$credentials = new Credentials(
$conf->global->OAUTH_STRIPE_TEST_ID,
$conf->global->STRIPE_TEST_SECRET_KEY,
$currentUri->getAbsoluteUri()
);
$requestedpermissionsarray=array();
if (GETPOST('state')) $requestedpermissionsarray=explode(',', GETPOST('state')); // Example: 'userinfo_email,userinfo_profile,cloud_print'. 'state' parameter is standard to retrieve some parameters back
/*if ($action != 'delete' && empty($requestedpermissionsarray))
{
print 'Error, parameter state is not defined';
exit;
}*/
//var_dump($requestedpermissionsarray);exit;
// Instantiate the Api service using the credentials, http client and storage mechanism for the token
/** @var $apiService Service */
//$apiService = $serviceFactory->createService('StripeTest', $credentials, $storage, $requestedpermissionsarray);
$sql="INSERT INTO ".MAIN_DB_PREFIX."oauth_token set service='StripeTest', entity=".$conf->entity;
$db->query($sql);
// access type needed to have oauth provider refreshing token
//$apiService->setAccessType('offline');
$langs->load("oauth");
/*
* Actions
*/
if ($action == 'delete')
{
$storage->clearToken('StripeTest');
setEventMessages($langs->trans('TokenDeleted'), null, 'mesgs');
header('Location: ' . $backtourl);
exit();
}
if (! empty($_GET['code'])) // We are coming from oauth provider page
{
// We should have
//$_GET=array('code' => string 'aaaaaaaaaaaaaa' (length=20), 'state' => string 'user,public_repo' (length=16))
dol_syslog("We are coming from the oauth provider page");
//llxHeader('',$langs->trans("OAuthSetup"));
//$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
//print load_fiche_titre($langs->trans("OAuthSetup"),$linkback,'title_setup');
//dol_fiche_head();
// retrieve the CSRF state parameter
$state = isset($_GET['state']) ? $_GET['state'] : null;
//print '<table>';
// This was a callback request from service, get the token
try {
//var_dump($_GET['code']);
//var_dump($state);
//var_dump($apiService); // OAuth\OAuth2\Service\GitHub
//$token = $apiService->requestAccessToken($_GET['code'], $state);
$token = $apiService->requestAccessToken($_GET['code']);
// Github is a service that does not need state to be stored.
// Into constructor of GitHub, the call
// parent::__construct($credentials, $httpClient, $storage, $scopes, $baseApiUri)
// has not the ending parameter to true like the Google class constructor.
setEventMessages($langs->trans('NewTokenStored'), null, 'mesgs'); // Stored into object managed by class DoliStorage so into table oauth_token
$backtourl = $_SESSION["backtourlsavedbeforeoauthjump"];
unset($_SESSION["backtourlsavedbeforeoauthjump"]);
header('Location: ' . $backtourl);
exit();
} catch (Exception $e) {
print $e->getMessage();
}
}
else // If entry on page with no parameter, we arrive here
{
$_SESSION["backtourlsavedbeforeoauthjump"]=$backtourl;
// This may create record into oauth_state before the header redirect.
// Creation of record with state in this tables depend on the Provider used (see its constructor).
if (GETPOST('state'))
{
$url = $apiService->getAuthorizationUri(array('state'=>GETPOST('state')));
}
else
{
//$url = $apiService->getAuthorizationUri(); // Parameter state will be randomly generated
//https://connect.stripe.com/oauth/authorize?response_type=code&client_id=ca_AX27ut70tJ1j6eyFCV3ObEXhNOo2jY6V&scope=read_write
$url = 'https://connect.stripe.com/oauth/authorize?response_type=code&client_id='.$conf->global->OAUTH_STRIPE_TEST_ID.'&scope=read_write';
}
// we go on oauth provider authorization page
header('Location: ' . $url);
exit();
}
/*
* View
*/
// No view at all, just actions
$db->close();

View File

@ -80,3 +80,5 @@ ALTER TABLE llx_c_paiement CHANGE COLUMN id id INTEGER AUTO_INCREMENT PRIMARY KE
ALTER TABLE llx_c_payment_term DROP INDEX uk_c_payment_term;
ALTER TABLE llx_c_payment_term CHANGE COLUMN rowid rowid INTEGER AUTO_INCREMENT PRIMARY KEY;
ALTER TABLE llx_c_payment_term ADD UNIQUE INDEX uk_c_payment_term_code(entity, code);
ALTER TABLE llx_oauth_token ADD COLUMN tokenstring text;

View File

@ -18,8 +18,9 @@
CREATE TABLE llx_oauth_token (
rowid integer AUTO_INCREMENT PRIMARY KEY,
service varchar(36),
token text,
token text, -- token in serialize() format, of an object StdOAuth2Token of library phpoauth2
tokenstring text, -- token in json format '{ "access_token": "sk_test_cccc", "refresh_token": "rt_aaa", "token_type": "bearer", ..., "scope": "read_write" }
fk_user integer,
fk_adherent integer,
entity integer DEFAULT 1
)ENGINE=InnoDB;
)ENGINE=InnoDB;

View File

@ -43,4 +43,6 @@ ONLINE_PAYMENT_WAREHOUSE=Stock to use for stock decrease when payment online pay
StripeLiveEnabled=Stripe live enabled (otherwise test/sandbox mode)
StripeImportPayment=Import Stripe payments
ExampleOfTestCreditCard=Example of credit card for test: %s (valid), %s (error CVC), %s (expired), %s (charge fails)
StripeGateways=Stripe gateways
StripeGateways=Stripe gateways
OAUTH_STRIPE_TEST_ID=Stripe Connect Client ID (ca_...)
OAUTH_STRIPE_LIVE_ID=Stripe Connect Client ID (ca_...)

View File

@ -116,6 +116,7 @@ if ($action=="setlive")
}
//TODO: import script for stripe account saving in alone or connect mode for stripe.class.php
/*
* View
*/
@ -169,62 +170,51 @@ else
print '</A>';
}
print '</td></tr>';
if (empty($conf->stripeconnect->enabled)) {
print '<tr class="oddeven"><td>';
print '<span class="fieldrequired">'.$langs->trans("STRIPE_TEST_PUBLISHABLE_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_TEST_PUBLISHABLE_KEY" value="'.$conf->global->STRIPE_TEST_PUBLISHABLE_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': pk_test_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
print '<tr class="oddeven"><td>';
print '<span class="titlefield fieldrequired">'.$langs->trans("STRIPE_TEST_SECRET_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_TEST_SECRET_KEY" value="'.$conf->global->STRIPE_TEST_SECRET_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': sk_test_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
print '<tr class="oddeven"><td>';
print '<span>'.$langs->trans("STRIPE_TEST_WEBHOOK_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_TEST_WEBHOOK_KEY" value="'.$conf->global->STRIPE_TEST_WEBHOOK_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
print '<tr class="oddeven"><td>';
print '<span class="fieldrequired">'.$langs->trans("STRIPE_LIVE_PUBLISHABLE_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_LIVE_PUBLISHABLE_KEY" value="'.$conf->global->STRIPE_LIVE_PUBLISHABLE_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': pk_live_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
print '<tr class="oddeven"><td>';
print '<span class="fieldrequired">'.$langs->trans("STRIPE_LIVE_SECRET_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_LIVE_SECRET_KEY" value="'.$conf->global->STRIPE_LIVE_SECRET_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': sk_live_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
print '<tr class="oddeven"><td>';
print '<span>'.$langs->trans("STRIPE_LIVE_WEBHOOK_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_LIVE_WEBHOOK_KEY" value="'.$conf->global->STRIPE_LIVE_WEBHOOK_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
} else {
print '<tr class="oddeven"><td>'.$langs->trans("StripeConnect").'</td>';
print '<td>'.$langs->trans("StripeConnect_Mode").'</td></tr>';
}
if (! empty($conf->banque->enabled)) //deplace here for separate stripe setting of general and common online payment settings
if (empty($conf->stripeconnect->enabled))
{
print '<tr class="oddeven"><td>';
print $langs->trans("BankAccount").'</td><td>';
print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS, 'STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1);
print '<span class="fieldrequired">'.$langs->trans("STRIPE_TEST_PUBLISHABLE_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_TEST_PUBLISHABLE_KEY" value="'.$conf->global->STRIPE_TEST_PUBLISHABLE_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': pk_test_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // target bank account for stripe transfer: automatic banktransfert with stripe webhook from stripe account (receiving funds, payment, debit fee/application fee, payment dispute) to real bank account
{
print '<tr class="oddeven"><td>';
print $langs->trans("BankAccountForBankTransfer").'</td><td>';
print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1);
print '</td></tr>';
}
print '<tr class="oddeven"><td>';
print '<span class="titlefield fieldrequired">'.$langs->trans("STRIPE_TEST_SECRET_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_TEST_SECRET_KEY" value="'.$conf->global->STRIPE_TEST_SECRET_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': sk_test_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
print '<tr class="oddeven"><td>';
print '<span>'.$langs->trans("STRIPE_TEST_WEBHOOK_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_TEST_WEBHOOK_KEY" value="'.$conf->global->STRIPE_TEST_WEBHOOK_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
print '<tr class="oddeven"><td>';
print '<span class="fieldrequired">'.$langs->trans("STRIPE_LIVE_PUBLISHABLE_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_LIVE_PUBLISHABLE_KEY" value="'.$conf->global->STRIPE_LIVE_PUBLISHABLE_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': pk_live_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
print '<tr class="oddeven"><td>';
print '<span class="fieldrequired">'.$langs->trans("STRIPE_LIVE_SECRET_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_LIVE_SECRET_KEY" value="'.$conf->global->STRIPE_LIVE_SECRET_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': sk_live_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
print '<tr class="oddeven"><td>';
print '<span>'.$langs->trans("STRIPE_LIVE_WEBHOOK_KEY").'</span></td><td>';
print '<input class="minwidth300" type="text" name="STRIPE_LIVE_WEBHOOK_KEY" value="'.$conf->global->STRIPE_LIVE_WEBHOOK_KEY.'">';
print ' &nbsp; '.$langs->trans("Example").': whsec_xxxxxxxxxxxxxxxxxxxxxxxx';
print '</td></tr>';
}
else
{
print '<tr class="oddeven"><td>'.$langs->trans("StripeConnect").'</td>';
print '<td>'.$langs->trans("StripeConnect_Mode").'</td></tr>';
}
print '</table>';
@ -243,21 +233,17 @@ print '<input size="64" type="text" name="ONLINE_PAYMENT_CREDITOR" value="'.$con
print ' &nbsp; '.$langs->trans("Example").': '.$mysoc->name;
print '</td></tr>';
if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // autodecrement selected web stock when generate invoice or paid an order->generate linked invoice as in a POS module for a full automatic functionality (useful when there is a lot of payment)
{
// Stock for automatic decrement
print '<tr class="oddeven"><td>';
print $langs->trans("ONLINE_PAYMENT_WAREHOUSE").'</td><td>';
print $formproduct->selectWarehouses($conf->global->ONLINE_PAYMENT_WAREHOUSE,'ONLINE_PAYMENT_WAREHOUSE','',1,$disabled);
print '</td></tr>';
print '<tr class="oddeven"><td>';
print $langs->trans("BankAccount").'</td><td>';
print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS, 'STRIPE_BANK_ACCOUNT_FOR_PAYMENTS', 0, '', 1);
print '</td></tr>';
if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is this for ?
{
print '<tr class="oddeven"><td>';
print $langs->trans("BankAccountForBankTransfer").'</td><td>';
print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1);
print '</td></tr>';
}
if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is this for ?
{
print '<tr class="oddeven"><td>';
print $langs->trans("BankAccountForBankTransfer").'</td><td>';
print $form->select_comptes($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS, 'STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS', 0, '', 1);
print '</td></tr>';
}
if ($conf->global->MAIN_FEATURES_LEVEL >= 2) // What is this for ?
@ -297,7 +283,7 @@ print '<tr class="oddeven"><td>';
print $langs->trans("ONLINE_PAYMENT_SENDEMAIL").'</td><td>';
print '<input size="32" type="email" name="ONLINE_PAYMENT_SENDEMAIL" value="'.$conf->global->ONLINE_PAYMENT_SENDEMAIL.'">';
print ' &nbsp; '.$langs->trans("Example").': myemail@myserver.com';
print '</td></tr>';
print '</td></tr>';
// Payment token for URL
print '<tr class="oddeven"><td>';

View File

@ -46,20 +46,36 @@ $offset = $conf->liste_limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
/*
* View
*/
* View
*/
llxHeader('', $langs->trans("StripeChargeList"));
$form = new Form($db);
$societestatic = new societe($db);
$acc = new Account($db);
$stripe=new Stripe($db);
if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha')))
{
$service = 'StripeTest';
dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning');
}
if (!$rowid){
else
{
$service = 'StripeLive';
}
$stripeaccount = $stripe->GetStripeAccount($service);
if (empty($stripeaccount))
{
print $langs->trans('ErrorStripeAccountNotDefined');
}
if (!$rowid && $stripeaccount)
{
print '<FORM method="GET" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<INPUT type="hidden" name="optioncss" value="'.$optioncss.'">';
print '<INPUT type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
@ -85,68 +101,71 @@ if (!$rowid){
print "</TR>\n";
print "</TR>\n";
$list=\Stripe\Charge::all(array("limit" => $limit),array("stripe_account" => $stripe->GetStripeAccount($conf->entity)));
//print $list;
foreach ($list->data as $charge) {
print '<TR class="oddeven">';
$societestatic->fetch($charge->metadata->idcustomer);
$societestatic->id=$charge->metadata->idcustomer;
$societestatic->lastname=$obj->lastname;
$societestatic->firstname=$obj->firstname;
$societestatic->admin=$obj->admin;
$societestatic->login=$obj->login;
$societestatic->email=$obj->email;
$societestatic->societe_id=$obj->fk_soc;
// Ref
$list=\Stripe\Charge::all(array("limit" => $limit), array("stripe_account" => $stripeaccount));
//print $list;
foreach ($list->data as $charge)
{
print '<TR class="oddeven">';
$societestatic->fetch($charge->metadata->idcustomer);
$societestatic->id=$charge->metadata->idcustomer;
$societestatic->lastname=$obj->lastname;
$societestatic->firstname=$obj->firstname;
$societestatic->admin=$obj->admin;
$societestatic->login=$obj->login;
$societestatic->email=$obj->email;
$societestatic->societe_id=$obj->fk_soc;
// Ref
print "<TD><A href='".DOL_URL_ROOT."/stripe/charge.php?rowid=".$charge->id."'>".$charge->id."</A></TD>\n";
// Employee
print "<TD>".$societestatic->getNomUrl(1)."</TD>\n";
// Origine
// Origine
print "<TD>";
if ($charge->metadata->source=="order"){
$object = new Commande($db);
$object->fetch($charge->metadata->idsource);
print "<A href='".DOL_URL_ROOT."/commande/card.php?id=".$charge->metadata->idsource."'>".img_picto('', 'object_order')." ".$object->ref."</A>";
} elseif ($charge->metadata->source=="invoice"){
$object = new Facture($db);
$object->fetch($charge->metadata->idsource);
print "<A href='".DOL_URL_ROOT."/compta/facture/card.php?facid=".$charge->metadata->idsource."'>".img_picto('', 'object_invoice')." ".$object->ref."</A>";
}
print "</TD>\n";
// Date payment
print '<TD align="center">'.dol_print_date($charge->created,'%d/%m/%Y %H:%M')."</TD>\n";
// Label payment
print "<TD>";
if ($charge->refunded=='1'){
print $langs->trans("refunded");
} elseif ($charge->paid=='1'){
print $langs->trans("".$charge->status."");
} else {
$label="Message: ".$charge->failure_message."<BR>";
$label.="Réseau: ".$charge->outcome->network_status."<BR>";
$label.="Statut: ".$langs->trans("".$charge->outcome->seller_message."");
print $form->textwithpicto($langs->trans("".$charge->status.""),$label,1);
}
print "</TD>\n";
// Type
print '<TD>';
if ($charge->source->object=='card'){
print $langs->trans("card");
}
elseif ($charge->source->type=='card'){
print $langs->trans("card");
} elseif ($charge->source->type=='three_d_secure'){
print $langs->trans("card3DS");
}
print '</TD>';
// Amount
print "<TD align=\"right\">".price(($charge->amount-$charge->amount_refunded)/100)."</TD>";
print "</TR>\n";
}
if ($charge->metadata->source=="order"){
$object = new Commande($db);
$object->fetch($charge->metadata->idsource);
print "<A href='".DOL_URL_ROOT."/commande/card.php?id=".$charge->metadata->idsource."'>".img_picto('', 'object_order')." ".$object->ref."</A>";
} elseif ($charge->metadata->source=="invoice"){
$object = new Facture($db);
$object->fetch($charge->metadata->idsource);
print "<A href='".DOL_URL_ROOT."/compta/facture/card.php?facid=".$charge->metadata->idsource."'>".img_picto('', 'object_invoice')." ".$object->ref."</A>";
}
print "</TD>\n";
// Date payment
print '<TD align="center">'.dol_print_date($charge->created,'%d/%m/%Y %H:%M')."</TD>\n";
// Label payment
print "<TD>";
if ($charge->refunded=='1'){
print $langs->trans("refunded");
} elseif ($charge->paid=='1'){
print $langs->trans("".$charge->status."");
} else {
$label="Message: ".$charge->failure_message."<BR>";
$label.="Réseau: ".$charge->outcome->network_status."<BR>";
$label.="Statut: ".$langs->trans("".$charge->outcome->seller_message."");
print $form->textwithpicto($langs->trans("".$charge->status.""),$label,1);
}
print "</TD>\n";
// Type
print '<TD>';
if ($charge->source->object=='card')
{
print $langs->trans("card");
}
elseif ($charge->source->type=='card'){
print $langs->trans("card");
} elseif ($charge->source->type=='three_d_secure'){
print $langs->trans("card3DS");
}
print '</TD>';
// Amount
print "<TD align=\"right\">".price(($charge->amount-$charge->amount_refunded)/100)."</TD>";
print "</TR>\n";
}
} else {
}
}
llxFooter();
$db->close();

View File

@ -21,23 +21,24 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/stripe/config.php';
/**
* \class Rewards
* \brief Class for Rewards
/**
* Stripe class
*/
class Stripe extends CommonObject
{
public $rowid;
public $fk_soc;
public $fk_key;
public $id;
public $mode;
public $entity;
public $statut;
public $type;
public $code;
public $message;
public $fk_soc;
public $fk_key;
public $id;
public $mode;
public $entity;
public $statut;
public $type;
public $code;
public $message;
/**
* Constructor
*
@ -48,273 +49,306 @@ class Stripe extends CommonObject
$this->db = $db;
}
public function GetStripeAccount($id) // TODO: move /transforme optimize function/data
/**
* GetStripeAccount
*
* @param string $mode 'StripeTest' or 'StripeLive'
* @return int ???
*/
public function GetStripeAccount($mode='StripeTest')
{
global $conf;
$sql = "SELECT key_account";
$sql.= " FROM ".MAIN_DB_PREFIX."stripe_entity";
$sql.= " WHERE entity = ".$id."";
$sql = "SELECT tokenstring";
$sql.= " FROM ".MAIN_DB_PREFIX."oauth_token";
$sql.= " WHERE entity = ".$conf->entity;
$sql.= " AND service = '".$mode."'";
dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
$result = $this->db->query($sql);
if ($result)
if ($result)
{
if ($this->db->num_rows($result))
{
$obj = $this->db->fetch_object($result);
$key=$obj->key_account;
}
else {$key=0;}
}
else {$key=0;}
return $key;
}
public function GetStripeCustomerAccount($id)
$tokenstring=$obj->tokenstring;
$tmparray = dol_json_decode($tokenstring);
$key = $tmparray->stripe_user_id;
}
else {
$tokenstring='';
}
}
else {
dol_print_error($this->db);
}
return $key;
}
/**
* GetStripeCustomerAccount
*
* @param int $id ???
* @return int ???
*/
public function GetStripeCustomerAccount($id)
{
global $conf;
$sql = "SELECT s.key_account as key_account, s.entity, e.fk_object";
$sql.= " FROM ".MAIN_DB_PREFIX."stripe_entity as s";
$sql.= " JOIN ".MAIN_DB_PREFIX."entity_extrafields as e ON s.entity=e.fk_object";
$sql.= " WHERE e.fk_soc=".$id." ";
$sql .= " FROM " . MAIN_DB_PREFIX . "stripe_entity as s";
$sql .= " JOIN " . MAIN_DB_PREFIX . "entity_extrafields as e ON s.entity=e.fk_object";
$sql .= " WHERE e.fk_soc=" . $id . " ";
dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
$result = $this->db->query($sql);
if ($result)
{
if ($this->db->num_rows($result))
{
if ($result) {
if ($this->db->num_rows($result)) {
$obj = $this->db->fetch_object($result);
$key=$obj->key_account;
}
else {$key=NULL;}
}
else {$key=NULL;}
return $key;
}
public function CustomerStripe($id,$key)
$key = $obj->key_account;
} else {
$key = NULL;
}
} else {
$key = NULL;
}
return $key;
}
/**
* CustomerStripe
*
* @param int $id ???
* @param string $key ???
* @return \Stripe\StripeObject|\Stripe\ApiResource
*/
public function CustomerStripe($id,$key)
{
global $conf;
if (empty($conf->global->STRIPECONNECT_LIVE))
{
$mode=0;
}
else
{
if (empty($conf->global->STRIPE_LIVE))
{
$mode=0;
}
else
{
$mode=$conf->global->STRIPE_LIVE;
}
}
global $conf;
if (empty($conf->global->STRIPECONNECT_LIVE)) {
$mode = 0;
} else {
if (empty($conf->global->STRIPE_LIVE)) {
$mode = 0;
} else {
$mode = $conf->global->STRIPE_LIVE;
}
}
$sql = "SELECT rowid,fk_soc,fk_key,mode,entity";
$sql.= " FROM ".MAIN_DB_PREFIX."societe_stripe";
$sql.= " WHERE fk_soc = ".$id." ";
$sql.= " AND mode=".$mode." AND entity IN (" . getEntity('stripe') . ")";
$sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe";
$sql .= " WHERE fk_soc = " . $id . " ";
$sql .= " AND mode=" . $mode . " AND entity IN (" . getEntity('stripe') . ")";
dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
$resql = $this->db->query($sql);
if ($resql) {
$soc = new Societe($this->db);
$soc->fetch($id);
$num=$this->db->num_rows($resql);
$soc = new Societe($this->db);
$soc->fetch($id);
$num = $this->db->num_rows($resql);
if ($num) {
$obj = $this->db->fetch_object($resql);
$tiers = $obj->fk_key;
if ($conf->entity==1){
$customer = \Stripe\Customer::retrieve("$tiers");
}else{
$customer = \Stripe\Customer::retrieve("$tiers",array("stripe_account" => $key));
}}
else {
if ($conf->entity==1){
$customer = \Stripe\Customer::create(array(
"email" => $soc->email,
"description" => $soc->name
));
}else{
$customer = \Stripe\Customer::create(array(
"email" => $soc->email,
"description" => $soc->name
), array("stripe_account" => $key));
}
$customer_id = "".$customer->id."";
$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_stripe (fk_soc,fk_key,mode,entity)";
$sql .= " VALUES ($id,'$customer_id',".$mode.",".$conf->entity.")";
dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG);
$resql = $this->db->query($sql);
}}
return $customer;
$obj = $this->db->fetch_object($resql);
$tiers = $obj->fk_key;
if ($conf->entity == 1) {
$customer = \Stripe\Customer::retrieve("$tiers");
} else {
$customer = \Stripe\Customer::retrieve("$tiers", array(
"stripe_account" => $key
));
}
} else {
if ($conf->entity == 1) {
$customer = \Stripe\Customer::create(array(
"email" => $soc->email,
"description" => $soc->name
));
} else {
$customer = \Stripe\Customer::create(array(
"email" => $soc->email,
"description" => $soc->name
), array(
"stripe_account" => $key
));
}
$customer_id = "" . $customer->id . "";
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_stripe (fk_soc,fk_key,mode,entity)";
$sql .= " VALUES ($id,'$customer_id'," . $mode . "," . $conf->entity . ")";
dol_syslog(get_class($this) . "::create sql=" . $sql, LOG_DEBUG);
$resql = $this->db->query($sql);
}
}
return $customer;
}
public function CreatePaymentStripe($amount,$currency,$origin,$item,$source,$customer,$account)
{
global $conf;
if (empty($conf->global->STRIPECONNECT_LIVE))
{
$mode=0;
}
else
{
if (empty($conf->global->STRIPE_LIVE))
{
$mode=0;
}
else
{
$mode=$conf->global->STRIPE_LIVE;
}
}
/**
* CreatePaymentStripe
*
* @param unknown $amount ???
* @param unknown $currency ???
* @param unknown $origin ???
* @param unknown $item ???
* @param unknown $source ???
* @param unknown $customer ???
* @param unknown $account ???
* @return Stripe
*/
public function CreatePaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account)
{
global $conf;
if (empty($conf->global->STRIPECONNECT_LIVE)) {
$mode = 0;
} else {
if (empty($conf->global->STRIPE_LIVE)) {
$mode = 0;
} else {
$mode = $conf->global->STRIPE_LIVE;
}
}
$sql = "SELECT fk_soc,fk_key,mode,entity";
$sql.= " FROM ".MAIN_DB_PREFIX."societe_stripe";
$sql.= " WHERE fk_key = '$customer' ";
$sql.= " AND mode=".$mode." ";
$sql .= " FROM " . MAIN_DB_PREFIX . "societe_stripe";
$sql .= " WHERE fk_key = '$customer' ";
$sql .= " AND mode=" . $mode . " ";
dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
$result = $this->db->query($sql);
if ($result)
{
if ($this->db->num_rows($result))
{
if ($result) {
if ($this->db->num_rows($result)) {
$obj = $this->db->fetch_object($result);
$entite=$obj->entity;
$fksoc=$obj->fk_soc;
}
}
$stripeamount=round($amount*100);
$societe = new Societe($this->db);
$societe->fetch($fksoc);
$entite = $obj->entity;
$fksoc = $obj->fk_soc;
}
}
$stripeamount = round($amount * 100);
$societe = new Societe($this->db);
$societe->fetch($fksoc);
if ($origin==order){
$order=new Commande($this->db);
$order->fetch($item);
$ref=$order->ref;
$description="ORD=".$ref.".CUS=".$societe->code_client;
}
elseif ($origin==invoice) {
$invoice=new Facture($this->db);
$invoice->fetch($item);
$ref=$invoice->ref;
$description="INV=".$ref.".CUS=".$societe->code_client;
}
if ($origin == order) {
$order = new Commande($this->db);
$order->fetch($item);
$ref = $order->ref;
$description = "ORD=" . $ref . ".CUS=" . $societe->code_client;
} elseif ($origin == invoice) {
$invoice = new Facture($this->db);
$invoice->fetch($item);
$ref = $invoice->ref;
$description = "INV=" . $ref . ".CUS=" . $societe->code_client;
}
$metadata = array(
"source" => "".$origin."",
"idsource" => "".$item."",
"idcustomer" => "".$societe->id.""
);
$return = new Stripe($this->db);
try {
if ($stripeamount>=100) {
if ($entite=='1' or empty($conf->stripeconnect->enabled)){
if (preg_match('/acct_/i',$source)){
$charge = \Stripe\Charge::create(array(
"amount" => "$stripeamount",
"currency" => "$currency",
// "statement_descriptor" => " ",
"metadata" => $metadata,
"source" => "$source"
)
);
} else {
$charge = \Stripe\Charge::create(array(
"amount" => "$stripeamount",
"currency" => "$currency",
// "statement_descriptor" => " ",
"description" => "$description",
"metadata" => $metadata,
"receipt_email" => $societe->email,
"source" => "$source",
"customer" => "$customer")
,array("idempotency_key" => "$ref")
);
}}else{
$fee=round(($amount*($conf->global->STRIPE_APPLICATION_FEE_PERCENT/100)+$conf->global->STRIPE_APPLICATION_FEE)*100);
if ($fee<($conf->global->STRIPE_APPLICATION_FEE_MINIMAL*100)){
$fee=round($conf->global->STRIPE_APPLICATION_FEE_MINIMAL*100);
}
$charge = \Stripe\Charge::create(array(
"amount" => "$stripeamount",
"currency" => "$currency",
// "statement_descriptor" => " ",
"description" => "$description",
"metadata" => $metadata,
"source" => "$source",
"customer" => "$customer",
"application_fee" => "$fee"
), array("idempotency_key" => "$ref","stripe_account" => "$account"));
}
if (isset($charge->id)){
$metadata = array(
"source" => "" . $origin . "",
"idsource" => "" . $item . "",
"idcustomer" => "" . $societe->id . ""
);
$return = new Stripe($this->db);
try {
if ($stripeamount >= 100) {
if ($entite == '1' or empty($conf->stripeconnect->enabled)) {
if (preg_match('/acct_/i', $source)) {
$charge = \Stripe\Charge::create(array(
"amount" => "$stripeamount",
"currency" => "$currency",
// "statement_descriptor" => " ",
"metadata" => $metadata,
"source" => "$source"
));
} else {
$charge = \Stripe\Charge::create(array(
"amount" => "$stripeamount",
"currency" => "$currency",
// "statement_descriptor" => " ",
"description" => "$description",
"metadata" => $metadata,
"receipt_email" => $societe->email,
"source" => "$source",
"customer" => "$customer"
), array(
"idempotency_key" => "$ref"
));
}
} else {
$fee = round(($amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE) * 100);
if ($fee < ($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100)) {
$fee = round($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100);
}
$charge = \Stripe\Charge::create(array(
"amount" => "$stripeamount",
"currency" => "$currency",
// "statement_descriptor" => " ",
"description" => "$description",
"metadata" => $metadata,
"source" => "$source",
"customer" => "$customer",
"application_fee" => "$fee"
), array(
"idempotency_key" => "$ref",
"stripe_account" => "$account"
));
}
if (isset($charge->id)) {}
}
$return->statut = 'success';
$return->id = $charge->id;
if ($charge->source->type == 'card') {
$return->message = $charge->source->card->brand . " ****" . $charge->source->card->last4;
} elseif ($charge->source->type == 'three_d_secure') {
$stripe = new Stripe($this->db);
$src = \Stripe\Source::retrieve("" . $charge->source->three_d_secure->card . "", array(
"stripe_account" => $stripe->GetStripeAccount($conf->entity)
));
$return->message = $src->card->brand . " ****" . $src->card->last4;
} else {
$return->message = $charge->id;
}
} catch (\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody();
$err = $body['error'];
$return->statut = 'error';
$return->id = $err['charge'];
$return->type = $err['type'];
$return->code = $err['code'];
$return->message = $err['message'];
$body = "Une erreur de paiement est survenue. Voici le code d'erreur: <br />" . $return->id . " " . $return->message . " ";
$subject = '[NOTIFICATION] Erreur de paiement';
$headers = 'From: "ptibogxiv.net" <' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '>';
mail('' . $conf->global->MAIN_INFO_SOCIETE_MAIL . '', $subject, $body, $headers);
$error ++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly
$error ++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (\Stripe\Error\InvalidRequest $e) {
// Invalid parameters were supplied to Stripe's API
$error ++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (\Stripe\Error\Authentication $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
$error ++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (\Stripe\Error\ApiConnection $e) {
// Network communication with Stripe failed
$error ++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (\Stripe\Error\Base $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
$error ++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
$error ++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
}
return $return;
}
}
}
$return->statut = 'success';
$return->id = $charge->id;
if ($charge->source->type=='card'){
$return->message = $charge->source->card->brand." ****".$charge->source->card->last4;
}elseif ($charge->source->type=='three_d_secure'){
$stripe=new Stripe($this->db);
$src = \Stripe\Source::retrieve("".$charge->source->three_d_secure->card."",array("stripe_account" => $stripe->GetStripeAccount($conf->entity)));
$return->message = $src->card->brand." ****".$src->card->last4;
}else {
$return->message = $charge->id;
}
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$body = $e->getJsonBody();
$err = $body['error'];
$return->statut = 'error';
$return->id = $err['charge'];
$return->type = $err['type'];
$return->code = $err['code'];
$return->message = $err['message'];
$body = "Une erreur de paiement est survenue. Voici le code d'erreur: <br />".$return->id." ".$return->message." ";
$subject = '[NOTIFICATION] Erreur de paiement';
$headers = 'From: "ptibogxiv.net" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
mail(''.$conf->global->MAIN_INFO_SOCIETE_MAIL.'', $subject, $body, $headers);
$error++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly
$error++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (\Stripe\Error\InvalidRequest $e) {
// Invalid parameters were supplied to Stripe's API
$error++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (\Stripe\Error\Authentication $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
$error++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (\Stripe\Error\ApiConnection $e) {
// Network communication with Stripe failed
$error++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (\Stripe\Error\Base $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
$error++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
$error++;
dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
}
return $return;
}
}

View File

@ -46,94 +46,109 @@ $offset = $conf->liste_limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
/*
* View
*/
/*
* View
*/
llxHeader('', $langs->trans("StripeTransactionList"));
$form = new Form($db);
$societestatic = new societe($db);
$acc = new Account($db);
$stripe=new Stripe($db);
if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox','alpha')))
$stripe = new Stripe($db);
if (! empty($conf->stripe->enabled) && (empty($conf->global->STRIPE_LIVE) || empty($conf->global->STRIPECONNECT_LIVE) || GETPOST('forcesandbox', 'alpha')))
{
dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode','Stripe'),'','warning');
$service = 'StripeTest';
dol_htmloutput_mesg($langs->trans('YouAreCurrentlyInSandboxMode', 'Stripe'), '', 'warning');
}
else
{
$servie = 'StripeLive';
}
if (!$rowid){
print '<FORM method="GET" action="'.$_SERVER["PHP_SELF"].'">';
if ($optioncss != '') print '<INPUT type="hidden" name="optioncss" value="'.$optioncss.'">';
print '<INPUT type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
$stripeaccount = $stripe->GetStripeAccount($service);
if (empty($stripeaccount))
{
print $langs->trans('ErrorStripeAccountNotDefined');
}
if (! $rowid && $stripeaccount) {
print '<FORM method="GET" action="' . $_SERVER["PHP_SELF"] . '">';
if ($optioncss != '')
print '<INPUT type="hidden" name="optioncss" value="' . $optioncss . '">';
print '<INPUT type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
print '<INPUT type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<INPUT type="hidden" name="action" value="list">';
print '<INPUT type="hidden" name="sortfield" value="'.$sortfield.'">';
print '<INPUT type="hidden" name="sortorder" value="'.$sortorder.'">';
print '<INPUT type="hidden" name="page" value="'.$page.'">';
print '<INPUT type="hidden" name="action" value="list">';
print '<INPUT type="hidden" name="sortfield" value="' . $sortfield . '">';
print '<INPUT type="hidden" name="sortorder" value="' . $sortorder . '">';
print '<INPUT type="hidden" name="page" value="' . $page . '">';
print_barre_liste($langs->trans("StripeTransactionList"),$page,$_SERVER["PHP_SELF"],$param,$sortfield,$sortorder,'',$num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit);
print_barre_liste($langs->trans("StripeTransactionList"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, 'title_accountancy.png', 0, '', '', $limit);
print '<DIV class="div-table-responsive">';
print '<TABLE class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
print '<DIV class="div-table-responsive">';
print '<TABLE class="tagtable liste' . ($moreforfilter ? " listwithfilterbefore" : "") . '">' . "\n";
print '<TR class="liste_titre">';
print_liste_field_titre("Ref",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder);
print_liste_field_titre("Customer",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder);
print_liste_field_titre("Origin",$_SERVER["PHP_SELF"],"","","","",$sortfield,$sortorder);
print_liste_field_titre("DatePayment",$_SERVER["PHP_SELF"],"","","",'align="center"',$sortfield,$sortorder);
print_liste_field_titre("Status",$_SERVER["PHP_SELF"],"","","",'align="left"');
print_liste_field_titre("Type",$_SERVER["PHP_SELF"],"","","",'align="left"',$sortfield,$sortorder);
print_liste_field_titre("Paid",$_SERVER["PHP_SELF"],"","","",'align="right"',$sortfield,$sortorder);
print_liste_field_titre("Fee",$_SERVER["PHP_SELF"],"","","",'align="right"',$sortfield,$sortorder);
print "</TR>\n";
print '<TR class="liste_titre">';
print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder);
print_liste_field_titre("Customer", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder);
print_liste_field_titre("Origin", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder);
print_liste_field_titre("DatePayment", $_SERVER["PHP_SELF"], "", "", "", 'align="center"', $sortfield, $sortorder);
print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "", "", "", 'align="left"');
print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "", "", "", 'align="left"', $sortfield, $sortorder);
print_liste_field_titre("Paid", $_SERVER["PHP_SELF"], "", "", "", 'align="right"', $sortfield, $sortorder);
print_liste_field_titre("Fee", $_SERVER["PHP_SELF"], "", "", "", 'align="right"', $sortfield, $sortorder);
print "</TR>\n";
print "</TR>\n";
$txn=\Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripe->GetStripeAccount($conf->entity)));
foreach ($txn->data as $txn) {
print '<TR class="oddeven">';
$societestatic->fetch($charge->metadata->idcustomer);
$societestatic->id=$charge->metadata->idcustomer;
$societestatic->lastname=$obj->lastname;
$societestatic->firstname=$obj->firstname;
$societestatic->admin=$obj->admin;
$societestatic->login=$obj->login;
$societestatic->email=$obj->email;
$societestatic->societe_id=$obj->fk_soc;
print "</TR>\n";
// Ref
print "<TD><A href='".DOL_URL_ROOT."/stripe/transaction.php?rowid=".$txn->source."'>".$txn->source."</A></TD>\n";
$stripeaccount = $stripe->GetStripeAccount($conf->entity);
$txn = \Stripe\BalanceTransaction::all(array("limit" => $limit), array("stripe_account" => $stripeaccount));
foreach ($txn->data as $txn) {
print '<TR class="oddeven">';
$societestatic->fetch($charge->metadata->idcustomer);
$societestatic->id = $charge->metadata->idcustomer;
$societestatic->lastname = $obj->lastname;
$societestatic->firstname = $obj->firstname;
$societestatic->admin = $obj->admin;
$societestatic->login = $obj->login;
$societestatic->email = $obj->email;
$societestatic->societe_id = $obj->fk_soc;
// Ref
print "<TD><A href='" . DOL_URL_ROOT . "/stripe/transaction.php?rowid=" . $txn->source . "'>" . $txn->source . "</A></TD>\n";
// Employee
print "<TD>".$societestatic->getNomUrl(1)."</TD>\n";
// Origine
print "<TD>" . $societestatic->getNomUrl(1) . "</TD>\n";
// Origine
print "<TD>";
if ($charge->metadata->source=="order"){
$object = new Commande($db);
$object->fetch($charge->metadata->idsource);
print "<A href='".DOL_URL_ROOT."/commande/card.php?id=".$txn->metadata->idsource."'>".img_picto('', 'object_order')." ".$object->ref."</A>";
} elseif ($txn->metadata->source=="invoice"){
$object = new Facture($db);
$object->fetch($txn->metadata->idsource);
print "<A href='".DOL_URL_ROOT."/compta/facture/card.php?facid=".$txn->metadata->idsource."'>".img_picto('', 'object_invoice')." ".$object->ref."</A>";
}
print "</TD>\n";
if ($charge->metadata->source == "order") {
$object = new Commande($db);
$object->fetch($charge->metadata->idsource);
print "<A href='" . DOL_URL_ROOT . "/commande/card.php?id=" . $txn->metadata->idsource . "'>" . img_picto('', 'object_order') . " " . $object->ref . "</A>";
} elseif ($txn->metadata->source == "invoice") {
$object = new Facture($db);
$object->fetch($txn->metadata->idsource);
print "<A href='" . DOL_URL_ROOT . "/compta/facture/card.php?facid=" . $txn->metadata->idsource . "'>" . img_picto('', 'object_invoice') . " " . $object->ref . "</A>";
}
print "</TD>\n";
// Date payment
print '<TD align="center">'.dol_print_date($txn->created,'%d/%m/%Y %H:%M')."</TD>\n";
// Label payment
print "<TD>";
print '<TD align="center">' . dol_print_date($txn->created, '%d/%m/%Y %H:%M') . "</TD>\n";
// Label payment
print "<TD>";
print "</TD>\n";
// Type
print '<TD>'.$txn->type.'</TD>';
// Amount
print "<TD align=\"right\">".price(($txn->amount)/100)."</TD>";
print "<TD align=\"right\">".price(($txn->fee)/100)."</TD>";
print "</TR>\n";
}
print "</TABLE>";
print '</DIV>';
print '</FORM>';
}else{
}
print "</TD>\n";
// Type
print '<TD>' . $txn->type . '</TD>';
// Amount
print "<TD align=\"right\">" . price(($txn->amount) / 100) . "</TD>";
print "<TD align=\"right\">" . price(($txn->fee) / 100) . "</TD>";
print "</TR>\n";
}
print "</TABLE>";
print '</DIV>';
print '</FORM>';
} else {}
llxFooter();
$db->close();