stripe.class.php 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386
  1. <?php
  2. /* Copyright (C) 2018-2021 Thibault FOUCART <support@ptibogxiv.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. // Put here all includes required by your class file
  18. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  19. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  20. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  21. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  22. require_once DOL_DOCUMENT_ROOT.'/stripe/config.php'; // This set stripe global env
  23. /**
  24. * Stripe class
  25. */
  26. class Stripe extends CommonObject
  27. {
  28. /**
  29. * @var int ID
  30. */
  31. public $rowid;
  32. /**
  33. * @var int Thirdparty ID
  34. */
  35. public $fk_soc;
  36. /**
  37. * @var int ID
  38. */
  39. public $fk_key;
  40. /**
  41. * @var int ID
  42. */
  43. public $id;
  44. public $mode;
  45. /**
  46. * @var int Entity
  47. */
  48. public $entity;
  49. public $statut;
  50. public $type;
  51. public $code;
  52. public $declinecode;
  53. /**
  54. * @var string Message
  55. */
  56. public $message;
  57. /**
  58. * Constructor
  59. *
  60. * @param DoliDB $db Database handler
  61. */
  62. public function __construct($db)
  63. {
  64. $this->db = $db;
  65. }
  66. /**
  67. * Return main company OAuth Connect stripe account
  68. *
  69. * @param string $mode 'StripeTest' or 'StripeLive'
  70. * @param int $fk_soc Id of thirdparty
  71. * @param int $entity Id of entity (-1 = current environment)
  72. * @return string Stripe account 'acc_....' or '' if no OAuth token found
  73. */
  74. public function getStripeAccount($mode = 'StripeTest', $fk_soc = 0, $entity = -1)
  75. {
  76. global $conf;
  77. $key = '';
  78. if ($entity < 0) {
  79. $entity = $conf->entity;
  80. }
  81. $sql = "SELECT tokenstring";
  82. $sql .= " FROM ".MAIN_DB_PREFIX."oauth_token";
  83. $sql .= " WHERE service = '".$this->db->escape($mode)."'";
  84. $sql .= " AND entity = ".((int) $entity);
  85. if ($fk_soc > 0) {
  86. $sql .= " AND fk_soc = ".((int) $fk_soc);
  87. } else {
  88. $sql .= " AND fk_soc IS NULL";
  89. }
  90. $sql .= " AND fk_user IS NULL AND fk_adherent IS NULL";
  91. dol_syslog(get_class($this)."::getStripeAccount", LOG_DEBUG);
  92. $result = $this->db->query($sql);
  93. if ($result) {
  94. if ($this->db->num_rows($result)) {
  95. $obj = $this->db->fetch_object($result);
  96. $tokenstring = $obj->tokenstring;
  97. if ($tokenstring) {
  98. $tmparray = json_decode($tokenstring);
  99. $key = empty($tmparray->stripe_user_id) ? '' : $tmparray->stripe_user_id;
  100. }
  101. } else {
  102. $tokenstring = '';
  103. }
  104. } else {
  105. dol_print_error($this->db);
  106. }
  107. dol_syslog("No dedicated Stripe Connect account available for entity ".$conf->entity);
  108. return $key;
  109. }
  110. /**
  111. * getStripeCustomerAccount
  112. *
  113. * @param int $id Id of third party
  114. * @param int $status Status
  115. * @param string $site_account Value to use to identify with account to use on site when site can offer several accounts. For example: 'pk_live_123456' when using Stripe service.
  116. * @return string Stripe customer ref 'cu_xxxxxxxxxxxxx' or ''
  117. */
  118. public function getStripeCustomerAccount($id, $status = 0, $site_account = '')
  119. {
  120. include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
  121. $societeaccount = new SocieteAccount($this->db);
  122. return $societeaccount->getCustomerAccount($id, 'stripe', $status, $site_account); // Get thirdparty cus_...
  123. }
  124. /**
  125. * Get the Stripe customer of a thirdparty (with option to create it in Stripe if not linked yet).
  126. * Search on site_account = 0 or = $stripearrayofkeysbyenv[$status]['publishable_key']
  127. *
  128. * @param Societe $object Object thirdparty to check, or create on stripe (create on stripe also update the stripe_account table for current entity)
  129. * @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect
  130. * @param int $status Status (0=test, 1=live)
  131. * @param int $createifnotlinkedtostripe 1=Create the stripe customer and the link if the thirdparty is not yet linked to a stripe customer
  132. * @return \Stripe\Customer|null Stripe Customer or null if not found
  133. */
  134. public function customerStripe(Societe $object, $key = '', $status = 0, $createifnotlinkedtostripe = 0)
  135. {
  136. global $conf, $user;
  137. if (empty($object->id)) {
  138. dol_syslog("customerStripe is called with the parameter object that is not loaded");
  139. return null;
  140. }
  141. $customer = null;
  142. // Force to use the correct API key
  143. global $stripearrayofkeysbyenv;
  144. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
  145. $sql = "SELECT sa.key_account as key_account, sa.entity"; // key_account is cus_....
  146. $sql .= " FROM ".MAIN_DB_PREFIX."societe_account as sa";
  147. $sql .= " WHERE sa.fk_soc = ".((int) $object->id);
  148. $sql .= " AND sa.entity IN (".getEntity('societe').")";
  149. $sql .= " AND sa.site = 'stripe' AND sa.status = ".((int) $status);
  150. $sql .= " AND (sa.site_account IS NULL OR sa.site_account = '' OR sa.site_account = '".$this->db->escape($stripearrayofkeysbyenv[$status]['publishable_key'])."')";
  151. $sql .= " AND sa.key_account IS NOT NULL AND sa.key_account <> ''";
  152. dol_syslog(get_class($this)."::customerStripe search stripe customer id for thirdparty id=".$object->id, LOG_DEBUG);
  153. $resql = $this->db->query($sql);
  154. if ($resql) {
  155. $num = $this->db->num_rows($resql);
  156. if ($num) {
  157. $obj = $this->db->fetch_object($resql);
  158. $tiers = $obj->key_account;
  159. dol_syslog(get_class($this)."::customerStripe found stripe customer key_account = ".$tiers.". We will try to read it on Stripe with publishable_key = ".$stripearrayofkeysbyenv[$status]['publishable_key']);
  160. try {
  161. if (empty($key)) { // If the Stripe connect account not set, we use common API usage
  162. //$customer = \Stripe\Customer::retrieve("$tiers");
  163. $customer = \Stripe\Customer::retrieve(array('id'=>"$tiers", 'expand[]'=>'sources'));
  164. } else {
  165. //$customer = \Stripe\Customer::retrieve("$tiers", array("stripe_account" => $key));
  166. $customer = \Stripe\Customer::retrieve(array('id'=>"$tiers", 'expand[]'=>'sources'), array("stripe_account" => $key));
  167. }
  168. } catch (Exception $e) {
  169. // For exemple, we may have error: 'No such customer: cus_XXXXX; a similar object exists in live mode, but a test mode key was used to make this request.'
  170. $this->error = $e->getMessage();
  171. }
  172. } elseif ($createifnotlinkedtostripe) {
  173. $ipaddress = getUserRemoteIP();
  174. $dataforcustomer = array(
  175. "email" => $object->email,
  176. "description" => $object->name,
  177. "metadata" => array('dol_id'=>$object->id, 'dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress)
  178. );
  179. $vatcleaned = $object->tva_intra ? $object->tva_intra : null;
  180. /*
  181. $taxinfo = array('type'=>'vat');
  182. if ($vatcleaned)
  183. {
  184. $taxinfo["tax_id"] = $vatcleaned;
  185. }
  186. // We force data to "null" if not defined as expected by Stripe
  187. if (empty($vatcleaned)) $taxinfo=null;
  188. $dataforcustomer["tax_info"] = $taxinfo;
  189. */
  190. //$a = \Stripe\Stripe::getApiKey();
  191. //var_dump($a);var_dump($key);exit;
  192. try {
  193. // Force to use the correct API key
  194. global $stripearrayofkeysbyenv;
  195. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
  196. if (empty($key)) { // If the Stripe connect account not set, we use common API usage
  197. $customer = \Stripe\Customer::create($dataforcustomer);
  198. } else {
  199. $customer = \Stripe\Customer::create($dataforcustomer, array("stripe_account" => $key));
  200. }
  201. // Create the VAT record in Stripe
  202. if (!empty($conf->global->STRIPE_SAVE_TAX_IDS)) { // We setup to save Tax info on Stripe side. Warning: This may result in error when saving customer
  203. if (!empty($vatcleaned)) {
  204. $isineec = isInEEC($object);
  205. if ($object->country_code && $isineec) {
  206. //$taxids = $customer->allTaxIds($customer->id);
  207. $customer->createTaxId($customer->id, array('type'=>'eu_vat', 'value'=>$vatcleaned));
  208. }
  209. }
  210. }
  211. // Create customer in Dolibarr
  212. $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_account (fk_soc, login, key_account, site, site_account, status, entity, date_creation, fk_user_creat)";
  213. $sql .= " VALUES (".((int) $object->id).", '', '".$this->db->escape($customer->id)."', 'stripe', '".$this->db->escape($stripearrayofkeysbyenv[$status]['publishable_key'])."', ".((int) $status).", ".((int) $conf->entity).", '".$this->db->idate(dol_now())."', ".((int) $user->id).")";
  214. $resql = $this->db->query($sql);
  215. if (!$resql) {
  216. $this->error = $this->db->lasterror();
  217. }
  218. } catch (Exception $e) {
  219. $this->error = $e->getMessage();
  220. }
  221. }
  222. } else {
  223. dol_print_error($this->db);
  224. }
  225. return $customer;
  226. }
  227. /**
  228. * Get the Stripe payment method Object from its ID
  229. *
  230. * @param string $paymentmethod Payment Method ID
  231. * @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect
  232. * @param int $status Status (0=test, 1=live)
  233. * @return \Stripe\PaymentMethod|null Stripe PaymentMethod or null if not found
  234. */
  235. public function getPaymentMethodStripe($paymentmethod, $key = '', $status = 0)
  236. {
  237. $stripepaymentmethod = null;
  238. try {
  239. // Force to use the correct API key
  240. global $stripearrayofkeysbyenv;
  241. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
  242. if (empty($key)) { // If the Stripe connect account not set, we use common API usage
  243. $stripepaymentmethod = \Stripe\PaymentMethod::retrieve((string) $paymentmethod->id);
  244. } else {
  245. $stripepaymentmethod = \Stripe\PaymentMethod::retrieve((string) $paymentmethod->id, array("stripe_account" => $key));
  246. }
  247. } catch (Exception $e) {
  248. $this->error = $e->getMessage();
  249. }
  250. return $stripepaymentmethod;
  251. }
  252. /**
  253. * Get the Stripe reader Object from its ID
  254. *
  255. * @param string $reader Reader ID
  256. * @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect
  257. * @param int $status Status (0=test, 1=live)
  258. * @return \Stripe\Terminal\Reader|null Stripe Reader or null if not found
  259. */
  260. public function getSelectedReader($reader, $key = '', $status = 0)
  261. {
  262. $selectedreader = null;
  263. try {
  264. // Force to use the correct API key
  265. global $stripearrayofkeysbyenv;
  266. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
  267. if (empty($key)) { // If the Stripe connect account not set, we use common API usage
  268. $selectedreader = \Stripe\Terminal\Reader::retrieve((string) $reader);
  269. } else {
  270. $stripepaymentmethod = \Stripe\Terminal\Reader::retrieve((string) $reader, array("stripe_account" => $key));
  271. }
  272. } catch (Exception $e) {
  273. $this->error = $e->getMessage();
  274. }
  275. return $selectedreader;
  276. }
  277. /**
  278. * Get the Stripe payment intent. Create it with confirmnow=false
  279. * Warning. If a payment was tried and failed, a payment intent was created.
  280. * But if we change something on object to pay (amount or other), reusing same payment intent is not allowed by Stripe.
  281. * Recommended solution is to recreate a new payment intent each time we need one (old one will be automatically closed after a delay),
  282. * that's why i comment the part of code to retrieve a payment intent with object id (never mind if we cumulate payment intent with old ones that will not be used)
  283. * Note: This is used when option STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION is on when making a payment from the public/payment/newpayment.php page
  284. * but not when using the STRIPE_USE_NEW_CHECKOUT.
  285. *
  286. * @param double $amount Amount
  287. * @param string $currency_code Currency code
  288. * @param string $tag Tag
  289. * @param string $description Description
  290. * @param mixed $object Object to pay with Stripe
  291. * @param string $customer Stripe customer ref 'cus_xxxxxxxxxxxxx' via customerStripe()
  292. * @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect
  293. * @param int $status Status (0=test, 1=live)
  294. * @param int $usethirdpartyemailforreceiptemail 1=use thirdparty email for receipt
  295. * @param int $mode automatic=automatic confirmation/payment when conditions are ok, manual=need to call confirm() on intent
  296. * @param boolean $confirmnow false=default, true=try to confirm immediatly after create (if conditions are ok)
  297. * @param string $payment_method 'pm_....' (if known)
  298. * @param string $off_session If we use an already known payment method to pay when customer is not available during the checkout flow.
  299. * @param string $noidempotency_key Do not use the idempotency_key when creating the PaymentIntent
  300. * @param int $did ID of an existing line into llx_prelevement_demande (Dolibarr intent). If provided, no new line will be created.
  301. * @return \Stripe\PaymentIntent|null Stripe PaymentIntent or null if not found and failed to create
  302. */
  303. public function getPaymentIntent($amount, $currency_code, $tag, $description = '', $object = null, $customer = null, $key = null, $status = 0, $usethirdpartyemailforreceiptemail = 0, $mode = 'automatic', $confirmnow = false, $payment_method = null, $off_session = 0, $noidempotency_key = 1, $did = 0)
  304. {
  305. global $conf, $user;
  306. dol_syslog(get_class($this)."::getPaymentIntent", LOG_INFO, 1);
  307. $error = 0;
  308. if (empty($status)) {
  309. $service = 'StripeTest';
  310. } else {
  311. $service = 'StripeLive';
  312. }
  313. $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
  314. if (!in_array($currency_code, $arrayzerounitcurrency)) {
  315. $stripeamount = $amount * 100;
  316. } else {
  317. $stripeamount = $amount;
  318. }
  319. $fee = 0;
  320. if (getDolGlobalString("STRIPE_APPLICATION_FEE_PERCENT")) {
  321. $fee = $amount * ((float) getDolGlobalString("STRIPE_APPLICATION_FEE_PERCENT", '0') / 100) + (float) getDolGlobalString("STRIPE_APPLICATION_FEE", '0');
  322. }
  323. if ($fee >= (float) getDolGlobalString("STRIPE_APPLICATION_FEE_MAXIMAL", '0') && (float) getDolGlobalString("STRIPE_APPLICATION_FEE_MAXIMAL", '0') > (float) getDolGlobalString("STRIPE_APPLICATION_FEE_MINIMAL", '0')) {
  324. $fee = (float) getDolGlobalString("STRIPE_APPLICATION_FEE_MAXIMAL", '0');
  325. } elseif ($fee < (float) getDolGlobalString("STRIPE_APPLICATION_FEE_MINIMAL", '0')) {
  326. $fee = (float) getDolGlobalString("STRIPE_APPLICATION_FEE_MINIMAL", '0');
  327. }
  328. if (!in_array($currency_code, $arrayzerounitcurrency)) {
  329. $stripefee = round($fee * 100);
  330. } else {
  331. $stripefee = round($fee);
  332. }
  333. $paymentintent = null;
  334. if (is_object($object) && getDolGlobalInt('STRIPE_REUSE_EXISTING_INTENT_IF_FOUND') && !getDolGlobalInt('STRIPE_CARD_PRESENT')) {
  335. // Warning. If a payment was tried and failed, a payment intent was created.
  336. // But if we change something on object to pay (amount or other that does not change the idempotency key), reusing same payment intent is not allowed by Stripe.
  337. // Recommended solution is to recreate a new payment intent each time we need one (old one will be automatically closed by Stripe after a delay), Stripe will
  338. // automatically return the existing payment intent if idempotency is provided when we try to create the new one.
  339. // That's why we can comment the part of code to retrieve a payment intent with object id (never mind if we cumulate payment intent with old ones that will not be used)
  340. $sql = "SELECT pi.ext_payment_id, pi.entity, pi.fk_facture, pi.sourcetype, pi.ext_payment_site";
  341. $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as pi";
  342. $sql .= " WHERE pi.fk_facture = ".((int) $object->id);
  343. $sql .= " AND pi.sourcetype = '".$this->db->escape($object->element)."'";
  344. $sql .= " AND pi.entity IN (".getEntity('societe').")";
  345. $sql .= " AND pi.ext_payment_site = '".$this->db->escape($service)."'";
  346. dol_syslog(get_class($this)."::getPaymentIntent search stripe payment intent for object id = ".$object->id, LOG_DEBUG);
  347. $resql = $this->db->query($sql);
  348. if ($resql) {
  349. $num = $this->db->num_rows($resql);
  350. if ($num) {
  351. $obj = $this->db->fetch_object($resql);
  352. $intent = $obj->ext_payment_id;
  353. dol_syslog(get_class($this)."::getPaymentIntent found existing payment intent record");
  354. // Force to use the correct API key
  355. global $stripearrayofkeysbyenv;
  356. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
  357. try {
  358. if (empty($key)) { // If the Stripe connect account not set, we use common API usage
  359. $paymentintent = \Stripe\PaymentIntent::retrieve($intent);
  360. } else {
  361. $paymentintent = \Stripe\PaymentIntent::retrieve($intent, array("stripe_account" => $key));
  362. }
  363. } catch (Exception $e) {
  364. $error++;
  365. $this->error = $e->getMessage();
  366. }
  367. }
  368. }
  369. }
  370. if (empty($paymentintent)) {
  371. // Try to create intent. See https://stripe.com/docs/api/payment_intents/create
  372. $ipaddress = getUserRemoteIP();
  373. $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress);
  374. if (is_object($object)) {
  375. $metadata['dol_type'] = $object->element;
  376. $metadata['dol_id'] = $object->id;
  377. if (is_object($object->thirdparty) && $object->thirdparty->id > 0) {
  378. $metadata['dol_thirdparty_id'] = $object->thirdparty->id;
  379. }
  380. }
  381. // list of payment method types
  382. $paymentmethodtypes = array("card");
  383. $descriptor = dol_trunc($tag, 10, 'right', 'UTF-8', 1);
  384. if (getDolGlobalInt('STRIPE_SEPA_DIRECT_DEBIT')) {
  385. $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC())
  386. //$descriptor = preg_replace('/ref=[^:=]+/', '', $descriptor); // Clean ref
  387. }
  388. if (getDolGlobalInt('STRIPE_KLARNA')) {
  389. $paymentmethodtypes[] = "klarna";
  390. }
  391. if (getDolGlobalInt('STRIPE_BANCONTACT')) {
  392. $paymentmethodtypes[] = "bancontact";
  393. }
  394. if (getDolGlobalInt('STRIPE_IDEAL')) {
  395. $paymentmethodtypes[] = "ideal";
  396. }
  397. if (getDolGlobalInt('STRIPE_GIROPAY')) {
  398. $paymentmethodtypes[] = "giropay";
  399. }
  400. if (getDolGlobalInt('STRIPE_SOFORT')) {
  401. $paymentmethodtypes[] = "sofort";
  402. }
  403. if (getDolGlobalInt('STRIPE_CARD_PRESENT') && $mode == 'terminal') {
  404. $paymentmethodtypes = array("card_present");
  405. }
  406. $dataforintent = array(
  407. "confirm" => $confirmnow, // Do not confirm immediatly during creation of intent
  408. "confirmation_method" => $mode,
  409. "amount" => $stripeamount,
  410. "currency" => $currency_code,
  411. "payment_method_types" => $paymentmethodtypes,
  412. "description" => $description,
  413. //"save_payment_method" => true,
  414. "setup_future_usage" => "on_session",
  415. "metadata" => $metadata
  416. );
  417. if ($descriptor) {
  418. $dataforintent["statement_descriptor_suffix"] = $descriptor; // For card payment, 22 chars that appears on bank receipt (prefix into stripe setup + this suffix)
  419. $dataforintent["statement_descriptor"] = $descriptor; // For SEPA, it will take only statement_descriptor, not statement_descriptor_suffix
  420. }
  421. if (!is_null($customer)) {
  422. $dataforintent["customer"] = $customer;
  423. }
  424. // payment_method =
  425. // payment_method_types = array('card')
  426. //var_dump($dataforintent);
  427. if ($off_session) {
  428. unset($dataforintent['setup_future_usage']);
  429. // We can't use both "setup_future_usage" = "off_session" and "off_session" = true.
  430. // Because $off_session parameter is dedicated to create paymentintent off_line (and not future payment), we need to use "off_session" = true.
  431. //$dataforintent["setup_future_usage"] = "off_session";
  432. $dataforintent["off_session"] = true;
  433. }
  434. if (getDolGlobalInt('STRIPE_GIROPAY')) {
  435. unset($dataforintent['setup_future_usage']);
  436. }
  437. if (getDolGlobalInt('STRIPE_KLARNA')) {
  438. unset($dataforintent['setup_future_usage']);
  439. }
  440. if (getDolGlobalInt('STRIPE_CARD_PRESENT') && $mode == 'terminal') {
  441. unset($dataforintent['setup_future_usage']);
  442. $dataforintent["capture_method"] = "manual";
  443. $dataforintent["confirmation_method"] = "manual";
  444. }
  445. if (!is_null($payment_method)) {
  446. $dataforintent["payment_method"] = $payment_method;
  447. $description .= ' - '.$payment_method;
  448. }
  449. if ($conf->entity != getDolGlobalInt('STRIPECONNECT_PRINCIPAL') && $stripefee > 0) {
  450. $dataforintent["application_fee_amount"] = $stripefee;
  451. }
  452. if ($usethirdpartyemailforreceiptemail && is_object($object) && $object->thirdparty->email) {
  453. $dataforintent["receipt_email"] = $object->thirdparty->email;
  454. }
  455. try {
  456. // Force to use the correct API key
  457. global $stripearrayofkeysbyenv;
  458. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
  459. $arrayofoptions = array();
  460. if (empty($noidempotency_key)) {
  461. $arrayofoptions["idempotency_key"] = $description;
  462. }
  463. // Note: If all data for payment intent are same than a previous on, even if we use 'create', Stripe will return ID of the old existing payment intent.
  464. if (!empty($key)) { // If the Stripe connect account not set, we use common API usage
  465. $arrayofoptions["stripe_account"] = $key;
  466. }
  467. dol_syslog("dataforintent to create paymentintent = ".var_export($dataforintent, true));
  468. $paymentintent = \Stripe\PaymentIntent::create($dataforintent, $arrayofoptions);
  469. // Store the payment intent
  470. if (is_object($object)) {
  471. $paymentintentalreadyexists = 0;
  472. if ($did > 0) {
  473. // If a payment request line provided, we do not need to recreate one, we just update it
  474. dol_syslog(get_class($this)."::getPaymentIntent search if payment intent already in prelevement_demande", LOG_DEBUG);
  475. $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_demande SET";
  476. $sql .= " ext_payment_site = '".$this->db->escape($service)."',";
  477. $sql .= " ext_payment_id = '".$this->db->escape($paymentintent->id)."'";
  478. $sql .= " WHERE rowid = ".((int) $did);
  479. $resql = $this->db->query($sql);
  480. if ($resql) {
  481. $paymentintentalreadyexists++;
  482. } else {
  483. $error++;
  484. dol_print_error($this->db);
  485. }
  486. } else {
  487. // Check that payment intent $paymentintent->id is not already recorded.
  488. dol_syslog(get_class($this)."::getPaymentIntent search if payment intent already in prelevement_demande", LOG_DEBUG);
  489. $sql = "SELECT pi.rowid";
  490. $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_demande as pi";
  491. $sql .= " WHERE pi.entity IN (".getEntity('societe').")";
  492. $sql .= " AND pi.ext_payment_site = '".$this->db->escape($service)."'";
  493. $sql .= " AND pi.ext_payment_id = '".$this->db->escape($paymentintent->id)."'";
  494. $resql = $this->db->query($sql);
  495. if ($resql) {
  496. $num = $this->db->num_rows($resql);
  497. if ($num) {
  498. $obj = $this->db->fetch_object($resql);
  499. if ($obj) {
  500. $paymentintentalreadyexists++;
  501. }
  502. }
  503. } else {
  504. $error++;
  505. dol_print_error($this->db);
  506. }
  507. }
  508. // If not, we create it.
  509. if (!$error && !$paymentintentalreadyexists) {
  510. $now = dol_now();
  511. $sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_demande (date_demande, fk_user_demande, ext_payment_id, fk_facture, sourcetype, entity, ext_payment_site, amount)";
  512. $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $user->id).", '".$this->db->escape($paymentintent->id)."', ".((int) $object->id).", '".$this->db->escape($object->element)."', ".((int) $conf->entity).", '".$this->db->escape($service)."', ".((float) $amount).")";
  513. $resql = $this->db->query($sql);
  514. if (!$resql) {
  515. $error++;
  516. $this->error = $this->db->lasterror();
  517. dol_syslog(get_class($this)."::PaymentIntent failed to insert paymentintent with id=".$paymentintent->id." into database.", LOG_ERR);
  518. }
  519. }
  520. } else {
  521. $_SESSION["stripe_payment_intent"] = $paymentintent;
  522. }
  523. } catch (Stripe\Error\Card $e) {
  524. $error++;
  525. $this->error = $e->getMessage();
  526. $this->code = $e->getStripeCode();
  527. $this->declinecode = $e->getDeclineCode();
  528. } catch (Exception $e) {
  529. //var_dump($dataforintent);
  530. //var_dump($description);
  531. //var_dump($key);
  532. //var_dump($paymentintent);
  533. //var_dump($e->getMessage());
  534. //var_dump($e);
  535. $error++;
  536. $this->error = $e->getMessage();
  537. $this->code = '';
  538. $this->declinecode = '';
  539. }
  540. }
  541. dol_syslog(get_class($this)."::getPaymentIntent return error=".$error." this->error=".$this->error, LOG_INFO, -1);
  542. if (!$error) {
  543. return $paymentintent;
  544. } else {
  545. return null;
  546. }
  547. }
  548. /**
  549. * Get the Stripe payment intent. Create it with confirmnow=false
  550. * Warning. If a payment was tried and failed, a payment intent was created.
  551. * But if we change something on object to pay (amount or other), reusing same payment intent is not allowed.
  552. * Recommanded solution is to recreate a new payment intent each time we need one (old one will be automatically closed after a delay),
  553. * that's why i comment the part of code to retrieve a payment intent with object id (never mind if we cumulate payment intent with old ones that will not be used)
  554. * Note: This is used when option STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION is on when making a payment from the public/payment/newpayment.php page
  555. * but not when using the STRIPE_USE_NEW_CHECKOUT.
  556. *
  557. * @param string $description Description
  558. * @param Societe $object Object of company to link the Stripe payment mode with
  559. * @param string $customer Stripe customer ref 'cus_xxxxxxxxxxxxx' via customerStripe()
  560. * @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect
  561. * @param int $status Status (0=test, 1=live)
  562. * @param int $usethirdpartyemailforreceiptemail 1=use thirdparty email for receipt
  563. * @param boolean $confirmnow false=default, true=try to confirm immediatly after create (if conditions are ok)
  564. * @return \Stripe\SetupIntent|null Stripe SetupIntent or null if not found and failed to create
  565. */
  566. public function getSetupIntent($description, $object, $customer, $key, $status, $usethirdpartyemailforreceiptemail = 0, $confirmnow = false)
  567. {
  568. global $conf;
  569. dol_syslog("getSetupIntent description=".$description.' confirmnow='.$confirmnow, LOG_INFO, 1);
  570. $error = 0;
  571. if (empty($status)) {
  572. $service = 'StripeTest';
  573. } else {
  574. $service = 'StripeLive';
  575. }
  576. $setupintent = null;
  577. if (empty($setupintent)) {
  578. $ipaddress = getUserRemoteIP();
  579. $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress);
  580. if (is_object($object)) {
  581. $metadata['dol_type'] = $object->element;
  582. $metadata['dol_id'] = $object->id;
  583. if (is_object($object->thirdparty) && $object->thirdparty->id > 0) {
  584. $metadata['dol_thirdparty_id'] = $object->thirdparty->id;
  585. }
  586. }
  587. // list of payment method types
  588. $paymentmethodtypes = array("card");
  589. if (!empty($conf->global->STRIPE_SEPA_DIRECT_DEBIT)) {
  590. $paymentmethodtypes[] = "sepa_debit"; //&& ($object->thirdparty->isInEEC())
  591. }
  592. if (!empty($conf->global->STRIPE_BANCONTACT)) {
  593. $paymentmethodtypes[] = "bancontact";
  594. }
  595. if (!empty($conf->global->STRIPE_IDEAL)) {
  596. $paymentmethodtypes[] = "ideal";
  597. }
  598. // Giropay not possible for setup intent
  599. if (!empty($conf->global->STRIPE_SOFORT)) {
  600. $paymentmethodtypes[] = "sofort";
  601. }
  602. $dataforintent = array(
  603. "confirm" => $confirmnow, // Do not confirm immediatly during creation of intent
  604. "payment_method_types" => $paymentmethodtypes,
  605. "usage" => "off_session",
  606. "metadata" => $metadata
  607. );
  608. if (!is_null($customer)) {
  609. $dataforintent["customer"] = $customer;
  610. }
  611. if (!is_null($description)) {
  612. $dataforintent["description"] = $description;
  613. }
  614. // payment_method =
  615. // payment_method_types = array('card')
  616. //var_dump($dataforintent);
  617. if ($usethirdpartyemailforreceiptemail && is_object($object) && $object->thirdparty->email) {
  618. $dataforintent["receipt_email"] = $object->thirdparty->email;
  619. }
  620. try {
  621. // Force to use the correct API key
  622. global $stripearrayofkeysbyenv;
  623. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
  624. dol_syslog("getSetupIntent ".$stripearrayofkeysbyenv[$status]['publishable_key'], LOG_DEBUG);
  625. // Note: If all data for payment intent are same than a previous on, even if we use 'create', Stripe will return ID of the old existing payment intent.
  626. if (empty($key)) { // If the Stripe connect account not set, we use common API usage
  627. //$setupintent = \Stripe\SetupIntent::create($dataforintent, array("idempotency_key" => "$description"));
  628. $setupintent = \Stripe\SetupIntent::create($dataforintent, array());
  629. } else {
  630. //$setupintent = \Stripe\SetupIntent::create($dataforintent, array("idempotency_key" => "$description", "stripe_account" => $key));
  631. $setupintent = \Stripe\SetupIntent::create($dataforintent, array("stripe_account" => $key));
  632. }
  633. //var_dump($setupintent->id);
  634. // Store the setup intent
  635. /*if (is_object($object))
  636. {
  637. $setupintentalreadyexists = 0;
  638. // Check that payment intent $setupintent->id is not already recorded.
  639. $sql = "SELECT pi.rowid";
  640. $sql.= " FROM " . MAIN_DB_PREFIX . "prelevement_demande as pi";
  641. $sql.= " WHERE pi.entity IN (".getEntity('societe').")";
  642. $sql.= " AND pi.ext_payment_site = '" . $this->db->escape($service) . "'";
  643. $sql.= " AND pi.ext_payment_id = '".$this->db->escape($setupintent->id)."'";
  644. dol_syslog(get_class($this) . "::getPaymentIntent search if payment intent already in prelevement_demande", LOG_DEBUG);
  645. $resql = $this->db->query($sql);
  646. if ($resql) {
  647. $num = $this->db->num_rows($resql);
  648. if ($num)
  649. {
  650. $obj = $this->db->fetch_object($resql);
  651. if ($obj) $setupintentalreadyexists++;
  652. }
  653. }
  654. else dol_print_error($this->db);
  655. // If not, we create it.
  656. if (! $setupintentalreadyexists)
  657. {
  658. $now=dol_now();
  659. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "prelevement_demande (date_demande, fk_user_demande, ext_payment_id, fk_facture, sourcetype, entity, ext_payment_site)";
  660. $sql .= " VALUES ('".$this->db->idate($now)."', ".((int) $user->id).", '".$this->db->escape($setupintent->id)."', ".((int) $object->id).", '".$this->db->escape($object->element)."', " . ((int) $conf->entity) . ", '" . $this->db->escape($service) . "', ".((float) $amount).")";
  661. $resql = $this->db->query($sql);
  662. if (! $resql)
  663. {
  664. $error++;
  665. $this->error = $this->db->lasterror();
  666. dol_syslog(get_class($this) . "::PaymentIntent failed to insert paymentintent with id=".$setupintent->id." into database.");
  667. }
  668. }
  669. }
  670. else
  671. {
  672. $_SESSION["stripe_setup_intent"] = $setupintent;
  673. }*/
  674. } catch (Exception $e) {
  675. //var_dump($dataforintent);
  676. //var_dump($description);
  677. //var_dump($key);
  678. //var_dump($setupintent);
  679. //var_dump($e->getMessage());
  680. $error++;
  681. $this->error = $e->getMessage();
  682. }
  683. }
  684. if (!$error) {
  685. dol_syslog("getSetupIntent ".(is_object($setupintent) ? $setupintent->id : ''), LOG_INFO, -1);
  686. return $setupintent;
  687. } else {
  688. dol_syslog("getSetupIntent return error=".$error, LOG_INFO, -1);
  689. return null;
  690. }
  691. }
  692. /**
  693. * Get the Stripe card of a company payment mode (option to create it on Stripe if not linked yet is no more available on new Stripe API)
  694. *
  695. * @param \Stripe\Customer $cu Object stripe customer.
  696. * @param CompanyPaymentMode $object Object companypaymentmode to check, or create on stripe (create on stripe also update the societe_rib table for current entity)
  697. * @param string $stripeacc ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect
  698. * @param int $status Status (0=test, 1=live)
  699. * @param int $createifnotlinkedtostripe 1=Create the stripe card and the link if the card is not yet linked to a stripe card. Deprecated with new Stripe API and SCA.
  700. * @return \Stripe\Card|\Stripe\PaymentMethod|null Stripe Card or null if not found
  701. */
  702. public function cardStripe($cu, CompanyPaymentMode $object, $stripeacc = '', $status = 0, $createifnotlinkedtostripe = 0)
  703. {
  704. global $conf, $user, $langs;
  705. $card = null;
  706. $sql = "SELECT sa.stripe_card_ref, sa.proprio, sa.exp_date_month, sa.exp_date_year, sa.number, sa.cvn"; // stripe_card_ref is card_....
  707. $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib as sa";
  708. $sql .= " WHERE sa.rowid = ".((int) $object->id); // We get record from ID, no need for filter on entity
  709. $sql .= " AND sa.type = 'card'";
  710. dol_syslog(get_class($this)."::cardStripe search stripe card id for paymentmode id=".$object->id.", stripeacc=".$stripeacc.", status=".$status.", createifnotlinkedtostripe=".$createifnotlinkedtostripe, LOG_DEBUG);
  711. $resql = $this->db->query($sql);
  712. if ($resql) {
  713. $num = $this->db->num_rows($resql);
  714. if ($num) {
  715. $obj = $this->db->fetch_object($resql);
  716. $cardref = $obj->stripe_card_ref;
  717. dol_syslog(get_class($this)."::cardStripe cardref=".$cardref);
  718. if ($cardref) {
  719. try {
  720. if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage
  721. if (!preg_match('/^pm_/', $cardref) && !empty($cu->sources)) {
  722. $card = $cu->sources->retrieve($cardref);
  723. } else {
  724. $card = \Stripe\PaymentMethod::retrieve($cardref);
  725. }
  726. } else {
  727. if (!preg_match('/^pm_/', $cardref) && !empty($cu->sources)) {
  728. //$card = $cu->sources->retrieve($cardref, array("stripe_account" => $stripeacc)); // this API fails when array stripe_account is provided
  729. $card = $cu->sources->retrieve($cardref);
  730. } else {
  731. //$card = \Stripe\PaymentMethod::retrieve($cardref, array("stripe_account" => $stripeacc)); // Don't know if this works
  732. $card = \Stripe\PaymentMethod::retrieve($cardref);
  733. }
  734. }
  735. } catch (Exception $e) {
  736. $this->error = $e->getMessage();
  737. dol_syslog($this->error, LOG_WARNING);
  738. }
  739. } elseif ($createifnotlinkedtostripe) {
  740. // Deprecated with new Stripe API and SCA. We should not use anymore this part of code now.
  741. $exp_date_month = $obj->exp_date_month;
  742. $exp_date_year = $obj->exp_date_year;
  743. $number = $obj->number;
  744. $cvc = $obj->cvn; // cvn in database, cvc for stripe
  745. $cardholdername = $obj->proprio;
  746. $ipaddress = getUserRemoteIP();
  747. $dataforcard = array(
  748. "source" => array(
  749. 'object'=>'card',
  750. 'exp_month'=>$exp_date_month,
  751. 'exp_year'=>$exp_date_year,
  752. 'number'=>$number,
  753. 'cvc'=>$cvc,
  754. 'name'=>$cardholdername
  755. ),
  756. "metadata" => array(
  757. 'dol_type'=>$object->element,
  758. 'dol_id'=>$object->id,
  759. 'dol_version'=>DOL_VERSION,
  760. 'dol_entity'=>$conf->entity,
  761. 'ipaddress'=>$ipaddress
  762. )
  763. );
  764. //$a = \Stripe\Stripe::getApiKey();
  765. //var_dump($a);
  766. //var_dump($stripeacc);exit;
  767. try {
  768. if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage
  769. if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) {
  770. dol_syslog("Try to create card with dataforcard = ".json_encode($dataforcard));
  771. $card = $cu->sources->create($dataforcard);
  772. if (!$card) {
  773. $this->error = 'Creation of card on Stripe has failed';
  774. }
  775. } else {
  776. $connect = '';
  777. if (!empty($stripeacc)) {
  778. $connect = $stripeacc.'/';
  779. }
  780. $url = 'https://dashboard.stripe.com/'.$connect.'test/customers/'.$cu->id;
  781. if ($status) {
  782. $url = 'https://dashboard.stripe.com/'.$connect.'customers/'.$cu->id;
  783. }
  784. $urtoswitchonstripe = '<a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe'), 'globe').'</a>';
  785. //dol_syslog("Error: This case is not supported", LOG_ERR);
  786. $this->error = str_replace('{s1}', $urtoswitchonstripe, $langs->trans('CreationOfPaymentModeMustBeDoneFromStripeInterface', '{s1}'));
  787. }
  788. } else {
  789. if (empty($conf->global->STRIPE_USE_INTENT_WITH_AUTOMATIC_CONFIRMATION)) {
  790. dol_syslog("Try to create card with dataforcard = ".json_encode($dataforcard));
  791. $card = $cu->sources->create($dataforcard, array("stripe_account" => $stripeacc));
  792. if (!$card) {
  793. $this->error = 'Creation of card on Stripe has failed';
  794. }
  795. } else {
  796. $connect = '';
  797. if (!empty($stripeacc)) {
  798. $connect = $stripeacc.'/';
  799. }
  800. $url = 'https://dashboard.stripe.com/'.$connect.'test/customers/'.$cu->id;
  801. if ($status) {
  802. $url = 'https://dashboard.stripe.com/'.$connect.'customers/'.$cu->id;
  803. }
  804. $urtoswitchonstripe = '<a href="'.$url.'" target="_stripe">'.img_picto($langs->trans('ShowInStripe'), 'globe').'</a>';
  805. //dol_syslog("Error: This case is not supported", LOG_ERR);
  806. $this->error = str_replace('{s1}', $urtoswitchonstripe, $langs->trans('CreationOfPaymentModeMustBeDoneFromStripeInterface', '{s1}'));
  807. }
  808. }
  809. if ($card) {
  810. $sql = "UPDATE ".MAIN_DB_PREFIX."societe_rib";
  811. $sql .= " SET stripe_card_ref = '".$this->db->escape($card->id)."', card_type = '".$this->db->escape($card->brand)."',";
  812. $sql .= " country_code = '".$this->db->escape($card->country)."',";
  813. $sql .= " approved = ".($card->cvc_check == 'pass' ? 1 : 0);
  814. $sql .= " WHERE rowid = ".((int) $object->id);
  815. $sql .= " AND type = 'card'";
  816. $resql = $this->db->query($sql);
  817. if (!$resql) {
  818. $this->error = $this->db->lasterror();
  819. }
  820. }
  821. } catch (Exception $e) {
  822. $this->error = $e->getMessage();
  823. dol_syslog($this->error, LOG_WARNING);
  824. }
  825. }
  826. }
  827. } else {
  828. dol_print_error($this->db);
  829. }
  830. return $card;
  831. }
  832. /**
  833. * Get the Stripe SEPA of a company payment mode (create it if it doesn't exists and $createifnotlinkedtostripe is set)
  834. *
  835. * @param \Stripe\Customer $cu Object stripe customer.
  836. * @param CompanyPaymentMode $object Object companypaymentmode to check, or create on stripe (create on stripe also update the societe_rib table for current entity)
  837. * @param string $stripeacc ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect
  838. * @param int $status Status (0=test, 1=live)
  839. * @param int $createifnotlinkedtostripe 1=Create the stripe sepa and the link if the sepa is not yet linked to a stripe sepa. Used by the "Create bank to Stripe" feature.
  840. * @return \Stripe\PaymentMethod|null Stripe SEPA or null if not found
  841. */
  842. public function sepaStripe($cu, CompanyPaymentMode $object, $stripeacc = '', $status = 0, $createifnotlinkedtostripe = 0)
  843. {
  844. global $conf;
  845. $sepa = null;
  846. $sql = "SELECT sa.stripe_card_ref, sa.proprio, sa.iban_prefix as iban, sa.rum"; // stripe_card_ref is 'src_...' for Stripe SEPA
  847. $sql .= " FROM ".MAIN_DB_PREFIX."societe_rib as sa";
  848. $sql .= " WHERE sa.rowid = ".((int) $object->id); // We get record from ID, no need for filter on entity
  849. $sql .= " AND sa.type = 'ban'"; //type ban to get normal bank account of customer (prelevement)
  850. $soc = new Societe($this->db);
  851. $soc->fetch($object->fk_soc);
  852. dol_syslog(get_class($this)."::sepaStripe search stripe ban id for paymentmode id=".$object->id.", stripeacc=".$stripeacc.", status=".$status.", createifnotlinkedtostripe=".$createifnotlinkedtostripe, LOG_DEBUG);
  853. $resql = $this->db->query($sql);
  854. if ($resql) {
  855. $num = $this->db->num_rows($resql);
  856. if ($num) {
  857. $obj = $this->db->fetch_object($resql);
  858. $cardref = $obj->stripe_card_ref;
  859. dol_syslog(get_class($this)."::sepaStripe paymentmode=".$cardref);
  860. if ($cardref) {
  861. try {
  862. if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage
  863. if (!preg_match('/^pm_/', $cardref) && !empty($cu->sources)) {
  864. $sepa = $cu->sources->retrieve($cardref);
  865. } else {
  866. $sepa = \Stripe\PaymentMethod::retrieve($cardref);
  867. }
  868. } else {
  869. if (!preg_match('/^pm_/', $cardref) && !empty($cu->sources)) {
  870. //$sepa = $cu->sources->retrieve($cardref, array("stripe_account" => $stripeacc)); // this API fails when array stripe_account is provided
  871. $sepa = $cu->sources->retrieve($cardref);
  872. } else {
  873. //$sepa = \Stripe\PaymentMethod::retrieve($cardref, array("stripe_account" => $stripeacc)); // Don't know if this works
  874. $sepa = \Stripe\PaymentMethod::retrieve($cardref);
  875. }
  876. }
  877. } catch (Exception $e) {
  878. $this->error = $e->getMessage();
  879. dol_syslog($this->error, LOG_WARNING);
  880. }
  881. } elseif ($createifnotlinkedtostripe) {
  882. $iban = $obj->iban;
  883. $ipaddress = getUserRemoteIP();
  884. $metadata = array('dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>$ipaddress);
  885. if (is_object($object)) {
  886. $metadata['dol_type'] = $object->element;
  887. $metadata['dol_id'] = $object->id;
  888. $metadata['dol_thirdparty_id'] = $soc->id;
  889. }
  890. $description = 'SEPA for IBAN '.$iban;
  891. $dataforcard = array(
  892. 'type'=>'sepa_debit',
  893. "sepa_debit" => array('iban' => $iban),
  894. 'billing_details' => array(
  895. 'name' => $soc->name,
  896. 'email' => !empty($soc->email) ? $soc->email : "",
  897. ),
  898. "metadata" => $metadata
  899. );
  900. // Complete owner name
  901. if (!empty($soc->town)) {
  902. $dataforcard['billing_details']['address']['city']=$soc->town;
  903. }
  904. if (!empty($soc->country_code)) {
  905. $dataforcard['billing_details']['address']['country']=$soc->country_code;
  906. }
  907. if (!empty($soc->address)) {
  908. $dataforcard['billing_details']['address']['line1']=$soc->address;
  909. }
  910. if (!empty($soc->zip)) {
  911. $dataforcard['billing_details']['address']['postal_code']=$soc->zip;
  912. }
  913. if (!empty($soc->state)) {
  914. $dataforcard['billing_details']['address']['state']=$soc->state;
  915. }
  916. //$a = \Stripe\Stripe::getApiKey();
  917. //var_dump($a);var_dump($stripeacc);exit;
  918. try {
  919. dol_syslog("Try to create sepa_debit");
  920. $service = 'StripeTest';
  921. $servicestatus = 0;
  922. if (!empty($conf->global->STRIPE_LIVE) && !GETPOST('forcesandbox', 'alpha')) {
  923. $service = 'StripeLive';
  924. $servicestatus = 1;
  925. }
  926. // Force to use the correct API key
  927. global $stripearrayofkeysbyenv;
  928. $stripeacc = $stripearrayofkeysbyenv[$servicestatus]['secret_key'];
  929. dol_syslog("Try to create sepa_debit with data = ".json_encode($dataforcard));
  930. $s = new \Stripe\StripeClient($stripeacc);
  931. //var_dump($dataforcard);exit;
  932. $sepa = $s->paymentMethods->create($dataforcard);
  933. if (!$sepa) {
  934. $this->error = 'Creation of payment method sepa_debit on Stripe has failed';
  935. } else {
  936. // link customer and src
  937. //$cs = $this->getSetupIntent($description, $soc, $cu, '', $status);
  938. $dataforintent = array(['description'=> $description, 'payment_method_types' => ['sepa_debit'], 'customer' => $cu->id, 'payment_method' => $sepa->id], 'metadata'=>$metadata);
  939. $cs = $s->setupIntents->create($dataforintent);
  940. //$cs = $s->setupIntents->update($cs->id, ['payment_method' => $sepa->id]);
  941. $cs = $s->setupIntents->confirm($cs->id, ['mandate_data' => ['customer_acceptance' => ['type' => 'offline']]]);
  942. // note: $cs->mandate contians ID of mandate on Stripe side
  943. if (!$cs) {
  944. $this->error = 'Link SEPA <-> Customer failed';
  945. } else {
  946. dol_syslog("Update the payment mode of the customer");
  947. // print json_encode($sepa);
  948. // Save the Stripe payment mode ID into the Dolibarr database
  949. $sql = "UPDATE ".MAIN_DB_PREFIX."societe_rib";
  950. $sql .= " SET stripe_card_ref = '".$this->db->escape($sepa->id)."',";
  951. $sql .= " card_type = 'sepa_debit',";
  952. $sql .= " stripe_account= '" . $this->db->escape($cu->id . "@" . $stripeacc) . "',";
  953. $sql .= " ext_payment_site = '".$this->db->escape($service)."'";
  954. if (!empty($cs->mandate)) {
  955. $mandateservice = new \Stripe\Mandate($stripeacc);
  956. $mandate = $mandateservice->retrieve($cs->mandate);
  957. if (is_object($mandate) && is_object($mandate->payment_method_details) && is_object($mandate->payment_method_details->sepa_debit)) {
  958. $refmandate = $mandate->payment_method_details->sepa_debit->reference;
  959. //$urlmandate = $mandate->payment_method_details->sepa_debit->url;
  960. $sql .= ", rum = '".$this->db->escape($refmandate)."'";
  961. }
  962. $sql .= ", comment = '".$this->db->escape($cs->mandate)."'";
  963. $sql .= ", date_rum = '".$this->db->idate(dol_now())."'";
  964. }
  965. $sql .= " WHERE rowid = ".((int) $object->id);
  966. $sql .= " AND type = 'ban'";
  967. $resql = $this->db->query($sql);
  968. if (!$resql) {
  969. $this->error = $this->db->lasterror();
  970. }
  971. }
  972. }
  973. } catch (Exception $e) {
  974. $sepa = null;
  975. $this->error = 'Stripe error: '.$e->getMessage().'. Check the BAN information.';
  976. dol_syslog($this->error, LOG_WARNING); // Error from Stripe, so a warning on Dolibarr
  977. }
  978. }
  979. }
  980. } else {
  981. dol_print_error($this->db);
  982. }
  983. return $sepa;
  984. }
  985. /**
  986. * Create charge.
  987. * This is called by page htdocs/stripe/payment.php and may be deprecated.
  988. *
  989. * @param int $amount Amount to pay
  990. * @param string $currency EUR, GPB...
  991. * @param string $origin Object type to pay (order, invoice, contract...)
  992. * @param int $item Object id to pay
  993. * @param string $source src_xxxxx or card_xxxxx or pm_xxxxx
  994. * @param string $customer Stripe customer ref 'cus_xxxxxxxxxxxxx' via customerStripe()
  995. * @param string $account Stripe account ref 'acc_xxxxxxxxxxxxx' via getStripeAccount()
  996. * @param int $status Status (0=test, 1=live)
  997. * @param int $usethirdpartyemailforreceiptemail Use thirdparty email as receipt email
  998. * @param boolean $capture Set capture flag to true (take payment) or false (wait)
  999. * @return Stripe
  1000. */
  1001. public function createPaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account, $status = 0, $usethirdpartyemailforreceiptemail = 0, $capture = true)
  1002. {
  1003. global $conf;
  1004. $error = 0;
  1005. if (empty($status)) {
  1006. $service = 'StripeTest';
  1007. } else {
  1008. $service = 'StripeLive';
  1009. }
  1010. $sql = "SELECT sa.key_account as key_account, sa.fk_soc, sa.entity";
  1011. $sql .= " FROM ".MAIN_DB_PREFIX."societe_account as sa";
  1012. $sql .= " WHERE sa.key_account = '".$this->db->escape($customer)."'";
  1013. //$sql.= " AND sa.entity IN (".getEntity('societe').")";
  1014. $sql .= " AND sa.site = 'stripe' AND sa.status = ".((int) $status);
  1015. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  1016. $result = $this->db->query($sql);
  1017. if ($result) {
  1018. if ($this->db->num_rows($result)) {
  1019. $obj = $this->db->fetch_object($result);
  1020. $key = $obj->fk_soc;
  1021. } else {
  1022. $key = null;
  1023. }
  1024. } else {
  1025. $key = null;
  1026. }
  1027. $arrayzerounitcurrency = array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
  1028. if (!in_array($currency, $arrayzerounitcurrency)) {
  1029. $stripeamount = $amount * 100;
  1030. } else {
  1031. $stripeamount = $amount;
  1032. }
  1033. $societe = new Societe($this->db);
  1034. if ($key > 0) {
  1035. $societe->fetch($key);
  1036. }
  1037. $description = "";
  1038. $ref = "";
  1039. if ($origin == 'order') {
  1040. $order = new Commande($this->db);
  1041. $order->fetch($item);
  1042. $ref = $order->ref;
  1043. $description = "ORD=".$ref.".CUS=".$societe->id.".PM=stripe";
  1044. } elseif ($origin == 'invoice') {
  1045. $invoice = new Facture($this->db);
  1046. $invoice->fetch($item);
  1047. $ref = $invoice->ref;
  1048. $description = "INV=".$ref.".CUS=".$societe->id.".PM=stripe";
  1049. }
  1050. $ipaddress = getUserRemoteIP();
  1051. $metadata = array(
  1052. "dol_id" => (string) $item,
  1053. "dol_type" => (string) $origin,
  1054. "dol_thirdparty_id" => (string) $societe->id,
  1055. 'dol_thirdparty_name' => $societe->name,
  1056. 'dol_version' => DOL_VERSION,
  1057. 'dol_entity' => $conf->entity,
  1058. 'ipaddress' => $ipaddress
  1059. );
  1060. $return = new Stripe($this->db);
  1061. try {
  1062. // Force to use the correct API key
  1063. global $stripearrayofkeysbyenv;
  1064. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
  1065. if (empty($conf->stripeconnect->enabled)) { // With a common Stripe account
  1066. if (preg_match('/pm_/i', $source)) {
  1067. $stripecard = $source;
  1068. $amountstripe = $stripeamount;
  1069. $FULLTAG = 'PFBO'; // Payment From Back Office
  1070. $stripe = $return;
  1071. $amounttopay = $amount;
  1072. $servicestatus = $status;
  1073. dol_syslog("* createPaymentStripe get stripeacc", LOG_DEBUG);
  1074. $stripeacc = $stripe->getStripeAccount($service); // Get Stripe OAuth connect account if it exists (no network access here)
  1075. dol_syslog("* createPaymentStripe Create payment for customer ".$customer->id." on source card ".$stripecard->id.", amounttopay=".$amounttopay.", amountstripe=".$amountstripe.", FULLTAG=".$FULLTAG, LOG_DEBUG);
  1076. // Create payment intent and charge payment (confirmnow = true)
  1077. $paymentintent = $stripe->getPaymentIntent($amounttopay, $currency, $FULLTAG, $description, $invoice, $customer->id, $stripeacc, $servicestatus, 0, 'automatic', true, $stripecard->id, 1);
  1078. $charge = new stdClass();
  1079. if ($paymentintent->status == 'succeeded') {
  1080. $charge->status = 'ok';
  1081. } else {
  1082. $charge->status = 'failed';
  1083. $charge->failure_code = $stripe->code;
  1084. $charge->failure_message = $stripe->error;
  1085. $charge->failure_declinecode = $stripe->declinecode;
  1086. $stripefailurecode = $stripe->code;
  1087. $stripefailuremessage = $stripe->error;
  1088. $stripefailuredeclinecode = $stripe->declinecode;
  1089. }
  1090. } elseif (preg_match('/acct_/i', $source)) {
  1091. $charge = \Stripe\Charge::create(array(
  1092. "amount" => "$stripeamount",
  1093. "currency" => "$currency",
  1094. "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
  1095. "description" => "Stripe payment: ".$description,
  1096. "capture" => $capture,
  1097. "metadata" => $metadata,
  1098. "source" => "$source"
  1099. ));
  1100. } else {
  1101. $paymentarray = array(
  1102. "amount" => "$stripeamount",
  1103. "currency" => "$currency",
  1104. "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
  1105. "description" => "Stripe payment: ".$description,
  1106. "capture" => $capture,
  1107. "metadata" => $metadata,
  1108. "source" => "$source",
  1109. "customer" => "$customer"
  1110. );
  1111. if ($societe->email && $usethirdpartyemailforreceiptemail) {
  1112. $paymentarray["receipt_email"] = $societe->email;
  1113. }
  1114. $charge = \Stripe\Charge::create($paymentarray, array("idempotency_key" => "$description"));
  1115. }
  1116. } else {
  1117. // With Stripe Connect
  1118. $fee = $amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE;
  1119. if ($fee >= $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL && $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL > $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) {
  1120. $fee = $conf->global->STRIPE_APPLICATION_FEE_MAXIMAL;
  1121. } elseif ($fee < $conf->global->STRIPE_APPLICATION_FEE_MINIMAL) {
  1122. $fee = $conf->global->STRIPE_APPLICATION_FEE_MINIMAL;
  1123. }
  1124. if (!in_array($currency, $arrayzerounitcurrency)) {
  1125. $stripefee = round($fee * 100);
  1126. } else {
  1127. $stripefee = round($fee);
  1128. }
  1129. $paymentarray = array(
  1130. "amount" => "$stripeamount",
  1131. "currency" => "$currency",
  1132. "statement_descriptor_suffix" => dol_trunc($description, 10, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt (company + description)
  1133. "description" => "Stripe payment: ".$description,
  1134. "capture" => $capture,
  1135. "metadata" => $metadata,
  1136. "source" => "$source",
  1137. "customer" => "$customer"
  1138. );
  1139. if ($conf->entity != $conf->global->STRIPECONNECT_PRINCIPAL && $stripefee > 0) {
  1140. $paymentarray["application_fee_amount"] = $stripefee;
  1141. }
  1142. if ($societe->email && $usethirdpartyemailforreceiptemail) {
  1143. $paymentarray["receipt_email"] = $societe->email;
  1144. }
  1145. if (preg_match('/pm_/i', $source)) {
  1146. $stripecard = $source;
  1147. $amountstripe = $stripeamount;
  1148. $FULLTAG = 'PFBO'; // Payment From Back Office
  1149. $stripe = $return;
  1150. $amounttopay = $amount;
  1151. $servicestatus = $status;
  1152. dol_syslog("* createPaymentStripe get stripeacc", LOG_DEBUG);
  1153. $stripeacc = $stripe->getStripeAccount($service); // Get Stripe OAuth connect account if it exists (no network access here)
  1154. dol_syslog("* createPaymentStripe Create payment on card ".$stripecard->id.", amounttopay=".$amounttopay.", amountstripe=".$amountstripe.", FULLTAG=".$FULLTAG, LOG_DEBUG);
  1155. // Create payment intent and charge payment (confirmnow = true)
  1156. $paymentintent = $stripe->getPaymentIntent($amounttopay, $currency, $FULLTAG, $description, $invoice, $customer->id, $stripeacc, $servicestatus, 0, 'automatic', true, $stripecard->id, 1);
  1157. $charge = new stdClass();
  1158. if ($paymentintent->status == 'succeeded') {
  1159. $charge->status = 'ok';
  1160. $charge->id = $paymentintent->id;
  1161. } else {
  1162. $charge->status = 'failed';
  1163. $charge->failure_code = $stripe->code;
  1164. $charge->failure_message = $stripe->error;
  1165. $charge->failure_declinecode = $stripe->declinecode;
  1166. }
  1167. } else {
  1168. $charge = \Stripe\Charge::create($paymentarray, array("idempotency_key" => "$description", "stripe_account" => "$account"));
  1169. }
  1170. }
  1171. if (isset($charge->id)) {
  1172. }
  1173. $return->statut = 'success';
  1174. $return->id = $charge->id;
  1175. if (preg_match('/pm_/i', $source)) {
  1176. $return->message = 'Payment retrieved by card status = '.$charge->status;
  1177. } else {
  1178. if ($charge->source->type == 'card') {
  1179. $return->message = $charge->source->card->brand." ....".$charge->source->card->last4;
  1180. } elseif ($charge->source->type == 'three_d_secure') {
  1181. $stripe = new Stripe($this->db);
  1182. $src = \Stripe\Source::retrieve("".$charge->source->three_d_secure->card, array(
  1183. "stripe_account" => $stripe->getStripeAccount($service)
  1184. ));
  1185. $return->message = $src->card->brand." ....".$src->card->last4;
  1186. } else {
  1187. $return->message = $charge->id;
  1188. }
  1189. }
  1190. } catch (\Stripe\Error\Card $e) {
  1191. include DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  1192. // Since it's a decline, \Stripe\Error\Card will be caught
  1193. $body = $e->getJsonBody();
  1194. $err = $body['error'];
  1195. $return->statut = 'error';
  1196. $return->id = $err['charge'];
  1197. $return->type = $err['type'];
  1198. $return->code = $err['code'];
  1199. $return->message = $err['message'];
  1200. $body = "Error: <br>".$return->id." ".$return->message." ";
  1201. $subject = '[Alert] Payment error using Stripe';
  1202. $cmailfile = new CMailFile($subject, $conf->global->ONLINE_PAYMENT_SENDEMAIL, $conf->global->MAIN_INFO_SOCIETE_MAIL, $body);
  1203. $cmailfile->sendfile();
  1204. $error++;
  1205. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  1206. } catch (\Stripe\Error\RateLimit $e) {
  1207. // Too many requests made to the API too quickly
  1208. $error++;
  1209. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  1210. } catch (\Stripe\Error\InvalidRequest $e) {
  1211. // Invalid parameters were supplied to Stripe's API
  1212. $error++;
  1213. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  1214. } catch (\Stripe\Error\Authentication $e) {
  1215. // Authentication with Stripe's API failed
  1216. // (maybe you changed API keys recently)
  1217. $error++;
  1218. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  1219. } catch (\Stripe\Error\ApiConnection $e) {
  1220. // Network communication with Stripe failed
  1221. $error++;
  1222. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  1223. } catch (\Stripe\Error\Base $e) {
  1224. // Display a very generic error to the user, and maybe send
  1225. // yourself an email
  1226. $error++;
  1227. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  1228. } catch (Exception $e) {
  1229. // Something else happened, completely unrelated to Stripe
  1230. $error++;
  1231. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  1232. }
  1233. return $return;
  1234. }
  1235. }