dolibarr 25.0.0-alpha
paymentok.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2001-2002 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2006-2013 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2021-2023 Waël Almoman <info@almoman.com>
6 * Copyright (C) 2021 Maxime Demarest <maxime@indelog.fr>
7 * Copyright (C) 2021 Dorian Vabre <dorian.vabre@gmail.com>
8 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
9 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program. If not, see <https://www.gnu.org/licenses/>.
23 */
24
34if (!defined('NOLOGIN')) {
35 define("NOLOGIN", 1); // This means this output page does not require to be logged.
36}
37if (!defined('NOCSRFCHECK')) {
38 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
39}
40if (!defined('NOIPCHECK')) {
41 define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
42}
43if (!defined('NOBROWSERNOTIF')) {
44 define('NOBROWSERNOTIF', '1');
45}
46if (!defined('XFRAMEOPTIONS_ALLOWALL')) {
47 define('XFRAMEOPTIONS_ALLOWALL', '1');
48}
49
50// For MultiCompany module.
51// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
52// Because 2 entities can have the same ref.
53$entity = (!empty($_GET['e']) ? (int) $_GET['e'] : (!empty($_POST['e']) ? (int) $_POST['e'] : 1));
54if (is_numeric($entity)) {
55 define("DOLENTITY", $entity);
56}
57
58// Load Dolibarr environment
59require '../../main.inc.php';
70require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
71require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
72require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
73if (isModEnabled('paypal')) {
74 require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php';
75 require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php';
76}
77
78// Hook to be used by external payment modules (ie Payzen, ...)
79$hookmanager = new HookManager($db);
80
81$hookmanager->initHooks(array('newpayment'));
82
83$langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paypal", "stripe"));
84
85// Clean parameters
86$PAYPAL_API_USER = "";
87$PAYPAL_API_PASSWORD = "";
88$PAYPAL_API_SIGNATURE = "";
89$PAYPAL_API_SANDBOX = "";
90$PAYPALTOKEN = "";
91$PAYPALPAYERID = "";
92if (isModEnabled('paypal')) {
93 $PAYPAL_API_USER = getDolGlobalString('PAYPAL_API_USER');
94 $PAYPAL_API_PASSWORD = getDolGlobalString('PAYPAL_API_PASSWORD');
95 $PAYPAL_API_SIGNATURE = getDolGlobalString('PAYPAL_API_SIGNATURE');
96 $PAYPAL_API_SANDBOX = getDolGlobalString('PAYPAL_API_SANDBOX');
97
98 $PAYPALTOKEN = GETPOST('TOKEN');
99 if (empty($PAYPALTOKEN)) {
100 $PAYPALTOKEN = GETPOST('token');
101 }
102 $PAYPALPAYERID = GETPOST('PAYERID');
103 if (empty($PAYPALPAYERID)) {
104 $PAYPALPAYERID = GETPOST('PayerID');
105 }
106}
107
108$FULLTAG = GETPOST('FULLTAG');
109if (empty($FULLTAG)) {
110 $FULLTAG = GETPOST('fulltag');
111}
112$source = GETPOST('s', 'alpha') ? GETPOST('s', 'alpha') : GETPOST('source', 'alpha');
113$ref = GETPOST('ref');
114
115$suffix = GETPOST("suffix", 'aZ09');
116$membertypeid = GETPOSTINT("membertypeid");
117
118
119// Detect $paymentmethod
120$paymentmethod = '';
121$reg = array();
122if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) {
123 $paymentmethod = $reg[1];
124}
125if (empty($paymentmethod)) {
126 dol_syslog("***** paymentok.php was called with a non valid parameter FULLTAG=".$FULLTAG, LOG_DEBUG, 0, '_payment');
127 dol_print_error(null, 'The callback url does not contain a parameter fulltag that should help us to find the payment method used');
128 exit;
129}
130
131dol_syslog("***** paymentok.php is called paymentmethod=".$paymentmethod." FULLTAG=".$FULLTAG." REQUEST_URI=".$_SERVER["REQUEST_URI"], LOG_DEBUG, 0, '_payment');
132
133// Detect $ws
134$reg_ws = array();
135$ws = preg_match('/WS=([^\.]+)/', $FULLTAG, $reg_ws) ? $reg_ws[1] : 0;
136if ($ws) {
137 dol_syslog("paymentok.php page is invoked from a website with ref ".$ws.". It performs actions and then redirects back to this website. A page with ref paymentok must be created for this website.", LOG_DEBUG, 0, '_payment');
138}
139
140$validpaymentmethod = getValidOnlinePaymentMethods($paymentmethod);
141
142// Security check
143if (empty($validpaymentmethod)) {
144 httponly_accessforbidden('No valid payment mode');
145}
146
147// Common variables
148$creditor = $mysoc->name;
149$paramcreditor = 'ONLINE_PAYMENT_CREDITOR';
150$paramcreditorlong = 'ONLINE_PAYMENT_CREDITOR_'.$suffix;
151if (getDolGlobalString($paramcreditorlong)) {
152 $creditor = getDolGlobalString($paramcreditorlong); // use label long of the seller to show
153} elseif (getDolGlobalString($paramcreditor)) {
154 $creditor = getDolGlobalString($paramcreditor); // use label short of the seller to show
155}
156
157
158$ispaymentok = false;
159// If payment is ok
160$PAYMENTSTATUS = $TRANSACTIONID = $LONGTRANSACTIONID = $TAXAMT = $NOTE = '';
161// If payment is ko
162$ErrorCode = $ErrorShortMsg = $ErrorLongMsg = $ErrorSeverityCode = '';
163
164
165$object = new stdClass(); // For triggers
166
167$error = 0;
168
169// Check if we have redirtodomain to do.
170$ws_virtuelhost = null;
171$ws_id = 0;
172$doactionsthenredirect = 0;
173if ($ws) {
174 $doactionsthenredirect = 1;
175 include_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php';
176 $website = new Website($db);
177 $result = $website->fetch(0, $ws);
178 if ($result > 0) {
179 $ws_virtuelhost = $website->virtualhost;
180 $ws_id = $website->id;
181 }
182}
183
184/*
185 * Actions
186 */
187
188// None
189
190
191/*
192 * View
193 */
194
195$now = dol_now();
196
197dol_syslog("Callback url when a payment was done. doactionsthenredirect=".$doactionsthenredirect." query_string=".(empty($_SERVER["QUERY_STRING"]) ? '' : dol_escape_htmltag($_SERVER["QUERY_STRING"]))." script_uri=".(empty($_SERVER["SCRIPT_URI"]) ? '' : dol_escape_htmltag($_SERVER["SCRIPT_URI"])), LOG_DEBUG, 0, '_payment');
198dol_syslog("_SERVER[SERVER_NAME] = ".(empty($_SERVER["SERVER_NAME"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_NAME"])), LOG_DEBUG, 0, '_payment');
199dol_syslog("_SERVER[SERVER_ADDR] = ".(empty($_SERVER["SERVER_ADDR"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_ADDR"])), LOG_DEBUG, 0, '_payment');
200
201$tracepost = "";
202foreach ($_POST as $k => $v) {
203 if (is_scalar($k) && is_scalar($v)) {
204 $tracepost .= "$k=$v\n";
205 }
206}
207dol_syslog("POST: ".$tracepost, LOG_DEBUG, 0, '_payment');
208
209$tracesession = "";
210foreach ($_SESSION as $k => $v) {
211 if (is_scalar($k) && is_scalar($v) && in_array($k, array('currencyCodeType', 'errormessage', 'FinalPaymentAmt', 'ipaddress', 'onlinetoken', 'payerID', 'paymentType', 'TRANSACTIONID', 'paymentoksessionkey', 'paymentkosessionkey'))) {
212 $tracesession .= "$k=$v\n";
213 }
214}
215dol_syslog("session_id=".session_id()." SESSION: ".$tracesession, LOG_DEBUG, 0, '_payment');
216
217dol_syslog("paymentoksessioncode=".GETPOST('paymentoksessioncode')." SESSION['paymentoksessioncode']=".$_SESSION['paymentoksessioncode'], LOG_DEBUG, 0, '_payment');
218
219$head = '';
220if (getDolGlobalString('ONLINE_PAYMENT_CSS_URL')) {
221 $head = '<link rel="stylesheet" type="text/css" href="' . getDolGlobalString('ONLINE_PAYMENT_CSS_URL').'?lang='.$langs->defaultlang.'">'."\n";
222}
223
224$conf->dol_hide_topmenu = 1;
225$conf->dol_hide_leftmenu = 1;
226
227
228// Show header
229if (empty($doactionsthenredirect)) {
230 $replacemainarea = (empty($conf->dol_hide_leftmenu) ? '<div>' : '').'<div>';
231 llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea);
232
233
234 // Show page content id="dolpaymentdiv"
235 print '<span id="dolpaymentspan"></span>'."\n";
236 print '<div id="dolpaymentdiv" class="center">'."\n";
237
238
239 // Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo)
240 // Define logo and logosmall
241 $logosmall = $mysoc->logo_small;
242 $logo = $mysoc->logo;
243 $paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix;
244 if (getDolGlobalString($paramlogo)) {
245 $logosmall = getDolGlobalString($paramlogo);
246 } elseif (getDolGlobalString('ONLINE_PAYMENT_LOGO')) {
247 $logosmall = getDolGlobalString('ONLINE_PAYMENT_LOGO');
248 }
249 //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n";
250 // Define urllogo
251 $urllogo = '';
252 $urllogofull = '';
253 if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) {
254 $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall);
255 $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall);
256 } elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) {
257 $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo);
258 $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo);
259 }
260
261 // Output html code for logo
262 if ($urllogo) {
263 print '<div class="backgreypublicpayment">';
264 print '<div class="logopublicpayment">';
265 print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
266 print '>';
267 print '</div>';
268 if (!getDolGlobalString('MAIN_HIDE_POWERED_BY')) {
269 print '<div class="poweredbypublicpayment opacitymedium right"><a class="poweredbyhref" href="https://www.dolibarr.org?utm_medium=website&utm_source=poweredby" target="dolibarr" rel="noopener">'.$langs->trans("PoweredBy").'<br><img class="poweredbyimg" src="'.DOL_URL_ROOT.'/theme/dolibarr_logo.svg" width="80px"></a></div>';
270 }
271 print '</div>';
272 } elseif ($creditor) {
273 print '<div class="backgreypublicpayment">';
274 print '<div class="logopublicpayment">';
275 print $creditor;
276 print '</div>';
277 print '</div>';
278 }
279 if (getDolGlobalString('MAIN_IMAGE_PUBLIC_PAYMENT')) {
280 print '<div class="backimagepublicpayment">';
281 print '<img id="idMAIN_IMAGE_PUBLIC_PAYMENT" src="' . getDolGlobalString('MAIN_IMAGE_PUBLIC_PAYMENT').'">';
282 print '</div>';
283 }
284
285
286 print '<br><br><br>';
287}
288
289
290// Add steps to validate payment is complete when we enter this page
291$service = $paymentmethod; // to have a default value. We may change it later for 'StripeLive' or 'StripeTest'...
292
293// For Paypal: validate the payment (Paypal need another step after the callback return to validate the payment).
294if (isModEnabled('paypal') && $paymentmethod === 'paypal') { // We call this page only if payment is ok on payment system
295 if (!empty($PAYPALTOKEN)) {
296 // TODO: Move this block to the top to ensure all session variables (e.g., TRANSACTIONID, FinalPaymentAmt, currencyCodeType, etc.) are loaded before executing checks for any payment module.
297 // Get on url call
298 $onlinetoken = $PAYPALTOKEN;
299 $fulltag = $FULLTAG;
300 $payerID = !empty($PAYPALPAYERID) ? $PAYPALPAYERID : '';
301 // Set by newpayment.php
302 $ipaddress = $_SESSION['ipaddress'];
303 $currencyCodeType = $_SESSION['currencyCodeType'];
304 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
305 $paymentType = $_SESSION['PaymentType']; // Value can be 'Mark', 'Sole', 'Sale' for example
306
307 dol_syslog("Call paymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
308
309 // Validate record
310 if (!empty($paymentType)) {
311 dol_syslog("We call GetExpressCheckoutDetails", LOG_DEBUG, 0, '_payment');
312 $resArray = getDetails($onlinetoken);
313 //var_dump($resarray);
314
315 $ack = strtoupper($resArray["ACK"]);
316 if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
317 // Nothing to do
318 dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
319 } else {
320 dol_syslog("Call to GetExpressCheckoutDetails return error: ".formatLogObject($resArray), LOG_WARNING, 0, '_payment');
321 }
322
323 dol_syslog("We call DoExpressCheckoutPayment token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
324 $resArray2 = confirmPayment($onlinetoken, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $fulltag);
325 //var_dump($resarray);
326
327 $ack = strtoupper($resArray2["ACK"]);
328 if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
329 dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
330
331 $object->source = $source;
332 $object->ref = $ref;
333 $object->payerID = $payerID;
334 $object->fulltag = $fulltag;
335 $object->resArray = $resArray2;
336
337 // resArray was built from a string like that
338 // TOKEN=EC%2d1NJ057703V9359028&TIMESTAMP=2010%2d11%2d01T11%3a40%3a13Z&CORRELATIONID=1efa8c6a36bd8&ACK=Success&VERSION=56&BUILD=1553277&TRANSACTIONID=9B994597K9921420R&TRANSACTIONTYPE=expresscheckout&PAYMENTTYPE=instant&ORDERTIME=2010%2d11%2d01T11%3a40%3a12Z&AMT=155%2e57&FEEAMT=5%2e54&TAXAMT=0%2e00&CURRENCYCODE=EUR&PAYMENTSTATUS=Completed&PENDINGREASON=None&REASONCODE=None
339 $PAYMENTSTATUS = urldecode($resArray2["PAYMENTSTATUS"]); // Should contains 'Completed'
340 $TRANSACTIONID = urldecode($resArray2["TRANSACTIONID"]);
341 $TAXAMT = urldecode($resArray2["TAXAMT"]);
342 $NOTE = urldecode($resArray2["NOTE"]);
343
344 $ispaymentok = true;
345 } else {
346 dol_syslog("Call to DoExpressCheckoutPayment return error: ".formatLogObject($resArray2), LOG_WARNING, 0, '_payment');
347
348 //Display a user friendly Error on the page using any of the following error information returned by PayPal
349 $ErrorCode = urldecode($resArray2["L_ERRORCODE0"]);
350 $ErrorShortMsg = urldecode($resArray2["L_SHORTMESSAGE0"]);
351 $ErrorLongMsg = urldecode($resArray2["L_LONGMESSAGE0"]);
352 $ErrorSeverityCode = urldecode($resArray2["L_SEVERITYCODE0"]);
353 }
354 } else {
355 $ErrorCode = "SESSIONEXPIRED";
356 $ErrorLongMsg = "Session expired. Can't retrieve PaymentType. Payment has not been validated.";
357 $ErrorShortMsg = "Session expired";
358
359 dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
360 dol_print_error(null, 'Session expired');
361 }
362 } else {
363 $ErrorCode = "PAYPALTOKENNOTDEFINED";
364 $ErrorLongMsg = "The parameter PAYPALTOKEN was not defined. Payment has not been validated.";
365 $ErrorShortMsg = "Parameter PAYPALTOKEN not defined";
366
367 dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
368 dol_print_error(null, 'PAYPALTOKEN not defined');
369 }
370}
371
372// For Stripe
373if (isModEnabled('stripe') && $paymentmethod === 'stripe') {
374 // TODO: Move this block to the top to ensure all session variables (e.g., TRANSACTIONID, FinalPaymentAmt, currencyCodeType, etc.) are loaded before executing checks for any payment module.
375 if (empty($TRANSACTIONID)) {
376 $TRANSACTIONID = empty($_SESSION['TRANSACTIONID']) ? '' : $_SESSION['TRANSACTIONID']; // pi_... or ch_...
377 if (empty($TRANSACTIONID) && GETPOST('payment_intent', 'alphanohtml')) {
378 // For the case we use STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION = 2
379 $TRANSACTIONID = GETPOST('payment_intent', 'alphanohtml');
380 }
381 }
382 $FinalPaymentAmt = empty($_SESSION["FinalPaymentAmt"]) ? '' : $_SESSION["FinalPaymentAmt"];
383 $currencyCodeType = empty($_SESSION['currencyCodeType']) ? '' : $_SESSION['currencyCodeType'];
384
385 $service = 'StripeTest';
386 $servicestatus = 0;
387 if (getDolGlobalString('STRIPE_LIVE')/* && !GETPOSTINT('forcesandbox') */) {
388 $service = 'StripeLive';
389 $servicestatus = 1;
390 }
391
392 // Check we are coming from the newpaymentpage
393 // Bypass session check when returning from Stripe confirmPayment() (mode STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION=2)
394 // In that case, payment_intent is passed in GET by Stripe and PaymentIntent::retrieve() below acts as verification
395 if (!GETPOST('payment_intent', 'alphanohtml') && GETPOST('paymentoksessioncode') !== $_SESSION['paymentoksessioncode']) {
396 $error++;
397 $errmsg = 'Attempted direct access to the paymentok page without a valid session.';
398 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
399 }
400
401 // Check on payment platform that the payment has been really validated
402 if (!$error && $TRANSACTIONID) {
403 // Stripe payment verification via Stripe API
404 try {
405 include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
406 $stripe = new Stripe($db);
407 $stripeacc = $stripe->getStripeAccount($service);
408
409 // Use the correct Stripe API key
410 global $stripearrayofkeysbyenv;
411 \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
412
413 try {
414 if (empty($stripeacc)) {
415 $paymentIntent = \Stripe\PaymentIntent::retrieve($TRANSACTIONID);
416 } else {
417 $paymentIntent = \Stripe\PaymentIntent::retrieve($TRANSACTIONID, array("stripe_account" => $stripeacc));
418 }
419
420 // Check amount and currency
421 // Handle zero-decimal currencies that don't use cents/subunits
422 $zeroDecimalCurrencies = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
423 if (in_array(strtoupper($currencyCodeType), $zeroDecimalCurrencies)) {
424 $expectedAmount = (int) round($FinalPaymentAmt); // No cents for these currencies
425 } else {
426 $expectedAmount = (int) round($FinalPaymentAmt * 100); // Stripe uses cents for most currencies
427 }
428 $expectedCurrency = strtolower($currencyCodeType);
429
430 if ((int) $paymentIntent->amount !== $expectedAmount || strtolower($paymentIntent->currency) !== $expectedCurrency) {
431 $error++;
432 $errmsg = 'Stripe payment information mismatch: expected amount ' . $expectedAmount . ' and currency ' . $expectedCurrency . ', got amount ' . $paymentIntent->amount . ' and currency ' . $paymentIntent->currency;
433 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
434 }
435 if ($paymentIntent->status !== 'succeeded') {
436 $error++;
437 $errmsg = 'Stripe payment not succeeded. Status: ' . $paymentIntent->status;
438 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
439 }
440
441 // Get $customerid and $pkey to forge $LONGTRANSACTIONID
442 $customerid = '';
443 $pkey = '';
444 if ($paymentIntent instanceof \Stripe\PaymentIntent) {
445 $customerid = $paymentIntent->customer;
446 }
447 if (isset($stripearrayofkeysbyenv[$servicestatus]['publishable_key'])) {
448 $pkey = $stripearrayofkeysbyenv[$servicestatus]['publishable_key'];
449 }
450
451 if ($customerid && $pkey) {
452 $LONGTRANSACTIONID = $TRANSACTIONID.':'.$customerid.'@'.$pkey;
453 }
454 } catch (\Stripe\Exception\ApiErrorException $e) {
455 $error++;
456 $errormessage = "Stripe API error: ".$e->getMessage();
457 dol_syslog($errormessage, LOG_ERR, 0, '_payment');
458 setEventMessages($e->getMessage(), null, 'errors');
459 } catch (Exception $e) {
460 $error++;
461 $errormessage = "CantRetrievePaymentIntent: ".$e->getMessage();
462 dol_syslog($errormessage, LOG_ERR, 0, '_payment');
463 setEventMessages($e->getMessage(), null, 'errors');
464 }
465 } catch (Exception $e) {
466 $error++;
467 $errmsg = 'Stripe API error: ' . $e->getMessage();
468 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
469 }
470 } else {
471 $error++;
472 $errmsg = 'Stripe payment verification failed: TRANSACTIONID is not set or session key does not match.';
473 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
474 setEventMessages($errmsg, null, 'errors');
475 }
476
477 if (!$error) {
478 $ispaymentok = true; // We will do the rest of code
479 } else {
480 $ispaymentok = false; // We won't do the rest of code
481 }
482}
483
484// For other payment modules
485if (!in_array($paymentmethod, array('paypal', 'paybox', 'stripe'))) {
486 // Check status of the object to verify if it is paid by external payment modules
487 $action = '';
488 $parameters = [
489 'paymentmethod' => $paymentmethod,
490 ];
491 $reshook = $hookmanager->executeHooks('isPaymentOK', $parameters, $object, $action);
492 if ($reshook >= 0) {
493 if (isset($hookmanager->resArray['ispaymentok'])) {
494 dol_syslog('ispaymentok overwrite by hook return with value='.$hookmanager->resArray['ispaymentok'], LOG_DEBUG, 0, '_payment');
495 $ispaymentok = $hookmanager->resArray['ispaymentok'];
496 }
497 } else {
498 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
499 }
500}
501
502// TODO: Move this block to the top to ensure all session variables (e.g., TRANSACTIONID, FinalPaymentAmt, currencyCodeType, etc.) are loaded before executing checks for any payment module.
503// Get variable into the session env
504if (empty($ipaddress)) {
505 $ipaddress = $_SESSION['ipaddress'];
506}
507if (empty($FinalPaymentAmt)) {
508 $FinalPaymentAmt = empty($_SESSION["FinalPaymentAmt"]) ? '' : $_SESSION["FinalPaymentAmt"];
509}
510if (empty($currencyCodeType)) {
511 $currencyCodeType = empty($_SESSION['currencyCodeType']) ? '' : $_SESSION['currencyCodeType'];
512}
513if (empty($paymentType)) { // Seems used only by Paypal
514 $paymentType = empty($_SESSION["paymentType"]) ? '' : $_SESSION["paymentType"];
515}
516
517if (empty($TRANSACTIONID)) {
518 $TRANSACTIONID = empty($_SESSION['TRANSACTIONID']) ? '' : $_SESSION['TRANSACTIONID']; // pi_... or ch_...
519 if (empty($TRANSACTIONID) && GETPOST('payment_intent', 'alphanohtml')) {
520 // For the case we use STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION = 2
521 $TRANSACTIONID = GETPOST('payment_intent', 'alphanohtml');
522 }
523}
524
525$fulltag = $FULLTAG;
526$tmptag = dolExplodeIntoArray($fulltag, '.', '=');
527
528
529dol_syslog("ispaymentok=".$ispaymentok." tmptag=".formatLogObject($tmptag), LOG_DEBUG, 0, '_payment');
530
531
532// Set $appli for emails title
533$appli = $mysoc->name;
534
535
536// Make complementary actions (post payment actions if payment is ok)
537$ispostactionok = 0;
538$paymentTypeId = 0;
539$postactionmessages = array();
540if ($ispaymentok) {
541 // Set permission for the anonymous user
542 if (empty($user->rights->societe)) {
543 $user->rights->societe = new stdClass();
544 }
545 if (empty($user->rights->facture)) {
546 $user->rights->facture = new stdClass();
547 $user->rights->facture->invoice_advance = new stdClass();
548 }
549 if (empty($user->rights->adherent)) {
550 $user->rights->adherent = new stdClass();
551 $user->rights->adherent->cotisation = new stdClass();
552 }
553 $user->rights->societe->creer = 1;
554 $user->rights->facture->creer = 1;
555 $user->rights->facture->invoice_advance->validate = 1;
556 $user->rights->adherent->cotisation->creer = 1;
557
558 if (array_key_exists('MEM', $tmptag) && $tmptag['MEM'] > 0) {
559 // Validate member
560 // Create subscription
561 // Create complementary actions (this include creation of thirdparty)
562 // Send confirmation email
563
564 // Record subscription
565 include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
566 include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
567 include_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
568 $adht = new AdherentType($db);
569 $object = new Adherent($db);
570
571 $result1 = $object->fetch((int) $tmptag['MEM']);
572 $result2 = $adht->fetch($object->typeid);
573
574 $defaultdelay = !empty($adht->duration_value) ? $adht->duration_value : 1;
575 $defaultdelayunit = !empty($adht->duration_unit) ? $adht->duration_unit : 'y';
576
577 dol_syslog("We have to process member with id=".$tmptag['MEM']." result1=".$result1." result2=".$result2, LOG_DEBUG, 0, '_payment');
578
579 if ($result1 > 0 && $result2 > 0) {
580 if ($paymentmethod == 'paybox') {
581 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
582 }
583 if ($paymentmethod == 'paypal') {
584 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
585 }
586 if ($paymentmethod == 'stripe') {
587 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
588 }
589 if (empty($paymentTypeId)) {
590 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
591
592 if (empty($paymentType)) {
593 $paymentType = 'CB';
594 }
595 // May return nothing when paymentType means nothing
596 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
597 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
598
599 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
600 if (empty($paymentTypeId) || $paymentTypeId < 0) {
601 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
602 }
603 }
604
605 dol_syslog("FinalPaymentAmt=".$FinalPaymentAmt." paymentTypeId=".$paymentTypeId." currencyCodeType=".$currencyCodeType, LOG_DEBUG, 0, '_payment');
606
607 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
608 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
609 $typeid = $object->typeid;
610 $amountbytype = $adht->amountByType(1); // Load the array of amount per type
611 $minimumamountbytype = $adht->minimumamountbytype(1); // Load the array of minimum amount per type
612 $minimumamount = empty($minimumamountbytype[$typeid]) ? 0 : $minimumamountbytype[$typeid];
613 // Security protection:
614 if (empty($adht->caneditamount)) { // If we didn't allow members to choose their membership amount (if the amount is allowed in edit mode, no need to check)
615 if ($object->status == $object::STATUS_DRAFT) { // If the member is not yet validated, we check that the amount is the same as expected.
616 // Set amount for the subscription:
617 // - First check the amount of the member type.
618 $amountexpected = empty($amountbytype[$typeid]) ? 0 : $amountbytype[$typeid];
619 // - If not set, we accept to have amount defined as parameter (for backward compatibility).
620 //if (empty($amount)) {
621 // $amount = (GETPOST('amount') ? price2num(GETPOST('amount', 'alpha'), 'MT', 2) : '');
622 //}
623 // - If a min is set, we take it into account
624 $amountexpected = max(0, (float) $amountexpected, (float) getDolGlobalInt("MEMBER_MIN_AMOUNT"), (float) $minimumamount);
625
626 if ($amountexpected && $amountexpected != $FinalPaymentAmt) {
627 $error++;
628 $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') propagated by payment page differs from the expected value for membership ('.$amountexpected.'). May be a hack to try to pay a different amount ?';
629 $postactionmessages[] = $errmsg;
630 $ispostactionok = -1;
631 dol_syslog("Failed to validate member (bad amount check): ".$errmsg, LOG_ERR, 0, '_payment');
632 }
633 }
634 }
635
636 // Security protection:
637 if (getDolGlobalInt('MEMBER_MIN_AMOUNT')) {
638 if ($FinalPaymentAmt < getDolGlobalInt('MEMBER_MIN_AMOUNT') || $FinalPaymentAmt < $minimumamount) {
639 $error++;
640 $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') is lower than the minimum allowed (' . max(getDolGlobalString('MEMBER_MIN_AMOUNT'), $minimumamount).'). May be a hack to try to pay a different amount ?';
641 $postactionmessages[] = $errmsg;
642 $ispostactionok = -1;
643 dol_syslog("Failed to validate member (amount propagated from payment page is lower than allowed minimum): ".$errmsg, LOG_ERR, 0, '_payment');
644 }
645 }
646
647 // Security protection:
648 if ($currencyCodeType && $currencyCodeType != $conf->currency) { // Check that currency is the good one
649 $error++;
650 $errmsg = 'Value of currencyCodeType ('.$currencyCodeType.') differs from value expected for membership ('.$conf->currency.'). May be a hack to try to pay a different amount ?';
651 $postactionmessages[] = $errmsg;
652 $ispostactionok = -1;
653 dol_syslog("Failed to validate member (bad currency check): ".$errmsg, LOG_ERR, 0, '_payment');
654 }
655
656 if (! $error) {
657 // We validate the member (no effect if it is already validated)
658 $result = ($object->status == $object::STATUS_EXCLUDED) ? -1 : $object->validate($user); // if membre is excluded (status == -2) the new validation is not possible
659 if ($result < 0) {
660 $error++;
661 $errmsg = $object->error;
662 $postactionmessages[] = $errmsg;
663 $postactionmessages = array_merge($postactionmessages, $object->errors);
664 $ispostactionok = -1;
665 dol_syslog("Failed to validate member: ".$errmsg, LOG_ERR, 0, '_payment');
666 }
667 // Member is validated but date of validation is empty so we set it
668 if (empty($object->datevalid)) {
669 dol_syslog("Member date of validation is empty. We define it", LOG_WARNING, 0, '_payment');
670 $now = dol_now();
671 $sql = "UPDATE ".MAIN_DB_PREFIX."adherent SET";
672 $sql .= " datevalid = '".$db->idate($now)."'";
673 $sql .= " WHERE rowid = ".((int) $object->id);
674 $result = $db->query($sql);
675 if ($result) {
676 $object->datevalid = $now;
677 } else {
678 $errmsg = $db->error();
679 $postactionmessages[] = $errmsg;
680 $error++;
681 $ispostactionok = -1;
682 dol_syslog("Failed to set date of validation: ".$errmsg, LOG_ERR, 0, '_payment');
683 }
684 }
685 }
686
687 // Guess the subscription start date
688 $datesubscription = $object->datevalid; // By default, the subscription start date is the payment date
689 if ($object->datefin > 0) {
690 $datesubscription = dol_time_plus_duree($object->datefin, 1, 'd');
691 } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER')) {
692 $datesubscription = dol_time_plus_duree($now, (int) substr(getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER'), 0, -1), substr(getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER'), -1));
693 }
694 // Now do a correction of the suggested date
695 if (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "m") {
696 $datesubscription = dol_get_first_day((int) dol_print_date($datesubscription, "%Y"), (int) dol_print_date($datesubscription, "%m"));
697 } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "3m") {
698 $datesubscription = dol_time_plus_duree($object->datefin, -3, 'm');
699 $datesubscription = dol_get_first_day((int) dol_print_date($datesubscription, "%Y"), (int) dol_print_date($datesubscription, "%m"));
700 } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "Y") {
701 $datesubscription = dol_get_first_day((int) dol_print_date($datesubscription, "%Y"));
702 }
703
704 $datesubend = 0;
705 if ($datesubscription && $defaultdelay && $defaultdelayunit) {
706 $datesubend = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
707 // the new end date of subscription must be in futur
708 while ($datesubend < $now) {
709 $datesubend = dol_time_plus_duree($datesubend, $defaultdelay, $defaultdelayunit);
710 $datesubscription = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
711 }
712 $datesubend = dol_time_plus_duree($datesubend, -1, 'd');
713 }
714
715 // Set output language
716 $outputlangs = new Translate('', $conf);
717 $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? (string) $mysoc->default_lang : (string) $object->thirdparty->default_lang);
718 $paymentdate = $now;
719 $amount = $FinalPaymentAmt;
720 $formatteddate = dol_print_date($paymentdate, 'dayhour', 'auto', $outputlangs);
721 $label = $langs->trans("OnlineSubscriptionPaymentLine", $formatteddate, $paymentmethod, $ipaddress, $TRANSACTIONID);
722
723 // Payment information
724 $accountid = 0;
725 if ($paymentmethod == 'paybox') {
726 $accountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
727 }
728 if ($paymentmethod == 'paypal') {
729 $accountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
730 }
731 if ($paymentmethod == 'stripe') {
732 $accountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
733 }
734
735 //Get bank account for a specific paymentmedthod
736 $parameters = [
737 'paymentmethod' => $paymentmethod,
738 ];
739 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
740 if ($reshook >= 0) {
741 if (isset($hookmanager->resArray['bankaccountid'])) {
742 dol_syslog('accountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
743 $accountid = $hookmanager->resArray['bankaccountid'];
744 }
745 }
746 if ($accountid < 0) {
747 $error++;
748 $errmsg = 'Setup of bank account to use for payment is not correctly done for payment method '.$paymentmethod;
749 $postactionmessages[] = $errmsg;
750 $ispostactionok = -1;
751 dol_syslog("Failed to get the bank account to record payment: ".$errmsg, LOG_ERR, 0, '_payment');
752 }
753
754 $operation = dol_getIdFromCode($db, $paymentTypeId, 'c_paiement', 'id', 'code', 1); // Payment mode code returned from payment mode id
755 $num_chq = '';
756 $emetteur_nom = '';
757 $emetteur_banque = '';
758 // Define default choice for complementary actions
759 $option = '';
760 if (getDolGlobalString('ADHERENT_BANK_USE') == 'bankviainvoice' && isModEnabled("bank") && isModEnabled("societe") && isModEnabled('invoice')) {
761 $option = 'bankviainvoice';
762 } elseif (getDolGlobalString('ADHERENT_BANK_USE') == 'bankdirect' && isModEnabled("bank")) {
763 $option = 'bankdirect';
764 } elseif (getDolGlobalString('ADHERENT_BANK_USE') == 'invoiceonly' && isModEnabled("bank") && isModEnabled("societe") && isModEnabled('invoice')) {
765 $option = 'invoiceonly';
766 }
767 if (empty($option)) {
768 $option = 'none';
769 }
770 $sendalsoemail = 1;
771 $crowid = 0;
772
773 // Record the subscription then complementary actions
774 $db->begin();
775
776 // Create subscription
777 if (!$error) {
778 dol_syslog("Call ->subscription to create subscription", LOG_DEBUG, 0, '_payment');
779
780 $crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend, $membertypeid);
781 if ($crowid <= 0) {
782 $error++;
783 $errmsg = $object->error;
784 $postactionmessages[] = $errmsg;
785 $ispostactionok = -1;
786 } else {
787 $postactionmessages[] = 'Subscription created (id='.$crowid.')';
788 $ispostactionok = 1;
789 }
790 }
791
792 $autocreatethirdparty = 0;
793
794 if (!$error) {
795 dol_syslog("Call ->subscriptionComplementaryActions option=".$option, LOG_DEBUG, 0, '_payment');
796
797 $autocreatethirdparty = 1; // will create third party if member not yet linked to a thirdparty
798
799 $result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque, $autocreatethirdparty, $TRANSACTIONID, $service);
800 if ($result < 0) {
801 dol_syslog("Error ".$object->error." ".implode(',', $object->errors), LOG_DEBUG, 0, '_payment');
802
803 $error++;
804 $postactionmessages[] = $object->error;
805 $postactionmessages = array_merge($postactionmessages, $object->errors);
806 $ispostactionok = -1;
807 } else {
808 if ($option == 'bankviainvoice') {
809 $postactionmessages[] = 'Invoice, payment and bank record created';
810 dol_syslog("Invoice, payment and bank record created", LOG_DEBUG, 0, '_payment');
811 }
812 if ($option == 'bankdirect') {
813 $postactionmessages[] = 'Bank record created';
814 dol_syslog("Bank record created", LOG_DEBUG, 0, '_payment');
815 }
816 if ($option == 'invoiceonly') {
817 $postactionmessages[] = 'Invoice recorded';
818 dol_syslog("Invoice recorded", LOG_DEBUG, 0, '_payment');
819 }
820 $ispostactionok = 1;
821
822 // If an invoice was created, it is into $object->invoice
823 }
824 }
825
826 if (!$error) {
827 // If payment using Stripe, save the Stripe payment info into societe_account
828 if ($paymentmethod == 'stripe' && $autocreatethirdparty && $option == 'bankviainvoice') {
829 $thirdparty_id = ($object->socid ? $object->socid : $object->fk_soc);
830
831 dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_payment');
832
833 $service = 'StripeTest';
834 $servicestatus = 0;
835 if (getDolGlobalString('STRIPE_LIVE')/* && !GETPOST('forcesandbox', 'alpha') */) {
836 $service = 'StripeLive';
837 $servicestatus = 1;
838 }
839 $stripeacc = ''; // No Oauth/connect use for public pages
840
841 $thirdparty = new Societe($db);
842 $thirdparty->fetch($thirdparty_id);
843
844 include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; // This also set $stripearrayofkeysbyenv
845 $stripe = new Stripe($db);
846 //$stripeacc = $stripe->getStripeAccount($service); Already defined previously
847
848 $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0);
849
850 if (!$customer && $TRANSACTIONID) { // Not linked to a stripe customer, we make the link
851 dol_syslog("No stripe profile found, so we add it for TRANSACTIONID = ".$TRANSACTIONID, LOG_DEBUG, 0, '_payment');
852
853 try {
854 global $stripearrayofkeysbyenv;
855 \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
856
857 if (preg_match('/^pi_/', $TRANSACTIONID)) {
858 // This may throw an error if not found.
859 $chpi = \Stripe\PaymentIntent::retrieve($TRANSACTIONID); // payment_intent (pi_...)
860 } else {
861 // This throw an error if not found
862 $chpi = \Stripe\Charge::retrieve($TRANSACTIONID); // old method, contains the charge id (ch_...)
863 }
864
865 if ($chpi) {
866 $stripecu = $chpi->customer; // value 'cus_....'. WARNING: This property may be empty if first payment was recorded before the stripe customer was created.
867
868 if (empty($stripecu)) {
869 // This include the INSERT
870 $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1);
871
872 // Link this customer to the payment intent
873 if (preg_match('/^pi_/', $TRANSACTIONID) && $customer) {
874 \Stripe\PaymentIntent::update($chpi->id, array('customer' => $customer->id));
875 }
876 } else {
877 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, site_account, status, entity, date_creation, fk_user_creat)";
878 $sql .= " VALUES (".((int) $thirdparty_id).", '', '".$db->escape($stripecu)."', 'stripe', '".$db->escape($stripearrayofkeysbyenv[$servicestatus]['publishable_key'])."', ".((int) $servicestatus).", ".((int) $conf->entity).", '".$db->idate(dol_now())."', 0)";
879 $resql = $db->query($sql);
880 if (!$resql) { // should not happen
881 $error++;
882 $errmsg = 'Failed to insert customer stripe id in database : '.$db->lasterror();
883 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
884 $postactionmessages[] = $errmsg;
885 $ispostactionok = -1;
886 }
887 }
888 } else { // should not happen
889 $error++;
890 $errmsg = 'Failed to retrieve paymentintent or charge from id';
891 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
892 $postactionmessages[] = $errmsg;
893 $ispostactionok = -1;
894 }
895 } catch (Exception $e) { // should not happen
896 $error++;
897 $errmsg = 'Failed to get or save customer stripe id in database : '.$e->getMessage();
898 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
899 $postactionmessages[] = $errmsg;
900 $ispostactionok = -1;
901 }
902 }
903 }
904 }
905
906 if (!$error) {
907 $db->commit();
908 } else {
909 $db->rollback();
910 }
911
912 // Set string to use to send email info
913 $infouserlogin = '';
914
915 // Create external user
916 if (getDolGlobalString('ADHERENT_CREATE_EXTERNAL_USER_LOGIN')) {
917 $nuser = new User($db);
918 $tmpuser = dol_clone($object, 0); // $object is type Adherent
919
920 // Check if a user login already exists for this member or not
921 $found = 0;
922 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."user WHERE fk_member = ".((int) $object->id);
923 $resqlcount = $db->query($sql);
924 if ($resqlcount) {
925 $objcount = $db->fetch_object($resqlcount);
926 if ($objcount) {
927 $found = $objcount->nb;
928 }
929 }
930
931 if (!$found) {
932 $result = $nuser->create_from_member($tmpuser, $object->login);
933 $newpassword = $nuser->setPassword($user, '');
934
935 if ($result < 0) {
936 $outputlangs->load("errors");
937 $postactionmessages[] = 'Error in create external user : '.$nuser->error;
938 } else {
939 $infouserlogin = $outputlangs->trans("Login").': '.$nuser->login.' '."\n".$outputlangs->trans("Password").': '.$newpassword;
940 $postactionmessages[] = $langs->trans("NewUserCreated", $nuser->login);
941 }
942 } else {
943 $outputlangs->load("errors");
944 $postactionmessages[] = 'No user created because a user linked to member already exists';
945 }
946 }
947
948 // Send email to member
949 if (!$error) {
950 dol_syslog("Send email to customer to ".$object->email." if we have to (sendalsoemail = ".$sendalsoemail.")", LOG_DEBUG, 0, '_payment');
951
952 // Send confirmation Email
953 if ($object->email && $sendalsoemail) {
954 $subject = '';
955 $msg = '';
956
957 // Send subscription email
958 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
959 $formmail = new FormMail($db);
960 // Load traductions files required by page
961 $outputlangs->loadLangs(array("main", "members"));
962 // Get email content from template
963 $arraydefaultmessage = null;
964 $labeltouse = getDolGlobalString('ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION');
965
966 if (!empty($labeltouse)) {
967 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
968 }
969
970 if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
971 $subject = $arraydefaultmessage->topic;
972 $msg = $arraydefaultmessage->content;
973 }
974
975 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
976
977 if ($infouserlogin) {
978 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = $infouserlogin;
979 }
980
981 complete_substitutions_array($substitutionarray, $outputlangs, $object);
982 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
983 $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
984
985 // Attach a file ?
986 $file = '';
987 $listofpaths = array();
988 $listofnames = array();
989 $listofmimes = array();
990 if (is_object($object->invoice)) {
991 $invoicediroutput = $conf->facture->dir_output;
992 $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
993 $file = $fileparams['fullname'];
994
995 $listofpaths = array($file);
996 $listofnames = array(basename($file));
997 $listofmimes = array(dol_mimetype($file));
998 }
999
1000 $moreinheader = 'X-Dolibarr-Info: send_an_email by public/payment/paymentok.php'."\r\n";
1001
1002 $result = $object->sendEmail($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, "", $moreinheader);
1003
1004 if ($result < 0) {
1005 $errmsg = $object->error;
1006 $postactionmessages[] = $errmsg;
1007 $ispostactionok = -1;
1008 } else {
1009 if ($file) {
1010 $postactionmessages[] = 'Email sent to member (with invoice document attached)';
1011 } else {
1012 $postactionmessages[] = 'Email sent to member (without any attached document)';
1013 }
1014
1015 // TODO Add actioncomm event
1016 }
1017 }
1018 }
1019 } else {
1020 $postactionmessages[] = 'Failed to get a valid value for "amount paid" or "payment type" to record the payment of subscription for member '.$tmptag['MEM'].'. May be payment was already recorded.';
1021 $ispostactionok = -1;
1022 }
1023 } else {
1024 $postactionmessages[] = 'Member '.$tmptag['MEM'].' for subscription paid was not found';
1025 $ispostactionok = -1;
1026 }
1027 } elseif (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) {
1028 // Record payment
1029 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1030 $object = new Facture($db);
1032 $result = $object->fetch((int) $tmptag['INV']);
1033 if ($result) {
1034 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1035
1036 $paymentTypeId = 0;
1037 if ($paymentmethod === 'paybox') {
1038 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1039 }
1040 if ($paymentmethod === 'paypal') {
1041 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1042 }
1043 if ($paymentmethod === 'stripe') {
1044 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1045 }
1046 if (empty($paymentTypeId)) {
1047 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1048
1049 if (empty($paymentType)) {
1050 $paymentType = 'CB';
1051 }
1052 // May return nothing when paymentType means nothing
1053 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1054 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1055
1056 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1057 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1058 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1059 }
1060 }
1061
1062 dol_syslog("FinalPaymentAmt = ".$FinalPaymentAmt." paymentTypeId = ".$paymentTypeId, LOG_DEBUG, 0, '_payment');
1063
1064 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1065 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1066 $db->begin();
1067
1068 // Creation of payment line
1069 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1070 $paiement = new Paiement($db);
1071 $paiement->datepaye = $now;
1072 if ($currencyCodeType == $conf->currency) {
1073 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1074 } else {
1075 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1076
1077 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1078 $ispostactionok = -1;
1079 $error++; // Not yet supported
1080 }
1081 $paiement->paiementid = $paymentTypeId;
1082 $paiement->num_payment = '';
1083 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1084
1085 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1086 if ($LONGTRANSACTIONID) {
1087 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1088 } else {
1089 $paiement->ext_payment_id = $TRANSACTIONID;
1090 }
1091 $paiement->ext_payment_site = $service;
1092
1093 // Validate invoice if not already validated (this can happen for automatically generated invoices with a free amount)
1094 if (!$error && $object->status == Facture::STATUS_DRAFT) {
1095 $result = $object->validate($user);
1096 if ($result < 0) {
1097 $postactionmessages[] = $object->error;
1098 $ispostactionok = -1;
1099 $error++;
1100 } else {
1101 $postactionmessages[] = 'Invoice validated';
1102 $ispostactionok = 1;
1103 }
1104 }
1105
1106 if (!$error) {
1107 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1108 if ($paiement_id < 0) {
1109 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1110 $ispostactionok = -1;
1111 $error++;
1112 } else {
1113 $postactionmessages[] = 'Payment created';
1114 $ispostactionok = 1;
1115 }
1116 }
1117
1118 if (!$error && isModEnabled("bank")) {
1119 $bankaccountid = 0;
1120 if ($paymentmethod == 'paybox') {
1121 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1122 } elseif ($paymentmethod == 'paypal') {
1123 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1124 } elseif ($paymentmethod == 'stripe') {
1125 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1126 }
1127
1128 //Get bank account for a specific paymentmedthod
1129 $parameters = [
1130 'paymentmethod' => $paymentmethod,
1131 ];
1132 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1133 if ($reshook >= 0) {
1134 if (isset($hookmanager->resArray['bankaccountid'])) {
1135 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1136 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1137 }
1138 }
1139 if ($bankaccountid > 0) {
1140 $label = '(CustomerInvoicePayment)';
1141 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1142 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1143 }
1144 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1145 if ($result < 0) {
1146 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1147 $ispostactionok = -1;
1148 $error++;
1149 } else {
1150 $postactionmessages[] = 'Bank transaction of payment created';
1151 $ispostactionok = 1;
1152 }
1153 } else {
1154 $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
1155 $ispostactionok = -1;
1156 $error++;
1157 }
1158 }
1159
1160 if (!$error) {
1161 $db->commit();
1162 } else {
1163 $db->rollback();
1164 }
1165 } else {
1166 $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['INV'].'. May be payment was already recorded.';
1167 $ispostactionok = -1;
1168 }
1169 } else {
1170 $postactionmessages[] = 'Invoice paid '.$tmptag['INV'].' was not found';
1171 $ispostactionok = -1;
1172 }
1173 } elseif (array_key_exists('ORD', $tmptag) && $tmptag['ORD'] > 0) {
1174 include_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
1175 $object = new Commande($db);
1176 $result = $object->fetch((int) $tmptag['ORD']);
1177 if ($result) {
1178 dol_syslog("We have loaded the order id=".$object->id." to use to create the invoice", LOG_DEBUG, 0, '_payment');
1179
1180 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1181
1182 $paymentTypeId = 0;
1183 if ($paymentmethod == 'paybox') {
1184 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1185 }
1186 if ($paymentmethod == 'paypal') {
1187 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1188 }
1189 if ($paymentmethod == 'stripe') {
1190 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1191 }
1192 if (empty($paymentTypeId)) {
1193 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1194
1195 if (empty($paymentType)) {
1196 $paymentType = 'CB';
1197 }
1198 // May return nothing when paymentType means nothing
1199 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1200 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1201
1202 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1203 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1204 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1205 }
1206 }
1207
1208 dol_syslog("The payment type id to use is paymentTypeId=".$paymentTypeId." and FinalPaymentAmt=".$FinalPaymentAmt, LOG_DEBUG, 0, '_payment');
1209
1210 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1211 if (isModEnabled('invoice')) {
1212 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1213 $db->begin();
1214
1215 include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1216 $invoice = new Facture($db);
1217 $result = $invoice->createFromOrder($object, $user);
1218 if ($result > 0) {
1219 if ($FinalPaymentAmt != $object->total_ttc) {
1220 // The amount paid can be lower than the order only if the user tried to modified the amount from the payment page. A payment has been received but it is a hack attempt
1221 // We can add a line to reduce the amount of the invoice but with which vat ?
1222 // TODO Test if vat on line is the same everywhere, if yes we can add
1223 // $invoice->addline('Fix amount of invoice', $FinalPaymentAmt - $object->total_ttc, 1, $txtva);
1224 // TODO Send a warning email.
1225 }
1226
1227 $object->classifyBilled($user); // The invoice has been created from the order so total is the same, so we can classify order to billed (even if payment may be partial).
1228
1229 $invoice->validate($user); // This may re-classify all linked orders to billed (done previously) if amount of invoice is ok by triggers, depending on the workflow module setup.
1230
1231 // Creation of payment line (warning: if amount has been modified on page, the payment may be partial)
1232 include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
1233 $paiement = new Paiement($db);
1234 $paiement->datepaye = $now;
1235 if ($currencyCodeType == $conf->currency) {
1236 $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1237 } else {
1238 $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
1239
1240 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1241 $ispostactionok = -1;
1242 $error++;
1243 }
1244 $paiement->paiementid = $paymentTypeId;
1245 $paiement->num_payment = '';
1246 $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
1247
1248 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1249 if ($LONGTRANSACTIONID) {
1250 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1251 } else {
1252 $paiement->ext_payment_id = $TRANSACTIONID;
1253 }
1254 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1255
1256 if (!$error) {
1257 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1258 if ($paiement_id < 0) {
1259 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1260 $ispostactionok = -1;
1261 $error++;
1262 } else {
1263 $postactionmessages[] = 'Payment created';
1264 $ispostactionok = 1;
1265 }
1266 }
1267
1268 if (!$error && isModEnabled("bank")) {
1269 $bankaccountid = 0;
1270 if ($paymentmethod == 'paybox') {
1271 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1272 } elseif ($paymentmethod == 'paypal') {
1273 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1274 } elseif ($paymentmethod == 'stripe') {
1275 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1276 }
1277
1278 //Get bank account for a specific paymentmedthod
1279 $parameters = [
1280 'paymentmethod' => $paymentmethod,
1281 ];
1282 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1283 if ($reshook >= 0) {
1284 if (isset($hookmanager->resArray['bankaccountid'])) {
1285 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1286 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1287 }
1288 }
1289 if ($bankaccountid > 0) {
1290 $label = '(CustomerInvoicePayment)';
1291 if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
1292 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1293 }
1294 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1295 if ($result < 0) {
1296 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1297 $ispostactionok = -1;
1298 $error++;
1299 } else {
1300 $postactionmessages[] = 'Bank transaction of payment created';
1301 $ispostactionok = 1;
1302 }
1303 } else {
1304 $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
1305 $ispostactionok = -1;
1306 $error++;
1307 }
1308 }
1309 } else {
1310 $postactionmessages[] = 'Failed to create invoice form order ' . $tmptag['ORD'] . '.';
1311 $ispostactionok = -1;
1312 $error++;
1313 }
1314
1315 if (!$error) {
1316 $db->commit();
1317 } else {
1318 $db->rollback();
1319 }
1320 } else {
1321 $postactionmessages[] = 'Failed to get a valid value for "amount paid" (' . $FinalPaymentAmt . ') or "payment type id" (' . $paymentTypeId . ') to record the payment of order ' . $tmptag['ORD'] . '. May be payment was already recorded.';
1322 $ispostactionok = -1;
1323 }
1324 } else {
1325 $postactionmessages[] = 'Invoice module is not enable';
1326 $ispostactionok = -1;
1327 }
1328 } else {
1329 $postactionmessages[] = 'Order paid ' . $tmptag['ORD'] . ' was not found';
1330 $ispostactionok = -1;
1331 }
1332 } elseif (array_key_exists('DON', $tmptag) && $tmptag['DON'] > 0) {
1333 include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
1334 $don = new Don($db);
1335 $result = $don->fetch((int) $tmptag['DON']);
1336 if ($result) {
1337 $paymentTypeId = 0;
1338 if ($paymentmethod == 'paybox') {
1339 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1340 }
1341 if ($paymentmethod == 'paypal') {
1342 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1343 }
1344 if ($paymentmethod == 'stripe') {
1345 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1346 }
1347 if (empty($paymentTypeId)) {
1348 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1349
1350 if (empty($paymentType)) {
1351 $paymentType = 'CB';
1352 }
1353 // May return nothing when paymentType means nothing
1354 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1355 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1356
1357 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1358 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1359 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1360 }
1361 }
1362
1363 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1364 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1365 $db->begin();
1366
1367 // Creation of paiement line for donation
1368 include_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php';
1369 $paiement = new PaymentDonation($db);
1370
1371 $totalpaid = $FinalPaymentAmt;
1372
1373 if ($currencyCodeType == $conf->currency) {
1374 $paiement->amounts = array($object->id => $totalpaid); // Array with all payments dispatching with donation
1375 } else {
1376 // PaymentDonation does not support multi currency
1377 $postactionmessages[] = 'Payment donation can\'t be paid with different currency than '.$conf->currency;
1378 $ispostactionok = -1;
1379 $error++; // Not yet supported
1380 }
1381
1382 $paiement->fk_donation = $don->id;
1383 $paiement->datep = $now;
1384 $paiement->paymenttype = $paymentTypeId;
1385 $paiement->num_payment = '';
1386 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1387
1388 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1389 if ($LONGTRANSACTIONID) {
1390 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1391 } else {
1392 $paiement->ext_payment_id = $TRANSACTIONID;
1393 }
1394 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1395
1396 if (!$error) {
1397 $paiement_id = $paiement->create($user, 1);
1398 if ($paiement_id < 0) {
1399 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1400 $ispostactionok = -1;
1401 $error++;
1402 } else {
1403 $postactionmessages[] = 'Payment created';
1404 $ispostactionok = 1;
1405
1406 if ($totalpaid >= $don->getRemainToPay()) {
1407 $don->valid_promesse($don->id, $user->id);
1408 $don->setPaid($don->id);
1409 }
1410 }
1411 }
1412
1413 if (!$error && isModEnabled("bank")) {
1414 $bankaccountid = 0;
1415 if ($paymentmethod == 'paybox') {
1416 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1417 } elseif ($paymentmethod == 'paypal') {
1418 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1419 } elseif ($paymentmethod == 'stripe') {
1420 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1421 }
1422
1423 //Get bank account for a specific paymentmedthod
1424 $parameters = [
1425 'paymentmethod' => $paymentmethod,
1426 ];
1427 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1428 if ($reshook >= 0) {
1429 if (isset($hookmanager->resArray['bankaccountid'])) {
1430 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1431 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1432 }
1433 }
1434 if ($bankaccountid > 0) {
1435 $label = '(DonationPayment)';
1436 $result = $paiement->addPaymentToBank($user, 'payment_donation', $label, $bankaccountid, '', '');
1437 if ($result < 0) {
1438 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1439 $ispostactionok = -1;
1440 $error++;
1441 } else {
1442 $postactionmessages[] = 'Bank transaction of payment created';
1443 $ispostactionok = 1;
1444 }
1445 } else {
1446 $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
1447 $ispostactionok = -1;
1448 $error++;
1449 }
1450 }
1451
1452 if (!$error) {
1453 $db->commit();
1454 } else {
1455 $db->rollback();
1456 }
1457 } else {
1458 $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of donation '.$tmptag['DON'].'. May be payment was already recorded.';
1459 $ispostactionok = -1;
1460 }
1461 } else {
1462 $postactionmessages[] = 'Donation paid '.$tmptag['DON'].' was not found';
1463 $ispostactionok = -1;
1464 }
1465
1466 // TODO send email with acknowledgment for the donation
1467 // (we need first that the donation module is able to generate a pdf document for the cerfa with pre filled content)
1468 } elseif (array_key_exists('ATT', $tmptag) && $tmptag['ATT'] > 0) {
1469 // Record payment for registration to an event for an attendee
1470 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1471 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1472 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1473 $object = new Facture($db);
1474 $result = $object->fetch((int) $ref); // @phan-suppress-curren-line PhanPluginSuspiciousParamPosition
1475 if ($result) {
1476 $paymentTypeId = 0;
1477 if ($paymentmethod == 'paybox') {
1478 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1479 }
1480 if ($paymentmethod == 'paypal') {
1481 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1482 }
1483 if ($paymentmethod == 'stripe') {
1484 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1485 }
1486 if (empty($paymentTypeId)) {
1487 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1488
1489 if (empty($paymentType)) {
1490 $paymentType = 'CB';
1491 }
1492 // May return nothing when paymentType means nothing
1493 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1494 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1495
1496 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1497 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1498 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1499 }
1500 }
1501
1502 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1503 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1504 $resultvalidate = $object->validate($user);
1505 if ($resultvalidate < 0) {
1506 $postactionmessages[] = 'Cannot validate invoice';
1507 $ispostactionok = -1;
1508 $error++; // Not yet supported
1509 } else {
1510 $db->begin();
1511
1512 // Creation of payment line
1513 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1514 $paiement = new Paiement($db);
1515 $paiement->datepaye = $now;
1516 if ($currencyCodeType == $conf->currency) {
1517 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1518 } else {
1519 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1520
1521 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1522 $ispostactionok = -1;
1523 $error++; // Not yet supported
1524 }
1525 $paiement->paiementid = $paymentTypeId;
1526 $paiement->num_payment = '';
1527 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress.' for event registration';
1528
1529 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1530 if ($LONGTRANSACTIONID) {
1531 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1532 } else {
1533 $paiement->ext_payment_id = $TRANSACTIONID;
1534 }
1535 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1536
1537 if (!$error) {
1538 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1539 if ($paiement_id < 0) {
1540 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1541 $ispostactionok = -1;
1542 $error++;
1543 } else {
1544 $postactionmessages[] = 'Payment created';
1545 $ispostactionok = 1;
1546 }
1547 }
1548
1549 if (!$error && isModEnabled("bank")) {
1550 $bankaccountid = 0;
1551 if ($paymentmethod == 'paybox') {
1552 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1553 } elseif ($paymentmethod == 'paypal') {
1554 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1555 } elseif ($paymentmethod == 'stripe') {
1556 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1557 }
1558
1559 //Get bank account for a specific paymentmedthod
1560 $parameters = [
1561 'paymentmethod' => $paymentmethod,
1562 ];
1563 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1564 if ($reshook >= 0) {
1565 if (isset($hookmanager->resArray['bankaccountid'])) {
1566 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1567 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1568 }
1569 }
1570 if ($bankaccountid > 0) {
1571 $label = '(CustomerInvoicePayment)';
1572 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1573 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1574 }
1575 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1576 if ($result < 0) {
1577 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1578 $ispostactionok = -1;
1579 $error++;
1580 } else {
1581 $postactionmessages[] = 'Bank transaction of payment created';
1582 $ispostactionok = 1;
1583 }
1584 } else {
1585 $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
1586 $ispostactionok = -1;
1587 $error++;
1588 }
1589 }
1590
1591 $attendeetovalidate = new ConferenceOrBoothAttendee($db);
1592
1593 if (!$error) {
1594 // Validating the attendee
1595 $resultattendee = $attendeetovalidate->fetch((int) $tmptag['ATT']);
1596 if ($resultattendee < 0) {
1597 $error++;
1598 setEventMessages(null, $attendeetovalidate->errors, "errors");
1599 } else {
1600 $attendeetovalidate->validate($user);
1601
1602 $attendeetovalidate->amount = $FinalPaymentAmt;
1603 $attendeetovalidate->date_subscription = dol_now();
1604 $attendeetovalidate->update($user);
1605 }
1606 }
1607
1608 if (!$error) {
1609 $db->commit();
1610 } else {
1611 setEventMessages(null, $postactionmessages, 'warnings');
1612
1613 $db->rollback();
1614 }
1615
1616 if (! $error) {
1617 // Sending mail
1618 $thirdparty = new Societe($db);
1619 $resultthirdparty = $thirdparty->fetch($attendeetovalidate->fk_soc);
1620 if ($resultthirdparty < 0) {
1621 setEventMessages($thirdparty->error, $thirdparty->errors, "errors");
1622 } else {
1623 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1624 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1625 $formmail = new FormMail($db);
1626 // Set output language
1627 $outputlangs = new Translate('', $conf);
1628 $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? (string) $mysoc->default_lang : (string) $thirdparty->default_lang);
1629 // Load traductions files required by page
1630 $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1631 // Get email content from template
1632 $arraydefaultmessage = null;
1633
1634 $idoftemplatetouse = getDolGlobalInt('EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_EVENT'); // Email to send for Event organization registration
1635
1636 if (!empty($idoftemplatetouse)) {
1637 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1638 }
1639
1640 if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1641 $subject = $arraydefaultmessage->topic;
1642 $msg = $arraydefaultmessage->content;
1643 } else {
1644 $subject = '['.$appli.'] '.$object->ref.' - '.$outputlangs->trans("NewRegistration");
1645 $msg = $outputlangs->trans("OrganizationEventPaymentOfRegistrationWasReceived");
1646 }
1647
1648 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1649 complete_substitutions_array($substitutionarray, $outputlangs, $object);
1650
1651 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1652 $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1653
1654 $sendto = $attendeetovalidate->email;
1655 $cc = '';
1656 if ($thirdparty->email) {
1657 $cc = $thirdparty->email ?? '';
1658 }
1659 if ($attendeetovalidate->email_company && $attendeetovalidate->email_company != $thirdparty->email) {
1660 $cc = ($cc ? ', ' : '').$attendeetovalidate->email_company;
1661 }
1662
1663 $from = getDolGlobalString('MAILING_EMAIL_FROM', getDolGlobalString("MAIN_MAIL_EMAIL_FROM"));
1664
1665 $urlback = $_SERVER["REQUEST_URI"];
1666
1667 $ishtml = dol_textishtml($texttosend); // May contain urls
1668
1669 // Attach a file ?
1670 $file = '';
1671 $listofpaths = array();
1672 $listofnames = array();
1673 $listofmimes = array();
1674 if (is_object($object)) {
1675 $invoicediroutput = $conf->facture->dir_output;
1676 $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->ref, preg_quote($object->ref, '/').'[^\-]+');
1677 $file = $fileparams['fullname'];
1678
1679 $listofpaths = array($file);
1680 $listofnames = array(basename($file));
1681 $listofmimes = array(dol_mimetype($file));
1682 }
1683
1684 $trackid = 'inv'.$object->id;
1685
1686 $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, $listofpaths, $listofmimes, $listofnames, $cc, '', 0, ($ishtml ? 1 : 0), '', '', $trackid, '', 'standard');
1687
1688 $result = $mailfile->sendfile();
1689 if ($result) {
1690 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1691 } else {
1692 dol_syslog("Failed to send EMail to ".$sendto.' - '.$mailfile->error, LOG_ERR, 0, '_payment');
1693 }
1694 }
1695 }
1696 }
1697 } else {
1698 $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['ATT'].'. May be payment was already recorded.';
1699 $ispostactionok = -1;
1700 }
1701 } else {
1702 $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1703 $ispostactionok = -1;
1704 }
1705 } elseif (array_key_exists('BOO', $tmptag) && $tmptag['BOO'] > 0) {
1706 // Record payment for booth or conference
1707 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1708 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1709 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1710 $object = new Facture($db);
1711 $result = $object->fetch((int) $ref); // @phan-suppress-current-line PhanPluginSuspiciousParamPosition
1712 if ($result) {
1713 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1714
1715 $paymentTypeId = 0;
1716 if ($paymentmethod == 'paybox') {
1717 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1718 }
1719 if ($paymentmethod == 'paypal') {
1720 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1721 }
1722 if ($paymentmethod == 'stripe') {
1723 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1724 }
1725 if (empty($paymentTypeId)) {
1726 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1727
1728 if (empty($paymentType)) {
1729 $paymentType = 'CB';
1730 }
1731 // May return nothing when paymentType means nothing
1732 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1733 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1734
1735 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1736 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1737 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1738 }
1739 }
1740
1741 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1742 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1743 $resultvalidate = $object->validate($user);
1744 if ($resultvalidate < 0) {
1745 $postactionmessages[] = 'Cannot validate invoice';
1746 $ispostactionok = -1;
1747 $error++; // Not yet supported
1748 } else {
1749 $db->begin();
1750
1751 // Creation of payment line
1752 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1753 $paiement = new Paiement($db);
1754 $paiement->datepaye = $now;
1755 if ($currencyCodeType == $conf->currency) {
1756 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1757 } else {
1758 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1759
1760 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1761 $ispostactionok = -1;
1762 $error++; // Not yet supported
1763 }
1764 $paiement->paiementid = $paymentTypeId;
1765 $paiement->num_payment = '';
1766 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1767
1768 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1769 if ($LONGTRANSACTIONID) {
1770 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1771 } else {
1772 $paiement->ext_payment_id = $TRANSACTIONID;
1773 }
1774 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1775
1776 if (!$error) {
1777 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1778 if ($paiement_id < 0) {
1779 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1780 $ispostactionok = -1;
1781 $error++;
1782 } else {
1783 $postactionmessages[] = 'Payment created';
1784 $ispostactionok = 1;
1785 }
1786 }
1787
1788 if (!$error && isModEnabled("bank")) {
1789 $bankaccountid = 0;
1790 if ($paymentmethod == 'paybox') {
1791 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1792 } elseif ($paymentmethod == 'paypal') {
1793 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1794 } elseif ($paymentmethod == 'stripe') {
1795 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1796 }
1797
1798 //Get bank account for a specific paymentmedthod
1799 $parameters = [
1800 'paymentmethod' => $paymentmethod,
1801 ];
1802 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1803 if ($reshook >= 0) {
1804 if (isset($hookmanager->resArray['bankaccountid'])) {
1805 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1806 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1807 }
1808 }
1809 if ($bankaccountid > 0) {
1810 $label = '(CustomerInvoicePayment)';
1811 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1812 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1813 }
1814 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1815 if ($result < 0) {
1816 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1817 $ispostactionok = -1;
1818 $error++;
1819 } else {
1820 $postactionmessages[] = 'Bank transaction of payment created';
1821 $ispostactionok = 1;
1822 }
1823 } else {
1824 $postactionmessages[] = 'Setup of bank account to use in module '.$paymentmethod.' was not set. Your payment was really executed but we failed to record it. Please contact us.';
1825 $ispostactionok = -1;
1826 $error++;
1827 }
1828 }
1829
1830 if (!$error) {
1831 // Putting the booth to "suggested" state
1832 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1833 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1834 $booth = new ConferenceOrBooth($db);
1835 $resultbooth = $booth->fetch((int) $tmptag['BOO']);
1836 if ($resultbooth < 0) {
1837 $error++;
1838 setEventMessages(null, $booth->errors, "errors");
1839 } else {
1840 $booth->status = ConferenceOrBooth::STATUS_SUGGESTED;
1841 $resultboothupdate = $booth->update($user);
1842 if ($resultboothupdate < 0) {
1843 // Finding the third party by getting the invoice
1844 $invoice = new Facture($db);
1845 $resultinvoice = $invoice->fetch((int) $ref); // @phan-suppress-current-line PhanPluginSuspiciousParamPosition
1846 if ($resultinvoice < 0) {
1847 $postactionmessages[] = 'Could not find the associated invoice.';
1848 $ispostactionok = -1;
1849 $error++;
1850 } else {
1851 $thirdparty = new Societe($db);
1852 $resultthirdparty = $thirdparty->fetch($invoice->socid);
1853 if ($resultthirdparty < 0) {
1854 $error++;
1855 setEventMessages(null, $thirdparty->errors, "errors");
1856 } else {
1857 // TODO Move the send of email out of the db transaction
1858
1859 // Sending mail
1860 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1861 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1862 $formmail = new FormMail($db);
1863 // Set output language
1864 $outputlangs = new Translate('', $conf);
1865 $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
1866 // Load traductions files required by page
1867 $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1868 // Get email content from template
1869 $arraydefaultmessage = null;
1870
1871 $idoftemplatetouse = getDolGlobalInt('EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_BOOTH'); // Email sent after registration for a Booth
1872
1873 if (!empty($idoftemplatetouse)) {
1874 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1875 }
1876
1877 if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1878 $subject = $arraydefaultmessage->topic;
1879 $msg = $arraydefaultmessage->content;
1880 } else {
1881 $subject = '['.$appli.'] '.$booth->ref.' - '.$outputlangs->trans("NewRegistration").']';
1882 $msg = $outputlangs->trans("OrganizationEventPaymentOfBoothWasReceived");
1883 }
1884
1885 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1886 complete_substitutions_array($substitutionarray, $outputlangs, $object);
1887
1888 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1889 $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1890
1891 $sendto = $thirdparty->email;
1892 $from = getDolGlobalString('MAILING_EMAIL_FROM');
1893 $urlback = $_SERVER["REQUEST_URI"];
1894
1895 $ishtml = dol_textishtml($texttosend); // May contain urls
1896 $trackid = 'inv'.$invoice->id;
1897
1898 $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, array(), array(), array(), '', '', 0, $ishtml ? 1 : 0, '', '', $trackid, '', 'standard');
1899
1900 $result = $mailfile->sendfile();
1901 if ($result) {
1902 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1903 } else {
1904 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
1905 }
1906 }
1907 }
1908 }
1909 }
1910 }
1911
1912 if (!$error) {
1913 $db->commit();
1914 } else {
1915 $db->rollback();
1916 }
1917 }
1918 } else {
1919 $postactionmessages[] = 'Failed to get a valid value for "amount paid" ('.$FinalPaymentAmt.') or "payment type id" ('.$paymentTypeId.') to record the payment of invoice '.$tmptag['ATT'].'. May be payment was already recorded.';
1920 $ispostactionok = -1;
1921 }
1922 } else {
1923 $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1924 $ispostactionok = -1;
1925 }
1926 } elseif (array_key_exists('CON', $tmptag) && $tmptag['CON'] > 0) {
1927 include_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php';
1928 $object = new Contrat($db);
1929 $result = $object->fetch((int) $tmptag['CON']);
1930 if ($result) {
1931 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1932
1933 $paymentTypeId = 0;
1934 if ($paymentmethod == 'paybox') {
1935 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1936 }
1937 if ($paymentmethod == 'paypal') {
1938 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1939 }
1940 if ($paymentmethod == 'stripe') {
1941 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1942 }
1943 if (empty($paymentTypeId)) {
1944 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1945
1946 if (empty($paymentType)) {
1947 $paymentType = 'CB';
1948 }
1949 // May return nothing when paymentType means nothing
1950 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1951 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1952
1953 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1954 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1955 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1956 }
1957 }
1958
1959 $currencyCodeType = $_SESSION['currencyCodeType'];
1960 $contract_lines = (array_key_exists('COL', $tmptag) && $tmptag['COL'] > 0) ? $tmptag['COL'] : null;
1961
1962 // Do action only if $FinalPaymentAmt is set (session variable is cleaned after this page to avoid duplicate actions when page is POST a second time)
1963 if (isModEnabled('invoice')) {
1964 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1965 $db->begin();
1966
1967 include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1968 $invoice = new Facture($db);
1969 $result = $invoice->createFromContract($object, $user, array((int) $contract_lines));
1970 if ($result > 0) {
1971 // $object->classifyBilled($user);
1972 $invoice->validate($user);
1973 // Creation of payment line
1974 include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
1975 $paiement = new Paiement($db);
1976 $paiement->datepaye = $now;
1977 if ($currencyCodeType == $conf->currency) {
1978 $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1979 } else {
1980 $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
1981
1982 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1983 $ispostactionok = -1;
1984 $error++;
1985 }
1986 $paiement->paiementid = $paymentTypeId;
1987 $paiement->num_payment = '';
1988 $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
1989
1990 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1991 if ($LONGTRANSACTIONID) {
1992 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1993 } else {
1994 $paiement->ext_payment_id = $TRANSACTIONID;
1995 }
1996 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1997
1998 if (!$error) {
1999 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
2000 if ($paiement_id < 0) {
2001 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
2002 $ispostactionok = -1;
2003 $error++;
2004 } else {
2005 $postactionmessages[] = 'Payment created';
2006 $ispostactionok = 1;
2007 }
2008 }
2009
2010 if (!$error && isModEnabled("bank")) {
2011 $bankaccountid = 0;
2012 if ($paymentmethod == 'paybox') {
2013 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
2014 } elseif ($paymentmethod == 'paypal') {
2015 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
2016 } elseif ($paymentmethod == 'stripe') {
2017 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
2018 }
2019
2020 //Get bank account for a specific paymentmedthod
2021 $parameters = [
2022 'paymentmethod' => $paymentmethod,
2023 ];
2024 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
2025 if ($reshook >= 0) {
2026 if (isset($hookmanager->resArray['bankaccountid'])) {
2027 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
2028 $bankaccountid = $hookmanager->resArray['bankaccountid'];
2029 }
2030 }
2031 if ($bankaccountid > 0) {
2032 $label = '(CustomerInvoicePayment)';
2033 if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
2034 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
2035 }
2036 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
2037 if ($result < 0) {
2038 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
2039 $ispostactionok = -1;
2040 $error++;
2041 } else {
2042 $postactionmessages[] = 'Bank transaction of payment created';
2043 $ispostactionok = 1;
2044 }
2045 } else {
2046 $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
2047 $ispostactionok = -1;
2048 $error++;
2049 }
2050 }
2051 } else {
2052 $msg = 'Failed to create invoice form contract ' . $tmptag['CON'];
2053 if (!empty($tmptag['COL'])) {
2054 $msg .= ' and col '. $tmptag['COL'] .'.';
2055 }
2056 $postactionmessages[] = $msg;
2057 $ispostactionok = -1;
2058 $error++;
2059 }
2060
2061 if (!$error) {
2062 $db->commit();
2063 } else {
2064 $db->rollback();
2065 }
2066 } else {
2067 $postactionmessages[] = 'Failed to get a valid value for "amount paid" (' . $FinalPaymentAmt . ') or "payment type id" (' . $paymentTypeId . ') to record the payment of contract ' . $tmptag['CON'] .'. Maybe payment was already recorded.';
2068 $ispostactionok = -1;
2069 }
2070 } else {
2071 $postactionmessages[] = 'Invoice module is not enable';
2072 $ispostactionok = -1;
2073 }
2074 } else {
2075 $msg = 'Contract paid ' . $tmptag['CON'] . ' was not found';
2076 if (!empty($tmptag['COL'])) {
2077 $msg .= ' for col '.$tmptag['COL'] .'.';
2078 }
2079 $postactionmessages[] = $msg;
2080 $ispostactionok = -1;
2081 }
2082 } else {
2083 // Nothing done
2084 }
2085}
2086
2087dol_syslog("ispaymentok=".$ispaymentok." ispostactionok=".$ispostactionok." doactionsthenredirect=".$doactionsthenredirect, LOG_DEBUG, 0, '_payment');
2088
2089if ($ispaymentok) {
2090 // Get on url call
2091 $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
2092 $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
2093 // Set by newpayment.php
2094 $currencyCodeType = empty($_SESSION['currencyCodeType']) ? '' : $_SESSION['currencyCodeType'];
2095 $FinalPaymentAmt = empty($_SESSION["FinalPaymentAmt"]) ? '' : $_SESSION["FinalPaymentAmt"];
2096 $paymentType = empty($_SESSION['PaymentType']) ? '' : $_SESSION['PaymentType']; // Seems used by paypal only
2097
2098 if (is_object($object) && method_exists($object, 'call_trigger')) {
2099 '@phan-var-force CommonObject $object';
2100 // Call trigger
2101 $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
2102 if ($result < 0) {
2103 $error++;
2104 }
2105 // End call triggers
2106 } elseif (get_class($object) == 'stdClass') {
2107 //In some cases $object is not instantiated (for payment on custom object) We need to deal with payment
2108 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
2109 $paiement = new Paiement($db);
2110 $result = $paiement->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
2111 if ($result < 0) {
2112 $error++;
2113 }
2114 }
2115}
2116
2117
2118// Show result message
2119if (empty($doactionsthenredirect)) {
2120 if ($ispaymentok) {
2121 print $langs->trans("YourPaymentHasBeenRecorded")."<br>\n";
2122 if ($TRANSACTIONID) {
2123 print $langs->trans("ThisIsTransactionId")." : ".$TRANSACTIONID."<br><br>\n";
2124 }
2125
2126 print '<center>';
2127 print img_picto('', 'tick', 'class="green fa-2x"');
2128 print '</center>';
2129
2130 // Show a custom message
2131 $key = 'ONLINE_PAYMENT_MESSAGE_OK';
2132 if (getDolGlobalString($key)) {
2133 print '<br>';
2134 print getDolGlobalString($key);
2135 }
2136 } else {
2137 print $langs->trans('DoExpressCheckoutPaymentAPICallFailed')."<br>\n";
2138 if ($ErrorLongMsg) {
2139 print $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n";
2140 }
2141 if ($ErrorShortMsg) {
2142 print $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n";
2143 }
2144 if ($ErrorCode) {
2145 print $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n";
2146 }
2147 if ($ErrorSeverityCode) {
2148 print $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n";
2149 }
2150
2151 if ($mysoc->email) {
2152 print "\nPlease, send a screenshot of this page to ".$mysoc->email."<br>\n";
2153 }
2154 }
2155}
2156
2157
2158// Send email
2159if ($ispaymentok) {
2160 $sendemail = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL');
2161
2162 $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
2163
2164 dol_syslog("Send email to admins if we have to (sendemail = ".$sendemail.")", LOG_DEBUG, 0, '_payment');
2165
2166 // Send an email to the admins
2167 if ($sendemail) {
2168 // Get default language to use for the company for supervision emails
2169 $myCompanyDefaultLang = (string) $mysoc->default_lang;
2170 if (empty($myCompanyDefaultLang) || $myCompanyDefaultLang === 'auto') {
2171 // We must guess the language from the company country. We must not use the language of the visitor. This is a technical email for supervision
2172 // so it must always be into the same language.
2173 $myCompanyDefaultLang = (string) getLanguageCodeFromCountryCode($mysoc->country_code);
2174 }
2175
2176 $companylangs = new Translate('', $conf);
2177 $companylangs->setDefaultLang($myCompanyDefaultLang);
2178 $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox', 'stripe'));
2179
2180 $sendto = $sendemail;
2181 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
2182 // Define $urlwithroot
2183 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2184 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2185 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
2186
2187 // Define link to login card
2188
2189 $urlback = $_SERVER["REQUEST_URI"];
2190 $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived");
2191 $content = "";
2192 if (array_key_exists('MEM', $tmptag)) {
2193 $url = $urlwithroot."/adherents/subscription.php?rowid=".((int) $tmptag['MEM']);
2194 $content .= '<strong>'.$companylangs->transnoentitiesnoconv("PaymentSubscription")."</strong><br><br>\n";
2195 $content .= $companylangs->transnoentitiesnoconv("MemberId").': <strong>'.$tmptag['MEM']."</strong><br>\n";
2196 $content .= $companylangs->transnoentitiesnoconv("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
2197 } elseif (array_key_exists('INV', $tmptag)) {
2198 $url = $urlwithroot."/compta/facture/card.php?id=".((int) $tmptag['INV']);
2199 $content .= '<strong>'.$companylangs->transnoentitiesnoconv("Payment")."</strong><br><br>\n";
2200 $content .= $companylangs->transnoentitiesnoconv("InvoiceId").': <strong>'.$tmptag['INV']."</strong><br>\n";
2201 //$content.=$companylangs->trans("ThirdPartyId").': '.$tmptag['CUS']."<br>\n";
2202 $content .= $companylangs->transnoentitiesnoconv("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
2203 } else {
2204 $content .= $companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived")."<br>\n";
2205 }
2206 $content .= $companylangs->transnoentitiesnoconv("PostActionAfterPayment").' : ';
2207 if ($ispostactionok > 0) {
2208 //$topic.=' ('.$companylangs->transnoentitiesnoconv("Status").' '.$companylangs->transnoentitiesnoconv("OK").')';
2209 $content .= '<span style="color: green">'.$companylangs->transnoentitiesnoconv("OK").'</span>';
2210 } elseif ($ispostactionok == 0) {
2211 $content .= $companylangs->transnoentitiesnoconv("None");
2212 } else {
2213 $topic .= ($ispostactionok ? '' : ' ('.$companylangs->trans("WarningPostActionErrorAfterPayment").')');
2214 $content .= '<span class="star">'.$companylangs->transnoentitiesnoconv("Error").'</span>';
2215 }
2216 $content .= '<br>'."\n";
2217 foreach ($postactionmessages as $postactionmessage) {
2218 $content .= ' * '.$postactionmessage.'<br>'."\n";
2219 }
2220 if ($ispostactionok < 0) {
2221 $content .= $langs->transnoentitiesnoconv("ARollbackWasPerformedOnPostActions");
2222 }
2223 $content .= '<br>'."\n";
2224
2225 $content .= "<br>\n";
2226 $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
2227 $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
2228 $content .= $companylangs->transnoentitiesnoconv("ThisIsTransactionId").': <strong>'.$TRANSACTIONID."</strong><br>\n";
2229 $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
2230 $content .= "<br>\n";
2231 $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
2232
2233 if (!empty($ErrorCode)) {
2234 $content .= "ErrorCode = ".$ErrorCode."<br>\n";
2235 }
2236 if (!empty($ErrorShortMsg)) {
2237 $content .= "ErrorShortMsg = ".$ErrorShortMsg."<br>\n";
2238 }
2239 if (!empty($ErrorLongMsg)) {
2240 $content .= "ErrorLongMsg = ".$ErrorLongMsg."<br>\n";
2241 }
2242 if (!empty($ErrorSeverityCode)) {
2243 $content .= "ErrorSeverityCode = ".$ErrorSeverityCode."<br>\n";
2244 }
2245
2246 dol_syslog("Content of email: ".$content, LOG_DEBUG, 0, '_payment');
2247
2248 $ishtml = dol_textishtml($content); // May contain urls
2249 $trackid = '';
2250
2251 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2252 $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml ? 1 : 0, '', '', $trackid, '', 'standard');
2253
2254 $result = $mailfile->sendfile();
2255 if ($result) {
2256 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
2257 //dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0);
2258 } else {
2259 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
2260 //dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0);
2261 }
2262 }
2263} else {
2264 $sendemail = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL');
2265
2266 // Get on url call
2267 $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
2268 $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
2269 // Set by newpayment.php
2270 $paymentType = $_SESSION['PaymentType'];
2271 $currencyCodeType = $_SESSION['currencyCodeType'];
2272 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
2273
2274 if (is_object($object) && method_exists($object, 'call_trigger')) {
2275 // Call trigger
2276 $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_KO', $user);
2277 if ($result < 0) {
2278 $error++;
2279 }
2280 // End call triggers
2281 }
2282
2283 // Send warning of error to administrator
2284 if ($sendemail) {
2285 $companylangs = new Translate('', $conf);
2286 $companylangs->setDefaultLang($mysoc->default_lang);
2287 $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox', 'stripe'));
2288
2289 $sendto = $sendemail;
2290 $from = getDolGlobalString('MAILING_EMAIL_FROM', getDolGlobalString("MAIN_MAIL_EMAIL_FROM"));
2291 // Define $urlwithroot
2292 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2293 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2294 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
2295
2296 $urlback = $_SERVER["REQUEST_URI"];
2297 $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("ValidationOfPaymentFailed");
2298 $content = "";
2299 $content .= '<span style="color: orange">'.$companylangs->transnoentitiesnoconv("PaymentSystemConfirmPaymentPageWasCalledButFailed")."</span>\n";
2300
2301 $content .= "<br><br>\n";
2302 $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
2303 $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
2304 $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
2305 $content .= "<br>\n";
2306 $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
2307
2308
2309 $ishtml = dol_textishtml($content); // May contain urls
2310 $trackid = '';
2311
2312 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2313 $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml ? 1 : 0, '', '', $trackid, '', 'standard');
2314
2315 $result = $mailfile->sendfile();
2316 if ($result) {
2317 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
2318 } else {
2319 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
2320 }
2321 }
2322}
2323
2324
2325// Clean session variables to avoid duplicate actions if post is resent
2326unset($_SESSION["FinalPaymentAmt"]);
2327unset($_SESSION["TRANSACTIONID"]);
2328
2329
2330// Close page content id="dolpaymentdiv"
2331if (empty($doactionsthenredirect)) {
2332 print "\n</div>\n";
2333
2334 print "<!-- Info for payment: FinalPaymentAmt=".dol_escape_htmltag($FinalPaymentAmt)." paymentTypeId=".dol_escape_htmltag((string) $paymentTypeId)." currencyCodeType=".dol_escape_htmltag($currencyCodeType)." -->\n";
2335}
2336
2337
2338// Show footer
2339if (empty($doactionsthenredirect)) {
2340 htmlPrintOnlineFooter($mysoc, $langs, 0, $suffix);
2341
2342 llxFooter('', 'public');
2343}
2344
2345
2346$db->close();
2347
2348
2349// If option to do a redirect somewhere else.
2350if (!empty($doactionsthenredirect)) {
2351 if ($ispaymentok) {
2352 // Redirect to a success page
2353 $randomseckey = getRandomPassword(true, null, 20);
2354 $_SESSION['paymentoksessioncode'] = $randomseckey; // key propagated between paymentok.php to another page like a paymentok of the website.
2355
2356 // Paymentok page must be created for the specific website
2357 if (!defined('USEDOLIBARRSERVER') && !empty($ws_virtuelhost)) {
2358 $ext_urlok = $ws_virtuelhost . '/paymentok.php?paymentoksessioncode='.urlencode($randomseckey).'&fulltag='.$FULLTAG;
2359 } else {
2360 $ext_urlok = DOL_URL_ROOT.'/public/website/index.php?paymentoksessioncode='.urlencode($randomseckey).'&website='.urlencode($ws).'&pageref=paymentok&fulltag='.$FULLTAG;
2361 }
2362
2363 dol_syslog("Now do a redirect using a Location: ".$ext_urlok, LOG_DEBUG, 0, '_payment');
2364 header("Location: ".$ext_urlok);
2365 exit;
2366 } else {
2367 // Redirect to an error page
2368 $randomseckey = getRandomPassword(true, null, 20);
2369 $_SESSION['paymentkosessioncode'] = $randomseckey; // key propagated between paymentok.php to another page like a paymentko of the website.
2370
2371 // Paymentko page must be created for the specific website
2372 if (!defined('USEDOLIBARRSERVER') && !empty($ws_virtuelhost)) {
2373 $ext_urlko = $ws_virtuelhost . '/paymentko.php?paymentkosessioncode='.urlencode($randomseckey).'&fulltag='.$FULLTAG;
2374 } else {
2375 $ext_urlko = DOL_URL_ROOT.'/public/website/index.php?paymentkosessioncode='.urlencode($randomseckey).'&website='.urlencode($ws).'&pageref=paymentko&fulltag='.$FULLTAG;
2376 }
2377
2378 dol_syslog("Now do a redirect using a Location:".$ext_urlko, LOG_DEBUG, 0, '_payment');
2379 header("Location: ".$ext_urlko);
2380 exit;
2381 }
2382}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
global $dolibarr_main_url_root
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage members of a foundation.
Class to manage members type.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class to manage customers orders.
Class for ConferenceOrBoothAttendee.
Class for ConferenceOrBooth.
Class to manage donations.
Definition don.class.php:41
Class to manage invoices.
const STATUS_DRAFT
Draft status.
const TYPE_CREDIT_NOTE
Credit note invoice.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class to manage hooks.
Class to manage payments of customer invoices.
Class to manage payments of donations.
Class to manage third parties objects (customers, suppliers, prospects...)
Stripe class @TODO No reason to extend CommonObject.
Class to manage translations.
Class to manage Dolibarr users.
Class Website.
htmlPrintOnlineFooter($fromcompany, $langs, $addformmessage=0, $suffix='', $object=null)
Show footer of company in HTML public pages.
global $mysoc
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:605
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition date.lib.php:126
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png) $', '^\.'), $nohook=0, $mode=0)
Return file(s) into a directory (by default most recent)
dol_now($mode='gmt')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
getLanguageCodeFromCountryCode($countrycode)
Return default language from country code.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
dolExplodeIntoArray($string, $delimiter=';', $kv='=')
Split a string with 2 keys into key array.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_textishtml($msg, $option=0)
Return if a text is a html content.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) formatLogObject($data)
Return a string serialized to be output on log with dol_syslog() An option allow to output log in one...
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $tag)
Validate payment.
getDetails($token)
Prepares the parameters for the GetExpressCheckoutDetails API Call.
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
httponly_accessforbidden($message='1', $http_response_code=403, $stringalreadysanitized=0)
Show a message to say access is forbidden and stop program.