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