dolibarr 24.0.0-beta
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 (empty(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 || empty($object->datevalid)) {
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 }
668
669 // Guess the subscription start date
670 $datesubscription = $object->datevalid; // By default, the subscription start date is the payment date
671 if ($object->datefin > 0) {
672 $datesubscription = dol_time_plus_duree($object->datefin, 1, 'd');
673 } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER')) {
674 $datesubscription = dol_time_plus_duree($now, (int) substr(getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER'), 0, -1), substr(getDolGlobalString('MEMBER_SUBSCRIPTION_START_AFTER'), -1));
675 }
676 // Now do a correction of the suggested date
677 if (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "m") {
678 $datesubscription = dol_get_first_day((int) dol_print_date($datesubscription, "%Y"), (int) dol_print_date($datesubscription, "%m"));
679 } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "3m") {
680 $datesubscription = dol_time_plus_duree($object->datefin, -3, 'm');
681 $datesubscription = dol_get_first_day((int) dol_print_date($datesubscription, "%Y"), (int) dol_print_date($datesubscription, "%m"));
682 } elseif (getDolGlobalString('MEMBER_SUBSCRIPTION_START_FIRST_DAY_OF') === "Y") {
683 $datesubscription = dol_get_first_day((int) dol_print_date($datesubscription, "%Y"));
684 }
685
686 $datesubend = 0;
687 if ($datesubscription && $defaultdelay && $defaultdelayunit) {
688 $datesubend = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
689 // the new end date of subscription must be in futur
690 while ($datesubend < $now) {
691 $datesubend = dol_time_plus_duree($datesubend, $defaultdelay, $defaultdelayunit);
692 $datesubscription = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
693 }
694 $datesubend = dol_time_plus_duree($datesubend, -1, 'd');
695 }
696
697 // Set output language
698 $outputlangs = new Translate('', $conf);
699 $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? (string) $mysoc->default_lang : (string) $object->thirdparty->default_lang);
700 $paymentdate = $now;
701 $amount = $FinalPaymentAmt;
702 $formatteddate = dol_print_date($paymentdate, 'dayhour', 'auto', $outputlangs);
703 $label = $langs->trans("OnlineSubscriptionPaymentLine", $formatteddate, $paymentmethod, $ipaddress, $TRANSACTIONID);
704
705 // Payment information
706 $accountid = 0;
707 if ($paymentmethod == 'paybox') {
708 $accountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
709 }
710 if ($paymentmethod == 'paypal') {
711 $accountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
712 }
713 if ($paymentmethod == 'stripe') {
714 $accountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
715 }
716
717 //Get bank account for a specific paymentmedthod
718 $parameters = [
719 'paymentmethod' => $paymentmethod,
720 ];
721 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
722 if ($reshook >= 0) {
723 if (isset($hookmanager->resArray['bankaccountid'])) {
724 dol_syslog('accountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
725 $accountid = $hookmanager->resArray['bankaccountid'];
726 }
727 }
728 if ($accountid < 0) {
729 $error++;
730 $errmsg = 'Setup of bank account to use for payment is not correctly done for payment method '.$paymentmethod;
731 $postactionmessages[] = $errmsg;
732 $ispostactionok = -1;
733 dol_syslog("Failed to get the bank account to record payment: ".$errmsg, LOG_ERR, 0, '_payment');
734 }
735
736 $operation = dol_getIdFromCode($db, $paymentTypeId, 'c_paiement', 'id', 'code', 1); // Payment mode code returned from payment mode id
737 $num_chq = '';
738 $emetteur_nom = '';
739 $emetteur_banque = '';
740 // Define default choice for complementary actions
741 $option = '';
742 if (getDolGlobalString('ADHERENT_BANK_USE') == 'bankviainvoice' && isModEnabled("bank") && isModEnabled("societe") && isModEnabled('invoice')) {
743 $option = 'bankviainvoice';
744 } elseif (getDolGlobalString('ADHERENT_BANK_USE') == 'bankdirect' && isModEnabled("bank")) {
745 $option = 'bankdirect';
746 } elseif (getDolGlobalString('ADHERENT_BANK_USE') == 'invoiceonly' && isModEnabled("bank") && isModEnabled("societe") && isModEnabled('invoice')) {
747 $option = 'invoiceonly';
748 }
749 if (empty($option)) {
750 $option = 'none';
751 }
752 $sendalsoemail = 1;
753 $crowid = 0;
754
755 // Record the subscription then complementary actions
756 $db->begin();
757
758 // Create subscription
759 if (!$error) {
760 dol_syslog("Call ->subscription to create subscription", LOG_DEBUG, 0, '_payment');
761
762 $crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend, $membertypeid);
763 if ($crowid <= 0) {
764 $error++;
765 $errmsg = $object->error;
766 $postactionmessages[] = $errmsg;
767 $ispostactionok = -1;
768 } else {
769 $postactionmessages[] = 'Subscription created (id='.$crowid.')';
770 $ispostactionok = 1;
771 }
772 }
773
774 $autocreatethirdparty = 0;
775
776 if (!$error) {
777 dol_syslog("Call ->subscriptionComplementaryActions option=".$option, LOG_DEBUG, 0, '_payment');
778
779 $autocreatethirdparty = 1; // will create third party if member not yet linked to a thirdparty
780
781 $result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque, $autocreatethirdparty, $TRANSACTIONID, $service);
782 if ($result < 0) {
783 dol_syslog("Error ".$object->error." ".implode(',', $object->errors), LOG_DEBUG, 0, '_payment');
784
785 $error++;
786 $postactionmessages[] = $object->error;
787 $postactionmessages = array_merge($postactionmessages, $object->errors);
788 $ispostactionok = -1;
789 } else {
790 if ($option == 'bankviainvoice') {
791 $postactionmessages[] = 'Invoice, payment and bank record created';
792 dol_syslog("Invoice, payment and bank record created", LOG_DEBUG, 0, '_payment');
793 }
794 if ($option == 'bankdirect') {
795 $postactionmessages[] = 'Bank record created';
796 dol_syslog("Bank record created", LOG_DEBUG, 0, '_payment');
797 }
798 if ($option == 'invoiceonly') {
799 $postactionmessages[] = 'Invoice recorded';
800 dol_syslog("Invoice recorded", LOG_DEBUG, 0, '_payment');
801 }
802 $ispostactionok = 1;
803
804 // If an invoice was created, it is into $object->invoice
805 }
806 }
807
808 if (!$error) {
809 // If payment using Stripe, save the Stripe payment info into societe_account
810 if ($paymentmethod == 'stripe' && $autocreatethirdparty && $option == 'bankviainvoice') {
811 $thirdparty_id = ($object->socid ? $object->socid : $object->fk_soc);
812
813 dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_payment');
814
815 $service = 'StripeTest';
816 $servicestatus = 0;
817 if (getDolGlobalString('STRIPE_LIVE')/* && !GETPOST('forcesandbox', 'alpha') */) {
818 $service = 'StripeLive';
819 $servicestatus = 1;
820 }
821 $stripeacc = ''; // No Oauth/connect use for public pages
822
823 $thirdparty = new Societe($db);
824 $thirdparty->fetch($thirdparty_id);
825
826 include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; // This also set $stripearrayofkeysbyenv
827 $stripe = new Stripe($db);
828 //$stripeacc = $stripe->getStripeAccount($service); Already defined previously
829
830 $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0);
831
832 if (!$customer && $TRANSACTIONID) { // Not linked to a stripe customer, we make the link
833 dol_syslog("No stripe profile found, so we add it for TRANSACTIONID = ".$TRANSACTIONID, LOG_DEBUG, 0, '_payment');
834
835 try {
836 global $stripearrayofkeysbyenv;
837 \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
838
839 if (preg_match('/^pi_/', $TRANSACTIONID)) {
840 // This may throw an error if not found.
841 $chpi = \Stripe\PaymentIntent::retrieve($TRANSACTIONID); // payment_intent (pi_...)
842 } else {
843 // This throw an error if not found
844 $chpi = \Stripe\Charge::retrieve($TRANSACTIONID); // old method, contains the charge id (ch_...)
845 }
846
847 if ($chpi) {
848 $stripecu = $chpi->customer; // value 'cus_....'. WARNING: This property may be empty if first payment was recorded before the stripe customer was created.
849
850 if (empty($stripecu)) {
851 // This include the INSERT
852 $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1);
853
854 // Link this customer to the payment intent
855 if (preg_match('/^pi_/', $TRANSACTIONID) && $customer) {
856 \Stripe\PaymentIntent::update($chpi->id, array('customer' => $customer->id));
857 }
858 } else {
859 $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, site_account, status, entity, date_creation, fk_user_creat)";
860 $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)";
861 $resql = $db->query($sql);
862 if (!$resql) { // should not happen
863 $error++;
864 $errmsg = 'Failed to insert customer stripe id in database : '.$db->lasterror();
865 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
866 $postactionmessages[] = $errmsg;
867 $ispostactionok = -1;
868 }
869 }
870 } else { // should not happen
871 $error++;
872 $errmsg = 'Failed to retrieve paymentintent or charge from id';
873 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
874 $postactionmessages[] = $errmsg;
875 $ispostactionok = -1;
876 }
877 } catch (Exception $e) { // should not happen
878 $error++;
879 $errmsg = 'Failed to get or save customer stripe id in database : '.$e->getMessage();
880 dol_syslog($errmsg, LOG_ERR, 0, '_payment');
881 $postactionmessages[] = $errmsg;
882 $ispostactionok = -1;
883 }
884 }
885 }
886 }
887
888 if (!$error) {
889 $db->commit();
890 } else {
891 $db->rollback();
892 }
893
894 // Set string to use to send email info
895 $infouserlogin = '';
896
897 // Create external user
898 if (getDolGlobalString('ADHERENT_CREATE_EXTERNAL_USER_LOGIN')) {
899 $nuser = new User($db);
900 $tmpuser = dol_clone($object, 0); // $object is type Adherent
901
902 // Check if a user login already exists for this member or not
903 $found = 0;
904 $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."user WHERE fk_member = ".((int) $object->id);
905 $resqlcount = $db->query($sql);
906 if ($resqlcount) {
907 $objcount = $db->fetch_object($resqlcount);
908 if ($objcount) {
909 $found = $objcount->nb;
910 }
911 }
912
913 if (!$found) {
914 $result = $nuser->create_from_member($tmpuser, $object->login);
915 $newpassword = $nuser->setPassword($user, '');
916
917 if ($result < 0) {
918 $outputlangs->load("errors");
919 $postactionmessages[] = 'Error in create external user : '.$nuser->error;
920 } else {
921 $infouserlogin = $outputlangs->trans("Login").': '.$nuser->login.' '."\n".$outputlangs->trans("Password").': '.$newpassword;
922 $postactionmessages[] = $langs->trans("NewUserCreated", $nuser->login);
923 }
924 } else {
925 $outputlangs->load("errors");
926 $postactionmessages[] = 'No user created because a user linked to member already exists';
927 }
928 }
929
930 // Send email to member
931 if (!$error) {
932 dol_syslog("Send email to customer to ".$object->email." if we have to (sendalsoemail = ".$sendalsoemail.")", LOG_DEBUG, 0, '_payment');
933
934 // Send confirmation Email
935 if ($object->email && $sendalsoemail) {
936 $subject = '';
937 $msg = '';
938
939 // Send subscription email
940 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
941 $formmail = new FormMail($db);
942 // Load traductions files required by page
943 $outputlangs->loadLangs(array("main", "members"));
944 // Get email content from template
945 $arraydefaultmessage = null;
946 $labeltouse = getDolGlobalString('ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION');
947
948 if (!empty($labeltouse)) {
949 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
950 }
951
952 if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
953 $subject = $arraydefaultmessage->topic;
954 $msg = $arraydefaultmessage->content;
955 }
956
957 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
958
959 if ($infouserlogin) {
960 $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = $infouserlogin;
961 }
962
963 complete_substitutions_array($substitutionarray, $outputlangs, $object);
964 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
965 $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
966
967 // Attach a file ?
968 $file = '';
969 $listofpaths = array();
970 $listofnames = array();
971 $listofmimes = array();
972 if (is_object($object->invoice)) {
973 $invoicediroutput = $conf->facture->dir_output;
974 $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
975 $file = $fileparams['fullname'];
976
977 $listofpaths = array($file);
978 $listofnames = array(basename($file));
979 $listofmimes = array(dol_mimetype($file));
980 }
981
982 $moreinheader = 'X-Dolibarr-Info: send_an_email by public/payment/paymentok.php'."\r\n";
983
984 $result = $object->sendEmail($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, "", $moreinheader);
985
986 if ($result < 0) {
987 $errmsg = $object->error;
988 $postactionmessages[] = $errmsg;
989 $ispostactionok = -1;
990 } else {
991 if ($file) {
992 $postactionmessages[] = 'Email sent to member (with invoice document attached)';
993 } else {
994 $postactionmessages[] = 'Email sent to member (without any attached document)';
995 }
996
997 // TODO Add actioncomm event
998 }
999 }
1000 }
1001 } else {
1002 $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.';
1003 $ispostactionok = -1;
1004 }
1005 } else {
1006 $postactionmessages[] = 'Member '.$tmptag['MEM'].' for subscription paid was not found';
1007 $ispostactionok = -1;
1008 }
1009 } elseif (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) {
1010 // Record payment
1011 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1012 $object = new Facture($db);
1014 $result = $object->fetch((int) $tmptag['INV']);
1015 if ($result) {
1016 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1017
1018 $paymentTypeId = 0;
1019 if ($paymentmethod === 'paybox') {
1020 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1021 }
1022 if ($paymentmethod === 'paypal') {
1023 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1024 }
1025 if ($paymentmethod === 'stripe') {
1026 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1027 }
1028 if (empty($paymentTypeId)) {
1029 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1030
1031 if (empty($paymentType)) {
1032 $paymentType = 'CB';
1033 }
1034 // May return nothing when paymentType means nothing
1035 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1036 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1037
1038 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1039 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1040 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1041 }
1042 }
1043
1044 dol_syslog("FinalPaymentAmt = ".$FinalPaymentAmt." paymentTypeId = ".$paymentTypeId, LOG_DEBUG, 0, '_payment');
1045
1046 // 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)
1047 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1048 $db->begin();
1049
1050 // Creation of payment line
1051 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1052 $paiement = new Paiement($db);
1053 $paiement->datepaye = $now;
1054 if ($currencyCodeType == $conf->currency) {
1055 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1056 } else {
1057 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1058
1059 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1060 $ispostactionok = -1;
1061 $error++; // Not yet supported
1062 }
1063 $paiement->paiementid = $paymentTypeId;
1064 $paiement->num_payment = '';
1065 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1066
1067 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1068 if ($LONGTRANSACTIONID) {
1069 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1070 } else {
1071 $paiement->ext_payment_id = $TRANSACTIONID;
1072 }
1073 $paiement->ext_payment_site = $service;
1074
1075 // Validate invoice if not already validated (this can happen for automatically generated invoices with a free amount)
1076 if (!$error && $object->status == Facture::STATUS_DRAFT) {
1077 $result = $object->validate($user);
1078 if ($result < 0) {
1079 $postactionmessages[] = $object->error;
1080 $ispostactionok = -1;
1081 $error++;
1082 } else {
1083 $postactionmessages[] = 'Invoice validated';
1084 $ispostactionok = 1;
1085 }
1086 }
1087
1088 if (!$error) {
1089 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1090 if ($paiement_id < 0) {
1091 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1092 $ispostactionok = -1;
1093 $error++;
1094 } else {
1095 $postactionmessages[] = 'Payment created';
1096 $ispostactionok = 1;
1097 }
1098 }
1099
1100 if (!$error && isModEnabled("bank")) {
1101 $bankaccountid = 0;
1102 if ($paymentmethod == 'paybox') {
1103 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1104 } elseif ($paymentmethod == 'paypal') {
1105 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1106 } elseif ($paymentmethod == 'stripe') {
1107 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1108 }
1109
1110 //Get bank account for a specific paymentmedthod
1111 $parameters = [
1112 'paymentmethod' => $paymentmethod,
1113 ];
1114 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1115 if ($reshook >= 0) {
1116 if (isset($hookmanager->resArray['bankaccountid'])) {
1117 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1118 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1119 }
1120 }
1121 if ($bankaccountid > 0) {
1122 $label = '(CustomerInvoicePayment)';
1123 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1124 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1125 }
1126 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1127 if ($result < 0) {
1128 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1129 $ispostactionok = -1;
1130 $error++;
1131 } else {
1132 $postactionmessages[] = 'Bank transaction of payment created';
1133 $ispostactionok = 1;
1134 }
1135 } else {
1136 $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.';
1137 $ispostactionok = -1;
1138 $error++;
1139 }
1140 }
1141
1142 if (!$error) {
1143 $db->commit();
1144 } else {
1145 $db->rollback();
1146 }
1147 } else {
1148 $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.';
1149 $ispostactionok = -1;
1150 }
1151 } else {
1152 $postactionmessages[] = 'Invoice paid '.$tmptag['INV'].' was not found';
1153 $ispostactionok = -1;
1154 }
1155 } elseif (array_key_exists('ORD', $tmptag) && $tmptag['ORD'] > 0) {
1156 include_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
1157 $object = new Commande($db);
1158 $result = $object->fetch((int) $tmptag['ORD']);
1159 if ($result) {
1160 dol_syslog("We have loaded the order id=".$object->id." to use to create the invoice", LOG_DEBUG, 0, '_payment');
1161
1162 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1163
1164 $paymentTypeId = 0;
1165 if ($paymentmethod == 'paybox') {
1166 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1167 }
1168 if ($paymentmethod == 'paypal') {
1169 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1170 }
1171 if ($paymentmethod == 'stripe') {
1172 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1173 }
1174 if (empty($paymentTypeId)) {
1175 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1176
1177 if (empty($paymentType)) {
1178 $paymentType = 'CB';
1179 }
1180 // May return nothing when paymentType means nothing
1181 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1182 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1183
1184 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1185 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1186 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1187 }
1188 }
1189
1190 dol_syslog("The payment type id to use is paymentTypeId=".$paymentTypeId." and FinalPaymentAmt=".$FinalPaymentAmt, LOG_DEBUG, 0, '_payment');
1191
1192 // 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)
1193 if (isModEnabled('invoice')) {
1194 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1195 $db->begin();
1196
1197 include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1198 $invoice = new Facture($db);
1199 $result = $invoice->createFromOrder($object, $user);
1200 if ($result > 0) {
1201 if ($FinalPaymentAmt != $object->total_ttc) {
1202 // 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
1203 // We can add a line to reduce the amount of the invoice but with which vat ?
1204 // TODO Test if vat on line is the same everywhere, if yes we can add
1205 // $invoice->addline('Fix amount of invoice', $FinalPaymentAmt - $object->total_ttc, 1, $txtva);
1206 // TODO Send a warning email.
1207 }
1208
1209 $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).
1210
1211 $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.
1212
1213 // Creation of payment line (warning: if amount has been modified on page, the payment may be partial)
1214 include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
1215 $paiement = new Paiement($db);
1216 $paiement->datepaye = $now;
1217 if ($currencyCodeType == $conf->currency) {
1218 $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1219 } else {
1220 $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
1221
1222 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1223 $ispostactionok = -1;
1224 $error++;
1225 }
1226 $paiement->paiementid = $paymentTypeId;
1227 $paiement->num_payment = '';
1228 $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
1229
1230 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1231 if ($LONGTRANSACTIONID) {
1232 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1233 } else {
1234 $paiement->ext_payment_id = $TRANSACTIONID;
1235 }
1236 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1237
1238 if (!$error) {
1239 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1240 if ($paiement_id < 0) {
1241 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1242 $ispostactionok = -1;
1243 $error++;
1244 } else {
1245 $postactionmessages[] = 'Payment created';
1246 $ispostactionok = 1;
1247 }
1248 }
1249
1250 if (!$error && isModEnabled("bank")) {
1251 $bankaccountid = 0;
1252 if ($paymentmethod == 'paybox') {
1253 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1254 } elseif ($paymentmethod == 'paypal') {
1255 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1256 } elseif ($paymentmethod == 'stripe') {
1257 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1258 }
1259
1260 //Get bank account for a specific paymentmedthod
1261 $parameters = [
1262 'paymentmethod' => $paymentmethod,
1263 ];
1264 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1265 if ($reshook >= 0) {
1266 if (isset($hookmanager->resArray['bankaccountid'])) {
1267 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1268 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1269 }
1270 }
1271 if ($bankaccountid > 0) {
1272 $label = '(CustomerInvoicePayment)';
1273 if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
1274 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1275 }
1276 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1277 if ($result < 0) {
1278 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1279 $ispostactionok = -1;
1280 $error++;
1281 } else {
1282 $postactionmessages[] = 'Bank transaction of payment created';
1283 $ispostactionok = 1;
1284 }
1285 } else {
1286 $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
1287 $ispostactionok = -1;
1288 $error++;
1289 }
1290 }
1291 } else {
1292 $postactionmessages[] = 'Failed to create invoice form order ' . $tmptag['ORD'] . '.';
1293 $ispostactionok = -1;
1294 $error++;
1295 }
1296
1297 if (!$error) {
1298 $db->commit();
1299 } else {
1300 $db->rollback();
1301 }
1302 } else {
1303 $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.';
1304 $ispostactionok = -1;
1305 }
1306 } else {
1307 $postactionmessages[] = 'Invoice module is not enable';
1308 $ispostactionok = -1;
1309 }
1310 } else {
1311 $postactionmessages[] = 'Order paid ' . $tmptag['ORD'] . ' was not found';
1312 $ispostactionok = -1;
1313 }
1314 } elseif (array_key_exists('DON', $tmptag) && $tmptag['DON'] > 0) {
1315 include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
1316 $don = new Don($db);
1317 $result = $don->fetch((int) $tmptag['DON']);
1318 if ($result) {
1319 $paymentTypeId = 0;
1320 if ($paymentmethod == 'paybox') {
1321 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1322 }
1323 if ($paymentmethod == 'paypal') {
1324 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1325 }
1326 if ($paymentmethod == 'stripe') {
1327 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1328 }
1329 if (empty($paymentTypeId)) {
1330 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1331
1332 if (empty($paymentType)) {
1333 $paymentType = 'CB';
1334 }
1335 // May return nothing when paymentType means nothing
1336 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1337 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1338
1339 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1340 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1341 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1342 }
1343 }
1344
1345 // 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)
1346 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1347 $db->begin();
1348
1349 // Creation of paiement line for donation
1350 include_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php';
1351 $paiement = new PaymentDonation($db);
1352
1353 $totalpaid = $FinalPaymentAmt;
1354
1355 if ($currencyCodeType == $conf->currency) {
1356 $paiement->amounts = array($object->id => $totalpaid); // Array with all payments dispatching with donation
1357 } else {
1358 // PaymentDonation does not support multi currency
1359 $postactionmessages[] = 'Payment donation can\'t be paid with different currency than '.$conf->currency;
1360 $ispostactionok = -1;
1361 $error++; // Not yet supported
1362 }
1363
1364 $paiement->fk_donation = $don->id;
1365 $paiement->datep = $now;
1366 $paiement->paymenttype = $paymentTypeId;
1367 $paiement->num_payment = '';
1368 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1369
1370 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1371 if ($LONGTRANSACTIONID) {
1372 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1373 } else {
1374 $paiement->ext_payment_id = $TRANSACTIONID;
1375 }
1376 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1377
1378 if (!$error) {
1379 $paiement_id = $paiement->create($user, 1);
1380 if ($paiement_id < 0) {
1381 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1382 $ispostactionok = -1;
1383 $error++;
1384 } else {
1385 $postactionmessages[] = 'Payment created';
1386 $ispostactionok = 1;
1387
1388 if ($totalpaid >= $don->getRemainToPay()) {
1389 $don->valid_promesse($don->id, $user->id);
1390 $don->setPaid($don->id);
1391 }
1392 }
1393 }
1394
1395 if (!$error && isModEnabled("bank")) {
1396 $bankaccountid = 0;
1397 if ($paymentmethod == 'paybox') {
1398 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1399 } elseif ($paymentmethod == 'paypal') {
1400 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1401 } elseif ($paymentmethod == 'stripe') {
1402 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1403 }
1404
1405 //Get bank account for a specific paymentmedthod
1406 $parameters = [
1407 'paymentmethod' => $paymentmethod,
1408 ];
1409 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1410 if ($reshook >= 0) {
1411 if (isset($hookmanager->resArray['bankaccountid'])) {
1412 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1413 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1414 }
1415 }
1416 if ($bankaccountid > 0) {
1417 $label = '(DonationPayment)';
1418 $result = $paiement->addPaymentToBank($user, 'payment_donation', $label, $bankaccountid, '', '');
1419 if ($result < 0) {
1420 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1421 $ispostactionok = -1;
1422 $error++;
1423 } else {
1424 $postactionmessages[] = 'Bank transaction of payment created';
1425 $ispostactionok = 1;
1426 }
1427 } else {
1428 $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.';
1429 $ispostactionok = -1;
1430 $error++;
1431 }
1432 }
1433
1434 if (!$error) {
1435 $db->commit();
1436 } else {
1437 $db->rollback();
1438 }
1439 } else {
1440 $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.';
1441 $ispostactionok = -1;
1442 }
1443 } else {
1444 $postactionmessages[] = 'Donation paid '.$tmptag['DON'].' was not found';
1445 $ispostactionok = -1;
1446 }
1447
1448 // TODO send email with acknowledgment for the donation
1449 // (we need first that the donation module is able to generate a pdf document for the cerfa with pre filled content)
1450 } elseif (array_key_exists('ATT', $tmptag) && $tmptag['ATT'] > 0) {
1451 // Record payment for registration to an event for an attendee
1452 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1453 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1454 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1455 $object = new Facture($db);
1456 $result = $object->fetch((int) $ref); // @phan-suppress-curren-line PhanPluginSuspiciousParamPosition
1457 if ($result) {
1458 $paymentTypeId = 0;
1459 if ($paymentmethod == 'paybox') {
1460 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1461 }
1462 if ($paymentmethod == 'paypal') {
1463 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1464 }
1465 if ($paymentmethod == 'stripe') {
1466 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1467 }
1468 if (empty($paymentTypeId)) {
1469 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1470
1471 if (empty($paymentType)) {
1472 $paymentType = 'CB';
1473 }
1474 // May return nothing when paymentType means nothing
1475 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1476 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1477
1478 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1479 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1480 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1481 }
1482 }
1483
1484 // 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)
1485 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1486 $resultvalidate = $object->validate($user);
1487 if ($resultvalidate < 0) {
1488 $postactionmessages[] = 'Cannot validate invoice';
1489 $ispostactionok = -1;
1490 $error++; // Not yet supported
1491 } else {
1492 $db->begin();
1493
1494 // Creation of payment line
1495 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1496 $paiement = new Paiement($db);
1497 $paiement->datepaye = $now;
1498 if ($currencyCodeType == $conf->currency) {
1499 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1500 } else {
1501 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1502
1503 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1504 $ispostactionok = -1;
1505 $error++; // Not yet supported
1506 }
1507 $paiement->paiementid = $paymentTypeId;
1508 $paiement->num_payment = '';
1509 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress.' for event registration';
1510
1511 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1512 if ($LONGTRANSACTIONID) {
1513 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1514 } else {
1515 $paiement->ext_payment_id = $TRANSACTIONID;
1516 }
1517 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1518
1519 if (!$error) {
1520 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1521 if ($paiement_id < 0) {
1522 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1523 $ispostactionok = -1;
1524 $error++;
1525 } else {
1526 $postactionmessages[] = 'Payment created';
1527 $ispostactionok = 1;
1528 }
1529 }
1530
1531 if (!$error && isModEnabled("bank")) {
1532 $bankaccountid = 0;
1533 if ($paymentmethod == 'paybox') {
1534 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1535 } elseif ($paymentmethod == 'paypal') {
1536 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1537 } elseif ($paymentmethod == 'stripe') {
1538 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1539 }
1540
1541 //Get bank account for a specific paymentmedthod
1542 $parameters = [
1543 'paymentmethod' => $paymentmethod,
1544 ];
1545 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1546 if ($reshook >= 0) {
1547 if (isset($hookmanager->resArray['bankaccountid'])) {
1548 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1549 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1550 }
1551 }
1552 if ($bankaccountid > 0) {
1553 $label = '(CustomerInvoicePayment)';
1554 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1555 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1556 }
1557 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1558 if ($result < 0) {
1559 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1560 $ispostactionok = -1;
1561 $error++;
1562 } else {
1563 $postactionmessages[] = 'Bank transaction of payment created';
1564 $ispostactionok = 1;
1565 }
1566 } else {
1567 $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.';
1568 $ispostactionok = -1;
1569 $error++;
1570 }
1571 }
1572
1573 $attendeetovalidate = new ConferenceOrBoothAttendee($db);
1574
1575 if (!$error) {
1576 // Validating the attendee
1577 $resultattendee = $attendeetovalidate->fetch((int) $tmptag['ATT']);
1578 if ($resultattendee < 0) {
1579 $error++;
1580 setEventMessages(null, $attendeetovalidate->errors, "errors");
1581 } else {
1582 $attendeetovalidate->validate($user);
1583
1584 $attendeetovalidate->amount = $FinalPaymentAmt;
1585 $attendeetovalidate->date_subscription = dol_now();
1586 $attendeetovalidate->update($user);
1587 }
1588 }
1589
1590 if (!$error) {
1591 $db->commit();
1592 } else {
1593 setEventMessages(null, $postactionmessages, 'warnings');
1594
1595 $db->rollback();
1596 }
1597
1598 if (! $error) {
1599 // Sending mail
1600 $thirdparty = new Societe($db);
1601 $resultthirdparty = $thirdparty->fetch($attendeetovalidate->fk_soc);
1602 if ($resultthirdparty < 0) {
1603 setEventMessages($thirdparty->error, $thirdparty->errors, "errors");
1604 } else {
1605 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1606 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1607 $formmail = new FormMail($db);
1608 // Set output language
1609 $outputlangs = new Translate('', $conf);
1610 $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? (string) $mysoc->default_lang : (string) $thirdparty->default_lang);
1611 // Load traductions files required by page
1612 $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1613 // Get email content from template
1614 $arraydefaultmessage = null;
1615
1616 $idoftemplatetouse = getDolGlobalInt('EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_EVENT'); // Email to send for Event organization registration
1617
1618 if (!empty($idoftemplatetouse)) {
1619 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1620 }
1621
1622 if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1623 $subject = $arraydefaultmessage->topic;
1624 $msg = $arraydefaultmessage->content;
1625 } else {
1626 $subject = '['.$appli.'] '.$object->ref.' - '.$outputlangs->trans("NewRegistration");
1627 $msg = $outputlangs->trans("OrganizationEventPaymentOfRegistrationWasReceived");
1628 }
1629
1630 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1631 complete_substitutions_array($substitutionarray, $outputlangs, $object);
1632
1633 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1634 $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1635
1636 $sendto = $attendeetovalidate->email;
1637 $cc = '';
1638 if ($thirdparty->email) {
1639 $cc = $thirdparty->email ?? '';
1640 }
1641 if ($attendeetovalidate->email_company && $attendeetovalidate->email_company != $thirdparty->email) {
1642 $cc = ($cc ? ', ' : '').$attendeetovalidate->email_company;
1643 }
1644
1645 $from = getDolGlobalString('MAILING_EMAIL_FROM', getDolGlobalString("MAIN_MAIL_EMAIL_FROM"));
1646
1647 $urlback = $_SERVER["REQUEST_URI"];
1648
1649 $ishtml = dol_textishtml($texttosend); // May contain urls
1650
1651 // Attach a file ?
1652 $file = '';
1653 $listofpaths = array();
1654 $listofnames = array();
1655 $listofmimes = array();
1656 if (is_object($object)) {
1657 $invoicediroutput = $conf->facture->dir_output;
1658 $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->ref, preg_quote($object->ref, '/').'[^\-]+');
1659 $file = $fileparams['fullname'];
1660
1661 $listofpaths = array($file);
1662 $listofnames = array(basename($file));
1663 $listofmimes = array(dol_mimetype($file));
1664 }
1665
1666 $trackid = 'inv'.$object->id;
1667
1668 $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, $listofpaths, $listofmimes, $listofnames, $cc, '', 0, ($ishtml ? 1 : 0), '', '', $trackid, '', 'standard');
1669
1670 $result = $mailfile->sendfile();
1671 if ($result) {
1672 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1673 } else {
1674 dol_syslog("Failed to send EMail to ".$sendto.' - '.$mailfile->error, LOG_ERR, 0, '_payment');
1675 }
1676 }
1677 }
1678 }
1679 } else {
1680 $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.';
1681 $ispostactionok = -1;
1682 }
1683 } else {
1684 $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1685 $ispostactionok = -1;
1686 }
1687 } elseif (array_key_exists('BOO', $tmptag) && $tmptag['BOO'] > 0) {
1688 // Record payment for booth or conference
1689 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1690 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1691 include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1692 $object = new Facture($db);
1693 $result = $object->fetch((int) $ref); // @phan-suppress-current-line PhanPluginSuspiciousParamPosition
1694 if ($result) {
1695 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1696
1697 $paymentTypeId = 0;
1698 if ($paymentmethod == 'paybox') {
1699 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1700 }
1701 if ($paymentmethod == 'paypal') {
1702 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1703 }
1704 if ($paymentmethod == 'stripe') {
1705 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1706 }
1707 if (empty($paymentTypeId)) {
1708 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1709
1710 if (empty($paymentType)) {
1711 $paymentType = 'CB';
1712 }
1713 // May return nothing when paymentType means nothing
1714 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1715 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1716
1717 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1718 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1719 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1720 }
1721 }
1722
1723 // 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)
1724 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1725 $resultvalidate = $object->validate($user);
1726 if ($resultvalidate < 0) {
1727 $postactionmessages[] = 'Cannot validate invoice';
1728 $ispostactionok = -1;
1729 $error++; // Not yet supported
1730 } else {
1731 $db->begin();
1732
1733 // Creation of payment line
1734 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1735 $paiement = new Paiement($db);
1736 $paiement->datepaye = $now;
1737 if ($currencyCodeType == $conf->currency) {
1738 $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1739 } else {
1740 $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1741
1742 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1743 $ispostactionok = -1;
1744 $error++; // Not yet supported
1745 }
1746 $paiement->paiementid = $paymentTypeId;
1747 $paiement->num_payment = '';
1748 $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1749
1750 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1751 if ($LONGTRANSACTIONID) {
1752 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1753 } else {
1754 $paiement->ext_payment_id = $TRANSACTIONID;
1755 }
1756 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1757
1758 if (!$error) {
1759 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1760 if ($paiement_id < 0) {
1761 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1762 $ispostactionok = -1;
1763 $error++;
1764 } else {
1765 $postactionmessages[] = 'Payment created';
1766 $ispostactionok = 1;
1767 }
1768 }
1769
1770 if (!$error && isModEnabled("bank")) {
1771 $bankaccountid = 0;
1772 if ($paymentmethod == 'paybox') {
1773 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1774 } elseif ($paymentmethod == 'paypal') {
1775 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1776 } elseif ($paymentmethod == 'stripe') {
1777 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
1778 }
1779
1780 //Get bank account for a specific paymentmedthod
1781 $parameters = [
1782 'paymentmethod' => $paymentmethod,
1783 ];
1784 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
1785 if ($reshook >= 0) {
1786 if (isset($hookmanager->resArray['bankaccountid'])) {
1787 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
1788 $bankaccountid = $hookmanager->resArray['bankaccountid'];
1789 }
1790 }
1791 if ($bankaccountid > 0) {
1792 $label = '(CustomerInvoicePayment)';
1793 if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1794 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1795 }
1796 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1797 if ($result < 0) {
1798 $postactionmessages[] = $paiement->error.' '.implode("<br>\n", $paiement->errors);
1799 $ispostactionok = -1;
1800 $error++;
1801 } else {
1802 $postactionmessages[] = 'Bank transaction of payment created';
1803 $ispostactionok = 1;
1804 }
1805 } else {
1806 $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.';
1807 $ispostactionok = -1;
1808 $error++;
1809 }
1810 }
1811
1812 if (!$error) {
1813 // Putting the booth to "suggested" state
1814 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1815 require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1816 $booth = new ConferenceOrBooth($db);
1817 $resultbooth = $booth->fetch((int) $tmptag['BOO']);
1818 if ($resultbooth < 0) {
1819 $error++;
1820 setEventMessages(null, $booth->errors, "errors");
1821 } else {
1822 $booth->status = ConferenceOrBooth::STATUS_SUGGESTED;
1823 $resultboothupdate = $booth->update($user);
1824 if ($resultboothupdate < 0) {
1825 // Finding the third party by getting the invoice
1826 $invoice = new Facture($db);
1827 $resultinvoice = $invoice->fetch((int) $ref); // @phan-suppress-current-line PhanPluginSuspiciousParamPosition
1828 if ($resultinvoice < 0) {
1829 $postactionmessages[] = 'Could not find the associated invoice.';
1830 $ispostactionok = -1;
1831 $error++;
1832 } else {
1833 $thirdparty = new Societe($db);
1834 $resultthirdparty = $thirdparty->fetch($invoice->socid);
1835 if ($resultthirdparty < 0) {
1836 $error++;
1837 setEventMessages(null, $thirdparty->errors, "errors");
1838 } else {
1839 // TODO Move the send of email out of the db transaction
1840
1841 // Sending mail
1842 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1843 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1844 $formmail = new FormMail($db);
1845 // Set output language
1846 $outputlangs = new Translate('', $conf);
1847 $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
1848 // Load traductions files required by page
1849 $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1850 // Get email content from template
1851 $arraydefaultmessage = null;
1852
1853 $idoftemplatetouse = getDolGlobalInt('EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_BOOTH'); // Email sent after registration for a Booth
1854
1855 if (!empty($idoftemplatetouse)) {
1856 $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1857 }
1858
1859 if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1860 $subject = $arraydefaultmessage->topic;
1861 $msg = $arraydefaultmessage->content;
1862 } else {
1863 $subject = '['.$appli.'] '.$booth->ref.' - '.$outputlangs->trans("NewRegistration").']';
1864 $msg = $outputlangs->trans("OrganizationEventPaymentOfBoothWasReceived");
1865 }
1866
1867 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1868 complete_substitutions_array($substitutionarray, $outputlangs, $object);
1869
1870 $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1871 $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1872
1873 $sendto = $thirdparty->email;
1874 $from = getDolGlobalString('MAILING_EMAIL_FROM');
1875 $urlback = $_SERVER["REQUEST_URI"];
1876
1877 $ishtml = dol_textishtml($texttosend); // May contain urls
1878 $trackid = 'inv'.$invoice->id;
1879
1880 $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, array(), array(), array(), '', '', 0, $ishtml ? 1 : 0, '', '', $trackid, '', 'standard');
1881
1882 $result = $mailfile->sendfile();
1883 if ($result) {
1884 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1885 } else {
1886 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
1887 }
1888 }
1889 }
1890 }
1891 }
1892 }
1893
1894 if (!$error) {
1895 $db->commit();
1896 } else {
1897 $db->rollback();
1898 }
1899 }
1900 } else {
1901 $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.';
1902 $ispostactionok = -1;
1903 }
1904 } else {
1905 $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1906 $ispostactionok = -1;
1907 }
1908 } elseif (array_key_exists('CON', $tmptag) && $tmptag['CON'] > 0) {
1909 include_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php';
1910 $object = new Contrat($db);
1911 $result = $object->fetch((int) $tmptag['CON']);
1912 if ($result) {
1913 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1914
1915 $paymentTypeId = 0;
1916 if ($paymentmethod == 'paybox') {
1917 $paymentTypeId = getDolGlobalInt('PAYBOX_PAYMENT_MODE_FOR_PAYMENTS');
1918 }
1919 if ($paymentmethod == 'paypal') {
1920 $paymentTypeId = getDolGlobalInt('PAYPAL_PAYMENT_MODE_FOR_PAYMENTS');
1921 }
1922 if ($paymentmethod == 'stripe') {
1923 $paymentTypeId = getDolGlobalInt('STRIPE_PAYMENT_MODE_FOR_PAYMENTS');
1924 }
1925 if (empty($paymentTypeId)) {
1926 dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1927
1928 if (empty($paymentType)) {
1929 $paymentType = 'CB';
1930 }
1931 // May return nothing when paymentType means nothing
1932 // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1933 $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1934
1935 // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1936 if (empty($paymentTypeId) || $paymentTypeId < 0) {
1937 $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1938 }
1939 }
1940
1941 $currencyCodeType = $_SESSION['currencyCodeType'];
1942 $contract_lines = (array_key_exists('COL', $tmptag) && $tmptag['COL'] > 0) ? $tmptag['COL'] : null;
1943
1944 // 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)
1945 if (isModEnabled('invoice')) {
1946 if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1947 $db->begin();
1948
1949 include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1950 $invoice = new Facture($db);
1951 $result = $invoice->createFromContract($object, $user, array((int) $contract_lines));
1952 if ($result > 0) {
1953 // $object->classifyBilled($user);
1954 $invoice->validate($user);
1955 // Creation of payment line
1956 include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
1957 $paiement = new Paiement($db);
1958 $paiement->datepaye = $now;
1959 if ($currencyCodeType == $conf->currency) {
1960 $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1961 } else {
1962 $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
1963
1964 $postactionmessages[] = 'Payment was done in a currency ('.$currencyCodeType.') other than the expected currency of company ('.$conf->currency.')';
1965 $ispostactionok = -1;
1966 $error++;
1967 }
1968 $paiement->paiementid = $paymentTypeId;
1969 $paiement->num_payment = '';
1970 $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
1971
1972 // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
1973 if ($LONGTRANSACTIONID) {
1974 $paiement->ext_payment_id = $LONGTRANSACTIONID;
1975 } else {
1976 $paiement->ext_payment_id = $TRANSACTIONID;
1977 }
1978 $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1979
1980 if (!$error) {
1981 $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1982 if ($paiement_id < 0) {
1983 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
1984 $ispostactionok = -1;
1985 $error++;
1986 } else {
1987 $postactionmessages[] = 'Payment created';
1988 $ispostactionok = 1;
1989 }
1990 }
1991
1992 if (!$error && isModEnabled("bank")) {
1993 $bankaccountid = 0;
1994 if ($paymentmethod == 'paybox') {
1995 $bankaccountid = getDolGlobalString('PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS');
1996 } elseif ($paymentmethod == 'paypal') {
1997 $bankaccountid = getDolGlobalString('PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS');
1998 } elseif ($paymentmethod == 'stripe') {
1999 $bankaccountid = getDolGlobalString('STRIPE_BANK_ACCOUNT_FOR_PAYMENTS');
2000 }
2001
2002 //Get bank account for a specific paymentmedthod
2003 $parameters = [
2004 'paymentmethod' => $paymentmethod,
2005 ];
2006 $reshook = $hookmanager->executeHooks('getBankAccountPaymentMethod', $parameters, $object, $action);
2007 if ($reshook >= 0) {
2008 if (isset($hookmanager->resArray['bankaccountid'])) {
2009 dol_syslog('bankaccountid overwrite by hook return with value='.$hookmanager->resArray['bankaccountid'], LOG_DEBUG, 0, '_payment');
2010 $bankaccountid = $hookmanager->resArray['bankaccountid'];
2011 }
2012 }
2013 if ($bankaccountid > 0) {
2014 $label = '(CustomerInvoicePayment)';
2015 if ($invoice->type == Facture::TYPE_CREDIT_NOTE) {
2016 $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
2017 }
2018 $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
2019 if ($result < 0) {
2020 $postactionmessages[] = $paiement->error . ' ' . implode("<br>\n", $paiement->errors);
2021 $ispostactionok = -1;
2022 $error++;
2023 } else {
2024 $postactionmessages[] = 'Bank transaction of payment created';
2025 $ispostactionok = 1;
2026 }
2027 } else {
2028 $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
2029 $ispostactionok = -1;
2030 $error++;
2031 }
2032 }
2033 } else {
2034 $msg = 'Failed to create invoice form contract ' . $tmptag['CON'];
2035 if (!empty($tmptag['COL'])) {
2036 $msg .= ' and col '. $tmptag['COL'] .'.';
2037 }
2038 $postactionmessages[] = $msg;
2039 $ispostactionok = -1;
2040 $error++;
2041 }
2042
2043 if (!$error) {
2044 $db->commit();
2045 } else {
2046 $db->rollback();
2047 }
2048 } else {
2049 $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.';
2050 $ispostactionok = -1;
2051 }
2052 } else {
2053 $postactionmessages[] = 'Invoice module is not enable';
2054 $ispostactionok = -1;
2055 }
2056 } else {
2057 $msg = 'Contract paid ' . $tmptag['CON'] . ' was not found';
2058 if (!empty($tmptag['COL'])) {
2059 $msg .= ' for col '.$tmptag['COL'] .'.';
2060 }
2061 $postactionmessages[] = $msg;
2062 $ispostactionok = -1;
2063 }
2064 } else {
2065 // Nothing done
2066 }
2067}
2068
2069dol_syslog("ispaymentok=".$ispaymentok." ispostactionok=".$ispostactionok." doactionsthenredirect=".$doactionsthenredirect, LOG_DEBUG, 0, '_payment');
2070
2071if ($ispaymentok) {
2072 // Get on url call
2073 $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
2074 $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
2075 // Set by newpayment.php
2076 $currencyCodeType = empty($_SESSION['currencyCodeType']) ? '' : $_SESSION['currencyCodeType'];
2077 $FinalPaymentAmt = empty($_SESSION["FinalPaymentAmt"]) ? '' : $_SESSION["FinalPaymentAmt"];
2078 $paymentType = empty($_SESSION['PaymentType']) ? '' : $_SESSION['PaymentType']; // Seems used by paypal only
2079
2080 if (is_object($object) && method_exists($object, 'call_trigger')) {
2081 '@phan-var-force CommonObject $object';
2082 // Call trigger
2083 $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
2084 if ($result < 0) {
2085 $error++;
2086 }
2087 // End call triggers
2088 } elseif (get_class($object) == 'stdClass') {
2089 //In some cases $object is not instantiated (for payment on custom object) We need to deal with payment
2090 include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
2091 $paiement = new Paiement($db);
2092 $result = $paiement->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
2093 if ($result < 0) {
2094 $error++;
2095 }
2096 }
2097}
2098
2099
2100// Show result message
2101if (empty($doactionsthenredirect)) {
2102 if ($ispaymentok) {
2103 print $langs->trans("YourPaymentHasBeenRecorded")."<br>\n";
2104 if ($TRANSACTIONID) {
2105 print $langs->trans("ThisIsTransactionId")." : ".$TRANSACTIONID."<br><br>\n";
2106 }
2107
2108 print '<center>';
2109 print img_picto('', 'tick', 'class="green fa-2x"');
2110 print '</center>';
2111
2112 // Show a custom message
2113 $key = 'ONLINE_PAYMENT_MESSAGE_OK';
2114 if (getDolGlobalString($key)) {
2115 print '<br>';
2116 print getDolGlobalString($key);
2117 }
2118 } else {
2119 print $langs->trans('DoExpressCheckoutPaymentAPICallFailed')."<br>\n";
2120 if ($ErrorLongMsg) {
2121 print $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n";
2122 }
2123 if ($ErrorShortMsg) {
2124 print $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n";
2125 }
2126 if ($ErrorCode) {
2127 print $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n";
2128 }
2129 if ($ErrorSeverityCode) {
2130 print $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n";
2131 }
2132
2133 if ($mysoc->email) {
2134 print "\nPlease, send a screenshot of this page to ".$mysoc->email."<br>\n";
2135 }
2136 }
2137}
2138
2139
2140// Send email
2141if ($ispaymentok) {
2142 $sendemail = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL');
2143
2144 $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
2145
2146 dol_syslog("Send email to admins if we have to (sendemail = ".$sendemail.")", LOG_DEBUG, 0, '_payment');
2147
2148 // Send an email to the admins
2149 if ($sendemail) {
2150 // Get default language to use for the company for supervision emails
2151 $myCompanyDefaultLang = (string) $mysoc->default_lang;
2152 if (empty($myCompanyDefaultLang) || $myCompanyDefaultLang === 'auto') {
2153 // 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
2154 // so it must always be into the same language.
2155 $myCompanyDefaultLang = (string) getLanguageCodeFromCountryCode($mysoc->country_code);
2156 }
2157
2158 $companylangs = new Translate('', $conf);
2159 $companylangs->setDefaultLang($myCompanyDefaultLang);
2160 $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox', 'stripe'));
2161
2162 $sendto = $sendemail;
2163 $from = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
2164 // Define $urlwithroot
2165 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2166 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2167 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
2168
2169 // Define link to login card
2170
2171 $urlback = $_SERVER["REQUEST_URI"];
2172 $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived");
2173 $content = "";
2174 if (array_key_exists('MEM', $tmptag)) {
2175 $url = $urlwithroot."/adherents/subscription.php?rowid=".((int) $tmptag['MEM']);
2176 $content .= '<strong>'.$companylangs->transnoentitiesnoconv("PaymentSubscription")."</strong><br><br>\n";
2177 $content .= $companylangs->transnoentitiesnoconv("MemberId").': <strong>'.$tmptag['MEM']."</strong><br>\n";
2178 $content .= $companylangs->transnoentitiesnoconv("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
2179 } elseif (array_key_exists('INV', $tmptag)) {
2180 $url = $urlwithroot."/compta/facture/card.php?id=".((int) $tmptag['INV']);
2181 $content .= '<strong>'.$companylangs->transnoentitiesnoconv("Payment")."</strong><br><br>\n";
2182 $content .= $companylangs->transnoentitiesnoconv("InvoiceId").': <strong>'.$tmptag['INV']."</strong><br>\n";
2183 //$content.=$companylangs->trans("ThirdPartyId").': '.$tmptag['CUS']."<br>\n";
2184 $content .= $companylangs->transnoentitiesnoconv("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
2185 } else {
2186 $content .= $companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived")."<br>\n";
2187 }
2188 $content .= $companylangs->transnoentitiesnoconv("PostActionAfterPayment").' : ';
2189 if ($ispostactionok > 0) {
2190 //$topic.=' ('.$companylangs->transnoentitiesnoconv("Status").' '.$companylangs->transnoentitiesnoconv("OK").')';
2191 $content .= '<span style="color: green">'.$companylangs->transnoentitiesnoconv("OK").'</span>';
2192 } elseif ($ispostactionok == 0) {
2193 $content .= $companylangs->transnoentitiesnoconv("None");
2194 } else {
2195 $topic .= ($ispostactionok ? '' : ' ('.$companylangs->trans("WarningPostActionErrorAfterPayment").')');
2196 $content .= '<span class="star">'.$companylangs->transnoentitiesnoconv("Error").'</span>';
2197 }
2198 $content .= '<br>'."\n";
2199 foreach ($postactionmessages as $postactionmessage) {
2200 $content .= ' * '.$postactionmessage.'<br>'."\n";
2201 }
2202 if ($ispostactionok < 0) {
2203 $content .= $langs->transnoentitiesnoconv("ARollbackWasPerformedOnPostActions");
2204 }
2205 $content .= '<br>'."\n";
2206
2207 $content .= "<br>\n";
2208 $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
2209 $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
2210 $content .= $companylangs->transnoentitiesnoconv("ThisIsTransactionId").': <strong>'.$TRANSACTIONID."</strong><br>\n";
2211 $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
2212 $content .= "<br>\n";
2213 $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
2214
2215 if (!empty($ErrorCode)) {
2216 $content .= "ErrorCode = ".$ErrorCode."<br>\n";
2217 }
2218 if (!empty($ErrorShortMsg)) {
2219 $content .= "ErrorShortMsg = ".$ErrorShortMsg."<br>\n";
2220 }
2221 if (!empty($ErrorLongMsg)) {
2222 $content .= "ErrorLongMsg = ".$ErrorLongMsg."<br>\n";
2223 }
2224 if (!empty($ErrorSeverityCode)) {
2225 $content .= "ErrorSeverityCode = ".$ErrorSeverityCode."<br>\n";
2226 }
2227
2228 dol_syslog("Content of email: ".$content, LOG_DEBUG, 0, '_payment');
2229
2230 $ishtml = dol_textishtml($content); // May contain urls
2231 $trackid = '';
2232
2233 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2234 $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml ? 1 : 0, '', '', $trackid, '', 'standard');
2235
2236 $result = $mailfile->sendfile();
2237 if ($result) {
2238 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
2239 //dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0);
2240 } else {
2241 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
2242 //dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0);
2243 }
2244 }
2245} else {
2246 $sendemail = getDolGlobalString('ONLINE_PAYMENT_SENDEMAIL');
2247
2248 // Get on url call
2249 $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
2250 $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
2251 // Set by newpayment.php
2252 $paymentType = $_SESSION['PaymentType'];
2253 $currencyCodeType = $_SESSION['currencyCodeType'];
2254 $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
2255
2256 if (is_object($object) && method_exists($object, 'call_trigger')) {
2257 // Call trigger
2258 $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_KO', $user);
2259 if ($result < 0) {
2260 $error++;
2261 }
2262 // End call triggers
2263 }
2264
2265 // Send warning of error to administrator
2266 if ($sendemail) {
2267 $companylangs = new Translate('', $conf);
2268 $companylangs->setDefaultLang($mysoc->default_lang);
2269 $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox', 'stripe'));
2270
2271 $sendto = $sendemail;
2272 $from = getDolGlobalString('MAILING_EMAIL_FROM', getDolGlobalString("MAIN_MAIL_EMAIL_FROM"));
2273 // Define $urlwithroot
2274 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
2275 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
2276 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
2277
2278 $urlback = $_SERVER["REQUEST_URI"];
2279 $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("ValidationOfPaymentFailed");
2280 $content = "";
2281 $content .= '<span style="color: orange">'.$companylangs->transnoentitiesnoconv("PaymentSystemConfirmPaymentPageWasCalledButFailed")."</span>\n";
2282
2283 $content .= "<br><br>\n";
2284 $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
2285 $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
2286 $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
2287 $content .= "<br>\n";
2288 $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
2289
2290
2291 $ishtml = dol_textishtml($content); // May contain urls
2292 $trackid = '';
2293
2294 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
2295 $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml ? 1 : 0, '', '', $trackid, '', 'standard');
2296
2297 $result = $mailfile->sendfile();
2298 if ($result) {
2299 dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
2300 } else {
2301 dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
2302 }
2303 }
2304}
2305
2306
2307// Clean session variables to avoid duplicate actions if post is resent
2308unset($_SESSION["FinalPaymentAmt"]);
2309unset($_SESSION["TRANSACTIONID"]);
2310
2311
2312// Close page content id="dolpaymentdiv"
2313if (empty($doactionsthenredirect)) {
2314 print "\n</div>\n";
2315
2316 print "<!-- Info for payment: FinalPaymentAmt=".dol_escape_htmltag($FinalPaymentAmt)." paymentTypeId=".dol_escape_htmltag((string) $paymentTypeId)." currencyCodeType=".dol_escape_htmltag($currencyCodeType)." -->\n";
2317}
2318
2319
2320// Show footer
2321if (empty($doactionsthenredirect)) {
2322 htmlPrintOnlineFooter($mysoc, $langs, 0, $suffix);
2323
2324 llxFooter('', 'public');
2325}
2326
2327
2328$db->close();
2329
2330
2331// If option to do a redirect somewhere else.
2332if (!empty($doactionsthenredirect)) {
2333 if ($ispaymentok) {
2334 // Redirect to a success page
2335 $randomseckey = getRandomPassword(true, null, 20);
2336 $_SESSION['paymentoksessioncode'] = $randomseckey; // key propagated between paymentok.php to another page like a paymentok of the website.
2337
2338 // Paymentok page must be created for the specific website
2339 if (!defined('USEDOLIBARRSERVER') && !empty($ws_virtuelhost)) {
2340 $ext_urlok = $ws_virtuelhost . '/paymentok.php?paymentoksessioncode='.urlencode($randomseckey).'&fulltag='.$FULLTAG;
2341 } else {
2342 $ext_urlok = DOL_URL_ROOT.'/public/website/index.php?paymentoksessioncode='.urlencode($randomseckey).'&website='.urlencode($ws).'&pageref=paymentok&fulltag='.$FULLTAG;
2343 }
2344
2345 dol_syslog("Now do a redirect using a Location: ".$ext_urlok, LOG_DEBUG, 0, '_payment');
2346 header("Location: ".$ext_urlok);
2347 exit;
2348 } else {
2349 // Redirect to an error page
2350 $randomseckey = getRandomPassword(true, null, 20);
2351 $_SESSION['paymentkosessioncode'] = $randomseckey; // key propagated between paymentok.php to another page like a paymentko of the website.
2352
2353 // Paymentko page must be created for the specific website
2354 if (!defined('USEDOLIBARRSERVER') && !empty($ws_virtuelhost)) {
2355 $ext_urlko = $ws_virtuelhost . '/paymentko.php?paymentkosessioncode='.urlencode($randomseckey).'&fulltag='.$FULLTAG;
2356 } else {
2357 $ext_urlko = DOL_URL_ROOT.'/public/website/index.php?paymentkosessioncode='.urlencode($randomseckey).'&website='.urlencode($ws).'&pageref=paymentko&fulltag='.$FULLTAG;
2358 }
2359
2360 dol_syslog("Now do a redirect using a Location:".$ext_urlko, LOG_DEBUG, 0, '_payment');
2361 header("Location: ".$ext_urlko);
2362 exit;
2363 }
2364}
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:604
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)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
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.