BxPaymentProviderChargebee.php 15 KB

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