BxPaymentProviderChargebee.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. require_once(BX_DIRECTORY_PATH_PLUGINS . 'chargebee/ChargeBee.php');
  12. define('CBEE_MODE_LIVE', 1);
  13. define('CBEE_MODE_TEST', 2);
  14. class BxPaymentProviderChargebee extends BxBaseModPaymentProvider implements iBxBaseModPaymentProvider
  15. {
  16. protected $_iMode;
  17. protected $_bCheckAmount;
  18. function __construct($aConfig)
  19. {
  20. $this->MODULE = 'bx_payment';
  21. parent::__construct($aConfig);
  22. $this->_bRedirectOnResult = false;
  23. $this->_bUseSsl = $this->getOption('ssl') == 'on';
  24. $this->_sLogFile = BX_DIRECTORY_PATH_LOGS . 'bx_pp_' . $this->_sName . '.log';
  25. $this->_iMode = (int)$this->getOption('mode');
  26. $this->_bCheckAmount = false; // Disabled for easier processing of discounted subscriptions.
  27. }
  28. public function initializeCheckout($iPendingId, $aCartInfo)
  29. {
  30. $aItem = array_shift($aCartInfo['items']);
  31. if(empty($aItem) || !is_array($aItem))
  32. return $this->_sLangsPrefix . 'err_empty_items';
  33. $aClient = $this->_oModule->getProfileInfo();
  34. $aVendor = $this->_oModule->getProfileInfo($aCartInfo['vendor_id']);
  35. $oPage = $this->createHostedPage($iPendingId, $aItem, $aClient, $aVendor);
  36. if($oPage === false)
  37. return $this->_sLangsPrefix . 'err_cannot_perform';
  38. return array(
  39. 'code' => 0,
  40. 'eval' => $this->_oModule->_oConfig->getJsObject('cart') . '.onSubscribeSubmit(oData);',
  41. 'redirect' => $oPage->url
  42. );
  43. }
  44. public function finalizeCheckout(&$aData)
  45. {
  46. $sPageId = bx_process_input($aData['id']);
  47. $iPendingId = bx_process_input($aData['pending_id'], BX_DATA_INT);
  48. if(empty($sPageId) || empty($iPendingId))
  49. return array('code' => 1, 'message' => $this->_sLangsPrefix . 'err_wrong_data');
  50. $oPage = $this->retreiveHostedPage($sPageId);
  51. if($oPage === false)
  52. return $this->_sLangsPrefix . 'err_cannot_perform';
  53. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  54. if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
  55. return array('code' => 3, 'message' => $this->_sLangsPrefix . 'err_already_processed');
  56. $oCustomer = $oPage->content()->customer();
  57. $oSubscription = $oPage->content()->subscription();
  58. $aResult = array(
  59. 'code' => BX_PAYMENT_RESULT_SUCCESS,
  60. 'message' => $this->_sLangsPrefix . 'cbee_msg_subscribed',
  61. 'pending_id' => $iPendingId,
  62. 'client_name' => _t($this->_sLangsPrefix . 'txt_buyer_name_mask', $oCustomer->firstName, $oCustomer->lastName),
  63. 'client_email' => $oCustomer->email,
  64. 'paid' => false
  65. );
  66. //--- Update pending transaction ---//
  67. $this->_oModule->_oDb->updateOrderPending($iPendingId, array(
  68. 'order' => $oSubscription->id,
  69. 'error_code' => $aResult['code'],
  70. 'error_msg' => _t($aResult['message'])
  71. ));
  72. $this->_oModule->onSubscriptionCreate($aPending, $aResult);
  73. return $aResult;
  74. }
  75. public function notify()
  76. {
  77. $iResult = $this->_processEvent();
  78. http_response_code($iResult);
  79. }
  80. public function createHostedPage($iPendingId, $aItem, $aClient, $aVendor) {
  81. $oPage = false;
  82. try {
  83. ChargeBee_Environment::configure($this->_getSite(), $this->_getApiKey());
  84. $oResult = ChargeBee_HostedPage::checkoutNew(array(
  85. 'redirectUrl' => bx_append_url_params($this->getReturnDataUrl($aVendor['id']), array(
  86. 'pending_id' => $iPendingId
  87. )),
  88. 'subscription' => array(
  89. 'planId' => $aItem['name']
  90. ),
  91. 'customer' => array(
  92. 'email' => $aClient['email'],
  93. 'firstName' => $aClient['name']
  94. ),
  95. ));
  96. $oPage = $oResult->hostedPage();
  97. }
  98. catch (Exception $oException) {
  99. $iError = $oException->getCode();
  100. $sError = $oException->getMessage();
  101. $this->log('Create Hosted Page Error: ' . $sError . '(' . $iError . ')');
  102. return false;
  103. }
  104. return $oPage;
  105. }
  106. public function retreiveHostedPage($sPageId) {
  107. $oPage = null;
  108. try {
  109. ChargeBee_Environment::configure($this->_getSite(), $this->_getApiKey());
  110. $oResult = ChargeBee_HostedPage::retrieve($sPageId);
  111. $oPage = $oResult->hostedPage();
  112. }
  113. catch (Exception $oException) {
  114. $iError = $oException->getCode();
  115. $sError = $oException->getMessage();
  116. $this->log('Retrieve Hosted Page Error: ' . $sError . '(' . $iError . ')');
  117. return false;
  118. }
  119. return $oPage;
  120. }
  121. public function retrieveSubscription($sSubscriptionId)
  122. {
  123. $oSubscription = null;
  124. try {
  125. ChargeBee_Environment::configure($this->_getSite(), $this->_getApiKey());
  126. $oResult = ChargeBee_Subscription::retrieve($sSubscriptionId);
  127. $oSubscription = $oResult->subscription();
  128. if($oSubscription->id != $sSubscriptionId)
  129. return false;
  130. }
  131. catch (Exception $oException) {
  132. $iError = $oException->getCode();
  133. $sError = $oException->getMessage();
  134. $this->log('Retrieve Subscription Error: ' . $sError . '(' . $iError . ')');
  135. return false;
  136. }
  137. return $oSubscription;
  138. }
  139. public function deleteSubscription($sSubscriptionId)
  140. {
  141. try {
  142. ChargeBee_Environment::configure($this->_getSite(), $this->_getApiKey());
  143. $oResult = ChargeBee_Subscription::cancel($sSubscriptionId);
  144. $oSubscription = $oResult->subscription();
  145. if($oSubscription->status != 'cancelled')
  146. return false;
  147. }
  148. catch (Exception $oException) {
  149. $aError = $oException->getJsonBody();
  150. $this->log('Delete Subscription Error: ' . $aError['error']['message']);
  151. $this->log($aError);
  152. return false;
  153. }
  154. return true;
  155. }
  156. protected function _getSite()
  157. {
  158. return $this->_iMode == CBEE_MODE_LIVE ? $this->getOption('live_site') : $this->getOption('test_site');
  159. }
  160. protected function _getApiKey()
  161. {
  162. return $this->_iMode == CBEE_MODE_LIVE ? $this->getOption('live_api_key') : $this->getOption('test_api_key');
  163. }
  164. protected function _processEvent()
  165. {
  166. $sInput = @file_get_contents("php://input");
  167. $aEvent = json_decode($sInput, true);
  168. if(empty($aEvent) || !is_array($aEvent))
  169. return 404;
  170. $sType = $aEvent['event_type'];
  171. if(!in_array($sType, array('payment_succeeded', ' payment_refunded', 'subscription_cancelled')))
  172. return 200;
  173. $this->log('Webhooks: ' . (!empty($sType) ? $sType : ''));
  174. $this->log($aEvent);
  175. $sMethod = '_processEvent' . bx_gen_method_name($sType, array('.', '_', '-'));
  176. if(!method_exists($this, $sMethod))
  177. return 200;
  178. return $this->$sMethod($aEvent) ? 200 : 403;
  179. }
  180. protected function _processEventPaymentSucceeded(&$aEvent)
  181. {
  182. $mixedResult = $this->_getData($aEvent, true);
  183. if($mixedResult === false)
  184. return false;
  185. list($aPending, $aTransaction) = $mixedResult;
  186. $fTransactionAmount = (float)$aTransaction['amount'] / 100;
  187. $sTransactionCurrency = strtoupper($aTransaction['currency_code']);
  188. if($this->_bCheckAmount && ((float)$aPending['amount'] != $fTransactionAmount || strcasecmp($this->_oModule->_oConfig->getDefaultCurrencyCode(), $sTransactionCurrency) !== 0))
  189. return false;
  190. return $this->_oModule->registerPayment($aPending);
  191. }
  192. protected function _processEventPaymentRefunded(&$aEvent)
  193. {
  194. $mixedResult = $this->_getData($aEvent);
  195. if($mixedResult === false)
  196. return false;
  197. list($aPending) = $mixedResult;
  198. return $this->_oModule->refundPayment($aPending);
  199. }
  200. protected function _processEventSubscriptionCancelled(&$aEvent)
  201. {
  202. $mixedResult = $this->_getData($aEvent);
  203. if($mixedResult === false)
  204. return false;
  205. list($aPending) = $mixedResult;
  206. return $this->_oModule->cancelSubscription($aPending);
  207. }
  208. protected function _getData(&$aEvent, $bWithStatusCheck = false)
  209. {
  210. $aTransaction = $aEvent['content']['transaction'];
  211. if(empty($aTransaction) || ($bWithStatusCheck && $aTransaction['status'] != 'success'))
  212. return false;
  213. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'order', 'order' => $aTransaction['subscription_id']));
  214. if(empty($aPending) || !is_array($aPending))
  215. return false;
  216. return array($aPending, $aTransaction);
  217. }
  218. }
  219. /** @} */