BxPaymentProviderChargebee.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. class BxPaymentProviderChargebee extends BxBaseModPaymentProvider implements iBxBaseModPaymentProvider
  19. {
  20. protected $_iMode;
  21. protected $_bCheckAmount;
  22. function __construct($aConfig)
  23. {
  24. $this->MODULE = 'bx_payment';
  25. parent::__construct($aConfig);
  26. $this->_aSbsStatuses = array(
  27. 'future' => BX_PAYMENT_SBS_STATUS_SCHEDULED,
  28. 'in_trial' => BX_PAYMENT_SBS_STATUS_TRIAL,
  29. 'active' => BX_PAYMENT_SBS_STATUS_ACTIVE,
  30. 'non_renewing' => BX_PAYMENT_SBS_STATUS_ACTIVE,
  31. 'paused' => BX_PAYMENT_SBS_STATUS_PAUSED,
  32. 'canceled' => BX_PAYMENT_SBS_STATUS_CANCELED,
  33. );
  34. }
  35. public function initOptions($aOptions)
  36. {
  37. parent::initOptions($aOptions);
  38. $this->_iMode = (int)$this->getOption('mode');
  39. $this->_bCheckAmount = $this->getOption('check_amount') == 'on';
  40. $this->_bUseSsl = $this->getOption('ssl') == 'on';
  41. }
  42. public function initializeCheckout($iPendingId, $aCartInfo)
  43. {
  44. $aItem = array_shift($aCartInfo['items']);
  45. if(empty($aItem) || !is_array($aItem))
  46. return $this->_sLangsPrefix . 'err_empty_items';
  47. $aClient = $this->_oModule->getProfileInfo();
  48. $aVendor = $this->_oModule->getProfileInfo($aCartInfo['vendor_id']);
  49. $oPage = $this->createHostedPage($aItem, $aClient, $aVendor, $iPendingId);
  50. if($oPage === false)
  51. return $this->_sLangsPrefix . 'err_cannot_perform';
  52. return array(
  53. 'code' => 0,
  54. 'eval' => $this->_oModule->_oConfig->getJsObject('cart') . '.onSubscribeSubmit(oData);',
  55. 'redirect' => $oPage->url
  56. );
  57. }
  58. public function finalizeCheckout(&$aData)
  59. {
  60. $sPageId = bx_process_input($aData['id']);
  61. $iPendingId = bx_process_input($aData['pending_id'], BX_DATA_INT);
  62. if(empty($sPageId) || empty($iPendingId))
  63. return array('code' => 1, 'message' => $this->_sLangsPrefix . 'err_wrong_data');
  64. $oPage = $this->retreiveHostedPage($sPageId);
  65. if($oPage === false)
  66. return $this->_sLangsPrefix . 'err_cannot_perform';
  67. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  68. if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
  69. return array('code' => 3, 'message' => $this->_sLangsPrefix . 'err_already_processed');
  70. $oCustomer = $oPage->content()->customer();
  71. $oSubscription = $oPage->content()->subscription();
  72. $aResult = array(
  73. 'code' => BX_PAYMENT_RESULT_SUCCESS,
  74. 'message' => $this->_sLangsPrefix . 'cbee_msg_subscribed',
  75. 'pending_id' => $iPendingId,
  76. 'customer_id' => $oCustomer->id,
  77. 'subscription_id' => $oSubscription->id,
  78. 'client_name' => _t($this->_sLangsPrefix . 'txt_buyer_name_mask', $oCustomer->firstName, $oCustomer->lastName),
  79. 'client_email' => $oCustomer->email,
  80. 'paid' => false,
  81. 'trial' => $oSubscription->status == 'in_trial',
  82. );
  83. //--- Update pending transaction ---//
  84. $this->_oModule->_oDb->updateOrderPending($iPendingId, array(
  85. 'order' => $oSubscription->id,
  86. 'error_code' => $aResult['code'],
  87. 'error_msg' => _t($aResult['message'])
  88. ));
  89. return $aResult;
  90. }
  91. public function notify()
  92. {
  93. $iResult = $this->_processEvent();
  94. http_response_code($iResult);
  95. }
  96. public function cancelRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
  97. {
  98. return $this->deleteSubscription($sSubscriptionId);
  99. }
  100. public function createHostedPage($aItem, $aClient, $aVendor = array(), $iPendingId = 0)
  101. {
  102. $oPage = false;
  103. try {
  104. $aPage = array(
  105. 'embed' => false, //--- Note. 'embed' should be disabled to allow payments via PayPal
  106. 'subscription' => array(
  107. 'planId' => $aItem['name']
  108. ),
  109. 'customer' => array(
  110. 'email' => $aClient['email'],
  111. 'firstName' => $aClient['name']
  112. ),
  113. );
  114. if(!empty($aItem['addons']) && is_array($aItem['addons']))
  115. $aPage['addons'] = $aItem['addons'];
  116. if(!empty($aVendor) && is_array($aVendor) && !empty($aVendor))
  117. $aPage['redirectUrl'] = bx_append_url_params($this->getReturnDataUrl($aVendor['id']), array(
  118. 'pending_id' => $iPendingId
  119. ));
  120. Environment::configure($this->_getSite(), $this->_getApiKey());
  121. $oResult = HostedPage::checkoutNew($aPage);
  122. $oPage = $oResult->hostedPage();
  123. }
  124. catch (Exception $oException) {
  125. $iError = $oException->getCode();
  126. $sError = $oException->getMessage();
  127. $this->log('Create Hosted Page Error: ' . $sError . '(' . $iError . ')');
  128. return false;
  129. }
  130. return $oPage;
  131. }
  132. public function retreiveHostedPage($sPageId)
  133. {
  134. $oPage = null;
  135. try {
  136. Environment::configure($this->_getSite(), $this->_getApiKey());
  137. $oResult = HostedPage::retrieve($sPageId);
  138. $oPage = $oResult->hostedPage();
  139. }
  140. catch (Exception $oException) {
  141. $iError = $oException->getCode();
  142. $sError = $oException->getMessage();
  143. $this->log('Retrieve Hosted Page Error: ' . $sError . '(' . $iError . ')');
  144. return false;
  145. }
  146. return $oPage;
  147. }
  148. public function retrieveSubscription($sSubscriptionId)
  149. {
  150. $oSubscription = null;
  151. try {
  152. Environment::configure($this->_getSite(), $this->_getApiKey());
  153. $oResult = Subscription::retrieve($sSubscriptionId);
  154. $oSubscription = $oResult->subscription();
  155. if($oSubscription->id != $sSubscriptionId)
  156. return false;
  157. }
  158. catch (Exception $oException) {
  159. $iError = $oException->getCode();
  160. $sError = $oException->getMessage();
  161. $this->log('Retrieve Subscription Error: ' . $sError . '(' . $iError . ')');
  162. return false;
  163. }
  164. return $oSubscription;
  165. }
  166. public function getSubscription($iPendingId, $sCustomerId, $sSubscriptionId)
  167. {
  168. $oSubscription = $this->retrieveSubscription($sSubscriptionId);
  169. if($oSubscription === false)
  170. return array();
  171. $sStatus = $oSubscription->status;
  172. $sStatus = isset($this->_aSbsStatuses[$sStatus]) ? $this->_aSbsStatuses[$sStatus] : BX_PAYMENT_SBS_STATUS_UNKNOWN;
  173. return array(
  174. 'status' => $sStatus,
  175. 'created' => $oSubscription->createdAt,
  176. 'started' => $oSubscription->startedAt,
  177. 'trial_start' => $oSubscription->trialStart,
  178. 'trial_end' => $oSubscription->trialEnd,
  179. 'cperiod_start' => $oSubscription->currentTermStart,
  180. 'cperiod_end' => $oSubscription->currentTermEnd,
  181. );
  182. }
  183. public function deleteSubscription($sSubscriptionId)
  184. {
  185. try {
  186. Environment::configure($this->_getSite(), $this->_getApiKey());
  187. $oResult = Subscription::cancel($sSubscriptionId);
  188. $oSubscription = $oResult->subscription();
  189. if($oSubscription->status != 'cancelled')
  190. return false;
  191. }
  192. catch (Exception $oException) {
  193. $aError = $oException->getJsonBody();
  194. $this->log('Delete Subscription Error: ' . $aError['error']['message']);
  195. $this->log($aError);
  196. return false;
  197. }
  198. $this->onDeleteSubscription($sSubscriptionId, $oSubscription->getValues());
  199. return true;
  200. }
  201. public function retrieveAddons($sStatus = 'active', $iLimit = 0)
  202. {
  203. $aAddons = array();
  204. try {
  205. $aParams = array();
  206. if(!empty($sStatus))
  207. $aParams['status[is]'] = $sStatus;
  208. if(!empty($iLimit))
  209. $aParams['limit'] = $iLimit;
  210. Environment::configure($this->_getSite(), $this->_getApiKey());
  211. $oResults = Addon::all($aParams);
  212. foreach($oResults as $oResult)
  213. $aAddons[] = $oResult->addon();
  214. }
  215. catch (Exception $oException) {
  216. $iError = $oException->getCode();
  217. $sError = $oException->getMessage();
  218. $this->log('Retrieve Addons Error: ' . $sError . '(' . $iError . ')');
  219. return false;
  220. }
  221. return $aAddons;
  222. }
  223. public function getAddons($sStatus = 'active', $iLimit = 0)
  224. {
  225. $aAddons = $this->retrieveAddons($sStatus, $iLimit);
  226. if(empty($aAddons) || !is_array($aAddons))
  227. return array();
  228. $aResult = array();
  229. foreach($aAddons as $oAddon)
  230. $aResult[] = $oAddon->getValues();
  231. return $aResult;
  232. }
  233. public function retrieveAddon($sId)
  234. {
  235. $oAddon = null;
  236. try {
  237. Environment::configure($this->_getSite(), $this->_getApiKey());
  238. $oResult = Addon::retrieve($sId);
  239. $oAddon = $oResult->addon();
  240. if($oAddon->id != $sId)
  241. return false;
  242. }
  243. catch (Exception $oException) {
  244. $iError = $oException->getCode();
  245. $sError = $oException->getMessage();
  246. $this->log('Retrieve Addon Error: ' . $sError . '(' . $iError . ')');
  247. return false;
  248. }
  249. return $oAddon;
  250. }
  251. public function getAddon($sId)
  252. {
  253. $oAddon = $this->retrieveAddon($sId);
  254. if($oAddon === false)
  255. return array();
  256. return $oAddon->getValues();
  257. }
  258. public function retrieveCustomer($sCustomerId)
  259. {
  260. $oCustomer = null;
  261. try {
  262. Environment::configure($this->_getSite(), $this->_getApiKey());
  263. $oResult = Customer::retrieve($sCustomerId);
  264. $oCustomer = $oResult->customer();
  265. if($oCustomer->id != $sCustomerId)
  266. return false;
  267. }
  268. catch (Exception $oException) {
  269. $iError = $oException->getCode();
  270. $sError = $oException->getMessage();
  271. $this->log('Retrieve Customer Error: ' . $sError . '(' . $iError . ')');
  272. return false;
  273. }
  274. return $oCustomer;
  275. }
  276. public function onDeleteSubscription($sSubscriptionId, $aSubscription)
  277. {
  278. bx_alert($this->_oModule->_oConfig->getName(), $this->_sName . '_cancel_subscription', 0, false, array(
  279. 'subscription_id' => $sSubscriptionId,
  280. 'subscription_info' => $aSubscription
  281. ));
  282. }
  283. protected function _getSite()
  284. {
  285. return $this->_iMode == CBEE_MODE_LIVE ? $this->getOption('live_site') : $this->getOption('test_site');
  286. }
  287. protected function _getApiKey()
  288. {
  289. return $this->_iMode == CBEE_MODE_LIVE ? $this->getOption('live_api_key') : $this->getOption('test_api_key');
  290. }
  291. protected function _processEvent()
  292. {
  293. $sInput = @file_get_contents("php://input");
  294. $aEvent = json_decode($sInput, true);
  295. if(empty($aEvent) || !is_array($aEvent))
  296. return 404;
  297. $sType = $aEvent['event_type'];
  298. if(!in_array($sType, array('payment_succeeded', ' payment_refunded', 'subscription_cancelled')))
  299. return 200;
  300. $this->log('Webhooks: ' . (!empty($sType) ? $sType : ''));
  301. $this->log($aEvent);
  302. $sMethod = '_processEvent' . bx_gen_method_name($sType, array('.', '_', '-'));
  303. if(!method_exists($this, $sMethod))
  304. return 200;
  305. return $this->$sMethod($aEvent) ? 200 : 403;
  306. }
  307. protected function _processEventPaymentSucceeded(&$aEvent)
  308. {
  309. $mixedResult = $this->_getDataTransaction($aEvent, 'success');
  310. if($mixedResult === false)
  311. return false;
  312. list($aPending, $aTransaction) = $mixedResult;
  313. $fTransactionAmount = (float)$aTransaction['amount'] / 100;
  314. $sTransactionCurrency = strtoupper($aTransaction['currency_code']);
  315. if($this->_bCheckAmount && ((float)$aPending['amount'] != $fTransactionAmount || strcasecmp($this->_oModule->_oConfig->getDefaultCurrencyCode(), $sTransactionCurrency) !== 0))
  316. return false;
  317. if($aPending['type'] == BX_PAYMENT_TYPE_RECURRING)
  318. $this->_oModule->getObjectSubscriptions()->prolong($aPending);
  319. return $this->_oModule->registerPayment($aPending);
  320. }
  321. protected function _processEventPaymentRefunded(&$aEvent)
  322. {
  323. $mixedResult = $this->_getDataTransaction($aEvent);
  324. if($mixedResult === false)
  325. return false;
  326. list($aPending) = $mixedResult;
  327. return $this->_oModule->refundPayment($aPending);
  328. }
  329. protected function _processEventSubscriptionCancelled(&$aEvent)
  330. {
  331. $mixedResult = $this->_getDataSubscription($aEvent);
  332. if($mixedResult === false)
  333. return false;
  334. list($aPending, $aSubscription) = $mixedResult;
  335. $this->onDeleteSubscription($aSubscription['id'], $aSubscription);
  336. return $this->_oModule->getObjectSubscriptions()->cancelLocal($aPending);
  337. }
  338. protected function _getDataTransaction(&$aEvent, $sWithStatusCheck = '')
  339. {
  340. $aTransaction = $aEvent['content']['transaction'];
  341. if(empty($aTransaction) || (!empty($sWithStatusCheck) && $aTransaction['status'] != $sWithStatusCheck))
  342. return false;
  343. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'order', 'order' => $aTransaction['subscription_id']));
  344. if(empty($aPending) || !is_array($aPending))
  345. return false;
  346. return array($aPending, $aTransaction);
  347. }
  348. protected function _getDataSubscription(&$aEvent, $sWithStatusCheck = '')
  349. {
  350. $aSubscription = $aEvent['content']['subscription'];
  351. if(empty($aSubscription) || (!empty($sWithStatusCheck) && $aSubscription['status'] != $sWithStatusCheck))
  352. return false;
  353. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'order', 'order' => $aSubscription['id']));
  354. if(empty($aPending) || !is_array($aPending))
  355. return false;
  356. return array($aPending, $aSubscription);
  357. }
  358. }
  359. /** @} */