BxPaymentProviderChargebeeV3.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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('BxPaymentProviderChargebee.php');
  12. use ChargeBee\ChargeBee\Environment;
  13. use ChargeBee\ChargeBee\Models\PortalSession;
  14. class BxPaymentProviderChargebeeV3 extends BxPaymentProviderChargebee
  15. {
  16. function __construct($aConfig)
  17. {
  18. $this->MODULE = 'bx_payment';
  19. parent::__construct($aConfig);
  20. $this->_aIncludeJs = array(
  21. 'https://js.chargebee.com/v2/chargebee.js',
  22. 'main.js',
  23. 'chargebee_v3.js'
  24. );
  25. $this->_aIncludeCss = array(
  26. 'chargebee_v3.css'
  27. );
  28. }
  29. public function actionGetHostedPageSingle($iClientId, $iVendorId)
  30. {
  31. $this->initOptionsByVendor($iVendorId);
  32. $aCartInfo = $this->_oModule->getObjectCart()->getInfo(BX_PAYMENT_TYPE_SINGLE, $iClientId, $iVendorId);
  33. $aItem = [
  34. 'amount' => 100 * $aCartInfo['items_price'],
  35. 'description' => _t($this->_sLangsPrefix . 'txt_payment_to', $aCartInfo['vendor_name'])
  36. ];
  37. $mixedItemAddons = bx_process_input(bx_get('addons'));
  38. if(!empty($mixedItemAddons)) {
  39. $aItemAddons = is_array($mixedItemAddons) ? $mixedItemAddons : $this->_oModule->_oConfig->s2a($mixedItemAddons);
  40. foreach($aItemAddons as $sItemAddon)
  41. if(!isset($aItem['addons'][$sItemAddon]))
  42. $aItem['addons'][$sItemAddon] = array(
  43. 'id' => $sItemAddon,
  44. 'quantity' => 1
  45. );
  46. else
  47. $aItem['addons'][$sItemAddon]['quantity'] += 1;
  48. $aItem['addons'] = array_values($aItem['addons']);
  49. }
  50. $aClient = $this->_oModule->getProfileInfo($iClientId);
  51. $oPage = $this->createHostedPageSingle($aItem, $aClient);
  52. if($oPage === false)
  53. return echoJson(array());
  54. header('Content-type: text/html; charset=utf-8');
  55. echo $oPage->toJson();
  56. }
  57. public function actionGetHostedPageRecurring($iClientId, $iVendorId, $sItemName)
  58. {
  59. $this->initOptionsByVendor($iVendorId);
  60. $aItem = array('name' => $sItemName);
  61. $mixedItemAddons = bx_process_input(bx_get('addons'));
  62. if(!empty($mixedItemAddons)) {
  63. $aItemAddons = is_array($mixedItemAddons) ? $mixedItemAddons : $this->_oModule->_oConfig->s2a($mixedItemAddons);
  64. foreach($aItemAddons as $sItemAddon)
  65. if(!isset($aItem['addons'][$sItemAddon]))
  66. $aItem['addons'][$sItemAddon] = array(
  67. 'id' => $sItemAddon,
  68. 'quantity' => 1
  69. );
  70. else
  71. $aItem['addons'][$sItemAddon]['quantity'] += 1;
  72. $aItem['addons'] = array_values($aItem['addons']);
  73. }
  74. $aClient = $this->_oModule->getProfileInfo($iClientId);
  75. $oPage = $this->createHostedPageRecurring($aItem, $aClient);
  76. if($oPage === false)
  77. return echoJson(array());
  78. header('Content-type: text/html; charset=utf-8');
  79. echo $oPage->toJson();
  80. }
  81. public function actionGetPortal($iPendingId)
  82. {
  83. if(!isLogged())
  84. return echoJson(array());
  85. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  86. if(empty($aPending) || !is_array($aPending))
  87. return echoJson(array());
  88. $this->initOptionsByVendor((int)$aPending['seller_id']);
  89. $aSubscription = $this->_oModule->_oDb->getSubscription(array('type' => 'pending_id', 'pending_id' => $iPendingId));
  90. if(empty($aSubscription) || !is_array($aSubscription))
  91. return echoJson(array());
  92. $oPortal = $this->getPortal($aSubscription['customer_id'], $aSubscription['subscription_id']);
  93. if($oPortal === false)
  94. return echoJson(array());
  95. header('Content-type: text/html; charset=utf-8');
  96. echo $oPortal->toJson();
  97. }
  98. public function addJsCss()
  99. {
  100. if(!$this->isActive())
  101. return;
  102. $this->_oModule->_oTemplate->addJs($this->_aIncludeJs);
  103. $this->_oModule->_oTemplate->addCss($this->_aIncludeCss);
  104. }
  105. public function getJsObject($aParams = array())
  106. {
  107. $sJsObject = $this->_oModule->_oConfig->getJsObject($this->_sName);
  108. if(isset($aParams['iModuleId'], $aParams['iSellerId'], $aParams['iItemId']))
  109. $sJsObject .= '_' . md5($aParams['iModuleId'] . '-' . $aParams['iSellerId'] . '-' . $aParams['iItemId']);
  110. return $sJsObject;
  111. }
  112. public function initializeCheckout($iPendingId, $aCartInfo, $sRedirect = '')
  113. {
  114. $sPageId = bx_process_input(bx_get('page_id'));
  115. if(empty($sPageId) || empty($iPendingId))
  116. return $this->_sLangsPrefix . 'err_wrong_data';
  117. $aItem = array_shift($aCartInfo['items']);
  118. if(empty($aItem) || !is_array($aItem))
  119. return $this->_sLangsPrefix . 'err_empty_items';
  120. $aClient = $this->_oModule->getProfileInfo();
  121. $aVendor = $this->_oModule->getProfileInfo($aCartInfo['vendor_id']);
  122. $oPage = $this->retreiveHostedPage($sPageId);
  123. if($oPage === false)
  124. return $this->_sLangsPrefix . 'err_cannot_perform';
  125. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  126. if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
  127. return $this->_sLangsPrefix . 'err_already_processed';
  128. $aResult = [];
  129. switch($aPending['type']) {
  130. case BX_PAYMENT_TYPE_SINGLE:
  131. $oInvoice = $oPage->content()->invoice();
  132. $aResult = [
  133. 'code' => 0,
  134. 'eval' => $this->_oModule->_oConfig->getJsObject('cart') . '.onCartCheckout(oData);',
  135. 'link' => $this->getReturnDataUrl($aVendor['id'], [
  136. 'order_id' => $oInvoice->id,
  137. 'customer_id' => $oInvoice->customerId,
  138. 'pending_id' => $aPending['id'],
  139. 'redirect' => $sRedirect
  140. ])
  141. ];
  142. break;
  143. case BX_PAYMENT_TYPE_RECURRING:
  144. $aResult = [
  145. 'code' => 0,
  146. 'eval' => $this->_oModule->_oConfig->getJsObject('cart') . '.onSubscribeSubmit(oData);',
  147. 'redirect' => $this->getReturnDataUrl($aVendor['id'], [
  148. 'order_id' => $oPage->content()->subscription()->id,
  149. 'customer_id' => $oPage->content()->customer()->id,
  150. 'pending_id' => $aPending['id'],
  151. 'redirect' => $sRedirect
  152. ])
  153. ];
  154. break;
  155. }
  156. return $aResult;
  157. }
  158. public function finalizeCheckout(&$aData)
  159. {
  160. $sOrderId = bx_process_input($aData['order_id']);
  161. $sCustomerId = bx_process_input($aData['customer_id']);
  162. $iPendingId = bx_process_input($aData['pending_id'], BX_DATA_INT);
  163. if(empty($iPendingId))
  164. return array('code' => 1, 'message' => $this->_sLangsPrefix . 'err_wrong_data');
  165. $sRedirect = bx_process_input($aData['redirect']);
  166. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  167. if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
  168. return array('code' => 3, 'message' => $this->_sLangsPrefix . 'err_already_processed');
  169. $oCustomer = $this->retrieveCustomer($sCustomerId);
  170. if($oCustomer === false)
  171. return array('code' => 4, 'message' => $this->_sLangsPrefix . 'err_cannot_perform');
  172. $sOrder = '';
  173. $aResult = [
  174. 'code' => BX_PAYMENT_RESULT_SUCCESS,
  175. 'message' => '',
  176. 'pending_id' => $iPendingId,
  177. 'client_name' => _t($this->_sLangsPrefix . 'txt_buyer_name_mask', $oCustomer->firstName, $oCustomer->lastName),
  178. 'client_email' => $oCustomer->email,
  179. 'paid' => false,
  180. 'redirect' => $sRedirect
  181. ];
  182. switch($aPending['type']) {
  183. case BX_PAYMENT_TYPE_SINGLE:
  184. $oInvoice = $this->retrieveInvoice($sOrderId);
  185. if($oInvoice === false || empty($oInvoice->linkedPayments))
  186. return ['code' => 4, 'message' => $this->_sLangsPrefix . 'err_cannot_perform'];
  187. $sOrder = $oInvoice->linkedPayments[0]->txnId;
  188. $aResult = array_merge($aResult, [
  189. 'message' => $this->_sLangsPrefix . 'cbee_msg_charged',
  190. 'paid' => $oInvoice->status == 'paid',
  191. ]);
  192. break;
  193. case BX_PAYMENT_TYPE_RECURRING:
  194. $oSubscription = $this->retrieveSubscription($sOrderId);
  195. if($oSubscription === false)
  196. return ['code' => 4, 'message' => $this->_sLangsPrefix . 'err_cannot_perform'];
  197. $sOrder = $oSubscription->id;
  198. $aResult = array_merge($aResult, [
  199. 'message' => $this->_sLangsPrefix . 'cbee_msg_subscribed',
  200. 'customer_id' => $oCustomer->id,
  201. 'subscription_id' => $oSubscription->id,
  202. 'trial' => $oSubscription->status == 'in_trial',
  203. ]);
  204. break;
  205. }
  206. //--- Update pending transaction ---//
  207. $this->_oModule->_oDb->updateOrderPending($iPendingId, [
  208. 'order' => $sOrder,
  209. 'error_code' => $aResult['code'],
  210. 'error_msg' => _t($aResult['message'])
  211. ]);
  212. return $aResult;
  213. }
  214. public function getPortal($sCustomerId, $sSubscriptionId)
  215. {
  216. $oPortal = false;
  217. try {
  218. Environment::configure($this->_getSite(), $this->_getApiKey());
  219. $oResult = PortalSession::create(array(
  220. 'customer' => array(
  221. 'id' => $sCustomerId
  222. )
  223. ));
  224. $oPortal = $oResult->portalSession();
  225. }
  226. catch (Exception $oException) {
  227. $iError = $oException->getCode();
  228. $sError = $oException->getMessage();
  229. $this->log('Get Portal Error: ' . $sError . '(' . $iError . ')', '', BX_LOG_ERR);
  230. return false;
  231. }
  232. return $oPortal;
  233. }
  234. public function getJsCode($aParams = array())
  235. {
  236. $sSite = '';
  237. /**
  238. * @hooks
  239. * @hookdef hook-bx_payment-chargebee_v3_get_js_code 'bx_payment', 'chargebee_v3_get_js_code' - hook to override JavaScript code
  240. * - $unit_name - equals `bx_payment`
  241. * - $action - equals `chargebee_v3_get_js_code`
  242. * - $object_id - not used
  243. * - $sender_id - not used
  244. * - $extra_params - array of additional params with the following array keys:
  245. * - `site` - [string] by ref, site name from ChargeBee account, can be overridden in hook processing
  246. * - `params` - [array] by ref, params array as key&value pairs, can be overridden in hook processing
  247. * @hook @ref hook-bx_payment-chargebee_v3_get_js_code
  248. */
  249. bx_alert($this->_oModule->_oConfig->getName(), $this->_sName . '_get_js_code', 0, 0, [
  250. 'site' => &$sSite,
  251. 'params' => &$aParams,
  252. 'site_ref' => &$sSite,
  253. 'param_ref' => &$aParams
  254. ]);
  255. return $this->_oModule->_oTemplate->getJsCode($this->_sName, array_merge(array(
  256. 'sProvider' => $this->_sName,
  257. 'sSite' => !empty($sSite) ? $sSite : $this->_getSite()
  258. ), $aParams));
  259. }
  260. public function getButtonSingle($iClientId, $iVendorId, $aParams = [])
  261. {
  262. $oCart = $this->_oModule->getObjectCart();
  263. $aCartInfo = $oCart->getInfo(BX_PAYMENT_TYPE_SINGLE, $iClientId, (int)$iVendorId);
  264. if(empty($aCartInfo) || !is_array($aCartInfo))
  265. return '';
  266. $aItems = [];
  267. $aCartItems = $oCart->getCartItems($iClientId, $iVendorId);
  268. foreach($aCartItems as $aCartItem)
  269. $aItems[] = $this->_oModule->_oConfig->descriptorA2S($aCartItem);
  270. return $this->_getButton(BX_PAYMENT_TYPE_SINGLE, $iClientId, $iVendorId, array_merge($aParams, [
  271. 'iSellerId' => $iVendorId,
  272. 'aItems' => $aItems
  273. ]));
  274. }
  275. public function getButtonSingleJs($iClientId, $iVendorId, $aParams = [])
  276. {
  277. $oCart = $this->_oModule->getObjectCart();
  278. $aCartInfo = $oCart->getInfo(BX_PAYMENT_TYPE_SINGLE, $iClientId, (int)$iVendorId);
  279. if(empty($aCartInfo) || !is_array($aCartInfo))
  280. return '';
  281. $aItems = [];
  282. $aCartItems = $oCart->getCartItems($iClientId, $iVendorId);
  283. foreach($aCartItems as $aCartItem)
  284. $aItems[] = $this->_oModule->_oConfig->descriptorA2S($aCartItem);
  285. return $this->_getButtonJs(BX_PAYMENT_TYPE_SINGLE, $iClientId, $iVendorId, array_merge($aParams, [
  286. 'iSellerId' => $iVendorId,
  287. 'aItems' => $aItems
  288. ]));
  289. }
  290. public function getButtonRecurring($iClientId, $iVendorId, $aParams = array())
  291. {
  292. return $this->_getButton(BX_PAYMENT_TYPE_RECURRING, $iClientId, $iVendorId, $aParams);
  293. }
  294. public function getButtonRecurringJs($iClientId, $iVendorId, $aParams = array())
  295. {
  296. return $this->_getButtonJs(BX_PAYMENT_TYPE_RECURRING, $iClientId, $iVendorId, $aParams);
  297. }
  298. protected function _getButton($sType, $iClientId, $iVendorId, $aParams = array())
  299. {
  300. list($sJsCode, $sJsMethod) = $this->_getButtonJs($sType, $iClientId, $iVendorId, $aParams);
  301. return $this->_oModule->_oTemplate->parseHtmlByName('cbee_v3_button_' . $sType . '.html', array(
  302. 'type' => $sType,
  303. 'link' => 'javascript:void(0)',
  304. 'caption' => _t($this->_sLangsPrefix . 'cbee_txt_checkout_with_' . $sType, $this->_sCaption),
  305. 'onclick' => $sJsMethod,
  306. 'js_object' => $this->_oModule->_oConfig->getJsObject($this->_sName),
  307. 'js_code' => $sJsCode
  308. ));
  309. }
  310. protected function _getButtonJs($sType, $iClientId, $iVendorId, $aParams = array())
  311. {
  312. $sSite = '';
  313. /**
  314. * @hooks
  315. * @hookdef hook-bx_payment-chargebee_v3_get_button 'bx_payment', 'chargebee_v3_get_button' - hook to override checkout/subscibe button
  316. * - $unit_name - equals `bx_payment`
  317. * - $action - equals `chargebee_v3_get_button`
  318. * - $object_id - not used
  319. * - $sender_id - client (buyer) profile id
  320. * - $extra_params - array of additional params with the following array keys:
  321. * - `type` - [string] by ref, payment type ('single' or 'recurring'), can be overridden in hook processing
  322. * - `site` - [string] by ref, site name from ChargeBee account, can be overridden in hook processing
  323. * - `params` - [array] by ref, params array as key&value pairs, can be overridden in hook processing
  324. * @hook @ref hook-bx_payment-chargebee_v3_get_button
  325. */
  326. bx_alert($this->_oModule->_oConfig->getName(), $this->_sName . '_get_button', 0, $iClientId, [
  327. 'type' => &$sType,
  328. 'site' => &$sSite,
  329. 'params' => &$aParams,
  330. 'type_ref' => &$sType,
  331. 'site_ref' => &$sSite,
  332. 'params_ref' => &$aParams,
  333. ]);
  334. $sJsMethod = '';
  335. $sJsObject = $this->getJsObject($aParams);
  336. switch($sType) {
  337. case BX_PAYMENT_TYPE_SINGLE:
  338. $sJsMethod = $sJsObject . '.checkout(this)';
  339. break;
  340. case BX_PAYMENT_TYPE_RECURRING:
  341. $sJsMethod = $sJsObject . '.subscribe(this)';
  342. break;
  343. }
  344. return array($this->_oModule->_oTemplate->getJsCode($this->_sName, array_merge(array(
  345. 'js_object' => $sJsObject,
  346. 'sProvider' => $this->_sName,
  347. 'sSite' => !empty($sSite) ? $sSite : $this->_getSite(),
  348. 'iClientId' => $iClientId
  349. ), $aParams)), $sJsMethod);
  350. }
  351. public function getMenuItemsActionsRecurring($iClientId, $iVendorId, $aParams = array())
  352. {
  353. if(empty($aParams['id']))
  354. return array();
  355. $sPrefix = 'bx-payment-strp-';
  356. $sJsObject = $this->_oModule->_oConfig->getJsObject($this->_sName);
  357. return array(
  358. array('id' => $sPrefix . 'manager', 'name' => $sPrefix . 'manager', 'class' => '', 'link' => 'javascript:void(0)', 'onclick' => "javascript:return " . $sJsObject . ".manage(this, '" . $aParams['id'] . "')", 'target' => '_self', 'title' => _t('_bx_payment_cbee_menu_item_title_manager'))
  359. );
  360. }
  361. }
  362. /** @} */