BxPaymentProviderChargebee.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup Payment Payment
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. define('CBEE_MODE_LIVE', 1);
  12. define('CBEE_MODE_TEST', 2);
  13. use ChargeBee\ChargeBee\Environment;
  14. use ChargeBee\ChargeBee\Models\Addon;
  15. use ChargeBee\ChargeBee\Models\Customer;
  16. use ChargeBee\ChargeBee\Models\HostedPage;
  17. use ChargeBee\ChargeBee\Models\Subscription;
  18. use ChargeBee\ChargeBee\Models\Invoice;
  19. class BxPaymentProviderChargebee extends BxBaseModPaymentProvider implements iBxBaseModPaymentProvider
  20. {
  21. protected $_iMode;
  22. protected $_bCheckAmount;
  23. function __construct($aConfig)
  24. {
  25. $this->MODULE = 'bx_payment';
  26. parent::__construct($aConfig);
  27. $this->_aSbsStatuses = array(
  28. 'future' => BX_PAYMENT_SBS_STATUS_SCHEDULED,
  29. 'in_trial' => BX_PAYMENT_SBS_STATUS_TRIAL,
  30. 'active' => BX_PAYMENT_SBS_STATUS_ACTIVE,
  31. 'non_renewing' => BX_PAYMENT_SBS_STATUS_ACTIVE,
  32. 'paused' => BX_PAYMENT_SBS_STATUS_PAUSED,
  33. 'canceled' => BX_PAYMENT_SBS_STATUS_CANCELED,
  34. );
  35. }
  36. public function initOptions($aOptions)
  37. {
  38. parent::initOptions($aOptions);
  39. $this->_iMode = (int)$this->getOption('mode');
  40. $this->_bCheckAmount = $this->getOption('check_amount') == 'on';
  41. $this->_bUseSsl = $this->getOption('ssl') == 'on';
  42. }
  43. public function initializeCheckout($iPendingId, $aCartInfo)
  44. {
  45. $aItem = array_shift($aCartInfo['items']);
  46. if(empty($aItem) || !is_array($aItem))
  47. return $this->_sLangsPrefix . 'err_empty_items';
  48. $aClient = $this->_oModule->getProfileInfo();
  49. $aVendor = $this->_oModule->getProfileInfo($aCartInfo['vendor_id']);
  50. $oPage = $this->createHostedPageRecurring($aItem, $aClient, $aVendor, $iPendingId);
  51. if($oPage === false)
  52. return $this->_sLangsPrefix . 'err_cannot_perform';
  53. return array(
  54. 'code' => 0,
  55. 'eval' => $this->_oModule->_oConfig->getJsObject('cart') . '.onSubscribeSubmit(oData);',
  56. 'redirect' => $oPage->url
  57. );
  58. }
  59. public function finalizeCheckout(&$aData)
  60. {
  61. $sPageId = bx_process_input($aData['id']);
  62. $iPendingId = bx_process_input($aData['pending_id'], BX_DATA_INT);
  63. if(empty($sPageId) || empty($iPendingId))
  64. return array('code' => 1, 'message' => $this->_sLangsPrefix . 'err_wrong_data');
  65. $oPage = $this->retreiveHostedPage($sPageId);
  66. if($oPage === false)
  67. return $this->_sLangsPrefix . 'err_cannot_perform';
  68. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  69. if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
  70. return array('code' => 3, 'message' => $this->_sLangsPrefix . 'err_already_processed');
  71. $oCustomer = $oPage->content()->customer();
  72. $oSubscription = $oPage->content()->subscription();
  73. $aResult = array(
  74. 'code' => BX_PAYMENT_RESULT_SUCCESS,
  75. 'message' => $this->_sLangsPrefix . 'cbee_msg_subscribed',
  76. 'pending_id' => $iPendingId,
  77. 'customer_id' => $oCustomer->id,
  78. 'subscription_id' => $oSubscription->id,
  79. 'client_name' => _t($this->_sLangsPrefix . 'txt_buyer_name_mask', $oCustomer->firstName, $oCustomer->lastName),
  80. 'client_email' => $oCustomer->email,
  81. 'paid' => false,
  82. 'trial' => $oSubscription->status == 'in_trial',
  83. );
  84. //--- Update pending transaction ---//
  85. $this->_oModule->_oDb->updateOrderPending($iPendingId, array(
  86. 'order' => $oSubscription->id,
  87. 'error_code' => $aResult['code'],
  88. 'error_msg' => _t($aResult['message'])
  89. ));
  90. return $aResult;
  91. }
  92. public function notify()
  93. {
  94. $iResult = $this->_processEvent();
  95. http_response_code($iResult);
  96. }
  97. public function cancelRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
  98. {
  99. return $this->deleteSubscription($sSubscriptionId);
  100. }
  101. public function createHostedPageSingle($aItem, $aClient, $aVendor = array(), $iPendingId = 0)
  102. {
  103. $oPage = false;
  104. try {
  105. $aPage = [
  106. 'embed' => false, //--- Note. 'embed' should be disabled to allow payments via PayPal
  107. 'charges' => [
  108. [
  109. 'amount' => $aItem['amount'],
  110. 'description' => $aItem['description'],
  111. ]
  112. ],
  113. 'customer' => [
  114. 'email' => $aClient['email'],
  115. 'firstName' => $aClient['name']
  116. ],
  117. ];
  118. if(!empty($aItem['addons']) && is_array($aItem['addons']))
  119. $aPage['addons'] = $aItem['addons'];
  120. if(!empty($aVendor) && is_array($aVendor) && !empty($aVendor))
  121. $aPage['redirectUrl'] = bx_append_url_params($this->getReturnDataUrl($aVendor['id']), array(
  122. 'pending_id' => $iPendingId
  123. ));
  124. Environment::configure($this->_getSite(), $this->_getApiKey());
  125. $oResult = HostedPage::checkoutOneTime($aPage);
  126. $oPage = $oResult->hostedPage();
  127. }
  128. catch (Exception $oException) {
  129. $iError = $oException->getCode();
  130. $sError = $oException->getMessage();
  131. $this->log('Create Hosted Page Error: ' . $sError . '(' . $iError . ')', '', BX_LOG_ERR);
  132. return false;
  133. }
  134. return $oPage;
  135. }
  136. public function createHostedPageRecurring($aItem, $aClient, $aVendor = array(), $iPendingId = 0)
  137. {
  138. $oPage = false;
  139. try {
  140. $aPage = [
  141. 'embed' => false, //--- Note. 'embed' should be disabled to allow payments via PayPal
  142. 'subscription' => [
  143. 'planId' => $aItem['name']
  144. ],
  145. 'customer' => [
  146. 'email' => $aClient['email'],
  147. 'firstName' => $aClient['name']
  148. ],
  149. ];
  150. if(!empty($aItem['addons']) && is_array($aItem['addons']))
  151. $aPage['addons'] = $aItem['addons'];
  152. if(!empty($aVendor) && is_array($aVendor) && !empty($aVendor))
  153. $aPage['redirectUrl'] = bx_append_url_params($this->getReturnDataUrl($aVendor['id']), array(
  154. 'pending_id' => $iPendingId
  155. ));
  156. Environment::configure($this->_getSite(), $this->_getApiKey());
  157. $oResult = HostedPage::checkoutNew($aPage);
  158. $oPage = $oResult->hostedPage();
  159. }
  160. catch (Exception $oException) {
  161. $iError = $oException->getCode();
  162. $sError = $oException->getMessage();
  163. $this->log('Create Hosted Page Error: ' . $sError . '(' . $iError . ')', '', BX_LOG_ERR);
  164. return false;
  165. }
  166. return $oPage;
  167. }
  168. public function retreiveHostedPage($sPageId)
  169. {
  170. $oPage = null;
  171. try {
  172. Environment::configure($this->_getSite(), $this->_getApiKey());
  173. $oResult = HostedPage::retrieve($sPageId);
  174. $oPage = $oResult->hostedPage();
  175. }
  176. catch (Exception $oException) {
  177. $iError = $oException->getCode();
  178. $sError = $oException->getMessage();
  179. $this->log('Retrieve Hosted Page Error: ' . $sError . '(' . $iError . ')', '', BX_LOG_ERR);
  180. return false;
  181. }
  182. return $oPage;
  183. }
  184. public function retrieveSubscription($sSubscriptionId)
  185. {
  186. $oSubscription = null;
  187. try {
  188. Environment::configure($this->_getSite(), $this->_getApiKey());
  189. $oResult = Subscription::retrieve($sSubscriptionId);
  190. $oSubscription = $oResult->subscription();
  191. if($oSubscription->id != $sSubscriptionId)
  192. return false;
  193. }
  194. catch (Exception $oException) {
  195. $iError = $oException->getCode();
  196. $sError = $oException->getMessage();
  197. $this->log('Retrieve Subscription Error: ' . $sError . '(' . $iError . ')', '', BX_LOG_ERR);
  198. return false;
  199. }
  200. return $oSubscription;
  201. }
  202. public function getSubscription($iPendingId, $sCustomerId, $sSubscriptionId)
  203. {
  204. $oSubscription = $this->retrieveSubscription($sSubscriptionId);
  205. if($oSubscription === false)
  206. return array();
  207. $sStatus = $oSubscription->status;
  208. $sStatus = isset($this->_aSbsStatuses[$sStatus]) ? $this->_aSbsStatuses[$sStatus] : BX_PAYMENT_SBS_STATUS_UNKNOWN;
  209. return array(
  210. 'status' => $sStatus,
  211. 'created' => $oSubscription->createdAt,
  212. 'started' => $oSubscription->startedAt,
  213. 'trial_start' => $oSubscription->trialStart,
  214. 'trial_end' => $oSubscription->trialEnd,
  215. 'cperiod_start' => $oSubscription->currentTermStart,
  216. 'cperiod_end' => $oSubscription->currentTermEnd,
  217. );
  218. }
  219. public function deleteSubscription($sSubscriptionId)
  220. {
  221. try {
  222. Environment::configure($this->_getSite(), $this->_getApiKey());
  223. $oResult = Subscription::cancel($sSubscriptionId);
  224. $oSubscription = $oResult->subscription();
  225. if($oSubscription->status != 'cancelled')
  226. return false;
  227. }
  228. catch (Exception $oException) {
  229. $aError = $oException->getJsonBody();
  230. $this->log('Delete Subscription Error: ' . $aError['error']['message'], '', BX_LOG_ERR);
  231. $this->log($aError, '', BX_LOG_ERR);
  232. return false;
  233. }
  234. $this->onDeleteSubscription($sSubscriptionId, $oSubscription->getValues());
  235. return true;
  236. }
  237. public function retrieveInvoice($sInvoiceId)
  238. {
  239. $oInvoice = null;
  240. try {
  241. Environment::configure($this->_getSite(), $this->_getApiKey());
  242. $oResult = Invoice::retrieve($sInvoiceId);
  243. $oInvoice = $oResult->invoice();
  244. if($oInvoice->id != $sInvoiceId)
  245. return false;
  246. }
  247. catch (Exception $oException) {
  248. $iError = $oException->getCode();
  249. $sError = $oException->getMessage();
  250. $this->log('Retrieve Invoice Error: ' . $sError . '(' . $iError . ')', '', BX_LOG_ERR);
  251. return false;
  252. }
  253. return $oInvoice;
  254. }
  255. public function retrieveAddons($sStatus = 'active', $iLimit = 0)
  256. {
  257. $aAddons = array();
  258. try {
  259. $aParams = array();
  260. if(!empty($sStatus))
  261. $aParams['status[is]'] = $sStatus;
  262. if(!empty($iLimit))
  263. $aParams['limit'] = $iLimit;
  264. Environment::configure($this->_getSite(), $this->_getApiKey());
  265. $oResults = Addon::all($aParams);
  266. foreach($oResults as $oResult)
  267. $aAddons[] = $oResult->addon();
  268. }
  269. catch (Exception $oException) {
  270. $iError = $oException->getCode();
  271. $sError = $oException->getMessage();
  272. $this->log('Retrieve Addons Error: ' . $sError . '(' . $iError . ')', '', BX_LOG_ERR);
  273. return false;
  274. }
  275. return $aAddons;
  276. }
  277. public function getAddons($sStatus = 'active', $iLimit = 0)
  278. {
  279. $aAddons = $this->retrieveAddons($sStatus, $iLimit);
  280. if(empty($aAddons) || !is_array($aAddons))
  281. return array();
  282. $aResult = array();
  283. foreach($aAddons as $oAddon)
  284. $aResult[] = $oAddon->getValues();
  285. return $aResult;
  286. }
  287. public function retrieveAddon($sId)
  288. {
  289. $oAddon = null;
  290. try {
  291. Environment::configure($this->_getSite(), $this->_getApiKey());
  292. $oResult = Addon::retrieve($sId);
  293. $oAddon = $oResult->addon();
  294. if($oAddon->id != $sId)
  295. return false;
  296. }
  297. catch (Exception $oException) {
  298. $iError = $oException->getCode();
  299. $sError = $oException->getMessage();
  300. $this->log('Retrieve Addon Error: ' . $sError . '(' . $iError . ')', '', BX_LOG_ERR);
  301. return false;
  302. }
  303. return $oAddon;
  304. }
  305. public function getAddon($sId)
  306. {
  307. $oAddon = $this->retrieveAddon($sId);
  308. if($oAddon === false)
  309. return array();
  310. return $oAddon->getValues();
  311. }
  312. public function retrieveCustomer($sCustomerId)
  313. {
  314. $oCustomer = null;
  315. try {
  316. Environment::configure($this->_getSite(), $this->_getApiKey());
  317. $oResult = Customer::retrieve($sCustomerId);
  318. $oCustomer = $oResult->customer();
  319. if($oCustomer->id != $sCustomerId)
  320. return false;
  321. }
  322. catch (Exception $oException) {
  323. $iError = $oException->getCode();
  324. $sError = $oException->getMessage();
  325. $this->log('Retrieve Customer Error: ' . $sError . '(' . $iError . ')', '', BX_LOG_ERR);
  326. return false;
  327. }
  328. return $oCustomer;
  329. }
  330. public function onDeleteSubscription($sSubscriptionId, $aSubscription)
  331. {
  332. /**
  333. * @hooks
  334. * @hookdef hook-bx_payment-chargebee_cancel_subscription 'bx_payment', 'chargebee_cancel_subscription' - hook after a subscription was canceled
  335. * - $unit_name - equals `bx_payment`
  336. * - $action - equals `chargebee_cancel_subscription`
  337. * - $object_id - not used
  338. * - $sender_id - not used
  339. * - $extra_params - array of additional params with the following array keys:
  340. * - `subscription_id` - [string] unique subscription id
  341. * - `subscription_info` - [array] subscription info
  342. * @hook @ref hook-bx_payment-chargebee_cancel_subscription
  343. */
  344. /**
  345. * @hooks
  346. * @hookdef hook-bx_payment-chargebee_v3_cancel_subscription 'bx_payment', 'chargebee_v3_cancel_subscription' - hook after a subscription was canceled
  347. * It's equivalent to @ref hook-bx_payment-chargebee_cancel_subscription
  348. * @hook @ref hook-bx_payment-chargebee_v3_cancel_subscription
  349. */
  350. bx_alert($this->_oModule->_oConfig->getName(), $this->_sName . '_cancel_subscription', 0, false, [
  351. 'subscription_id' => $sSubscriptionId,
  352. 'subscription_info' => $aSubscription
  353. ]);
  354. }
  355. protected function _getSite()
  356. {
  357. return $this->_iMode == CBEE_MODE_LIVE ? $this->getOption('live_site') : $this->getOption('test_site');
  358. }
  359. protected function _getApiKey()
  360. {
  361. return $this->_iMode == CBEE_MODE_LIVE ? $this->getOption('live_api_key') : $this->getOption('test_api_key');
  362. }
  363. protected function _processEvent()
  364. {
  365. $sInput = @file_get_contents("php://input");
  366. $aEvent = json_decode($sInput, true);
  367. if(empty($aEvent) || !is_array($aEvent))
  368. return 404;
  369. $sType = $aEvent['event_type'];
  370. if(!in_array($sType, array('payment_succeeded', ' payment_refunded', 'subscription_cancelled')))
  371. return 200;
  372. $this->log('Webhooks: ' . (!empty($sType) ? $sType : ''), '', BX_LOG_INFO);
  373. $this->log($aEvent, '', BX_LOG_INFO);
  374. $sMethod = '_processEvent' . bx_gen_method_name($sType, array('.', '_', '-'));
  375. if(!method_exists($this, $sMethod))
  376. return 200;
  377. return $this->$sMethod($aEvent) ? 200 : 403;
  378. }
  379. protected function _processEventPaymentSucceeded(&$aEvent)
  380. {
  381. $mixedResult = $this->_getDataTransaction($aEvent, 'success');
  382. if($mixedResult === false)
  383. return false;
  384. list($aPending, $aTransaction) = $mixedResult;
  385. $fTransactionAmount = (float)$aTransaction['amount'] / 100;
  386. $sTransactionCurrency = strtoupper($aTransaction['currency_code']);
  387. if($this->_bCheckAmount && ((float)$aPending['amount'] != $fTransactionAmount || strcasecmp($this->_oModule->_oConfig->getDefaultCurrencyCode(), $sTransactionCurrency) !== 0))
  388. return false;
  389. if($aPending['type'] == BX_PAYMENT_TYPE_RECURRING)
  390. $this->_oModule->getObjectSubscriptions()->prolong($aPending);
  391. return $this->_oModule->registerPayment($aPending);
  392. }
  393. protected function _processEventPaymentRefunded(&$aEvent)
  394. {
  395. $mixedResult = $this->_getDataTransaction($aEvent);
  396. if($mixedResult === false)
  397. return false;
  398. list($aPending) = $mixedResult;
  399. return $this->_oModule->refundPayment($aPending);
  400. }
  401. protected function _processEventSubscriptionCancelled(&$aEvent)
  402. {
  403. $mixedResult = $this->_getDataSubscription($aEvent);
  404. if($mixedResult === false)
  405. return false;
  406. list($aPending, $aSubscription) = $mixedResult;
  407. $this->onDeleteSubscription($aSubscription['id'], $aSubscription);
  408. return $this->_oModule->getObjectSubscriptions()->cancelLocal($aPending);
  409. }
  410. protected function _getDataTransaction(&$aEvent, $sWithStatusCheck = '')
  411. {
  412. $aTransaction = $aEvent['content']['transaction'];
  413. if(empty($aTransaction) || (!empty($sWithStatusCheck) && $aTransaction['status'] != $sWithStatusCheck))
  414. return false;
  415. $sOrder = '';
  416. if(isset($aTransaction['subscription_id']))
  417. $sOrder = $aTransaction['subscription_id'];
  418. else if(isset($aTransaction['id']))
  419. $sOrder = $aTransaction['id'];
  420. if(empty($sOrder))
  421. return false;
  422. $aPending = $this->_oModule->_oDb->getOrderPending(['type' => 'order', 'order' => $sOrder]);
  423. if(empty($aPending) || !is_array($aPending))
  424. return false;
  425. return array($aPending, $aTransaction);
  426. }
  427. protected function _getDataSubscription(&$aEvent, $sWithStatusCheck = '')
  428. {
  429. $aSubscription = $aEvent['content']['subscription'];
  430. if(empty($aSubscription) || (!empty($sWithStatusCheck) && $aSubscription['status'] != $sWithStatusCheck))
  431. return false;
  432. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'order', 'order' => $aSubscription['id']));
  433. if(empty($aPending) || !is_array($aPending))
  434. return false;
  435. return array($aPending, $aSubscription);
  436. }
  437. }
  438. /** @} */