stripe.class.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. <?php
  2. /* Copyright (C) 2018 PtibogXIV <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 <http://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. public $fk_key;
  37. /**
  38. * @var int ID
  39. */
  40. public $id;
  41. public $mode;
  42. /**
  43. * @var int Entity
  44. */
  45. public $entity;
  46. public $statut;
  47. public $type;
  48. public $code;
  49. public $message;
  50. /**
  51. * Constructor
  52. *
  53. * @param DoliDB $db Database handler
  54. */
  55. public function __construct($db)
  56. {
  57. $this->db = $db;
  58. }
  59. /**
  60. * Return main company OAuth Connect stripe account
  61. *
  62. * @param string $mode 'StripeTest' or 'StripeLive'
  63. * @return string Stripe account 'acc_....' or '' if no OAuth token found
  64. */
  65. public function getStripeAccount($mode='StripeTest')
  66. {
  67. global $conf;
  68. $sql = "SELECT tokenstring";
  69. $sql.= " FROM ".MAIN_DB_PREFIX."oauth_token";
  70. $sql.= " WHERE entity = ".$conf->entity;
  71. $sql.= " AND service = '".$mode."'";
  72. dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
  73. $result = $this->db->query($sql);
  74. if ($result)
  75. {
  76. if ($this->db->num_rows($result))
  77. {
  78. $obj = $this->db->fetch_object($result);
  79. $tokenstring=$obj->tokenstring;
  80. $tmparray = dol_json_decode($tokenstring);
  81. $key = $tmparray->stripe_user_id;
  82. }
  83. else {
  84. $tokenstring='';
  85. }
  86. }
  87. else {
  88. dol_print_error($this->db);
  89. }
  90. dol_syslog("No dedicated Stripe Connect account available for entity ".$conf->entity);
  91. return $key;
  92. }
  93. /**
  94. * getStripeCustomerAccount
  95. *
  96. * @param int $id Id of third party
  97. * @param int $status Status
  98. * @return string Stripe customer ref 'cu_xxxxxxxxxxxxx' or ''
  99. */
  100. public function getStripeCustomerAccount($id, $status=0)
  101. {
  102. global $conf;
  103. include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
  104. $societeaccount = new SocieteAccount($this->db);
  105. return $societeaccount->getCustomerAccount($id, 'stripe', $status); // Get thirdparty cus_...
  106. }
  107. /**
  108. * Get the Stripe customer of a thirdparty (with option to create it if not linked yet)
  109. *
  110. * @param Societe $object Object thirdparty to check, or create on stripe (create on stripe also update the stripe_account table for current entity)
  111. * @param string $key ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect
  112. * @param int $status Status (0=test, 1=live)
  113. * @param int $createifnotlinkedtostripe 1=Create the stripe customer and the link if the thirdparty is not yet linked to a stripe customer
  114. * @return \Stripe\StripeCustomer|null Stripe Customer or null if not found
  115. */
  116. public function customerStripe(Societe $object, $key='', $status=0, $createifnotlinkedtostripe=0)
  117. {
  118. global $conf, $user;
  119. if (empty($object->id))
  120. {
  121. dol_syslog("customerStripe is called with param object not loaded");
  122. return null;
  123. }
  124. $customer = null;
  125. $sql = "SELECT sa.key_account as key_account, sa.entity"; // key_account is cus_....
  126. $sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa";
  127. $sql.= " WHERE sa.fk_soc = " . $object->id;
  128. $sql.= " AND sa.entity IN (".getEntity('societe').")";
  129. $sql.= " AND sa.site = 'stripe' AND sa.status = ".((int) $status);
  130. $sql.= " AND key_account IS NOT NULL AND key_account <> ''";
  131. dol_syslog(get_class($this) . "::customerStripe search stripe customer id for thirdparty id=".$object->id, LOG_DEBUG);
  132. $resql = $this->db->query($sql);
  133. if ($resql) {
  134. $num = $this->db->num_rows($resql);
  135. if ($num)
  136. {
  137. $obj = $this->db->fetch_object($resql);
  138. $tiers = $obj->key_account;
  139. dol_syslog(get_class($this) . "::customerStripe found stripe customer key_account = ".$tiers);
  140. // Force to use the correct API key
  141. global $stripearrayofkeysbyenv;
  142. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
  143. try {
  144. if (empty($key)) { // If the Stripe connect account not set, we use common API usage
  145. $customer = \Stripe\Customer::retrieve("$tiers");
  146. } else {
  147. $customer = \Stripe\Customer::retrieve("$tiers", array("stripe_account" => $key));
  148. }
  149. }
  150. catch(Exception $e)
  151. {
  152. $this->error = $e->getMessage();
  153. }
  154. }
  155. elseif ($createifnotlinkedtostripe)
  156. {
  157. $dataforcustomer = array(
  158. "email" => $object->email,
  159. "business_vat_id" => $object->tva_intra,
  160. "description" => $object->name,
  161. "metadata" => array('dol_id'=>$object->id, 'dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR']))
  162. );
  163. //$a = \Stripe\Stripe::getApiKey();
  164. //var_dump($a);var_dump($key);exit;
  165. try {
  166. // Force to use the correct API key
  167. global $stripearrayofkeysbyenv;
  168. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
  169. if (empty($key)) { // If the Stripe connect account not set, we use common API usage
  170. $customer = \Stripe\Customer::create($dataforcustomer);
  171. } else {
  172. $customer = \Stripe\Customer::create($dataforcustomer, array("stripe_account" => $key));
  173. }
  174. $sql = "INSERT INTO " . MAIN_DB_PREFIX . "societe_account (fk_soc, login, key_account, site, status, entity, date_creation, fk_user_creat)";
  175. $sql .= " VALUES (".$object->id.", '', '".$this->db->escape($customer->id)."', 'stripe', " . $status . ", " . $conf->entity . ", '".$this->db->idate(dol_now())."', ".$user->id.")";
  176. $resql = $this->db->query($sql);
  177. if (! $resql)
  178. {
  179. $this->error = $this->db->lasterror();
  180. }
  181. }
  182. catch(Exception $e)
  183. {
  184. $this->error = $e->getMessage();
  185. }
  186. }
  187. }
  188. else
  189. {
  190. dol_print_error($this->db);
  191. }
  192. return $customer;
  193. }
  194. /**
  195. * Get the Stripe card of a company payment mode (with option to create it on Stripe if not linked yet)
  196. *
  197. * @param \Stripe\StripeCustomer $cu Object stripe customer
  198. * @param CompanyPaymentMode $object Object companypaymentmode to check, or create on stripe (create on stripe also update the societe_rib table for current entity)
  199. * @param string $stripeacc ''=Use common API. If not '', it is the Stripe connect account 'acc_....' to use Stripe connect
  200. * @param int $status Status (0=test, 1=live)
  201. * @param int $createifnotlinkedtostripe 1=Create the stripe card and the link if the card is not yet linked to a stripe card
  202. * @return \Stripe\StripeCard|null Stripe Card or null if not found
  203. */
  204. public function cardStripe($cu, CompanyPaymentMode $object, $stripeacc='', $status=0, $createifnotlinkedtostripe=0)
  205. {
  206. global $conf, $user;
  207. $card = null;
  208. $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_....
  209. $sql.= " FROM " . MAIN_DB_PREFIX . "societe_rib as sa";
  210. $sql.= " WHERE sa.rowid = " . $object->id;
  211. //$sql.= " AND sa.entity IN (".getEntity('societe').")";
  212. $sql.= " AND sa.type = 'card'";
  213. dol_syslog(get_class($this) . "::fetch search stripe card id for paymentmode id=".$object->id.", stripeacc=".$stripeacc.", status=".$status.", createifnotlinkedtostripe=".$createifnotlinkedtostripe, LOG_DEBUG);
  214. $resql = $this->db->query($sql);
  215. if ($resql) {
  216. $num = $this->db->num_rows($resql);
  217. if ($num)
  218. {
  219. $obj = $this->db->fetch_object($resql);
  220. $cardref = $obj->stripe_card_ref;
  221. dol_syslog("************* cardref=".$cardref);
  222. if ($cardref)
  223. {
  224. try {
  225. if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage
  226. $card = $cu->sources->retrieve($cardref);
  227. } else {
  228. //$card = $cu->sources->retrieve($cardref, array("stripe_account" => $stripeacc)); // this API fails when array stripe_account is provided
  229. $card = $cu->sources->retrieve($cardref);
  230. }
  231. }
  232. catch(Exception $e)
  233. {
  234. $this->error = $e->getMessage();
  235. dol_syslog($this->error, LOG_WARNING);
  236. }
  237. }
  238. elseif ($createifnotlinkedtostripe)
  239. {
  240. $exp_date_month=$obj->exp_date_month;
  241. $exp_date_year=$obj->exp_date_year;
  242. $number=$obj->number;
  243. $cvc=$obj->cvn; // cvn in database, cvc for stripe
  244. $cardholdername=$obj->proprio;
  245. $dataforcard = array(
  246. "source" => array('object'=>'card', 'exp_month'=>$exp_date_month, 'exp_year'=>$exp_date_year, 'number'=>$number, 'cvc'=>$cvc, 'name'=>$cardholdername),
  247. "metadata" => array('dol_id'=>$object->id, 'dol_version'=>DOL_VERSION, 'dol_entity'=>$conf->entity, 'ipaddress'=>(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR']))
  248. );
  249. //$a = \Stripe\Stripe::getApiKey();
  250. //var_dump($a);var_dump($stripeacc);exit;
  251. dol_syslog("Try to create card dataforcard = ".dol_json_encode($dataforcard));
  252. try {
  253. if (empty($stripeacc)) { // If the Stripe connect account not set, we use common API usage
  254. $card = $cu->sources->create($dataforcard);
  255. } else {
  256. $card = $cu->sources->create($dataforcard, array("stripe_account" => $stripeacc));
  257. }
  258. if ($card)
  259. {
  260. $sql = "UPDATE " . MAIN_DB_PREFIX . "societe_rib";
  261. $sql.= " SET stripe_card_ref = '".$this->db->escape($card->id)."', card_type = '".$this->db->escape($card->brand)."',";
  262. $sql.= " country_code = '".$this->db->escape($card->country)."',";
  263. $sql.= " approved = ".($card->cvc_check == 'pass' ? 1 : 0);
  264. $sql.= " WHERE rowid = " . $object->id;
  265. $sql.= " AND type = 'card'";
  266. $resql = $this->db->query($sql);
  267. if (! $resql)
  268. {
  269. $this->error = $this->db->lasterror();
  270. }
  271. }
  272. else
  273. {
  274. $this->error = 'Call to cu->source->create return empty card';
  275. }
  276. }
  277. catch(Exception $e)
  278. {
  279. $this->error = $e->getMessage();
  280. dol_syslog($this->error, LOG_WARNING);
  281. }
  282. }
  283. }
  284. }
  285. else
  286. {
  287. dol_print_error($this->db);
  288. }
  289. return $card;
  290. }
  291. /**
  292. * Create charge with public/payment/newpayment.php, stripe/card.php, cronjobs or REST API
  293. *
  294. * @param int $amount Amount to pay
  295. * @param string $currency EUR, GPB...
  296. * @param string $origin Object type to pay (order, invoice, contract...)
  297. * @param int $item Object id to pay
  298. * @param string $source src_xxxxx or card_xxxxx
  299. * @param string $customer Stripe customer ref 'cus_xxxxxxxxxxxxx' via customerStripe()
  300. * @param string $account Stripe account ref 'acc_xxxxxxxxxxxxx' via getStripeAccount()
  301. * @param int $status Status (0=test, 1=live)
  302. * @param int $usethirdpartyemailforreceiptemail Use thirdparty email as receipt email
  303. * @param boolean $capture Set capture flag to true (take payment) or false (wait)
  304. * @return Stripe
  305. */
  306. public function createPaymentStripe($amount, $currency, $origin, $item, $source, $customer, $account, $status=0, $usethirdpartyemailforreceiptemail=0, $capture=true)
  307. {
  308. global $conf;
  309. $error = 0;
  310. if (empty($status)) $service = 'StripeTest';
  311. else $service = 'StripeLive';
  312. $sql = "SELECT sa.key_account as key_account, sa.fk_soc, sa.entity";
  313. $sql.= " FROM " . MAIN_DB_PREFIX . "societe_account as sa";
  314. $sql.= " WHERE sa.key_account = '" . $this->db->escape($customer) . "'";
  315. //$sql.= " AND sa.entity IN (".getEntity('societe').")";
  316. $sql.= " AND sa.site = 'stripe' AND sa.status = ".((int) $status);
  317. dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
  318. $result = $this->db->query($sql);
  319. if ($result) {
  320. if ($this->db->num_rows($result)) {
  321. $obj = $this->db->fetch_object($result);
  322. $key = $obj->fk_soc;
  323. } else {
  324. $key = null;
  325. }
  326. } else {
  327. $key = null;
  328. }
  329. $arrayzerounitcurrency=array('BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF');
  330. if (! in_array($currency, $arrayzerounitcurrency)) $stripeamount=$amount * 100;
  331. else $stripeamount = $amount;
  332. $societe = new Societe($this->db);
  333. if ($key > 0) $societe->fetch($key);
  334. $description = "";
  335. $ref = "";
  336. if ($origin == order) {
  337. $order = new Commande($this->db);
  338. $order->fetch($item);
  339. $ref = $order->ref;
  340. $description = "ORD=" . $ref . ".CUS=" . $societe->id.".PM=stripe";
  341. } elseif ($origin == invoice) {
  342. $invoice = new Facture($this->db);
  343. $invoice->fetch($item);
  344. $ref = $invoice->ref;
  345. $description = "INV=" . $ref . ".CUS=" . $societe->id.".PM=stripe";
  346. }
  347. $metadata = array(
  348. "dol_id" => "" . $item . "",
  349. "dol_type" => "" . $origin . "",
  350. "dol_thirdparty_id" => "" . $societe->id . "",
  351. 'dol_thirdparty_name' => $societe->name,
  352. 'dol_version'=>DOL_VERSION,
  353. 'dol_entity'=>$conf->entity,
  354. 'ipaddress'=>(empty($_SERVER['REMOTE_ADDR'])?'':$_SERVER['REMOTE_ADDR'])
  355. );
  356. $return = new Stripe($this->db);
  357. try {
  358. // Force to use the correct API key
  359. global $stripearrayofkeysbyenv;
  360. \Stripe\Stripe::setApiKey($stripearrayofkeysbyenv[$status]['secret_key']);
  361. if (empty($conf->stripeconnect->enabled))
  362. {
  363. if (preg_match('/acct_/i', $source))
  364. {
  365. $charge = \Stripe\Charge::create(array(
  366. "amount" => "$stripeamount",
  367. "currency" => "$currency",
  368. "statement_descriptor" => dol_trunc(dol_trunc(dol_string_unaccent($mysoc->name), 8, 'right', 'UTF-8', 1).' '.$description, 22, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt
  369. "description" => "Stripe payment: ".$description,
  370. "capture" => $capture,
  371. "metadata" => $metadata,
  372. "source" => "$source"
  373. ));
  374. } else {
  375. $paymentarray = array(
  376. "amount" => "$stripeamount",
  377. "currency" => "$currency",
  378. "statement_descriptor" => dol_trunc(dol_trunc(dol_string_unaccent($mysoc->name), 8, 'right', 'UTF-8', 1).' '.$description, 22, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt
  379. "description" => "Stripe payment: ".$description,
  380. "capture" => $capture,
  381. "metadata" => $metadata,
  382. "source" => "$source",
  383. "customer" => "$customer"
  384. );
  385. if ($societe->email && $usethirdpartyemailforreceiptemail)
  386. {
  387. $paymentarray["receipt_email"] = $societe->email;
  388. }
  389. $charge = \Stripe\Charge::create($paymentarray, array("idempotency_key" => "$ref"));
  390. }
  391. } else {
  392. $fee = round(($amount * ($conf->global->STRIPE_APPLICATION_FEE_PERCENT / 100) + $conf->global->STRIPE_APPLICATION_FEE) * 100);
  393. if ($fee < ($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100)) {
  394. $fee = round($conf->global->STRIPE_APPLICATION_FEE_MINIMAL * 100);
  395. }
  396. $paymentarray = array(
  397. "amount" => "$stripeamount",
  398. "currency" => "$currency",
  399. "statement_descriptor" => dol_trunc(dol_trunc(dol_string_unaccent($mysoc->name), 8, 'right', 'UTF-8', 1).' '.$description, 22, 'right', 'UTF-8', 1), // 22 chars that appears on bank receipt
  400. "description" => "Stripe payment: ".$description,
  401. "capture" => $capture,
  402. "metadata" => $metadata,
  403. "source" => "$source",
  404. "customer" => "$customer"
  405. );
  406. if ($conf->entity!=$conf->global->STRIPECONNECT_PRINCIPAL && $fee>0)
  407. {
  408. $paymentarray["application_fee"] = $fee;
  409. }
  410. if ($societe->email && $usethirdpartyemailforreceiptemail)
  411. {
  412. $paymentarray["receipt_email"] = $societe->email;
  413. }
  414. $charge = \Stripe\Charge::create($paymentarray, array("idempotency_key" => "$ref","stripe_account" => "$account"));
  415. }
  416. if (isset($charge->id)) {}
  417. $return->statut = 'success';
  418. $return->id = $charge->id;
  419. if ($charge->source->type == 'card') {
  420. $return->message = $charge->source->card->brand . " ...." . $charge->source->card->last4;
  421. } elseif ($charge->source->type == 'three_d_secure') {
  422. $stripe = new Stripe($this->db);
  423. $src = \Stripe\Source::retrieve("" . $charge->source->three_d_secure->card . "", array(
  424. "stripe_account" => $stripe->getStripeAccount($service)
  425. ));
  426. $return->message = $src->card->brand . " ...." . $src->card->last4;
  427. } else {
  428. $return->message = $charge->id;
  429. }
  430. } catch (\Stripe\Error\Card $e) {
  431. include DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
  432. // Since it's a decline, \Stripe\Error\Card will be caught
  433. $body = $e->getJsonBody();
  434. $err = $body['error'];
  435. $return->statut = 'error';
  436. $return->id = $err['charge'];
  437. $return->type = $err['type'];
  438. $return->code = $err['code'];
  439. $return->message = $err['message'];
  440. $body = "Error: <br>" . $return->id . " " . $return->message . " ";
  441. $subject = '[Alert] Payment error using Stripe';
  442. $cmailfile = new CMailFile($subject, $conf->global->ONLINE_PAYMENT_SENDEMAIL, $conf->global->MAIN_INFO_SOCIETE_MAIL, $body);
  443. $cmailfile->sendfile();
  444. $error++;
  445. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  446. } catch (\Stripe\Error\RateLimit $e) {
  447. // Too many requests made to the API too quickly
  448. $error++;
  449. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  450. } catch (\Stripe\Error\InvalidRequest $e) {
  451. // Invalid parameters were supplied to Stripe's API
  452. $error++;
  453. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  454. } catch (\Stripe\Error\Authentication $e) {
  455. // Authentication with Stripe's API failed
  456. // (maybe you changed API keys recently)
  457. $error++;
  458. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  459. } catch (\Stripe\Error\ApiConnection $e) {
  460. // Network communication with Stripe failed
  461. $error++;
  462. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  463. } catch (\Stripe\Error\Base $e) {
  464. // Display a very generic error to the user, and maybe send
  465. // yourself an email
  466. $error++;
  467. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  468. } catch (Exception $e) {
  469. // Something else happened, completely unrelated to Stripe
  470. $error++;
  471. dol_syslog($e->getMessage(), LOG_WARNING, 0, '_stripe');
  472. }
  473. return $return;
  474. }
  475. }