ipn.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. if (!defined('NOLOGIN')) {
  19. define("NOLOGIN", 1); // This means this output page does not require to be logged.
  20. }
  21. if (!defined('NOCSRFCHECK')) {
  22. define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
  23. }
  24. if (!defined('NOIPCHECK')) {
  25. define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
  26. }
  27. if (!defined('NOBROWSERNOTIF')) {
  28. define('NOBROWSERNOTIF', '1');
  29. }
  30. $entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
  31. if (is_numeric($entity)) {
  32. define("DOLENTITY", $entity);
  33. }
  34. require '../../main.inc.php';
  35. require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
  36. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  37. require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php';
  38. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  41. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  42. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  43. require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  44. require_once DOL_DOCUMENT_ROOT.'/includes/stripe/stripe-php/init.php';
  45. require_once DOL_DOCUMENT_ROOT.'/stripe/class/stripe.class.php';
  46. // You can find your endpoint's secret in your webhook settings
  47. if (isset($_GET['connect'])) {
  48. if (isset($_GET['test'])) {
  49. $endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_CONNECT_KEY;
  50. $service = 'StripeTest';
  51. $servicestatus = 0;
  52. } else {
  53. $endpoint_secret = $conf->global->STRIPE_LIVE_WEBHOOK_CONNECT_KEY;
  54. $service = 'StripeLive';
  55. $servicestatus = 1;
  56. }
  57. } else {
  58. if (isset($_GET['test'])) {
  59. $endpoint_secret = $conf->global->STRIPE_TEST_WEBHOOK_KEY;
  60. $service = 'StripeTest';
  61. $servicestatus = 0;
  62. } else {
  63. $endpoint_secret = $conf->global->STRIPE_LIVE_WEBHOOK_KEY;
  64. $service = 'StripeLive';
  65. $servicestatus = 1;
  66. }
  67. }
  68. if (empty($conf->stripe->enabled)) {
  69. httponly_accessforbidden('Module Stripe not enabled');
  70. }
  71. if (empty($endpoint_secret)) {
  72. httponly_accessforbidden('Error: Setup of module Stripe not complete for mode '.dol_escape_htmltag($service).'. The WEBHOOK_KEY is not defined.', 400, 1);
  73. }
  74. if (!empty($conf->global->STRIPE_USER_ACCOUNT_FOR_ACTIONS)) {
  75. // We set the user to use for all ipn actions in Dolibarr
  76. $user = new User($db);
  77. $user->fetch($conf->global->STRIPE_USER_ACCOUNT_FOR_ACTIONS);
  78. $user->getrights();
  79. } else {
  80. 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);
  81. }
  82. // TODO Add a check on a security key
  83. /*
  84. * Actions
  85. */
  86. $payload = @file_get_contents("php://input");
  87. $sig_header = $_SERVER["HTTP_STRIPE_SIGNATURE"];
  88. $event = null;
  89. $error = 0;
  90. try {
  91. $event = \Stripe\Webhook::constructEvent($payload, $sig_header, $endpoint_secret);
  92. } catch (\UnexpectedValueException $e) {
  93. // Invalid payload
  94. httponly_accessforbidden('Invalid payload', 400);
  95. } catch (\Stripe\Error\SignatureVerification $e) {
  96. httponly_accessforbidden('Invalid signature', 400);
  97. }
  98. // Do something with $event
  99. $langs->load("main");
  100. if (isModEnabled('multicompany') && !empty($conf->stripeconnect->enabled) && is_object($mc)) {
  101. $sql = "SELECT entity";
  102. $sql .= " FROM ".MAIN_DB_PREFIX."oauth_token";
  103. $sql .= " WHERE service = '".$db->escape($service)."' and tokenstring LIKE '%".$db->escape($event->account)."%'";
  104. dol_syslog(get_class($db)."::fetch", LOG_DEBUG);
  105. $result = $db->query($sql);
  106. if ($result) {
  107. if ($db->num_rows($result)) {
  108. $obj = $db->fetch_object($result);
  109. $key = $obj->entity;
  110. } else {
  111. $key = 1;
  112. }
  113. } else {
  114. $key = 1;
  115. }
  116. $ret = $mc->switchEntity($key);
  117. }
  118. // list of action
  119. $stripe = new Stripe($db);
  120. // Subject
  121. $societeName = $conf->global->MAIN_INFO_SOCIETE_NOM;
  122. if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
  123. $societeName = $conf->global->MAIN_APPLICATION_TITLE;
  124. }
  125. top_httphead();
  126. dol_syslog("***** Stripe IPN was called with event->type = ".$event->type);
  127. if ($event->type == 'payout.created') {
  128. $error = 0;
  129. $result = dolibarr_set_const($db, $service."_NEXTPAYOUT", date('Y-m-d H:i:s', $event->data->object->arrival_date), 'chaine', 0, '', $conf->entity);
  130. if ($result > 0) {
  131. $subject = $societeName.' - [NOTIFICATION] Stripe payout scheduled';
  132. if (!empty($user->email)) {
  133. $sendto = dolGetFirstLastname($user->firstname, $user->lastname)." <".$user->email.">";
  134. } else {
  135. $sendto = $conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
  136. }
  137. $replyto = $sendto;
  138. $sendtocc = '';
  139. if (!empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) {
  140. $sendtocc = $conf->global->ONLINE_PAYMENT_SENDEMAIL.'" <'.$conf->global->ONLINE_PAYMENT_SENDEMAIL.'>';
  141. }
  142. $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');
  143. $mailfile = new CMailFile(
  144. $subject,
  145. $sendto,
  146. $replyto,
  147. $message,
  148. array(),
  149. array(),
  150. array(),
  151. $sendtocc,
  152. '',
  153. 0,
  154. -1
  155. );
  156. $ret = $mailfile->sendfile();
  157. return 1;
  158. } else {
  159. $error++;
  160. http_response_code(500);
  161. return -1;
  162. }
  163. } elseif ($event->type == 'payout.paid') {
  164. global $conf;
  165. $error = 0;
  166. $result = dolibarr_set_const($db, $service."_NEXTPAYOUT", null, 'chaine', 0, '', $conf->entity);
  167. if ($result) {
  168. $langs->load("errors");
  169. $dateo = dol_now();
  170. $label = $event->data->object->description;
  171. $amount = $event->data->object->amount / 100;
  172. $amount_to = $event->data->object->amount / 100;
  173. require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
  174. $accountfrom = new Account($db);
  175. $accountfrom->fetch($conf->global->STRIPE_BANK_ACCOUNT_FOR_PAYMENTS);
  176. $accountto = new Account($db);
  177. $accountto->fetch($conf->global->STRIPE_BANK_ACCOUNT_FOR_BANKTRANSFERS);
  178. if (($accountto->id != $accountfrom->id) && empty($error)) {
  179. $bank_line_id_from = 0;
  180. $bank_line_id_to = 0;
  181. $result = 0;
  182. // By default, electronic transfert from bank to bank
  183. $typefrom = 'PRE';
  184. $typeto = 'VIR';
  185. if (!$error) {
  186. $bank_line_id_from = $accountfrom->addline($dateo, $typefrom, $label, -1 * price2num($amount), '', '', $user);
  187. }
  188. if (!($bank_line_id_from > 0)) {
  189. $error++;
  190. }
  191. if (!$error) {
  192. $bank_line_id_to = $accountto->addline($dateo, $typeto, $label, price2num($amount), '', '', $user);
  193. }
  194. if (!($bank_line_id_to > 0)) {
  195. $error++;
  196. }
  197. if (!$error) {
  198. $result = $accountfrom->add_url_line($bank_line_id_from, $bank_line_id_to, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert');
  199. }
  200. if (!($result > 0)) {
  201. $error++;
  202. }
  203. if (!$error) {
  204. $result = $accountto->add_url_line($bank_line_id_to, $bank_line_id_from, DOL_URL_ROOT.'/compta/bank/line.php?rowid=', '(banktransfert)', 'banktransfert');
  205. }
  206. if (!($result > 0)) {
  207. $error++;
  208. }
  209. }
  210. $subject = $societeName.' - [NOTIFICATION] Stripe payout done';
  211. if (!empty($user->email)) {
  212. $sendto = dolGetFirstLastname($user->firstname, $user->lastname)." <".$user->email.">";
  213. } else {
  214. $sendto = $conf->global->MAIN_INFO_SOCIETE_MAIL.'" <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
  215. }
  216. $replyto = $sendto;
  217. $sendtocc = '';
  218. if (!empty($conf->global->ONLINE_PAYMENT_SENDEMAIL)) {
  219. $sendtocc = $conf->global->ONLINE_PAYMENT_SENDEMAIL.'" <'.$conf->global->ONLINE_PAYMENT_SENDEMAIL.'>';
  220. }
  221. $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');
  222. $mailfile = new CMailFile(
  223. $subject,
  224. $sendto,
  225. $replyto,
  226. $message,
  227. array(),
  228. array(),
  229. array(),
  230. $sendtocc,
  231. '',
  232. 0,
  233. -1
  234. );
  235. $ret = $mailfile->sendfile();
  236. return 1;
  237. } else {
  238. $error++;
  239. http_response_code(500);
  240. return -1;
  241. }
  242. } elseif ($event->type == 'customer.source.created') {
  243. //TODO: save customer's source
  244. } elseif ($event->type == 'customer.source.updated') {
  245. //TODO: update customer's source
  246. } elseif ($event->type == 'customer.source.delete') {
  247. //TODO: delete customer's source
  248. } elseif ($event->type == 'customer.deleted') {
  249. $db->begin();
  250. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_account WHERE key_account = '".$db->escape($event->data->object->id)."' and site='stripe'";
  251. $db->query($sql);
  252. $db->commit();
  253. } elseif ($event->type == 'payment_intent.succeeded') { // Called when making payment with PaymentIntent method ($conf->global->STRIPE_USE_NEW_CHECKOUT is on).
  254. // TODO: create fees
  255. // TODO: Redirect to paymentok.php
  256. } elseif ($event->type == 'payment_intent.payment_failed') {
  257. // TODO: Redirect to paymentko.php
  258. } elseif ($event->type == 'checkout.session.completed') { // Called when making payment with new Checkout method ($conf->global->STRIPE_USE_NEW_CHECKOUT is on).
  259. // TODO: create fees
  260. // TODO: Redirect to paymentok.php
  261. } elseif ($event->type == 'payment_method.attached') {
  262. require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php';
  263. require_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
  264. $societeaccount = new SocieteAccount($db);
  265. $companypaymentmode = new CompanyPaymentMode($db);
  266. $idthirdparty = $societeaccount->getThirdPartyID($db->escape($event->data->object->customer), 'stripe', $servicestatus);
  267. if ($idthirdparty > 0) { // If the payment mode is on an external customer that is known in societeaccount, we can create the payment mode
  268. $companypaymentmode->stripe_card_ref = $db->escape($event->data->object->id);
  269. $companypaymentmode->fk_soc = $idthirdparty;
  270. $companypaymentmode->bank = null;
  271. $companypaymentmode->label = null;
  272. $companypaymentmode->number = $db->escape($event->data->object->id);
  273. $companypaymentmode->last_four = $db->escape($event->data->object->card->last4);
  274. $companypaymentmode->card_type = $db->escape($event->data->object->card->branding);
  275. $companypaymentmode->proprio = $db->escape($event->data->object->billing_details->name);
  276. $companypaymentmode->exp_date_month = $db->escape($event->data->object->card->exp_month);
  277. $companypaymentmode->exp_date_year = $db->escape($event->data->object->card->exp_year);
  278. $companypaymentmode->cvn = null;
  279. $companypaymentmode->datec = $db->escape($event->data->object->created);
  280. $companypaymentmode->default_rib = 0;
  281. $companypaymentmode->type = $db->escape($event->data->object->type);
  282. $companypaymentmode->country_code = $db->escape($event->data->object->card->country);
  283. $companypaymentmode->status = $servicestatus;
  284. $db->begin();
  285. if (!$error) {
  286. $result = $companypaymentmode->create($user);
  287. if ($result < 0) {
  288. $error++;
  289. }
  290. }
  291. if (!$error) {
  292. $db->commit();
  293. } else {
  294. $db->rollback();
  295. }
  296. }
  297. } elseif ($event->type == 'payment_method.updated') {
  298. require_once DOL_DOCUMENT_ROOT.'/societe/class/companypaymentmode.class.php';
  299. $companypaymentmode = new CompanyPaymentMode($db);
  300. $companypaymentmode->fetch(0, '', 0, '', " AND stripe_card_ref = '".$db->escape($event->data->object->id)."'");
  301. $companypaymentmode->bank = null;
  302. $companypaymentmode->label = null;
  303. $companypaymentmode->number = $db->escape($event->data->object->id);
  304. $companypaymentmode->last_four = $db->escape($event->data->object->card->last4);
  305. $companypaymentmode->proprio = $db->escape($event->data->object->billing_details->name);
  306. $companypaymentmode->exp_date_month = $db->escape($event->data->object->card->exp_month);
  307. $companypaymentmode->exp_date_year = $db->escape($event->data->object->card->exp_year);
  308. $companypaymentmode->cvn = null;
  309. $companypaymentmode->datec = $db->escape($event->data->object->created);
  310. $companypaymentmode->default_rib = 0;
  311. $companypaymentmode->type = $db->escape($event->data->object->type);
  312. $companypaymentmode->country_code = $db->escape($event->data->object->card->country);
  313. $companypaymentmode->status = $servicestatus;
  314. $db->begin();
  315. if (!$error) {
  316. $result = $companypaymentmode->update($user);
  317. if ($result < 0) {
  318. $error++;
  319. }
  320. }
  321. if (!$error) {
  322. $db->commit();
  323. } else {
  324. $db->rollback();
  325. }
  326. } elseif ($event->type == 'payment_method.detached') {
  327. $db->begin();
  328. $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_rib WHERE number = '".$db->escape($event->data->object->id)."' and status = ".((int) $servicestatus);
  329. $db->query($sql);
  330. $db->commit();
  331. } elseif ($event->type == 'charge.succeeded') {
  332. // TODO: create fees
  333. // TODO: Redirect to paymentok.php
  334. } elseif ($event->type == 'charge.failed') {
  335. // TODO: Redirect to paymentko.php
  336. } elseif (($event->type == 'source.chargeable') && ($event->data->object->type == 'three_d_secure') && ($event->data->object->three_d_secure->authenticated == true)) {
  337. // This event is deprecated.
  338. }
  339. // End of page. Default return HTTP code will be 200