dolibarr  18.0.6
ipn.php
1 <?php
2 /* Copyright (C) 2018-2020 Thibault FOUCART <support@ptibogxiv.net>
3  * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 
19 if (!defined('NOLOGIN')) {
20  define("NOLOGIN", 1); // This means this output page does not require to be logged.
21 }
22 if (!defined('NOCSRFCHECK')) {
23  define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
24 }
25 if (!defined('NOIPCHECK')) {
26  define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
27 }
28 if (!defined('NOBROWSERNOTIF')) {
29  define('NOBROWSERNOTIF', '1');
30 }
31 
32 $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
33 if (is_numeric($entity)) {
34  define("DOLENTITY", $entity);
35 }
36 
37 // So log file will have a suffix
38 if (!defined('USESUFFIXINLOG')) {
39  define('USESUFFIXINLOG', '_stripeipn');
40 }
41 
42 // Load Dolibarr environment
43 require '../../main.inc.php';
44 require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
45 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
46 require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php';
47 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
48 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
49 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
50 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
51 require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
52 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
53 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
54 require_once DOL_DOCUMENT_ROOT.'/includes/stripe/stripe-php/init.php';
55 require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
56 
57 
58 // You can find your endpoint's secret in your webhook settings
59 if (isset($_GET['connect'])) {
60  if (isset($_GET['test'])) {
61  $endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_CONNECT_KEY;
62  $service = 'StripeTest';
63  $servicestatus = 0;
64  } else {
65  $endpoint_secret = $conf->global->STRIPE_LIVE_WEBHOOK_CONNECT_KEY;
66  $service = 'StripeLive';
67  $servicestatus = 1;
68  }
69 } else {
70  if (isset($_GET['test'])) {
71  $endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_KEY;
72  $service = 'StripeTest';
73  $servicestatus = 0;
74  } else {
75  $endpoint_secret = $conf->global->STRIPE_LIVE_WEBHOOK_KEY;
76  $service = 'StripeLive';
77  $servicestatus = 1;
78  }
79 }
80 
81 if (!isModEnabled('stripe')) {
82  httponly_accessforbidden('Module Stripe not enabled');
83 }
84 
85 if (empty($endpoint_secret)) {
86  httponly_accessforbidden('Error: Setup of module Stripe not complete for mode '.dol_escape_htmltag($service).'. The WEBHOOK_KEY is not defined.', 400, 1);
87 }
88 
89 if (!empty($conf->global->STRIPE_USER_ACCOUNT_FOR_ACTIONS)) {
90  // We set the user to use for all ipn actions in Dolibarr
91  $user = new User($db);
92  $user->fetch($conf->global->STRIPE_USER_ACCOUNT_FOR_ACTIONS);
93  $user->getrights();
94 } else {
95  httponly_accessforbidden('Error: Setup of module Stripe not complete for mode '.dol_escape_htmltag($service).'. The STRIPE_USER_ACCOUNT_FOR_ACTIONS is not defined.', 400, 1);
96 }
97 
98 
99 // TODO Add a check on a security key
100 
101 
102 
103 /*
104  * Actions
105  */
106 
107 $payload = @file_get_contents("php://input");
108 $sig_header = empty($_SERVER["HTTP_STRIPE_SIGNATURE"]) ? '' : $_SERVER["HTTP_STRIPE_SIGNATURE"];
109 $event = null;
110 
111 if (getDolGlobalString('STRIPE_DEBUG')) {
112  $fh = fopen(DOL_DATA_ROOT.'/dolibarr_stripeipn_payload.log', 'w+');
113  if ($fh) {
114  fwrite($fh, dol_print_date(dol_now('gmt'), 'standard').' IPN Called. service='.$service.' HTTP_STRIPE_SIGNATURE='.$sig_header."\n");
115  fwrite($fh, $payload);
116  fclose($fh);
117  dolChmod(DOL_DATA_ROOT.'/dolibarr_stripeipn_payload.log');
118  }
119 }
120 
121 $error = 0;
122 
123 try {
124  $event = \Stripe\Webhook::constructEvent($payload, $sig_header, $endpoint_secret);
125 } catch (UnexpectedValueException $e) {
126  // Invalid payload
127  httponly_accessforbidden('Invalid payload', 400);
128 } catch (\Stripe\Exception\SignatureVerificationException $e) {
129  httponly_accessforbidden('Invalid signature. May be a hook for an event created by another Stripe env ? Check setup of your keys whsec_...', 400);
130 } catch (Exception $e) {
131  httponly_accessforbidden('Error '.$e->getMessage(), 400);
132 }
133 
134 // Do something with $event
135 
136 $langs->load("main");
137 
138 
139 if (isModEnabled('multicompany') && !empty($conf->stripeconnect->enabled) && is_object($mc)) {
140  $sql = "SELECT entity";
141  $sql .= " FROM ".MAIN_DB_PREFIX."oauth_token";
142  $sql .= " WHERE service = '".$db->escape($service)."' and tokenstring LIKE '%".$db->escape($db->escapeforlike($event->account))."%'";
143 
144  dol_syslog(get_class($db)."::fetch", LOG_DEBUG);
145  $result = $db->query($sql);
146  if ($result) {
147  if ($db->num_rows($result)) {
148  $obj = $db->fetch_object($result);
149  $key = $obj->entity;
150  } else {
151  $key = 1;
152  }
153  } else {
154  $key = 1;
155  }
156  $ret = $mc->switchEntity($key);
157 }
158 
159 // list of action
160 $stripe = new Stripe($db);
161 
162 // Subject
163 $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
164 if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
165  $societeName = $conf->global->MAIN_APPLICATION_TITLE;
166 }
167 
168 top_httphead();
169 
170 dol_syslog("***** Stripe IPN was called with event->type = ".$event->type);
171 
172 
173 if ($event->type == 'payout.created') {
174  $error = 0;
175 
176  $result = dolibarr_set_const($db, $service."_NEXTPAYOUT", date('Y-m-d H:i:s', $event->data->object->arrival_date), 'chaine', 0, '', $conf->entity);
177 
178  if ($result > 0) {
179  $subject = $societeName.' - [NOTIFICATION] Stripe payout scheduled';
180  if (!empty($user->email)) {
181  $sendto = dolGetFirstLastname($user->firstname, $user->lastname)." <".$user->email.">";
182  } else {
183  $sendto = $conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
184  }
185  $replyto = $sendto;
186  $sendtocc = '';
187  if (!empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) {
188  $sendtocc = $conf->global->ONLINE_PAYMENT_SENDEMAIL.'" <'.$conf->global->ONLINE_PAYMENT_SENDEMAIL.'>';
189  }
190 
191  $message = "A bank transfer of ".price2num($event->data->object->amount / 100)." ".$event->data->object->currency." should arrive in your account the ".dol_print_date($event->data->object->arrival_date, 'dayhour');
192 
193  $mailfile = new CMailFile(
194  $subject,
195  $sendto,
196  $replyto,
197  $message,
198  array(),
199  array(),
200  array(),
201  $sendtocc,
202  '',
203  0,
204  -1
205  );
206 
207  $ret = $mailfile->sendfile();
208 
209  return 1;
210  } else {
211  $error++;
212  http_response_code(500);
213  return -1;
214  }
215 } elseif ($event->type == 'payout.paid') {
216  $error = 0;
217  $result = dolibarr_set_const($db, $service."_NEXTPAYOUT", null, 'chaine', 0, '', $conf->entity);
218  if ($result) {
219  $langs->load("errors");
220 
221  $dateo = dol_now();
222  $label = $event->data->object->description;
223  $amount = $event->data->object->amount / 100;
224  $amount_to = $event->data->object->amount / 100;
225  require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
226 
227  $accountfrom = new Account($db);
228  $accountfrom->fetch($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS);
229 
230  $accountto = new Account($db);
231  $accountto->fetch($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS);
232 
233  if (($accountto->id != $accountfrom->id) && empty($error)) {
234  $bank_line_id_from = 0;
235  $bank_line_id_to = 0;
236  $result = 0;
237 
238  // By default, electronic transfert from bank to bank
239  $typefrom = 'PRE';
240  $typeto = 'VIR';
241 
242  if (!$error) {
243  $bank_line_id_from = $accountfrom->addline($dateo, $typefrom, $label, -1 * price2num($amount), '', '', $user);
244  }
245  if (!($bank_line_id_from > 0)) {
246  $error++;
247  }
248  if (!$error) {
249  $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount), '', '', $user);
250  }
251  if (!($bank_line_id_to > 0)) {
252  $error++;
253  }
254 
255  if (!$error) {
256  $result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert');
257  }
258  if (!($result > 0)) {
259  $error++;
260  }
261  if (!$error) {
262  $result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert');
263  }
264  if (!($result > 0)) {
265  $error++;
266  }
267  }
268 
269  $subject = $societeName.' - [NOTIFICATION] Stripe payout done';
270  if (!empty($user->email)) {
271  $sendto = dolGetFirstLastname($user->firstname, $user->lastname)." <".$user->email.">";
272  } else {
273  $sendto = $conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
274  }
275  $replyto = $sendto;
276  $sendtocc = '';
277  if (!empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) {
278  $sendtocc = $conf->global->ONLINE_PAYMENT_SENDEMAIL.'" <'.$conf->global->ONLINE_PAYMENT_SENDEMAIL.'>';
279  }
280 
281  $message = "A bank transfer of ".price2num($event->data->object->amount / 100)." ".$event->data->object->currency." has been done to your account the ".dol_print_date($event->data->object->arrival_date, 'dayhour');
282 
283  $mailfile = new CMailFile(
284  $subject,
285  $sendto,
286  $replyto,
287  $message,
288  array(),
289  array(),
290  array(),
291  $sendtocc,
292  '',
293  0,
294  -1
295  );
296 
297  $ret = $mailfile->sendfile();
298 
299  return 1;
300  } else {
301  $error++;
302  http_response_code(500);
303  return -1;
304  }
305 } elseif ($event->type == 'customer.source.created') {
306  //TODO: save customer's source
307 } elseif ($event->type == 'customer.source.updated') {
308  //TODO: update customer's source
309 } elseif ($event->type == 'customer.source.delete') {
310  //TODO: delete customer's source
311 } elseif ($event->type == 'customer.deleted') {
312  $db->begin();
313  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_account WHERE key_account = '".$db->escape($event->data->object->id)."' and site='stripe'";
314  $db->query($sql);
315  $db->commit();
316 } elseif ($event->type == 'payment_intent.succeeded') { // Called when making payment with PaymentIntent method ($conf->global->STRIPE_USE_NEW_CHECKOUT is on).
317  //dol_syslog("object = ".var_export($event->data, true));
318  include_once DOL_DOCUMENT_ROOT . '/compta/paiement/class/paiement.class.php';
319  global $stripearrayofkeysbyenv;
320  $error = 0;
321  $object = $event->data->object;
322  $TRANSACTIONID = $object->id;
323  $ipaddress = $object->metadata->ipaddress;
324  $now = dol_now();
325  $currencyCodeType = strtoupper($object->currency);
326  $paymentmethodstripeid = $object->payment_method;
327  $customer_id = $object->customer;
328  $invoice_id = "";
329  $paymentTypeId = "";
330  $payment_amount = 0;
331 
332  dol_syslog("Try to find the payment in database for the payment id = ".$TRANSACTIONID);
333 
334  $sql = "SELECT pi.fk_facture, pi.fk_prelevement_bons, pi.amount, pi.type";
335  $sql .= " FROM llx_prelevement_demande as pi";
336  $sql .= " WHERE pi.ext_payment_id = '".$db->escape($TRANSACTIONID)."'";
337  $sql .= " AND pi.traite = '1'";
338  $sql .= " AND pi.ext_payment_site = '".$db->escape($service)."'";
339 
340  $result = $db->query($sql);
341  if ($result) {
342  $obj = $db->fetch_object($result);
343  if ($obj) {
344  $invoice_id = $obj->fk_facture;
345  $prelevement_bons_id = $obj->fk_prelevement_bons;
346  $payment_amount = $obj->amount;
347  $paymentTypeId = $obj->type;
348  }
349  } else {
350  http_response_code(500);
351  print $db->lasterror();
352  return -1;
353  }
354 
355  $stripeacc = $stripearrayofkeysbyenv[$servicestatus]['secret_key'];
356 
357  dol_syslog("Get the Stripe payment object for the payment method id = ".json_encode($paymentmethodstripeid));
358 
359  $s = new \Stripe\StripeClient($stripeacc);
360 
361  $paymentmethodstripe = $s->paymentMethods->retrieve($paymentmethodstripeid);
362  $paymentTypeId = $paymentmethodstripe->type;
363  if ($paymentTypeId == "ban" || $paymentTypeId == "sepa_debit") {
364  $paymentTypeId = "PRE";
365  } elseif ($paymentTypeId == "card") {
366  $paymentTypeId = "CB";
367  }
368 
369  if ($paymentTypeId == "PRE") {
370  $paiement = new Paiement($db);
371  $paiement->datepaye = $now;
372  $paiement->date = $now;
373  if ($currencyCodeType == $conf->currency) {
374  $paiement->amounts = [$invoice_id => $payment_amount]; // Array with all payments dispatching with invoice id
375  } else {
376  $paiement->multicurrency_amounts = [$invoice_id => $payment_amount]; // Array with all payments dispatching
377 
378  $postactionmessages[] = 'Payment was done in a different currency than currency expected of company';
379  $ispostactionok = -1;
380  // Not yet supported, so error
381  $error++;
382  }
383  $paiement->paiementid = $paymentTypeId;
384  $paiement->num_payment = '';
385  $paiement->note_public = '';
386  $paiement->note_private = 'StripeSepa payment ' . dol_print_date($now, 'standard') . ' using ' . $servicestatus . ($ipaddress ? ' from ip ' . $ipaddress : '') . ' - Transaction ID = ' . $TRANSACTIONID;
387  $paiement->ext_payment_id = $TRANSACTIONID.':'.$customer_id.'@'.$stripearrayofkeysbyenv[$servicestatus]['publishable_key']; // May be we should store py_... instead of pi_... but we started with pi_... so we continue.
388  $paiement->ext_payment_site = $service;
389 
390  $ispaymentdone = 0;
391  $sql = "SELECT p.rowid FROM llx_paiement as p";
392  $sql .= " WHERE p.ext_payment_id = '".$db->escape($paiement->ext_payment_id)."'";
393  $sql .= " AND p.ext_payment_site = '".$db->escape($paiement->ext_payment_site)."'";
394  $result = $db->query($sql);
395  if ($result) {
396  if ($db->num_rows($result)) {
397  $ispaymentdone = 1;
398  dol_syslog('* Payment for ext_payment_id '.$paiement->ext_payment_id.' already done. We do not recreate the payment');
399  }
400  }
401 
402  $db->begin();
403 
404  if (!$error && !$ispaymentdone) {
405  dol_syslog('* Record payment for invoice id ' . $invoice_id . '. It includes closing of invoice and regenerating document');
406 
407  // This include closing invoices to 'paid' (and trigger including unsuspending) and regenerating document
408  $paiement_id = $paiement->create($user, 1);
409  if ($paiement_id < 0) {
410  $postactionmessages[] = $paiement->error . ($paiement->error ? ' ' : '') . join("<br>\n", $paiement->errors);
411  $ispostactionok = -1;
412  $error++;
413 
414  dol_syslog("Failed to create the payment for invoice id " . $invoice_id);
415  } else {
416  $postactionmessages[] = 'Payment created';
417 
418  dol_syslog("The payment has been created for invoice id " . $invoice_id);
419  }
420  }
421 
422  if (!$error && isModEnabled('banque')) {
423  // Search again the payment to see if it is already linked to a bank payment record (We should always find the payement now we have created before).
424  $ispaymentdone = 0;
425  $sql = "SELECT p.rowid, p.fk_bank FROM llx_paiement as p";
426  $sql .= " WHERE p.ext_payment_id = '".$db->escape($paiement->ext_payment_id)."'";
427  $sql .= " AND p.ext_payment_site = '".$db->escape($paiement->ext_payment_site)."'";
428  $sql .= " AND p.fk_bank <> 0";
429  $result = $db->query($sql);
430  if ($result) {
431  if ($db->num_rows($result)) {
432  $ispaymentdone = 1;
433  $obj = $db->fetch_object($result);
434  dol_syslog('* Payment already linked to bank record '.$obj->fk_bank.' . We do not recreate the link');
435  }
436  }
437  if (!$ispaymentdone) {
438  dol_syslog('* Add payment to bank');
439 
440  // The bank used is the one defined into Stripe setup
441  $paymentmethod = 'stripe';
442  $bankaccountid = getDolGlobalInt("STRIPE_BANK_ACCOUNT_FOR_PAYMENTS");
443 
444  if ($bankaccountid > 0) {
445  $label = '(CustomerInvoicePayment)';
446  $result = $paiement->addPaymentToBank($user, 'payment', $label, $bankaccountid, $customer_id, '');
447  if ($result < 0) {
448  $postactionmessages[] = $paiement->error . ($paiement->error ? ' ' : '') . join("<br>\n", $paiement->errors);
449  $ispostactionok = -1;
450  $error++;
451  } else {
452  $postactionmessages[] = 'Bank transaction of payment created (by makeStripeSepaRequest)';
453  }
454  } else {
455  $postactionmessages[] = 'Setup of bank account to use in module ' . $paymentmethod . ' was not set. No way to record the payment.';
456  $ispostactionok = -1;
457  $error++;
458  }
459  }
460  }
461 
462  if (!$error && isModEnabled('prelevement')) {
463  $bon = new BonPrelevement($db);
464  $idbon = 0;
465  $sql = "SELECT dp.fk_prelevement_bons as idbon";
466  $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as dp";
467  $sql .= " JOIN ".MAIN_DB_PREFIX."prelevement_bons as pb"; // Here we join to prevent modification of a prelevement bon already credited
468  $sql .= " ON pb.rowid = dp.fk_prelevement_bons";
469  $sql .= " WHERE dp.fk_facture = ".((int) $invoice_id);
470  $sql .= " AND dp.sourcetype = 'facture'";
471  $sql .= " AND dp.ext_payment_id = '".$db->escape($TRANSACTIONID)."'";
472  $sql .= " AND dp.traite = 1";
473  $sql .= " AND statut = ".((int) $bon::STATUS_TRANSFERED); // To be sure that it's not already credited
474  $result = $db->query($sql);
475  if ($result) {
476  if ($db->num_rows($result)) {
477  $obj = $db->fetch_object($result);
478  $idbon = $obj->idbon;
479  dol_syslog('* Set prelevement to credite');
480  } else {
481  dol_syslog('* Prelevement not found or already credited');
482  }
483  } else {
484  $postactionmessages[] = $db->lasterror();
485  $ispostactionok = -1;
486  $error++;
487  }
488 
489  if (!$error && !empty($idbon)) {
490  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
491  $sql .= " SET fk_user_credit = ".((int) $user->id);
492  $sql .= ", statut = ".((int) $bon::STATUS_CREDITED);
493  $sql .= ", date_credit = '".$db->idate($now)."'";
494  $sql .= ", credite = 1";
495  $sql .= " WHERE rowid = ".((int) $idbon);
496  $sql .= " AND statut = ".((int) $bon::STATUS_TRANSFERED);
497 
498  $result = $db->query($sql);
499  if (!$result) {
500  $postactionmessages[] = $db->lasterror();
501  $ispostactionok = -1;
502  $error++;
503  }
504  }
505 
506  if (!$error && !empty($idbon)) {
507  $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_lignes";
508  $sql .= " SET statut = 2";
509  $sql .= " WHERE fk_prelevement_bons = ".((int) $idbon);
510  $result = $db->query($sql);
511  if (!$result) {
512  $postactionmessages[] = $db->lasterror();
513  $ispostactionok = -1;
514  $error++;
515  }
516  }
517  }
518 
519  if (!$error) {
520  $db->commit();
521  http_response_code(200);
522  return 1;
523  } else {
524  $db->rollback();
525  http_response_code(500);
526  return -1;
527  }
528  } else {
529  dol_syslog("The payment mode of this payment is ".$paymentTypeId.". This payment mode is not managed by the IPN");
530  }
531 } elseif ($event->type == 'payment_intent.payment_failed') {
532  dol_syslog("A try to make a payment has failed");
533 } elseif ($event->type == 'checkout.session.completed') { // Called when making payment with new Checkout method ($conf->global->STRIPE_USE_NEW_CHECKOUT is on).
534  // TODO: create fees
535 } elseif ($event->type == 'payment_method.attached') {
536  require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php';
537  require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
538  $societeaccount = new SocieteAccount($db);
539 
540  $companypaymentmode = new CompanyPaymentMode($db);
541 
542  $idthirdparty = $societeaccount->getThirdPartyID($db->escape($event->data->object->customer), 'stripe', $servicestatus);
543  if ($idthirdparty > 0) {
544  // If the payment mode attached is to a stripe account owned by an external customer in societe_account (so a thirdparty that has a Stripe account),
545  // we can create the payment mode
546  $companypaymentmode->stripe_card_ref = $db->escape($event->data->object->id);
547  $companypaymentmode->fk_soc = $idthirdparty;
548  $companypaymentmode->bank = null;
549  $companypaymentmode->label = null;
550  $companypaymentmode->number = $db->escape($event->data->object->id);
551  $companypaymentmode->last_four = $db->escape($event->data->object->card->last4);
552  $companypaymentmode->card_type = $db->escape($event->data->object->card->branding);
553  $companypaymentmode->proprio = $db->escape($event->data->object->billing_details->name);
554  $companypaymentmode->exp_date_month = $db->escape($event->data->object->card->exp_month);
555  $companypaymentmode->exp_date_year = $db->escape($event->data->object->card->exp_year);
556  $companypaymentmode->cvn = null;
557  $companypaymentmode->datec = $db->escape($event->data->object->created);
558  $companypaymentmode->default_rib = 0;
559  $companypaymentmode->type = $db->escape($event->data->object->type);
560  $companypaymentmode->country_code = $db->escape($event->data->object->card->country);
561  $companypaymentmode->status = $servicestatus;
562 
563  // TODO Check that a payment mode $companypaymentmode->stripe_card_ref does not exists yet to avoid to create duplicates
564  // so we can remove the test on STRIPE_NO_DUPLICATE_CHECK
565  if (getDolGlobalString('STRIPE_NO_DUPLICATE_CHECK')) {
566  $db->begin();
567  $result = $companypaymentmode->create($user);
568  if ($result < 0) {
569  $error++;
570  }
571  if (!$error) {
572  $db->commit();
573  } else {
574  $db->rollback();
575  }
576  }
577  }
578 } elseif ($event->type == 'payment_method.updated') {
579  require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php';
580  $companypaymentmode = new CompanyPaymentMode($db);
581  $companypaymentmode->fetch(0, '', 0, '', " AND stripe_card_ref = '".$db->escape($event->data->object->id)."'");
582  if ($companypaymentmode->id > 0) {
583  // If we found a payment mode with the ID
584  $companypaymentmode->bank = null;
585  $companypaymentmode->label = null;
586  $companypaymentmode->number = $db->escape($event->data->object->id);
587  $companypaymentmode->last_four = $db->escape($event->data->object->card->last4);
588  $companypaymentmode->proprio = $db->escape($event->data->object->billing_details->name);
589  $companypaymentmode->exp_date_month = $db->escape($event->data->object->card->exp_month);
590  $companypaymentmode->exp_date_year = $db->escape($event->data->object->card->exp_year);
591  $companypaymentmode->cvn = null;
592  $companypaymentmode->datec = $db->escape($event->data->object->created);
593  $companypaymentmode->default_rib = 0;
594  $companypaymentmode->type = $db->escape($event->data->object->type);
595  $companypaymentmode->country_code = $db->escape($event->data->object->card->country);
596  $companypaymentmode->status = $servicestatus;
597 
598  $db->begin();
599  if (!$error) {
600  $result = $companypaymentmode->update($user);
601  if ($result < 0) {
602  $error++;
603  }
604  }
605  if (!$error) {
606  $db->commit();
607  } else {
608  $db->rollback();
609  }
610  }
611 } elseif ($event->type == 'payment_method.detached') {
612  $db->begin();
613  $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_rib WHERE number = '".$db->escape($event->data->object->id)."' and status = ".((int) $servicestatus);
614  $db->query($sql);
615  $db->commit();
616 } elseif ($event->type == 'charge.succeeded') {
617  // TODO: create fees
618  // TODO: Redirect to paymentok.php
619 } elseif ($event->type == 'charge.failed') {
620  // TODO: Redirect to paymentko.php
621 } elseif (($event->type == 'source.chargeable') && ($event->data->object->type == 'three_d_secure') && ($event->data->object->three_d_secure->authenticated == true)) {
622  // This event is deprecated.
623 }
624 
625 // End of page. Default return HTTP code will be 200
dolibarr_set_const($db, $name, $value, $type='chaine', $visible=0, $note='', $entity=1)
Insert a parameter (key,value) into database (delete old key then insert it again).
Definition: admin.lib.php:638
Class to manage bank accounts.
Class to manage withdrawal receipts.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
Class for CompanyPaymentMode.
Class to manage payments of customer invoices.
Class for SocieteAccount.
Stripe class.
Class to manage Dolibarr users.
Definition: user.class.php:48
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
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
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('NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
Definition: main.inc.php:1510
httponly_accessforbidden($message=1, $http_response_code=403, $stringalreadysanitized=0)
Show a message to say access is forbidden and stop program.