stripe.class.php 17 KB

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