dolibarr  19.0.0-dev
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 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  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program. If not, see <https://www.gnu.org/licenses/>.
21  */
22 
32 if (!defined('NOLOGIN')) {
33  define("NOLOGIN", 1); // This means this output page does not require to be logged.
34 }
35 if (!defined('NOCSRFCHECK')) {
36  define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
37 }
38 if (!defined('NOIPCHECK')) {
39  define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
40 }
41 if (!defined('NOBROWSERNOTIF')) {
42  define('NOBROWSERNOTIF', '1');
43 }
44 
45 // For MultiCompany module.
46 // Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
47 // TODO This should be useless. Because entity must be retrieve from object ref and not from url.
48 $entity = (!empty($_GET['e']) ? (int) $_GET['e'] : (!empty($_POST['e']) ? (int) $_POST['e'] : 1));
49 if (is_numeric($entity)) {
50  define("DOLENTITY", $entity);
51 }
52 
53 // Load Dolibarr environment
54 require '../../main.inc.php';
55 require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
56 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
57 if (isModEnabled('paypal')) {
58  require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypal.lib.php';
59  require_once DOL_DOCUMENT_ROOT.'/paypal/lib/paypalfunctions.lib.php';
60 }
61 
62 // Hook to be used by external payment modules (ie Payzen, ...)
63 $hookmanager = new HookManager($db);
64 
65 $hookmanager->initHooks(array('newpayment'));
66 
67 $langs->loadLangs(array("main", "other", "dict", "bills", "companies", "paybox", "paypal"));
68 
69 // Clean parameters
70 if (isModEnabled('paypal')) {
71  $PAYPAL_API_USER = "";
72  if (!empty($conf->global->PAYPAL_API_USER)) {
73  $PAYPAL_API_USER = $conf->global->PAYPAL_API_USER;
74  }
75  $PAYPAL_API_PASSWORD = "";
76  if (!empty($conf->global->PAYPAL_API_PASSWORD)) {
77  $PAYPAL_API_PASSWORD = $conf->global->PAYPAL_API_PASSWORD;
78  }
79  $PAYPAL_API_SIGNATURE = "";
80  if (!empty($conf->global->PAYPAL_API_SIGNATURE)) {
81  $PAYPAL_API_SIGNATURE = $conf->global->PAYPAL_API_SIGNATURE;
82  }
83  $PAYPAL_API_SANDBOX = "";
84  if (!empty($conf->global->PAYPAL_API_SANDBOX)) {
85  $PAYPAL_API_SANDBOX = $conf->global->PAYPAL_API_SANDBOX;
86  }
87  $PAYPAL_API_OK = "";
88  if ($urlok) {
89  $PAYPAL_API_OK = $urlok;
90  }
91  $PAYPAL_API_KO = "";
92  if ($urlko) {
93  $PAYPAL_API_KO = $urlko;
94  }
95 
96  $PAYPALTOKEN = GETPOST('TOKEN');
97  if (empty($PAYPALTOKEN)) {
98  $PAYPALTOKEN = GETPOST('token');
99  }
100  $PAYPALPAYERID = GETPOST('PAYERID');
101  if (empty($PAYPALPAYERID)) {
102  $PAYPALPAYERID = GETPOST('PayerID');
103  }
104 }
105 
106 $FULLTAG = GETPOST('FULLTAG');
107 if (empty($FULLTAG)) {
108  $FULLTAG = GETPOST('fulltag');
109 }
110 $source = GETPOST('s', 'alpha') ? GETPOST('s', 'alpha') : GETPOST('source', 'alpha');
111 $ref = GETPOST('ref');
112 
113 $suffix = GETPOST("suffix", 'aZ09');
114 $membertypeid = GETPOST("membertypeid", 'int');
115 
116 
117 // Detect $paymentmethod
118 $paymentmethod = '';
119 $reg = array();
120 if (preg_match('/PM=([^\.]+)/', $FULLTAG, $reg)) {
121  $paymentmethod = $reg[1];
122 }
123 if (empty($paymentmethod)) {
124  dol_syslog("***** paymentok.php was called with a non valid parameter FULLTAG=".$FULLTAG, LOG_DEBUG, 0, '_payment');
125  dol_print_error(null, 'The callback url does not contain a parameter fulltag that should help us to find the payment method used');
126  exit;
127 }
128 
129 dol_syslog("***** paymentok.php is called paymentmethod=".$paymentmethod." FULLTAG=".$FULLTAG." REQUEST_URI=".$_SERVER["REQUEST_URI"], LOG_DEBUG, 0, '_payment');
130 
131 
132 $validpaymentmethod = array();
133 if (isModEnabled('paypal')) {
134  $validpaymentmethod['paypal'] = 'paypal';
135 }
136 if (isModEnabled('paybox')) {
137  $validpaymentmethod['paybox'] = 'paybox';
138 }
139 if (isModEnabled('stripe')) {
140  $validpaymentmethod['stripe'] = 'stripe';
141 }
142 
143 // Security check
144 if (empty($validpaymentmethod)) {
145  httponly_accessforbidden('No valid payment mode');
146 }
147 
148 
149 $ispaymentok = false;
150 // If payment is ok
151 $PAYMENTSTATUS = $TRANSACTIONID = $TAXAMT = $NOTE = '';
152 // If payment is ko
153 $ErrorCode = $ErrorShortMsg = $ErrorLongMsg = $ErrorSeverityCode = '';
154 
155 
156 $object = new stdClass(); // For triggers
157 
158 $error = 0;
159 
160 
161 /*
162  * Actions
163  */
164 
165 
166 
167 /*
168  * View
169  */
170 
171 $now = dol_now();
172 
173 dol_syslog("Callback url when a payment was done. 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');
174 dol_syslog("_SERVER[SERVER_NAME] = ".(empty($_SERVER["SERVER_NAME"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_NAME"])), LOG_DEBUG, 0, '_payment');
175 dol_syslog("_SERVER[SERVER_ADDR] = ".(empty($_SERVER["SERVER_ADDR"]) ? '' : dol_escape_htmltag($_SERVER["SERVER_ADDR"])), LOG_DEBUG, 0, '_payment');
176 
177 $tracepost = "";
178 foreach ($_POST as $k => $v) {
179  if (is_scalar($k) && is_scalar($v)) {
180  $tracepost .= "$k - $v\n";
181  }
182 }
183 dol_syslog("POST=".$tracepost, LOG_DEBUG, 0, '_payment');
184 $tracesession = "";
185 foreach ($_SESSION as $k => $v) {
186  if (is_scalar($k) && is_scalar($v)) {
187  $tracesession .= "$k - $v\n";
188  }
189 }
190 dol_syslog("SESSION=".$tracesession, LOG_DEBUG, 0, '_payment');
191 
192 $head = '';
193 if (!empty($conf->global->ONLINE_PAYMENT_CSS_URL)) {
194  $head = '<link rel="stylesheet" type="text/css" href="'.$conf->global->ONLINE_PAYMENT_CSS_URL.'?lang='.$langs->defaultlang.'">'."\n";
195 }
196 
197 $conf->dol_hide_topmenu = 1;
198 $conf->dol_hide_leftmenu = 1;
199 
200 $replacemainarea = (empty($conf->dol_hide_leftmenu) ? '<div>' : '').'<div>';
201 llxHeader($head, $langs->trans("PaymentForm"), '', '', 0, 0, '', '', '', 'onlinepaymentbody', $replacemainarea);
202 
203 
204 // Show message
205 print '<span id="dolpaymentspan"></span>'."\n";
206 print '<div id="dolpaymentdiv" class="center">'."\n";
207 
208 
209 // Show logo (search order: logo defined by PAYMENT_LOGO_suffix, then PAYMENT_LOGO, then small company logo, large company logo, theme logo, common logo)
210 // Define logo and logosmall
211 $logosmall = $mysoc->logo_small;
212 $logo = $mysoc->logo;
213 $paramlogo = 'ONLINE_PAYMENT_LOGO_'.$suffix;
214 if (!empty($conf->global->$paramlogo)) {
215  $logosmall = $conf->global->$paramlogo;
216 } elseif (!empty($conf->global->ONLINE_PAYMENT_LOGO)) {
217  $logosmall = $conf->global->ONLINE_PAYMENT_LOGO;
218 }
219 //print '<!-- Show logo (logosmall='.$logosmall.' logo='.$logo.') -->'."\n";
220 // Define urllogo
221 $urllogo = '';
222 $urllogofull = '';
223 if (!empty($logosmall) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$logosmall)) {
224  $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/thumbs/'.$logosmall);
225  $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/thumbs/'.$logosmall);
226 } elseif (!empty($logo) && is_readable($conf->mycompany->dir_output.'/logos/'.$logo)) {
227  $urllogo = DOL_URL_ROOT.'/viewimage.php?modulepart=mycompany&amp;entity='.$conf->entity.'&amp;file='.urlencode('logos/'.$logo);
228  $urllogofull = $dolibarr_main_url_root.'/viewimage.php?modulepart=mycompany&entity='.$conf->entity.'&file='.urlencode('logos/'.$logo);
229 }
230 
231 // Output html code for logo
232 if ($urllogo) {
233  print '<div class="backgreypublicpayment">';
234  print '<div class="logopublicpayment">';
235  print '<img id="dolpaymentlogo" src="'.$urllogo.'"';
236  print '>';
237  print '</div>';
238  if (empty($conf->global->MAIN_HIDE_POWERED_BY)) {
239  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>';
240  }
241  print '</div>';
242 }
243 if (!empty($conf->global->MAIN_IMAGE_PUBLIC_PAYMENT)) {
244  print '<div class="backimagepublicpayment">';
245  print '<img id="idMAIN_IMAGE_PUBLIC_PAYMENT" src="'.$conf->global->MAIN_IMAGE_PUBLIC_PAYMENT.'">';
246  print '</div>';
247 }
248 
249 
250 print '<br><br><br>';
251 
252 
253 if (isModEnabled('paypal')) {
254  if ($paymentmethod === 'paypal') { // We call this page only if payment is ok on payment system
255  if ($PAYPALTOKEN) {
256  // Get on url call
257  $onlinetoken = $PAYPALTOKEN;
258  $fulltag = $FULLTAG;
259  $payerID = $PAYPALPAYERID;
260  // Set by newpayment.php
261  $currencyCodeType = $_SESSION['currencyCodeType'];
262  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
263  $paymentType = $_SESSION['PaymentType']; // Value can be 'Mark', 'Sole', 'Sale' for example
264  // From env
265  $ipaddress = $_SESSION['ipaddress'];
266 
267  dol_syslog("Call paymentok with token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
268 
269  // Validate record
270  if (!empty($paymentType)) {
271  dol_syslog("We call GetExpressCheckoutDetails", LOG_DEBUG, 0, '_payment');
272  $resArray = getDetails($onlinetoken);
273  //var_dump($resarray);
274 
275  $ack = strtoupper($resArray["ACK"]);
276  if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
277  // Nothing to do
278  dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
279  } else {
280  dol_syslog("Call to GetExpressCheckoutDetails return error: ".json_encode($resArray), LOG_WARNING, '_payment');
281  }
282 
283  dol_syslog("We call DoExpressCheckoutPayment token=".$onlinetoken." paymentType=".$paymentType." currencyCodeType=".$currencyCodeType." payerID=".$payerID." ipaddress=".$ipaddress." FinalPaymentAmt=".$FinalPaymentAmt." fulltag=".$fulltag, LOG_DEBUG, 0, '_payment');
284  $resArray2 = confirmPayment($onlinetoken, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $fulltag);
285  //var_dump($resarray);
286 
287  $ack = strtoupper($resArray2["ACK"]);
288  if ($ack == "SUCCESS" || $ack == "SUCCESSWITHWARNING") {
289  dol_syslog("Call to GetExpressCheckoutDetails return ".$ack, LOG_DEBUG, 0, '_payment');
290 
291  $object->source = $source;
292  $object->ref = $ref;
293  $object->payerID = $payerID;
294  $object->fulltag = $fulltag;
295  $object->resArray = $resArray2;
296 
297  // resArray was built from a string like that
298  // 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
299  $PAYMENTSTATUS = urldecode($resArray2["PAYMENTSTATUS"]); // Should contains 'Completed'
300  $TRANSACTIONID = urldecode($resArray2["TRANSACTIONID"]);
301  $TAXAMT = urldecode($resArray2["TAXAMT"]);
302  $NOTE = urldecode($resArray2["NOTE"]);
303 
304  $ispaymentok = true;
305  } else {
306  dol_syslog("Call to DoExpressCheckoutPayment return error: ".json_encode($resArray2), LOG_WARNING, 0, '_payment');
307 
308  //Display a user friendly Error on the page using any of the following error information returned by PayPal
309  $ErrorCode = urldecode($resArray2["L_ERRORCODE0"]);
310  $ErrorShortMsg = urldecode($resArray2["L_SHORTMESSAGE0"]);
311  $ErrorLongMsg = urldecode($resArray2["L_LONGMESSAGE0"]);
312  $ErrorSeverityCode = urldecode($resArray2["L_SEVERITYCODE0"]);
313  }
314  } else {
315  $ErrorCode = "SESSIONEXPIRED";
316  $ErrorLongMsg = "Session expired. Can't retreive PaymentType. Payment has not been validated.";
317  $ErrorShortMsg = "Session expired";
318 
319  dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
320  dol_print_error('', 'Session expired');
321  }
322  } else {
323  $ErrorCode = "PAYPALTOKENNOTDEFINED";
324  $ErrorLongMsg = "The parameter PAYPALTOKEN was not defined. Payment has not been validated.";
325  $ErrorShortMsg = "Parameter PAYPALTOKEN not defined";
326 
327  dol_syslog($ErrorLongMsg, LOG_WARNING, 0, '_payment');
328  dol_print_error('', 'PAYPALTOKEN not defined');
329  }
330  }
331 }
332 
333 if (isModEnabled('paybox')) {
334  if ($paymentmethod === 'paybox') {
335  // TODO Add a check to validate that payment is ok.
336  $ispaymentok = true; // We call this page only if payment is ok on payment system
337  }
338 }
339 
340 if (isModEnabled('stripe')) {
341  if ($paymentmethod === 'stripe') {
342  // TODO Add a check to validate that payment is ok. We can request Stripe with payment_intent and payment_intent_client_secret
343  $ispaymentok = true; // We call this page only if payment is ok on payment system
344  }
345 }
346 
347 // Check status of the object to verify if it is paid by external payment modules
348 $action = '';
349 $parameters = [
350  'paymentmethod' => $paymentmethod,
351 ];
352 $reshook = $hookmanager->executeHooks('isPaymentOK', $parameters, $object, $action);
353 if ($reshook >= 0) {
354  if (isset($hookmanager->resArray['ispaymentok'])) {
355  dol_syslog('ispaymentok overwrite by hook return with value='.$hookmanager->resArray['ispaymentok'], LOG_DEBUG, 0, '_payment');
356  $ispaymentok = $hookmanager->resArray['ispaymentok'];
357  }
358 }
359 
360 
361 // If data not provided into callback url, search them into the session env
362 if (empty($ipaddress)) {
363  $ipaddress = $_SESSION['ipaddress'];
364 }
365 if (empty($TRANSACTIONID)) {
366  $TRANSACTIONID = $_SESSION['TRANSACTIONID']; // pi_... or ch_...
367  if (empty($TRANSACTIONID) && GETPOST('payment_intent', 'alphanohtml')) {
368  // For the case we use STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION = 2
369  $TRANSACTIONID = GETPOST('payment_intent', 'alphanohtml');
370  }
371 }
372 if (empty($FinalPaymentAmt)) {
373  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
374 }
375 if (empty($currencyCodeType)) {
376  $currencyCodeType = $_SESSION['currencyCodeType'];
377 }
378 // Seems used onyl by Paypal
379 if (empty($paymentType)) {
380  $paymentType = $_SESSION["paymentType"];
381 }
382 
383 $fulltag = $FULLTAG;
384 $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
385 
386 
387 dol_syslog("ispaymentok=".$ispaymentok." tmptag=".var_export($tmptag, true), LOG_DEBUG, 0, '_payment');
388 
389 
390 // Make complementary actions
391 $ispostactionok = 0;
392 $postactionmessages = array();
393 if ($ispaymentok) {
394  // Set permission for the anonymous user
395  if (empty($user->rights->societe)) {
396  $user->rights->societe = new stdClass();
397  }
398  if (empty($user->rights->facture)) {
399  $user->rights->facture = new stdClass();
400  $user->rights->facture->invoice_advance = new stdClass();
401  }
402  if (empty($user->rights->adherent)) {
403  $user->rights->adherent = new stdClass();
404  $user->rights->adherent->cotisation = new stdClass();
405  }
406  $user->rights->societe->creer = 1;
407  $user->rights->facture->creer = 1;
408  $user->rights->facture->invoice_advance->validate = 1;
409  $user->rights->adherent->cotisation->creer = 1;
410 
411  if (array_key_exists('MEM', $tmptag) && $tmptag['MEM'] > 0) {
412  // Validate member
413  // Create subscription
414  // Create complementary actions (this include creation of thirdparty)
415  // Send confirmation email
416 
417  $defaultdelay = 1;
418  $defaultdelayunit = 'y';
419 
420  // Record subscription
421  include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
422  include_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
423  include_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
424  $adht = new AdherentType($db);
425  $object = new Adherent($db);
426 
427  $result1 = $object->fetch((int) $tmptag['MEM']);
428  $result2 = $adht->fetch($object->typeid);
429 
430  dol_syslog("We have to process member with id=".$tmptag['MEM']." result1=".$result1." result2=".$result2, LOG_DEBUG, 0, '_payment');
431 
432  if ($result1 > 0 && $result2 > 0) {
433  $paymentTypeId = 0;
434  if ($paymentmethod == 'paybox') {
435  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
436  }
437  if ($paymentmethod == 'paypal') {
438  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
439  }
440  if ($paymentmethod == 'stripe') {
441  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
442  }
443  if (empty($paymentTypeId)) {
444  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
445 
446  if (empty($paymentType)) {
447  $paymentType = 'CB';
448  }
449  // May return nothing when paymentType means nothing
450  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
451  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
452 
453  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
454  if (empty($paymentTypeId) || $paymentTypeId < 0) {
455  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
456  }
457  }
458 
459  dol_syslog("FinalPaymentAmt=".$FinalPaymentAmt." paymentTypeId=".$paymentTypeId." currencyCodeType=".$currencyCodeType, LOG_DEBUG, 0, '_payment');
460 
461  // 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)
462  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
463  // Security protection:
464  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)
465  if ($object->status == $object::STATUS_DRAFT) { // If the member is not yet validated, we check that the amount is the same as expected.
466  $typeid = $object->typeid;
467 
468  // Set amount for the subscription:
469  // - First check the amount of the member type.
470  $amountbytype = $adht->amountByType(1); // Load the array of amount per type
471  $amountexpected = empty($amountbytype[$typeid]) ? 0 : $amountbytype[$typeid];
472  // - If not found, take the default amount
473  if (empty($amountexpected) && !empty($conf->global->MEMBER_NEWFORM_AMOUNT)) {
474  $amountexpected = $conf->global->MEMBER_NEWFORM_AMOUNT;
475  }
476 
477  if ($amountexpected && $amountexpected != $FinalPaymentAmt) {
478  $error++;
479  $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') differs from value expected for membership ('.$amountexpected.'). May be a hack to try to pay a different amount ?';
480  $postactionmessages[] = $errmsg;
481  $ispostactionok = -1;
482  dol_syslog("Failed to validate member (bad amount check): ".$errmsg, LOG_ERR, 0, '_payment');
483  }
484  }
485  }
486 
487  // Security protection:
488  if (!empty($conf->global->MEMBER_MIN_AMOUNT)) {
489  if ($FinalPaymentAmt < $conf->global->MEMBER_MIN_AMOUNT) {
490  $error++;
491  $errmsg = 'Value of FinalPayment ('.$FinalPaymentAmt.') is lower than the minimum allowed ('.$conf->global->MEMBER_MIN_AMOUNT.'). May be a hack to try to pay a different amount ?';
492  $postactionmessages[] = $errmsg;
493  $ispostactionok = -1;
494  dol_syslog("Failed to validate member (amount lower than minimum): ".$errmsg, LOG_ERR, 0, '_payment');
495  }
496  }
497 
498  // Security protection:
499  if ($currencyCodeType && $currencyCodeType != $conf->currency) { // Check that currency is the good one
500  $error++;
501  $errmsg = 'Value of currencyCodeType ('.$currencyCodeType.') differs from value expected for membership ('.$conf->currency.'). May be a hack to try to pay a different amount ?';
502  $postactionmessages[] = $errmsg;
503  $ispostactionok = -1;
504  dol_syslog("Failed to validate member (bad currency check): ".$errmsg, LOG_ERR, 0, '_payment');
505  }
506 
507  if (! $error) {
508  // We validate the member (no effect if it is already validated)
509  $result = ($object->status == $object::STATUS_EXCLUDED) ? -1 : $object->validate($user); // if membre is excluded (status == -2) the new validation is not possible
510  if ($result < 0 || empty($object->datevalid)) {
511  $error++;
512  $errmsg = $object->error;
513  $postactionmessages[] = $errmsg;
514  $postactionmessages = array_merge($postactionmessages, $object->errors);
515  $ispostactionok = -1;
516  dol_syslog("Failed to validate member: ".$errmsg, LOG_ERR, 0, '_payment');
517  }
518  }
519 
520  // Subscription informations
521  $datesubscription = $object->datevalid;
522  if ($object->datefin > 0) {
523  $datesubscription = dol_time_plus_duree($object->datefin, 1, 'd');
524  }
525 
526  $datesubend = null;
527  if ($datesubscription && $defaultdelay && $defaultdelayunit) {
528  $datesubend = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
529  // the new end date of subscription must be in futur
530  while ($datesubend < $now) {
531  $datesubend = dol_time_plus_duree($datesubend, $defaultdelay, $defaultdelayunit);
532  $datesubscription = dol_time_plus_duree($datesubscription, $defaultdelay, $defaultdelayunit);
533  }
534  $datesubend = dol_time_plus_duree($datesubend, -1, 'd');
535  }
536 
537  // Set output language
538  $outputlangs = new Translate('', $conf);
539  $outputlangs->setDefaultLang(empty($object->thirdparty->default_lang) ? $mysoc->default_lang : $object->thirdparty->default_lang);
540  $paymentdate = $now;
541  $amount = $FinalPaymentAmt;
542  $formatteddate = dol_print_date($paymentdate, 'dayhour', 'auto', $outputlangs);
543  $label = $langs->trans("OnlineSubscriptionPaymentLine", $formatteddate, $paymentmethod, $ipaddress, $TRANSACTIONID);
544 
545  // Payment informations
546  $accountid = 0;
547  if ($paymentmethod == 'paybox') {
548  $accountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
549  }
550  if ($paymentmethod == 'paypal') {
551  $accountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
552  }
553  if ($paymentmethod == 'stripe') {
554  $accountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
555  }
556  if ($accountid < 0) {
557  $error++;
558  $errmsg = 'Setup of bank account to use for payment is not correctly done for payment method '.$paymentmethod;
559  $postactionmessages[] = $errmsg;
560  $ispostactionok = -1;
561  dol_syslog("Failed to get the bank account to record payment: ".$errmsg, LOG_ERR, 0, '_payment');
562  }
563 
564  $operation = dol_getIdFromCode($db, $paymentTypeId, 'c_paiement', 'id', 'code', 1); // Payment mode code returned from payment mode id
565  $num_chq = '';
566  $emetteur_nom = '';
567  $emetteur_banque = '';
568  // Define default choice for complementary actions
569  $option = '';
570  if (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankviainvoice' && isModEnabled("banque") && isModEnabled("societe") && isModEnabled('facture')) {
571  $option = 'bankviainvoice';
572  } elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'bankdirect' && isModEnabled("banque")) {
573  $option = 'bankdirect';
574  } elseif (!empty($conf->global->ADHERENT_BANK_USE) && $conf->global->ADHERENT_BANK_USE == 'invoiceonly' && isModEnabled("banque") && isModEnabled("societe") && isModEnabled('facture')) {
575  $option = 'invoiceonly';
576  }
577  if (empty($option)) {
578  $option = 'none';
579  }
580  $sendalsoemail = 1;
581 
582  // Record the subscription then complementary actions
583  $db->begin();
584 
585  // Create subscription
586  if (!$error) {
587  dol_syslog("Call ->subscription to create subscription", LOG_DEBUG, 0, '_payment');
588 
589  $crowid = $object->subscription($datesubscription, $amount, $accountid, $operation, $label, $num_chq, $emetteur_nom, $emetteur_banque, $datesubend, $membertypeid);
590  if ($crowid <= 0) {
591  $error++;
592  $errmsg = $object->error;
593  $postactionmessages[] = $errmsg;
594  $ispostactionok = -1;
595  } else {
596  $postactionmessages[] = 'Subscription created (id='.$crowid.')';
597  $ispostactionok = 1;
598  }
599  }
600 
601  if (!$error) {
602  dol_syslog("Call ->subscriptionComplementaryActions option=".$option, LOG_DEBUG, 0, '_payment');
603 
604  $autocreatethirdparty = 1; // will create thirdparty if member not yet linked to a thirdparty
605 
606  $result = $object->subscriptionComplementaryActions($crowid, $option, $accountid, $datesubscription, $paymentdate, $operation, $label, $amount, $num_chq, $emetteur_nom, $emetteur_banque, $autocreatethirdparty, $TRANSACTIONID, $service);
607  if ($result < 0) {
608  dol_syslog("Error ".$object->error." ".join(',', $object->errors), LOG_DEBUG, 0, '_payment');
609 
610  $error++;
611  $postactionmessages[] = $object->error;
612  $postactionmessages = array_merge($postactionmessages, $object->errors);
613  $ispostactionok = -1;
614  } else {
615  if ($option == 'bankviainvoice') {
616  $postactionmessages[] = 'Invoice, payment and bank record created';
617  dol_syslog("Invoice, payment and bank record created", LOG_DEBUG, 0, '_payment');
618  }
619  if ($option == 'bankdirect') {
620  $postactionmessages[] = 'Bank record created';
621  dol_syslog("Bank record created", LOG_DEBUG, 0, '_payment');
622  }
623  if ($option == 'invoiceonly') {
624  $postactionmessages[] = 'Invoice recorded';
625  dol_syslog("Invoice recorded", LOG_DEBUG, 0, '_payment');
626  }
627  $ispostactionok = 1;
628 
629  // If an invoice was created, it is into $object->invoice
630  }
631  }
632 
633  if (!$error) {
634  if ($paymentmethod == 'stripe' && $autocreatethirdparty && $option == 'bankviainvoice') {
635  $thirdparty_id = $object->fk_soc;
636 
637  dol_syslog("Search existing Stripe customer profile for thirdparty_id=".$thirdparty_id, LOG_DEBUG, 0, '_payment');
638 
639  $service = 'StripeTest';
640  $servicestatus = 0;
641  if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) {
642  $service = 'StripeLive';
643  $servicestatus = 1;
644  }
645  $stripeacc = null; // No Oauth/connect use for public pages
646 
647  $thirdparty = new Societe($db);
648  $thirdparty->fetch($thirdparty_id);
649 
650  include_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php'; // This also set $stripearrayofkeysbyenv
651  $stripe = new Stripe($db);
652  //$stripeacc = $stripe->getStripeAccount($service); Already defined previously
653 
654  $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 0);
655 
656  if (!$customer && $TRANSACTIONID) { // Not linked to a stripe customer, we make the link
657  dol_syslog("No stripe profile found, so we add it for TRANSACTIONID = ".$TRANSACTIONID, LOG_DEBUG, 0, '_payment');
658 
659  try {
660  global $stripearrayofkeysbyenv;
661  \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$servicestatus]['secret_key']);
662 
663  if (preg_match('/^pi_/', $TRANSACTIONID)) {
664  // This may throw an error if not found.
665  $chpi = \Stripe\PaymentIntent::retrieve($TRANSACTIONID); // payment_intent (pi_...)
666  } else {
667  // This throw an error if not found
668  $chpi = \Stripe\Charge::retrieve($TRANSACTIONID); // old method, contains the charge id (ch_...)
669  }
670 
671  if ($chpi) {
672  $stripecu = $chpi->customer; // value 'cus_....'. WARNING: This property may be empty if first payment was recorded before the stripe customer was created.
673 
674  if (empty($stripecu)) {
675  // This include the INSERT
676  $customer = $stripe->customerStripe($thirdparty, $stripeacc, $servicestatus, 1);
677 
678  // Link this customer to the payment intent
679  if (preg_match('/^pi_/', $TRANSACTIONID) && $customer) {
680  \Stripe\PaymentIntent::update($chpi->id, array('customer' => $customer->id));
681  }
682  } else {
683  $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, site_account, status, entity, date_creation, fk_user_creat)";
684  $sql .= " VALUES (".((int) $object->fk_soc).", '', '".$db->escape($stripecu)."', 'stripe', '".$db->escape($stripearrayofkeysbyenv[$servicestatus]['publishable_key'])."', ".((int) $servicestatus).", ".((int) $conf->entity).", '".$db->idate(dol_now())."', 0)";
685  $resql = $db->query($sql);
686  if (!$resql) { // should not happen
687  $error++;
688  $errmsg = 'Failed to insert customer stripe id in database : '.$db->lasterror();
689  dol_syslog($errmsg, LOG_ERR, 0, '_payment');
690  $postactionmessages[] = $errmsg;
691  $ispostactionok = -1;
692  }
693  }
694  } else { // should not happen
695  $error++;
696  $errmsg = 'Failed to retreive paymentintent or charge from id';
697  dol_syslog($errmsg, LOG_ERR, 0, '_payment');
698  $postactionmessages[] = $errmsg;
699  $ispostactionok = -1;
700  }
701  } catch (Exception $e) { // should not happen
702  $error++;
703  $errmsg = 'Failed to get or save customer stripe id in database : '.$e->getMessage();
704  dol_syslog($errmsg, LOG_ERR, 0, '_payment');
705  $postactionmessages[] = $errmsg;
706  $ispostactionok = -1;
707  }
708  }
709  }
710  }
711 
712  if (!$error) {
713  $db->commit();
714  } else {
715  $db->rollback();
716  }
717 
718  // Send email to member
719  if (!$error) {
720  dol_syslog("Send email to customer to ".$object->email." if we have to (sendalsoemail = ".$sendalsoemail.")", LOG_DEBUG, 0, '_payment');
721 
722  // Send confirmation Email
723  if ($object->email && $sendalsoemail) {
724  $subject = '';
725  $msg = '';
726 
727  // Send subscription email
728  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
729  $formmail = new FormMail($db);
730  // Load traductions files required by page
731  $outputlangs->loadLangs(array("main", "members"));
732  // Get email content from template
733  $arraydefaultmessage = null;
734  $labeltouse = $conf->global->ADHERENT_EMAIL_TEMPLATE_SUBSCRIPTION;
735 
736  if (!empty($labeltouse)) {
737  $arraydefaultmessage = $formmail->getEMailTemplate($db, 'member', $user, $outputlangs, 0, 1, $labeltouse);
738  }
739 
740  if (!empty($labeltouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
741  $subject = $arraydefaultmessage->topic;
742  $msg = $arraydefaultmessage->content;
743  }
744 
745  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
746 
747  // Create external user
748  if (!empty($conf->global->ADHERENT_CREATE_EXTERNAL_USER_LOGIN)) {
749  $infouserlogin = '';
750  $nuser = new User($db);
751  $tmpuser = dol_clone($object);
752 
753  $result = $nuser->create_from_member($tmpuser, $object->login);
754  $newpassword = $nuser->setPassword($user, '');
755 
756  if ($result < 0) {
757  $outputlangs->load("errors");
758  $postactionmessages[] = 'Error in create external user : '.$nuser->error;
759  } else {
760  $infouserlogin = $outputlangs->trans("Login").': '.$nuser->login.' '."\n".$outputlangs->trans("Password").': '.$newpassword;
761  $postactionmessages[] = $langs->trans("NewUserCreated", $nuser->login);
762  }
763  $substitutionarray['__MEMBER_USER_LOGIN_INFORMATION__'] = $infouserlogin;
764  }
765 
766  complete_substitutions_array($substitutionarray, $outputlangs, $object);
767  $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
768  $texttosend = make_substitutions(dol_concatdesc($msg, $adht->getMailOnSubscription()), $substitutionarray, $outputlangs);
769 
770  // Attach a file ?
771  $file = '';
772  $listofpaths = array();
773  $listofnames = array();
774  $listofmimes = array();
775  if (is_object($object->invoice)) {
776  $invoicediroutput = $conf->facture->dir_output;
777  $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->invoice->ref, preg_quote($object->invoice->ref, '/').'[^\-]+');
778  $file = $fileparams['fullname'];
779 
780  $listofpaths = array($file);
781  $listofnames = array(basename($file));
782  $listofmimes = array(dol_mimetype($file));
783  }
784 
785  $moreinheader = 'X-Dolibarr-Info: send_an_email by public/payment/paymentok.php'."\r\n";
786 
787  $result = $object->sendEmail($texttosend, $subjecttosend, $listofpaths, $listofmimes, $listofnames, "", "", 0, -1, "", $moreinheader);
788 
789  if ($result < 0) {
790  $errmsg = $object->error;
791  $postactionmessages[] = $errmsg;
792  $ispostactionok = -1;
793  } else {
794  if ($file) {
795  $postactionmessages[] = 'Email sent to member (with invoice document attached)';
796  } else {
797  $postactionmessages[] = 'Email sent to member (without any attached document)';
798  }
799 
800  // TODO Add actioncomm event
801  }
802  }
803  }
804  } else {
805  $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.';
806  $ispostactionok = -1;
807  }
808  } else {
809  $postactionmessages[] = 'Member '.$tmptag['MEM'].' for subscription paid was not found';
810  $ispostactionok = -1;
811  }
812  } elseif (array_key_exists('INV', $tmptag) && $tmptag['INV'] > 0) {
813  // Record payment
814  include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
815  $object = new Facture($db);
816  $result = $object->fetch((int) $tmptag['INV']);
817  if ($result) {
818  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
819 
820  $paymentTypeId = 0;
821  if ($paymentmethod === 'paybox') {
822  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
823  }
824  if ($paymentmethod === 'paypal') {
825  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
826  }
827  if ($paymentmethod === 'stripe') {
828  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
829  }
830  if (empty($paymentTypeId)) {
831  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
832 
833  if (empty($paymentType)) {
834  $paymentType = 'CB';
835  }
836  // May return nothing when paymentType means nothing
837  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
838  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
839 
840  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
841  if (empty($paymentTypeId) || $paymentTypeId < 0) {
842  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
843  }
844  }
845 
846  dol_syslog("FinalPaymentAmt = ".$FinalPaymentAmt." paymentTypeId = ".$paymentTypeId, LOG_DEBUG, 0, '_payment');
847 
848  // 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)
849  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
850  $db->begin();
851 
852  // Creation of payment line
853  include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
854  $paiement = new Paiement($db);
855  $paiement->datepaye = $now;
856  if ($currencyCodeType == $conf->currency) {
857  $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
858  } else {
859  $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
860 
861  $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
862  $ispostactionok = -1;
863  $error++; // Not yet supported
864  }
865  $paiement->paiementid = $paymentTypeId;
866  $paiement->num_payment = '';
867  $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
868  $paiement->ext_payment_id = $TRANSACTIONID; // TODO LDR May be we should store py_... instead of pi_... but we started with pi_... so we continue.
869  //$paiement->ext_payment_id = $TRANSACTIONID.':'.$customer->id.'@'.$stripearrayofkeysbyenv[$servicestatus]['publishable_key']; // TODO LDR It would be better if we could store this. Do we have customer->id and publishable_key ?
870  $paiement->ext_payment_site = $service;
871 
872  if (!$error) {
873  $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
874  if ($paiement_id < 0) {
875  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
876  $ispostactionok = -1;
877  $error++;
878  } else {
879  $postactionmessages[] = 'Payment created';
880  $ispostactionok = 1;
881  }
882  }
883 
884  if (!$error && isModEnabled("banque")) {
885  $bankaccountid = 0;
886  if ($paymentmethod == 'paybox') {
887  $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
888  } elseif ($paymentmethod == 'paypal') {
889  $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
890  } elseif ($paymentmethod == 'stripe') {
891  $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
892  }
893 
894  if ($bankaccountid > 0) {
895  $label = '(CustomerInvoicePayment)';
896  if ($object->type == Facture::TYPE_CREDIT_NOTE) {
897  $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
898  }
899  $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
900  if ($result < 0) {
901  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
902  $ispostactionok = -1;
903  $error++;
904  } else {
905  $postactionmessages[] = 'Bank transaction of payment created';
906  $ispostactionok = 1;
907  }
908  } else {
909  $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.';
910  $ispostactionok = -1;
911  $error++;
912  }
913  }
914 
915  if (!$error) {
916  $db->commit();
917  } else {
918  $db->rollback();
919  }
920  } else {
921  $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.';
922  $ispostactionok = -1;
923  }
924  } else {
925  $postactionmessages[] = 'Invoice paid '.$tmptag['INV'].' was not found';
926  $ispostactionok = -1;
927  }
928  } elseif (array_key_exists('ORD', $tmptag) && $tmptag['ORD'] > 0) {
929  include_once DOL_DOCUMENT_ROOT . '/commande/class/commande.class.php';
930  $object = new Commande($db);
931  $result = $object->fetch((int) $tmptag['ORD']);
932  if ($result) {
933  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
934 
935  $paymentTypeId = 0;
936  if ($paymentmethod == 'paybox') {
937  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
938  }
939  if ($paymentmethod == 'paypal') {
940  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
941  }
942  if ($paymentmethod == 'stripe') {
943  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
944  }
945  if (empty($paymentTypeId)) {
946  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
947 
948  if (empty($paymentType)) {
949  $paymentType = 'CB';
950  }
951  // May return nothing when paymentType means nothing
952  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
953  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
954 
955  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
956  if (empty($paymentTypeId) || $paymentTypeId < 0) {
957  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
958  }
959  }
960 
961  // 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)
962  if (isModEnabled('facture')) {
963  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0 ) {
964  include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
965  $invoice = new Facture($db);
966  $result = $invoice->createFromOrder($object, $user);
967  if ($result > 0) {
968  $object->classifyBilled($user);
969  $invoice->validate($user);
970  // Creation of payment line
971  include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
972  $paiement = new Paiement($db);
973  $paiement->datepaye = $now;
974  if ($currencyCodeType == $conf->currency) {
975  $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
976  } else {
977  $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
978 
979  $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
980  $ispostactionok = -1;
981  $error++;
982  }
983  $paiement->paiementid = $paymentTypeId;
984  $paiement->num_payment = '';
985  $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
986  $paiement->ext_payment_id = $TRANSACTIONID; // pi_... for Stripe, ...
987  $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
988 
989  if (!$error) {
990  $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
991  if ($paiement_id < 0) {
992  $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
993  $ispostactionok = -1;
994  $error++;
995  } else {
996  $postactionmessages[] = 'Payment created';
997  $ispostactionok = 1;
998  }
999  }
1000 
1001  if (!$error && isModEnabled("banque")) {
1002  $bankaccountid = 0;
1003  if ($paymentmethod == 'paybox') $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
1004  elseif ($paymentmethod == 'paypal') $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
1005  elseif ($paymentmethod == 'stripe') $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
1006 
1007  if ($bankaccountid > 0) {
1008  $label = '(CustomerInvoicePayment)';
1009  if ($object->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1010  $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1011  if ($result < 0) {
1012  $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
1013  $ispostactionok = -1;
1014  $error++;
1015  } else {
1016  $postactionmessages[] = 'Bank transaction of payment created';
1017  $ispostactionok = 1;
1018  }
1019  } else {
1020  $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
1021  $ispostactionok = -1;
1022  $error++;
1023  }
1024  }
1025 
1026  if (!$error) {
1027  $db->commit();
1028  } else {
1029  $db->rollback();
1030  }
1031  } else {
1032  $postactionmessages[] = 'Failed to create invoice form order ' . $tmptag['ORD'] . '.';
1033  $ispostactionok = -1;
1034  }
1035  } else {
1036  $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.';
1037  $ispostactionok = -1;
1038  }
1039  } else {
1040  $postactionmessages[] = 'Invoice module is not enable';
1041  $ispostactionok = -1;
1042  }
1043  } else {
1044  $postactionmessages[] = 'Order paid ' . $tmptag['ORD'] . ' was not found';
1045  $ispostactionok = -1;
1046  }
1047  } elseif (array_key_exists('DON', $tmptag) && $tmptag['DON'] > 0) {
1048  include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php';
1049  $don = new Don($db);
1050  $result = $don->fetch((int) $tmptag['DON']);
1051  if ($result) {
1052  $paymentTypeId = 0;
1053  if ($paymentmethod == 'paybox') {
1054  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
1055  }
1056  if ($paymentmethod == 'paypal') {
1057  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
1058  }
1059  if ($paymentmethod == 'stripe') {
1060  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
1061  }
1062  if (empty($paymentTypeId)) {
1063  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1064 
1065  if (empty($paymentType)) {
1066  $paymentType = 'CB';
1067  }
1068  // May return nothing when paymentType means nothing
1069  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1070  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1071 
1072  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1073  if (empty($paymentTypeId) || $paymentTypeId < 0) {
1074  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1075  }
1076  }
1077 
1078  // 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)
1079  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1080  $db->begin();
1081 
1082  // Creation of paiement line for donation
1083  include_once DOL_DOCUMENT_ROOT.'/don/class/paymentdonation.class.php';
1084  $paiement = new PaymentDonation($db);
1085 
1086  $totalpaid = $FinalPaymentAmt;
1087 
1088  if ($currencyCodeType == $conf->currency) {
1089  $paiement->amounts = array($object->id => $totalpaid); // Array with all payments dispatching with donation
1090  } else {
1091  // PaymentDonation does not support multi currency
1092  $postactionmessages[] = 'Payment donation can\'t be payed with diffent currency than '.$conf->currency;
1093  $ispostactionok = -1;
1094  $error++; // Not yet supported
1095  }
1096 
1097  $paiement->fk_donation = $don->id;
1098  $paiement->datep = $now;
1099  $paiement->paymenttype = $paymentTypeId;
1100  $paiement->num_payment = '';
1101  $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1102  $paiement->ext_payment_id = $TRANSACTIONID;
1103  $paiement->ext_payment_site = $service;
1104 
1105  if (!$error) {
1106  $paiement_id = $paiement->create($user, 1);
1107  if ($paiement_id < 0) {
1108  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1109  $ispostactionok = -1;
1110  $error++;
1111  } else {
1112  $postactionmessages[] = 'Payment created';
1113  $ispostactionok = 1;
1114 
1115  if ($totalpaid >= $don->getRemainToPay()) {
1116  $don->setPaid($don->id);
1117  }
1118  }
1119  }
1120 
1121  if (!$error && isModEnabled("banque")) {
1122  $bankaccountid = 0;
1123  if ($paymentmethod == 'paybox') {
1124  $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
1125  } elseif ($paymentmethod == 'paypal') {
1126  $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
1127  } elseif ($paymentmethod == 'stripe') {
1128  $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
1129  }
1130 
1131  if ($bankaccountid > 0) {
1132  $result = $paiement->addPaymentToBank($user, 'payment_donation', '(DonationPayment)', $bankaccountid, '', '');
1133  if ($result < 0) {
1134  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1135  $ispostactionok = -1;
1136  $error++;
1137  } else {
1138  $postactionmessages[] = 'Bank transaction of payment created';
1139  $ispostactionok = 1;
1140  }
1141  } else {
1142  $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.';
1143  $ispostactionok = -1;
1144  $error++;
1145  }
1146  }
1147 
1148  if (!$error) {
1149  $db->commit();
1150  } else {
1151  $db->rollback();
1152  }
1153  } else {
1154  $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.';
1155  $ispostactionok = -1;
1156  }
1157  } else {
1158  $postactionmessages[] = 'Donation paid '.$tmptag['DON'].' was not found';
1159  $ispostactionok = -1;
1160  }
1161 
1162  // TODO send email with acknowledgment for the donation
1163  // (we need first that the donation module is able to generate a pdf document for the cerfa with pre filled content)
1164  } elseif (array_key_exists('ATT', $tmptag) && $tmptag['ATT'] > 0) {
1165  // Record payment for registration to an event for an attendee
1166  require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1167  require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1168  include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1169  $object = new Facture($db);
1170  $result = $object->fetch($ref);
1171  if ($result) {
1172  $paymentTypeId = 0;
1173  if ($paymentmethod == 'paybox') {
1174  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
1175  }
1176  if ($paymentmethod == 'paypal') {
1177  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
1178  }
1179  if ($paymentmethod == 'stripe') {
1180  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
1181  }
1182  if (empty($paymentTypeId)) {
1183  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1184 
1185  if (empty($paymentType)) {
1186  $paymentType = 'CB';
1187  }
1188  // May return nothing when paymentType means nothing
1189  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1190  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1191 
1192  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1193  if (empty($paymentTypeId) || $paymentTypeId < 0) {
1194  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1195  }
1196  }
1197 
1198  // 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)
1199  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1200  $resultvalidate = $object->validate($user);
1201  if ($resultvalidate < 0) {
1202  $postactionmessages[] = 'Cannot validate invoice';
1203  $ispostactionok = -1;
1204  $error++; // Not yet supported
1205  } else {
1206  $db->begin();
1207 
1208  // Creation of payment line
1209  include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1210  $paiement = new Paiement($db);
1211  $paiement->datepaye = $now;
1212  if ($currencyCodeType == $conf->currency) {
1213  $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1214  } else {
1215  $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1216 
1217  $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
1218  $ispostactionok = -1;
1219  $error++; // Not yet supported
1220  }
1221  $paiement->paiementid = $paymentTypeId;
1222  $paiement->num_payment = '';
1223  $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress.' for event registration';
1224  $paiement->ext_payment_id = $TRANSACTIONID;
1225  $paiement->ext_payment_site = $service;
1226 
1227  if (!$error) {
1228  $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1229  if ($paiement_id < 0) {
1230  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1231  $ispostactionok = -1;
1232  $error++;
1233  } else {
1234  $postactionmessages[] = 'Payment created';
1235  $ispostactionok = 1;
1236  }
1237  }
1238 
1239  if (!$error && isModEnabled("banque")) {
1240  $bankaccountid = 0;
1241  if ($paymentmethod == 'paybox') {
1242  $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
1243  } elseif ($paymentmethod == 'paypal') {
1244  $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
1245  } elseif ($paymentmethod == 'stripe') {
1246  $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
1247  }
1248 
1249  if ($bankaccountid > 0) {
1250  $label = '(CustomerInvoicePayment)';
1251  if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1252  $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1253  }
1254  $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1255  if ($result < 0) {
1256  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1257  $ispostactionok = -1;
1258  $error++;
1259  } else {
1260  $postactionmessages[] = 'Bank transaction of payment created';
1261  $ispostactionok = 1;
1262  }
1263  } else {
1264  $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.';
1265  $ispostactionok = -1;
1266  $error++;
1267  }
1268  }
1269 
1270  if (!$error) {
1271  // Validating the attendee
1272  $attendeetovalidate = new ConferenceOrBoothAttendee($db);
1273  $resultattendee = $attendeetovalidate->fetch((int) $tmptag['ATT']);
1274  if ($resultattendee < 0) {
1275  $error++;
1276  setEventMessages(null, $attendeetovalidate->errors, "errors");
1277  } else {
1278  $attendeetovalidate->validate($user);
1279 
1280  $attendeetovalidate->amount = $FinalPaymentAmt;
1281  $attendeetovalidate->date_subscription = dol_now();
1282  $attendeetovalidate->update($user);
1283  }
1284  }
1285 
1286  if (!$error) {
1287  $db->commit();
1288  } else {
1289  setEventMessages(null, $postactionmessages, 'warnings');
1290 
1291  $db->rollback();
1292  }
1293 
1294  if (! $error) {
1295  // Sending mail
1296  $thirdparty = new Societe($db);
1297  $resultthirdparty = $thirdparty->fetch($attendeetovalidate->fk_soc);
1298  if ($resultthirdparty < 0) {
1299  setEventMessages($resultthirdparty->error, $resultthirdparty->errors, "errors");
1300  } else {
1301  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1302  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1303  $formmail = new FormMail($db);
1304  // Set output language
1305  $outputlangs = new Translate('', $conf);
1306  $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
1307  // Load traductions files required by page
1308  $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1309  // Get email content from template
1310  $arraydefaultmessage = null;
1311 
1312  $idoftemplatetouse = $conf->global->EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_EVENT; // Email to send for Event organization registration
1313 
1314  if (!empty($idoftemplatetouse)) {
1315  $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1316  }
1317 
1318  if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1319  $subject = $arraydefaultmessage->topic;
1320  $msg = $arraydefaultmessage->content;
1321  } else {
1322  $subject = '['.$appli.'] '.$object->ref.' - '.$outputlangs->trans("NewRegistration").']';
1323  $msg = $outputlangs->trans("OrganizationEventPaymentOfRegistrationWasReceived");
1324  }
1325 
1326  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1327  complete_substitutions_array($substitutionarray, $outputlangs, $object);
1328 
1329  $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1330  $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1331 
1332  $sendto = $attendeetovalidate->email;
1333  $cc = '';
1334  if ($thirdparty->email) {
1335  $cc = $thirdparty->email;
1336  }
1337  if ($attendeetovalidate->email_company && $attendeetovalidate->email_company != $thirdparty->email) {
1338  $cc = ($cc ? ', ' : '').$attendeetovalidate->email_company;
1339  }
1340 
1341  $from = !empty($conf->global->MAILING_EMAIL_FROM) ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
1342 
1343  $urlback = $_SERVER["REQUEST_URI"];
1344 
1345  $ishtml = dol_textishtml($texttosend); // May contain urls
1346 
1347  // Attach a file ?
1348  $file = '';
1349  $listofpaths = array();
1350  $listofnames = array();
1351  $listofmimes = array();
1352  if (is_object($object)) {
1353  $invoicediroutput = $conf->facture->dir_output;
1354  $fileparams = dol_most_recent_file($invoicediroutput.'/'.$object->ref, preg_quote($object->ref, '/').'[^\-]+');
1355  $file = $fileparams['fullname'];
1356 
1357  $listofpaths = array($file);
1358  $listofnames = array(basename($file));
1359  $listofmimes = array(dol_mimetype($file));
1360  }
1361 
1362  $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, $listofpaths, $listofmimes, $listofnames, $cc, '', 0, $ishtml);
1363 
1364  $result = $mailfile->sendfile();
1365  if ($result) {
1366  dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1367  } else {
1368  dol_syslog("Failed to send EMail to ".$sendto.' - '.$mailfile->error, LOG_ERR, 0, '_payment');
1369  }
1370  }
1371  }
1372  }
1373  } else {
1374  $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.';
1375  $ispostactionok = -1;
1376  }
1377  } else {
1378  $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1379  $ispostactionok = -1;
1380  }
1381  } elseif (array_key_exists('BOO', $tmptag) && $tmptag['BOO'] > 0) {
1382  // Record payment for booth or conference
1383  require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1384  require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1385  include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1386  $object = new Facture($db);
1387  $result = $object->fetch($ref);
1388  if ($result) {
1389  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1390 
1391  $paymentTypeId = 0;
1392  if ($paymentmethod == 'paybox') {
1393  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
1394  }
1395  if ($paymentmethod == 'paypal') {
1396  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
1397  }
1398  if ($paymentmethod == 'stripe') {
1399  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
1400  }
1401  if (empty($paymentTypeId)) {
1402  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1403 
1404  if (empty($paymentType)) {
1405  $paymentType = 'CB';
1406  }
1407  // May return nothing when paymentType means nothing
1408  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1409  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1410 
1411  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1412  if (empty($paymentTypeId) || $paymentTypeId < 0) {
1413  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1414  }
1415  }
1416 
1417  // 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)
1418  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0) {
1419  $resultvalidate = $object->validate($user);
1420  if ($resultvalidate < 0) {
1421  $postactionmessages[] = 'Cannot validate invoice';
1422  $ispostactionok = -1;
1423  $error++; // Not yet supported
1424  } else {
1425  $db->begin();
1426 
1427  // Creation of payment line
1428  include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1429  $paiement = new Paiement($db);
1430  $paiement->datepaye = $now;
1431  if ($currencyCodeType == $conf->currency) {
1432  $paiement->amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1433  } else {
1434  $paiement->multicurrency_amounts = array($object->id => $FinalPaymentAmt); // Array with all payments dispatching
1435 
1436  $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
1437  $ispostactionok = -1;
1438  $error++; // Not yet supported
1439  }
1440  $paiement->paiementid = $paymentTypeId;
1441  $paiement->num_payment = '';
1442  $paiement->note_public = 'Online payment '.dol_print_date($now, 'standard').' from '.$ipaddress;
1443  $paiement->ext_payment_id = $TRANSACTIONID;
1444  $paiement->ext_payment_site = $service;
1445 
1446  if (!$error) {
1447  $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1448  if ($paiement_id < 0) {
1449  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1450  $ispostactionok = -1;
1451  $error++;
1452  } else {
1453  $postactionmessages[] = 'Payment created';
1454  $ispostactionok = 1;
1455  }
1456  }
1457 
1458  if (!$error && isModEnabled("banque")) {
1459  $bankaccountid = 0;
1460  if ($paymentmethod == 'paybox') {
1461  $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
1462  } elseif ($paymentmethod == 'paypal') {
1463  $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
1464  } elseif ($paymentmethod == 'stripe') {
1465  $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
1466  }
1467 
1468  if ($bankaccountid > 0) {
1469  $label = '(CustomerInvoicePayment)';
1470  if ($object->type == Facture::TYPE_CREDIT_NOTE) {
1471  $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1472  }
1473  $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1474  if ($result < 0) {
1475  $postactionmessages[] = $paiement->error.' '.join("<br>\n", $paiement->errors);
1476  $ispostactionok = -1;
1477  $error++;
1478  } else {
1479  $postactionmessages[] = 'Bank transaction of payment created';
1480  $ispostactionok = 1;
1481  }
1482  } else {
1483  $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.';
1484  $ispostactionok = -1;
1485  $error++;
1486  }
1487  }
1488 
1489  if (!$error) {
1490  // Putting the booth to "suggested" state
1491  require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorboothattendee.class.php';
1492  require_once DOL_DOCUMENT_ROOT.'/eventorganization/class/conferenceorbooth.class.php';
1493  $booth = new ConferenceOrBooth($db);
1494  $resultbooth = $booth->fetch((int) $tmptag['BOO']);
1495  if ($resultbooth < 0) {
1496  $error++;
1497  setEventMessages(null, $booth->errors, "errors");
1498  } else {
1499  $booth->status = ConferenceOrBooth::STATUS_SUGGESTED;
1500  $resultboothupdate = $booth->update($user);
1501  if ($resultboothupdate<0) {
1502  // Finding the thirdparty by getting the invoice
1503  $invoice = new Facture($db);
1504  $resultinvoice = $invoice->fetch($ref);
1505  if ($resultinvoice<0) {
1506  $postactionmessages[] = 'Could not find the associated invoice.';
1507  $ispostactionok = -1;
1508  $error++;
1509  } else {
1510  $thirdparty = new Societe($db);
1511  $resultthirdparty = $thirdparty->fetch($invoice->socid);
1512  if ($resultthirdparty<0) {
1513  $error++;
1514  setEventMessages(null, $thirdparty->errors, "errors");
1515  } else {
1516  // Sending mail
1517  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1518  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1519  $formmail = new FormMail($db);
1520  // Set output language
1521  $outputlangs = new Translate('', $conf);
1522  $outputlangs->setDefaultLang(empty($thirdparty->default_lang) ? $mysoc->default_lang : $thirdparty->default_lang);
1523  // Load traductions files required by page
1524  $outputlangs->loadLangs(array("main", "members", "eventorganization"));
1525  // Get email content from template
1526  $arraydefaultmessage = null;
1527 
1528  $idoftemplatetouse = $conf->global->EVENTORGANIZATION_TEMPLATE_EMAIL_AFT_SUBS_BOOTH; // Email sent after registration for a Booth
1529 
1530  if (!empty($idoftemplatetouse)) {
1531  $arraydefaultmessage = $formmail->getEMailTemplate($db, 'conferenceorbooth', $user, $outputlangs, $idoftemplatetouse, 1, '');
1532  }
1533 
1534  if (!empty($idoftemplatetouse) && is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
1535  $subject = $arraydefaultmessage->topic;
1536  $msg = $arraydefaultmessage->content;
1537  } else {
1538  $subject = '['.$appli.'] '.$booth->ref.' - '.$outputlangs->trans("NewRegistration").']';
1539  $msg = $outputlangs->trans("OrganizationEventPaymentOfBoothWasReceived");
1540  }
1541 
1542  $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $thirdparty);
1543  complete_substitutions_array($substitutionarray, $outputlangs, $object);
1544 
1545  $subjecttosend = make_substitutions($subject, $substitutionarray, $outputlangs);
1546  $texttosend = make_substitutions($msg, $substitutionarray, $outputlangs);
1547 
1548  $sendto = $thirdparty->email;
1549  $from = $conf->global->MAILING_EMAIL_FROM;
1550  $urlback = $_SERVER["REQUEST_URI"];
1551 
1552  $ishtml = dol_textishtml($texttosend); // May contain urls
1553 
1554  $mailfile = new CMailFile($subjecttosend, $sendto, $from, $texttosend, array(), array(), array(), '', '', 0, $ishtml);
1555 
1556  $result = $mailfile->sendfile();
1557  if ($result) {
1558  dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1559  } else {
1560  dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
1561  }
1562  }
1563  }
1564  }
1565  }
1566  }
1567 
1568  if (!$error) {
1569  $db->commit();
1570  } else {
1571  $db->rollback();
1572  }
1573  }
1574  } else {
1575  $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.';
1576  $ispostactionok = -1;
1577  }
1578  } else {
1579  $postactionmessages[] = 'Invoice paid '.$tmptag['ATT'].' was not found';
1580  $ispostactionok = -1;
1581  }
1582  } elseif (array_key_exists('CON', $tmptag) && $tmptag['CON'] > 0) {
1583  include_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php';
1584  $object = new Contrat($db);
1585  $result = $object->fetch((int) $tmptag['CON']);
1586  if ($result) {
1587  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1588 
1589  $paymentTypeId = 0;
1590  if ($paymentmethod == 'paybox') {
1591  $paymentTypeId = $conf->global->PAYBOX_PAYMENT_MODE_FOR_PAYMENTS;
1592  }
1593  if ($paymentmethod == 'paypal') {
1594  $paymentTypeId = $conf->global->PAYPAL_PAYMENT_MODE_FOR_PAYMENTS;
1595  }
1596  if ($paymentmethod == 'stripe') {
1597  $paymentTypeId = $conf->global->STRIPE_PAYMENT_MODE_FOR_PAYMENTS;
1598  }
1599  if (empty($paymentTypeId)) {
1600  dol_syslog("paymentType = ".$paymentType, LOG_DEBUG, 0, '_payment');
1601 
1602  if (empty($paymentType)) {
1603  $paymentType = 'CB';
1604  }
1605  // May return nothing when paymentType means nothing
1606  // (for example when paymentType is 'Mark', 'Sole', 'Sale', for paypal)
1607  $paymentTypeId = dol_getIdFromCode($db, $paymentType, 'c_paiement', 'code', 'id', 1);
1608 
1609  // If previous line has returned nothing, we force to get the ID of payment of Credit Card (hard coded code 'CB').
1610  if (empty($paymentTypeId) || $paymentTypeId < 0) {
1611  $paymentTypeId = dol_getIdFromCode($db, 'CB', 'c_paiement', 'code', 'id', 1);
1612  }
1613  }
1614 
1615  $currencyCodeType = $_SESSION['currencyCodeType'];
1616  $contract_lines = (array_key_exists('COL', $tmptag) && $tmptag['COL'] > 0) ? $tmptag['COL'] : null;
1617 
1618  // 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)
1619  if (isModEnabled('facture')) {
1620  if (!empty($FinalPaymentAmt) && $paymentTypeId > 0 ) {
1621  include_once DOL_DOCUMENT_ROOT . '/compta/facture/class/facture.class.php';
1622  $invoice = new Facture($db);
1623  $result = $invoice->createFromContract($object, $user, array((int) $contract_lines));
1624  if ($result > 0) {
1625  // $object->classifyBilled($user);
1626  $invoice->validate($user);
1627  // Creation of payment line
1628  include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
1629  $paiement = new Paiement($db);
1630  $paiement->datepaye = $now;
1631  if ($currencyCodeType == $conf->currency) {
1632  $paiement->amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching with invoice id
1633  } else {
1634  $paiement->multicurrency_amounts = array($invoice->id => $FinalPaymentAmt); // Array with all payments dispatching
1635 
1636  $postactionmessages[] = 'Payment was done in a different currency that currency expected of company';
1637  $ispostactionok = -1;
1638  $error++;
1639  }
1640  $paiement->paiementid = $paymentTypeId;
1641  $paiement->num_payment = '';
1642  $paiement->note_public = 'Online payment ' . dol_print_date($now, 'standard') . ' from ' . $ipaddress;
1643  $paiement->ext_payment_id = $TRANSACTIONID; // pi_... for Stripe, ...
1644  $paiement->ext_payment_site = $service; // 'StripeLive' or 'Stripe', or ...
1645 
1646  if (!$error) {
1647  $paiement_id = $paiement->create($user, 1); // This include closing invoices and regenerating documents
1648  if ($paiement_id < 0) {
1649  $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
1650  $ispostactionok = -1;
1651  $error++;
1652  } else {
1653  $postactionmessages[] = 'Payment created';
1654  $ispostactionok = 1;
1655  }
1656  }
1657 
1658  if (!$error && isModEnabled("banque")) {
1659  $bankaccountid = 0;
1660  if ($paymentmethod == 'paybox') $bankaccountid = $conf->global->PAYBOX_BANK_ACCOUNT_FOR_PAYMENTS;
1661  elseif ($paymentmethod == 'paypal') $bankaccountid = $conf->global->PAYPAL_BANK_ACCOUNT_FOR_PAYMENTS;
1662  elseif ($paymentmethod == 'stripe') $bankaccountid = $conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS;
1663 
1664  if ($bankaccountid > 0) {
1665  $label = '(CustomerInvoicePayment)';
1666  if ($object->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note
1667  $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, '', '');
1668  if ($result < 0) {
1669  $postactionmessages[] = $paiement->error . ' ' . join("<br>\n", $paiement->errors);
1670  $ispostactionok = -1;
1671  $error++;
1672  } else {
1673  $postactionmessages[] = 'Bank transaction of payment created';
1674  $ispostactionok = 1;
1675  }
1676  } else {
1677  $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
1678  $ispostactionok = -1;
1679  $error++;
1680  }
1681  }
1682 
1683  if (!$error) {
1684  $db->commit();
1685  } else {
1686  $db->rollback();
1687  }
1688  } else {
1689  $msg = 'Failed to create invoice form contract ' . $tmptag['CON'];
1690  if (!empty($cols)) $msg .= ' and col '. $cols .'.';
1691  $postactionmessages[] = $msg;
1692  $ispostactionok = -1;
1693  }
1694  } else {
1695  $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.';
1696  $ispostactionok = -1;
1697  }
1698  } else {
1699  $postactionmessages[] = 'Invoice module is not enable';
1700  $ispostactionok = -1;
1701  }
1702  } else {
1703  $msg = 'Contract paid ' . $tmptag['CON'] . ' was not found';
1704  if (!empty($cols)) $msg .= ' for col '.$tmptag['COL'] .'.';
1705  $postactionmessages[] = $msg;
1706  $ispostactionok = -1;
1707  }
1708  } else {
1709  // Nothing done
1710  }
1711 }
1712 
1713 
1714 // Set $appli for emails title
1715 $appli = $mysoc->name;
1716 
1717 
1718 if ($ispaymentok) {
1719  // Get on url call
1720  $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
1721  $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
1722  // Set by newpayment.php
1723  $currencyCodeType = $_SESSION['currencyCodeType'];
1724  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1725  $paymentType = $_SESSION['PaymentType']; // Seems used by paypal only
1726 
1727  if (is_object($object) && method_exists($object, 'call_trigger')) {
1728  // Call trigger
1729  $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
1730  if ($result < 0) {
1731  $error++;
1732  }
1733  // End call triggers
1734  } elseif (get_class($object) == 'stdClass') {
1735  //In some case $object is not instanciate (for paiement on custom object) We need to deal with payment
1736  include_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
1737  $paiement = new Paiement($db);
1738  $result = $paiement->call_trigger('PAYMENTONLINE_PAYMENT_OK', $user);
1739  if ($result < 0) $error++;
1740  }
1741 
1742  print $langs->trans("YourPaymentHasBeenRecorded")."<br>\n";
1743  if ($TRANSACTIONID) {
1744  print $langs->trans("ThisIsTransactionId", $TRANSACTIONID)."<br><br>\n";
1745  }
1746 
1747  $key = 'ONLINE_PAYMENT_MESSAGE_OK';
1748  if (!empty($conf->global->$key)) {
1749  print '<br>';
1750  print $conf->global->$key;
1751  }
1752 
1753  $sendemail = '';
1754  if (!empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) {
1755  $sendemail = $conf->global->ONLINE_PAYMENT_SENDEMAIL;
1756  }
1757 
1758  $tmptag = dolExplodeIntoArray($fulltag, '.', '=');
1759 
1760  dol_syslog("Send email to admins if we have to (sendemail = ".$sendemail.")", LOG_DEBUG, 0, '_payment');
1761 
1762  // Send an email to admins
1763  if ($sendemail) {
1764  $companylangs = new Translate('', $conf);
1765  $companylangs->setDefaultLang($mysoc->default_lang);
1766  $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox'));
1767 
1768  $sendto = $sendemail;
1769  $from = !empty($conf->global->MAILING_EMAIL_FROM) ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
1770  // Define $urlwithroot
1771  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1772  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1773  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1774 
1775  // Define link to login card
1776 
1777  $urlback = $_SERVER["REQUEST_URI"];
1778  $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived");
1779  $content = "";
1780  if (array_key_exists('MEM', $tmptag)) {
1781  $url = $urlwithroot."/adherents/subscription.php?rowid=".((int) $tmptag['MEM']);
1782  $content .= '<strong>'.$companylangs->trans("PaymentSubscription")."</strong><br><br>\n";
1783  $content .= $companylangs->trans("MemberId").': <strong>'.$tmptag['MEM']."</strong><br>\n";
1784  $content .= $companylangs->trans("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
1785  } elseif (array_key_exists('INV', $tmptag)) {
1786  $url = $urlwithroot."/compta/facture/card.php?id=".((int) $tmptag['INV']);
1787  $content .= '<strong>'.$companylangs->trans("Payment")."</strong><br><br>\n";
1788  $content .= $companylangs->trans("InvoiceId").': <strong>'.$tmptag['INV']."</strong><br>\n";
1789  //$content.=$companylangs->trans("ThirdPartyId").': '.$tmptag['CUS']."<br>\n";
1790  $content .= $companylangs->trans("Link").': <a href="'.$url.'">'.$url.'</a>'."<br>\n";
1791  } else {
1792  $content .= $companylangs->transnoentitiesnoconv("NewOnlinePaymentReceived")."<br>\n";
1793  }
1794  $content .= $companylangs->transnoentities("PostActionAfterPayment").' : ';
1795  if ($ispostactionok > 0) {
1796  //$topic.=' ('.$companylangs->transnoentitiesnoconv("Status").' '.$companylangs->transnoentitiesnoconv("OK").')';
1797  $content .= '<span style="color: green">'.$companylangs->transnoentitiesnoconv("OK").'</span>';
1798  } elseif ($ispostactionok == 0) {
1799  $content .= $companylangs->transnoentitiesnoconv("None");
1800  } else {
1801  $topic .= ($ispostactionok ? '' : ' ('.$companylangs->trans("WarningPostActionErrorAfterPayment").')');
1802  $content .= '<span class="star">'.$companylangs->transnoentitiesnoconv("Error").'</span>';
1803  }
1804  $content .= '<br>'."\n";
1805  foreach ($postactionmessages as $postactionmessage) {
1806  $content .= ' * '.$postactionmessage.'<br>'."\n";
1807  }
1808  if ($ispostactionok < 0) {
1809  $content .= $langs->transnoentities("ARollbackWasPerformedOnPostActions");
1810  }
1811  $content .= '<br>'."\n";
1812 
1813  $content .= "<br>\n";
1814  $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
1815  $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
1816  $content .= $companylangs->transnoentitiesnoconv("ThisIsTransactionId").': <strong>'.$TRANSACTIONID."</strong><br>\n";
1817  $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
1818  $content .= "<br>\n";
1819  $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
1820 
1821  if (!empty($ErrorCode)) {
1822  $content .= "ErrorCode = ".$ErrorCode."<br>\n";
1823  }
1824  if (!empty($ErrorShortMsg)) {
1825  $content .= "ErrorShortMsg = ".$ErrorShortMsg."<br>\n";
1826  }
1827  if (!empty($ErrorLongMsg)) {
1828  $content .= "ErrorLongMsg = ".$ErrorLongMsg."<br>\n";
1829  }
1830  if (!empty($ErrorSeverityCode)) {
1831  $content .= "ErrorSeverityCode = ".$ErrorSeverityCode."<br>\n";
1832  }
1833 
1834 
1835  $ishtml = dol_textishtml($content); // May contain urls
1836 
1837  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1838  $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml);
1839 
1840  $result = $mailfile->sendfile();
1841  if ($result) {
1842  dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1843  //dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0);
1844  } else {
1845  dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
1846  //dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0);
1847  }
1848  }
1849 } else {
1850  // Get on url call
1851  $onlinetoken = empty($PAYPALTOKEN) ? $_SESSION['onlinetoken'] : $PAYPALTOKEN;
1852  $payerID = empty($PAYPALPAYERID) ? $_SESSION['payerID'] : $PAYPALPAYERID;
1853  // Set by newpayment.php
1854  $paymentType = $_SESSION['PaymentType'];
1855  $currencyCodeType = $_SESSION['currencyCodeType'];
1856  $FinalPaymentAmt = $_SESSION["FinalPaymentAmt"];
1857 
1858  if (is_object($object) && method_exists($object, 'call_trigger')) {
1859  // Call trigger
1860  $result = $object->call_trigger('PAYMENTONLINE_PAYMENT_KO', $user);
1861  if ($result < 0) {
1862  $error++;
1863  }
1864  // End call triggers
1865  }
1866 
1867  print $langs->trans('DoExpressCheckoutPaymentAPICallFailed')."<br>\n";
1868  print $langs->trans('DetailedErrorMessage').": ".$ErrorLongMsg."<br>\n";
1869  print $langs->trans('ShortErrorMessage').": ".$ErrorShortMsg."<br>\n";
1870  print $langs->trans('ErrorCode').": ".$ErrorCode."<br>\n";
1871  print $langs->trans('ErrorSeverityCode').": ".$ErrorSeverityCode."<br>\n";
1872 
1873  if ($mysoc->email) {
1874  print "\nPlease, send a screenshot of this page to ".$mysoc->email."<br>\n";
1875  }
1876 
1877  $sendemail = '';
1878  if (!empty($conf->global->PAYMENTONLINE_SENDEMAIL)) {
1879  $sendemail = $conf->global->PAYMENTONLINE_SENDEMAIL;
1880  }
1881  // TODO Remove local option to keep only the generic one ?
1882  if ($paymentmethod == 'paypal' && !empty($conf->global->PAYPAL_PAYONLINE_SENDEMAIL)) {
1883  $sendemail = $conf->global->PAYPAL_PAYONLINE_SENDEMAIL;
1884  } elseif ($paymentmethod == 'paybox' && !empty($conf->global->PAYBOX_PAYONLINE_SENDEMAIL)) {
1885  $sendemail = $conf->global->PAYBOX_PAYONLINE_SENDEMAIL;
1886  } elseif ($paymentmethod == 'stripe' && !empty($conf->global->STRIPE_PAYONLINE_SENDEMAIL)) {
1887  $sendemail = $conf->global->STRIPE_PAYONLINE_SENDEMAIL;
1888  }
1889 
1890  // Send warning of error to administrator
1891  if ($sendemail) {
1892  $companylangs = new Translate('', $conf);
1893  $companylangs->setDefaultLang($mysoc->default_lang);
1894  $companylangs->loadLangs(array('main', 'members', 'bills', 'paypal', 'paybox'));
1895 
1896  $sendto = $sendemail;
1897  $from = !empty($conf->global->MAILING_EMAIL_FROM) ? $conf->global->MAILING_EMAIL_FROM : getDolGlobalString("MAIN_MAIL_EMAIL_FROM");
1898  // Define $urlwithroot
1899  $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1900  $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1901  //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
1902 
1903  $urlback = $_SERVER["REQUEST_URI"];
1904  $topic = '['.$appli.'] '.$companylangs->transnoentitiesnoconv("ValidationOfPaymentFailed");
1905  $content = "";
1906  $content .= '<span style="color: orange">'.$companylangs->transnoentitiesnoconv("PaymentSystemConfirmPaymentPageWasCalledButFailed")."</span>\n";
1907 
1908  $content .= "<br><br>\n";
1909  $content .= '<u>'.$companylangs->transnoentitiesnoconv("TechnicalInformation").":</u><br>\n";
1910  $content .= $companylangs->transnoentitiesnoconv("OnlinePaymentSystem").': <strong>'.$paymentmethod."</strong><br>\n";
1911  $content .= $companylangs->transnoentitiesnoconv("ReturnURLAfterPayment").': '.$urlback."<br>\n";
1912  $content .= "<br>\n";
1913  $content .= "tag=".$fulltag."<br>\ntoken=".$onlinetoken."<br>\npaymentType=".$paymentType."<br>\ncurrencycodeType=".$currencyCodeType."<br>\npayerId=".$payerID."<br>\nipaddress=".$ipaddress."<br>\nFinalPaymentAmt=".$FinalPaymentAmt."<br>\n";
1914 
1915 
1916  $ishtml = dol_textishtml($content); // May contain urls
1917 
1918  require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1919  $mailfile = new CMailFile($topic, $sendto, $from, $content, array(), array(), array(), '', '', 0, $ishtml);
1920 
1921  $result = $mailfile->sendfile();
1922  if ($result) {
1923  dol_syslog("EMail sent to ".$sendto, LOG_DEBUG, 0, '_payment');
1924  } else {
1925  dol_syslog("Failed to send EMail to ".$sendto, LOG_ERR, 0, '_payment');
1926  }
1927  }
1928 }
1929 
1930 
1931 print "\n</div>\n";
1932 
1933 print "<!-- Info for payment: FinalPaymentAmt=".dol_escape_htmltag($FinalPaymentAmt)." paymentTypeId=".dol_escape_htmltag($paymentTypeId)." currencyCodeType=".dol_escape_htmltag($currencyCodeType)." -->\n";
1934 
1935 
1936 htmlPrintOnlineFooter($mysoc, $langs, 0, $suffix);
1937 
1938 
1939 // Clean session variables to avoid duplicate actions if post is resent
1940 unset($_SESSION["FinalPaymentAmt"]);
1941 unset($_SESSION["TRANSACTIONID"]);
1942 
1943 
1944 llxFooter('', 'public');
1945 
1946 $db->close();
if(!defined('NOREQUIRESOC')) if(!defined('NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) llxHeader()
Empty header.
Definition: wrapper.php:56
llxFooter()
Empty footer.
Definition: wrapper.php:70
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 contracts.
Class to manage donations.
Definition: don.class.php:40
Class to manage invoices.
const TYPE_CREDIT_NOTE
Credit note invoice.
Classe permettant la generation du formulaire html d'envoi de mail unitaire Usage: $formail = new For...
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.
Class to manage translations.
Class to manage Dolibarr users.
Definition: user.class.php:48
htmlPrintOnlineFooter($fromcompany, $langs, $addformmessage=0, $suffix='', $object=null)
Show footer of company in HTML pages.
if(isModEnabled('facture') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $sql
Social contributions to pay.
Definition: index.php:746
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0)
Add a delay to a date.
Definition: date.lib.php:122
dol_most_recent_file($dir, $regexfilter='', $excludefilter=array('(\.meta|_preview.*\.png)$', '^\.'), $nohook=false, $mode='')
Return file(s) into a directory (by default most recent)
Definition: files.lib.php:2524
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_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_textishtml($msg, $option=0)
Return if a text is a html content.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0)
Set event messages in dol_events session object.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null, $include=null)
Return array of possible common substitutions.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
confirmPayment($token, $paymentType, $currencyCodeType, $payerID, $ipaddress, $FinalPaymentAmt, $tag)
Validate payment.
Definition: paypal.lib.php:357
getDetails($token)
Prepares the parameters for the GetExpressCheckoutDetails API Call.
Definition: paypal.lib.php:308
httponly_accessforbidden($message=1, $http_response_code=403, $stringalreadysanitized=0)
Show a message to say access is forbidden and stop program.