BxPaymentProviderCredits.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. /**
  12. * Credits payment provider can be used when
  13. * Credits module is installed and active.
  14. */
  15. class BxPaymentProviderCredits extends BxBaseModPaymentProvider implements iBxBaseModPaymentProvider
  16. {
  17. protected $_sModuleCredits;
  18. function __construct($aConfig)
  19. {
  20. $this->MODULE = 'bx_payment';
  21. parent::__construct($aConfig);
  22. $this->_sModuleCredits = $this->_oModule->_oConfig->CNF['MODULE_CREDITS'];
  23. }
  24. public function initializeCheckout($iPendingId, $aCartInfo, $sRedirect = '')
  25. {
  26. if(!BxDolModuleQuery::getInstance()->isEnabledByName($this->_sModuleCredits))
  27. return ($sMsg = $this->_sLangsPrefix . 'cdt_err_not_available') && $this->_bIsApi ? [bx_api_get_msg($sMsg)] : $sMsg;
  28. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  29. if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
  30. return ($sMsg = $this->_sLangsPrefix . 'err_already_processed') && $this->_bIsApi ? [bx_api_get_msg($sMsg)] : $sMsg;
  31. $iSellerId = (int)$aCartInfo['vendor_id'];
  32. $sCustomData = $this->_constructCustomData($aCartInfo['vendor_id'], $iPendingId);
  33. $sReturnDataUrl = $this->getReturnDataUrl($iSellerId);
  34. switch($aPending['type']) {
  35. case BX_PAYMENT_TYPE_SINGLE:
  36. $aFormData = array(
  37. 'currency_code' => $aCartInfo['vendor_currency_code'],
  38. 'currency_sign' => $aCartInfo['vendor_currency_sign'],
  39. 'seller' => $iSellerId,
  40. 'amount' => (float)$aCartInfo['items_price'],
  41. 'items_count' => count($aCartInfo['items']),
  42. 'custom' => $sCustomData,
  43. 'return_data_url' => $sReturnDataUrl,
  44. );
  45. $iIndex = 0;
  46. foreach($aCartInfo['items'] as $aItem) {
  47. $aFormData['item_title_' . $iIndex] = bx_process_output($aItem['title']);
  48. $aFormData['item_quantity_' . $iIndex] = $aItem['quantity'];
  49. $iIndex += 1;
  50. }
  51. $sCheckoutUrl = bx_srv($this->_sModuleCredits, 'get_checkout_url');
  52. if($this->_bIsApi)
  53. return ['redirect' => bx_api_get_relative_url(bx_append_url_params($sCheckoutUrl, $aFormData))];
  54. $this->_oModule->_oTemplate->displayPageCodeRedirect($sCheckoutUrl, $aFormData);
  55. exit;
  56. case BX_PAYMENT_TYPE_RECURRING:
  57. $aItem = array_shift($aCartInfo['items']);
  58. return array(
  59. 'code' => 0,
  60. 'popup' => array(
  61. 'html' => bx_srv($this->_sModuleCredits, 'get_popup_subscribe', array(array(
  62. 'currency_code' => $aCartInfo['vendor_currency_code'],
  63. 'currency_sign' => $aCartInfo['vendor_currency_sign'],
  64. 'seller' => $iSellerId,
  65. 'title' => bx_process_output($aItem['title']),
  66. 'amount' => $aItem['price_recurring'],
  67. 'period' => $aItem['period_recurring'],
  68. 'period_unit' => $aItem['period_unit_recurring'],
  69. 'trial' => isset($aItem['trial_recurring']) ? $aItem['trial_recurring'] : 0,
  70. 'custom' => $sCustomData,
  71. 'return_data_url' => $sReturnDataUrl,
  72. ))),
  73. 'options' => array(
  74. 'closeOnOuterClick' => true,
  75. 'removeOnClose' => true
  76. )
  77. )
  78. );
  79. }
  80. }
  81. public function finalizeCheckout(&$aData)
  82. {
  83. $aResult = $this->_finalizeCheckout($aData);
  84. if((int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS) {
  85. $this->log('Finalize Checkout: Failed', '', BX_LOG_ERR);
  86. $this->log($aData, '', BX_LOG_ERR);
  87. $this->log($aResult, '', BX_LOG_ERR);
  88. }
  89. if(!empty($aResult['pending_id']))
  90. $this->_oModule->_oDb->updateOrderPending($aResult['pending_id'], array(
  91. 'order' => $aResult['order'],
  92. 'error_code' => $aResult['code'],
  93. 'error_msg' => _t($aResult['message'])
  94. ));
  95. return $aResult;
  96. }
  97. public function makePayment($mixedPending)
  98. {
  99. if(!BxDolModuleQuery::getInstance()->isEnabledByName($this->_sModuleCredits))
  100. return ['code' => 1, 'message' => $this->_sLangsPrefix . 'cdt_err_not_available'];
  101. if(!is_array($mixedPending))
  102. $mixedPending = $this->_oModule->_oDb->getOrderPending(['type' => 'id', 'id' => (int)$mixedPending]);
  103. if(empty($mixedPending) || !is_array($mixedPending))
  104. return ['code' => 2, 'message' => $this->_sLangsPrefix . 'err_not_found_pending'];
  105. $iClient = (int)$mixedPending['client_id'];
  106. $oClient = BxDolProfile::getInstance($iClient);
  107. $iSeller = (int)$mixedPending['seller_id'];
  108. $oSeller = BxDolProfile::getInstance($iSeller);
  109. if(!$oClient || !$oSeller)
  110. return ['code' => 3, 'message' => $this->_sLangsPrefix . 'err_wrong_data'];
  111. $fAmountM = $this->_getAmountByPending($mixedPending);
  112. $fAmountC = bx_srv($this->_sModuleCredits, 'convert_money_to_credits', [$fAmountM]);
  113. $fClientBalance = bx_srv($this->_sModuleCredits, 'get_profile_balance', [$iClient]);
  114. if($fAmountC > $fClientBalance) {
  115. $aSubscription = $this->_oModule->_oDb->getSubscription([
  116. 'type' => 'pending_id',
  117. 'pending_id' => $mixedPending['id']
  118. ]);
  119. if(!empty($aSubscription) && is_array($aSubscription)) {
  120. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate($this->_oModule->_oConfig->getPrefix('general') . 'wrong_balance', [
  121. 'profile_name' => $oClient->getDisplayName(),
  122. 'profile_link' => $oClient->getUrl(),
  123. 'subscription_id' => $aSubscription['subscription_id'],
  124. 'subscription_customer' => $aSubscription['customer_id'],
  125. 'subscription_provider' => _t('_bx_payment_txt_name_' . $mixedPending['provider']),
  126. 'subscription_date' => date(getParam('sys_format_date'), $aSubscription['date_add']),
  127. ], 0, $iClient);
  128. if($aTemplate !== false)
  129. sendMail($oClient->getAccountObject()->getEmail(), $aTemplate['Subject'], $aTemplate['Body'], 0, [], BX_EMAIL_SYSTEM);
  130. }
  131. return ['code' => 4, 'message' => $this->_sLangsPrefix . 'cdt_err_wrong_balance'];
  132. }
  133. if(!bx_srv($this->_sModuleCredits, 'make_payment', [$iClient, $fAmountC, $iSeller, $mixedPending['order']]))
  134. return ['code' => 5, 'message' => $this->_sLangsPrefix . 'err_cannot_perform'];
  135. return true;
  136. }
  137. public function cancelRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
  138. {
  139. /**
  140. * @hooks
  141. * @hookdef hook-bx_payment-credits_cancel_subscription 'bx_payment', 'credits_cancel_subscription' - hook after a subscription was canceled
  142. * - $unit_name - equals `bx_payment`
  143. * - $action - equals `credits_cancel_subscription`
  144. * - $object_id - not used
  145. * - $sender_id - not used
  146. * - $extra_params - array of additional params with the following array keys:
  147. * - `pending_id` - [string] pending transaction id
  148. * - `subscription_id` - [string] unique subscription id
  149. * @hook @ref hook-bx_payment-credits_cancel_subscription
  150. */
  151. bx_alert($this->MODULE, $this->_sName . '_cancel_subscription', 0, false, [
  152. 'pending_id' => $iPendingId,
  153. 'subscription_id' => $sSubscriptionId,
  154. ]);
  155. return true;
  156. }
  157. public function getMenuItemsActionsRecurring($iClientId, $iVendorId, $aParams = array())
  158. {
  159. return array();
  160. }
  161. protected function _finalizeCheckout(&$aData)
  162. {
  163. list($iSellerId, $iPendingId) = $this->_deconstructCustomData($aData['c']);
  164. if(empty($this->_aOptions) && !empty($iPendingId))
  165. $this->_aOptions = $this->getOptionsByPending((int)$iPendingId);
  166. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  167. if(empty($aPending) || !is_array($aPending))
  168. return array('code' => 1, 'message' => $this->_sLangsPrefix . 'err_not_found_pending');
  169. if(empty($this->_aOptions) || !BxDolModuleQuery::getInstance()->isEnabledByName($this->_sModuleCredits))
  170. return array('code' => 2, 'message' => $this->_sLangsPrefix . 'err_incorrect_provider', 'pending_id' => $iPendingId);
  171. switch($aPending['type']) {
  172. case BX_PAYMENT_TYPE_SINGLE:
  173. if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
  174. return array('code' => 3, 'message' => $this->_sLangsPrefix . 'err_already_processed');
  175. $sOrder = $aData['o'];
  176. $fAmount = $this->_getAmountByPending($aPending);
  177. if(!bx_srv($this->_sModuleCredits, 'validate_checkout', array((int)$aPending['seller_id'], (int)$aPending['client_id'], $fAmount, $sOrder)))
  178. return array('code' => 4, 'message' => $this->_sLangsPrefix . 'cdt_err_wrong_transaction', 'pending_id' => $iPendingId);
  179. $aResult = array(
  180. 'message' => $this->_sLangsPrefix . 'cdt_msg_charged',
  181. 'order' => $sOrder,
  182. 'paid' => true
  183. );
  184. break;
  185. case BX_PAYMENT_TYPE_RECURRING:
  186. $sSubscriptionId = bx_process_input($aData['sb']);
  187. $aResult = array(
  188. 'message' => $this->_sLangsPrefix . 'cdt_msg_subscribed',
  189. 'customer_id' => bx_process_input($aData['cs']),
  190. 'subscription_id' => $sSubscriptionId,
  191. 'trial' => (bool)$aData['tr'],
  192. 'order' => $sSubscriptionId,
  193. );
  194. break;
  195. }
  196. $oClient = BxDolProfile::getInstance($aPending['client_id']);
  197. return array_merge(array(
  198. 'code' => BX_PAYMENT_RESULT_SUCCESS,
  199. 'message' => '',
  200. 'pending_id' => $iPendingId,
  201. 'client_name' => $oClient->getDisplayName(),
  202. 'client_email' => $oClient->getAccountObject()->getEmail(),
  203. 'order' => ''
  204. ), $aResult);
  205. }
  206. protected function _constructCustomData()
  207. {
  208. $aParams = func_get_args();
  209. return urlencode(base64_encode(implode('|', $aParams)));
  210. }
  211. protected function _deconstructCustomData($data)
  212. {
  213. return explode('|', base64_decode(urldecode($data)));
  214. }
  215. protected function _getAmountByPending($aPending)
  216. {
  217. $fCurrencyRate = false;
  218. $sCurrencyDefault = $this->_oModule->_oConfig->getDefaultCurrencyCode();
  219. if(!empty($aPending['data'])) {
  220. $aPendingData = unserialize($aPending['data']);
  221. if(!empty($aPendingData['cur_rate']))
  222. $fCurrencyRate = (float)$aPendingData['cur_rate'];
  223. if(!empty($aPendingData['cur_def']))
  224. $sCurrencyDefault = $aPendingData['cur_def'];
  225. }
  226. $fAmount = (float)$aPending['amount'];
  227. if(strcmp($aPending['currency'], $sCurrencyDefault) != 0)
  228. $fAmount = $this->_oModule->serviceConvert($fAmount, $aPending['currency'], $sCurrencyDefault, $fCurrencyRate);
  229. return $fAmount;
  230. }
  231. }
  232. /** @} */