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