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