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