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