ipn.php 14 KB

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