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