BxPaymentModule.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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('BX_PAYMENT_ORDERS_TYPE_PENDING', 'pending');
  12. define('BX_PAYMENT_ORDERS_TYPE_PROCESSED', 'processed');
  13. define('BX_PAYMENT_ORDERS_TYPE_SUBSCRIPTION', 'subscription');
  14. define('BX_PAYMENT_ORDERS_TYPE_HISTORY', 'history');
  15. define('BX_PAYMENT_EMPTY_ID', 0);
  16. define('BX_PAYMENT_RESULT_SUCCESS', 0);
  17. /**
  18. * Payment module by BoonEx
  19. *
  20. * This module is needed to work with payment providers and organize the process
  21. * of some item purchasing. Shopping Cart and Orders Manager are included.
  22. *
  23. * Integration notes:
  24. * To integrate your module with this one, you need:
  25. * 1. Get 'Add To Cart' button using serviceGetAddToCartLink service.
  26. * 2. Add info about your module in the 'bx_pmt_modules' table.
  27. * 3. Realize the following service methods in your Module class.
  28. * a. serviceGetItems($iSellerId) - Is used in Orders Administration to get all products of the requested seller(vendor).
  29. * b. serviceGetCartItem($iClientId, $iItemId) - Is used in Shopping Cart to get one product by specified id.
  30. * c. serviceRegisterCartItem($iClientId, $iSellerId, $iItemId, $iItemCount, $sOrderId) - Register purchased product.
  31. * d. serviceUnregisterCartItem($iClientId, $iSellerId, $iItemId, $iItemCount, $sOrderId) - Unregister the product purchased earlier.
  32. * @see You may see an example of integration in Membership module.
  33. *
  34. *
  35. * Profile's Wall:
  36. * no spy events
  37. *
  38. *
  39. *
  40. * Spy:
  41. * no spy events
  42. *
  43. *
  44. *
  45. * Memberships/ACL:
  46. * Doesn't depend on user's membership.
  47. *
  48. *
  49. *
  50. * Service methods:
  51. *
  52. * Is used to get "Add to cart" link for some item(s) in your module.
  53. * @see BxPmtModule::serviceGetAddToCartLink
  54. * BxDolService::call('payment', 'get_add_to_cart_link', array($iSellerId, $mixedModuleId, $iItemId, $iItemCount));
  55. *
  56. * Check transaction(s) in database which satisty all conditions.
  57. * @see BxPmtModule::serviceGetOrdersInfo
  58. * BxDolService::call('payment', 'get_orders_info', array($aConditions), 'Orders');
  59. *
  60. * Get total count of items in Shopping Cart.
  61. * @see BxPmtModule::serviceGetCartItemsCount
  62. * BxDolService::call('payment', 'get_cart_items_count', array($iUserId, $iOldCount));
  63. * @note is needed for internal usage(integration with member tool bar).
  64. *
  65. * Get Shopping cart content.
  66. * @see BxPmtModule::serviceGetCartItems
  67. * BxDolService::call('payment', 'get_cart_items');
  68. * @note is needed for internal usage(integration with member tool bar).
  69. *
  70. *
  71. * Alerts:
  72. * no alerts available
  73. *
  74. */
  75. class BxPaymentModule extends BxBaseModPaymentModule
  76. {
  77. protected $_iUserId;
  78. protected $_aOrderTypes;
  79. function __construct($aModule)
  80. {
  81. parent::__construct($aModule);
  82. $this->_iUserId = $this->getProfileId();
  83. $this->_aOrderTypes = array(
  84. BX_PAYMENT_ORDERS_TYPE_PENDING,
  85. BX_PAYMENT_ORDERS_TYPE_PROCESSED,
  86. BX_PAYMENT_ORDERS_TYPE_SUBSCRIPTION,
  87. BX_PAYMENT_ORDERS_TYPE_HISTORY
  88. );
  89. }
  90. /**
  91. * Manage Orders Methods
  92. */
  93. public function actionGetClients()
  94. {
  95. $sTerm = bx_get('term');
  96. $aResult = BxDolService::call('system', 'profiles_search', array($sTerm), 'TemplServiceProfiles');
  97. echoJson($aResult);
  98. }
  99. public function actionGetItems($sType, $iModuleId)
  100. {
  101. $iSellerId = $this->getProfileId();
  102. $aItems = $this->callGetCartItems((int)$iModuleId, array($iSellerId));
  103. echoJson(array(
  104. 'code' => 0,
  105. 'data' => $this->_oTemplate->displayItems($sType, $aItems)
  106. ));
  107. }
  108. /**
  109. * @page service Service Calls
  110. * @section bx_payment Payment
  111. * @subsection bx_payment-purchase_processing Purchase Processing
  112. * @subsubsection bx_payment-is_accepting_payments is_accepting_payments
  113. *
  114. * @code bx_srv('bx_payment', 'is_accepting_payments', [...]); @endcode
  115. *
  116. * Check whether the specified vendor has a configured payment provider or not.
  117. *
  118. * @param $iVendorId integer value with vendor ID.
  119. * @param $sPaymentType (optional) string value with payment type. If specified then the vendor will be checked for having the payment provider of the requested type.
  120. * @return boolean value determining the result of checking.
  121. *
  122. * @see BxPaymentModule::serviceIsAcceptingPayments
  123. */
  124. /**
  125. * @ref bx_payment-is_accepting_payments "is_accepting_payments"
  126. */
  127. public function serviceIsAcceptingPayments($iVendorId, $sPaymentType = '')
  128. {
  129. $bResult = false;
  130. switch($sPaymentType) {
  131. case BX_PAYMENT_TYPE_SINGLE:
  132. $aProvidersCart = $this->_oDb->getVendorInfoProvidersSingle($iVendorId);
  133. $bResult = !empty($aProvidersCart);
  134. break;
  135. case BX_PAYMENT_TYPE_RECURRING:
  136. $aProvidersSubscription = $this->_oDb->getVendorInfoProvidersRecurring($iVendorId);
  137. $bResult = !empty($aProvidersSubscription);
  138. break;
  139. default:
  140. $aProviders = $this->_oDb->getVendorInfoProviders($iVendorId);
  141. $bResult = !empty($aProviders);
  142. }
  143. return $bResult;
  144. }
  145. /**
  146. * @page service Service Calls
  147. * @section bx_payment Payment
  148. * @subsection bx_payment-purchase_processing Purchase Processing
  149. * @subsubsection bx_payment-is_payment_provider is_payment_provider
  150. *
  151. * @code bx_srv('bx_payment', 'is_payment_provider', [...]); @endcode
  152. *
  153. * Check whether the specified vendor has configured the specified payment provider or not.
  154. *
  155. * @param $iVendorId integer value with vendor ID.
  156. * @param $sVendorProvider string value with payment provider name.
  157. * @param $sPaymentType (optional) string value with payment type. If specified then the vendor will be checked for having the payment provider of the requested type.
  158. * @return boolean value determining the result of checking.
  159. *
  160. * @see BxPaymentModule::serviceIsPaymentProvider
  161. */
  162. /**
  163. * @ref bx_payment-is_payment_provider "is_payment_provider"
  164. */
  165. public function serviceIsPaymentProvider($iVendorId, $sVendorProvider, $sPaymentType = '')
  166. {
  167. $aProvider = $this->serviceGetPaymentProvider($iVendorId, $sVendorProvider, $sPaymentType);
  168. return $aProvider !== false;
  169. }
  170. /**
  171. * @page service Service Calls
  172. * @section bx_payment Payment
  173. * @subsection bx_payment-purchase_processing Purchase Processing
  174. * @subsubsection bx_payment-get_payment_provider get_payment_provider
  175. *
  176. * @code bx_srv('bx_payment', 'is_payment_provider', [...]); @endcode
  177. *
  178. * Get configuration settings for the payment provider entered by the specified vendor.
  179. *
  180. * @param $iVendorId integer value with vendor ID.
  181. * @param $sVendorProvider string value with payment provider name.
  182. * @param $sPaymentType (optional) string value with payment type. If specified then the vendor will be checked for having the payment provider of the requested type.
  183. * @return an array with special format describing the payment provider or false value if something is wrong.
  184. *
  185. * @see BxPaymentModule::serviceGetPaymentProvider
  186. */
  187. /**
  188. * @ref bx_payment-get_payment_provider "get_payment_provider"
  189. */
  190. public function serviceGetPaymentProvider($iVendorId, $sVendorProvider, $sPaymentType = '')
  191. {
  192. $aProviders = array();
  193. switch($sPaymentType) {
  194. case BX_PAYMENT_TYPE_SINGLE:
  195. $aProviders = $this->_oDb->getVendorInfoProvidersSingle($iVendorId);
  196. break;
  197. case BX_PAYMENT_TYPE_RECURRING:
  198. $aProviders = $this->_oDb->getVendorInfoProvidersRecurring($iVendorId);
  199. break;
  200. default:
  201. $aProviders = $this->_oDb->getVendorInfoProviders($iVendorId);
  202. }
  203. return !empty($aProviders) && !empty($aProviders[$sVendorProvider]) && is_array(($aProviders[$sVendorProvider])) ? $aProviders[$sVendorProvider] : false;
  204. }
  205. /**
  206. * @page service Service Calls
  207. * @section bx_payment Payment
  208. * @subsection bx_payment-other Other
  209. * @subsubsection bx_payment-get_options_default_currency_code get_options_default_currency_code
  210. *
  211. * @code bx_srv('bx_payment', 'get_options_default_currency_code', [...]); @endcode
  212. *
  213. * Get an array with available currencies. Is used in forms.
  214. *
  215. * @return an array with available currencies represented as key => value pairs.
  216. *
  217. * @see BxPaymentModule::serviceGetOptionsDefaultCurrencyCode
  218. */
  219. /**
  220. * @ref bx_payment-get_options_default_currency_code "get_options_default_currency_code"
  221. */
  222. public function serviceGetOptionsDefaultCurrencyCode()
  223. {
  224. $CNF = &$this->_oConfig->CNF;
  225. $aCurrencies = BxDolForm::getDataItems($CNF['OBJECT_FORM_PRELISTS_CURRENCIES']);
  226. $aResult = array();
  227. foreach($aCurrencies as $sKey => $sValue)
  228. $aResult[] = array(
  229. 'key' => $sKey,
  230. 'value' => $sValue
  231. );
  232. return $aResult;
  233. }
  234. /**
  235. * @page service Service Calls
  236. * @section bx_payment Payment
  237. * @subsection bx_payment-other Other
  238. * @subsubsection bx_payment-get_options_site_admin get_options_site_admin
  239. *
  240. * @code bx_srv('bx_payment', 'get_options_site_admin', [...]); @endcode
  241. *
  242. * Get an array with profiles which can be used as 'Site Admin (Owner)'. 'Site Admin' is a person who will be displayed to buyers when something is selling on behalf of the site.
  243. *
  244. * @return an array with profiles represented as key => value pairs.
  245. *
  246. * @see BxPaymentModule::serviceGetOptionsSiteAdmin
  247. */
  248. /**
  249. * @ref bx_payment-get_options_site_admin "get_options_site_admin"
  250. */
  251. public function serviceGetOptionsSiteAdmin()
  252. {
  253. $aResult = array(
  254. array('key' => '', 'value' => _t('_Select_one'))
  255. );
  256. $aIds = $this->_oDb->getAdminsIds();
  257. foreach($aIds as $iId) {
  258. $aUser = $this->getProfileInfo($iId);
  259. $aResult[] = array(
  260. 'key' => $iId,
  261. 'value' => $aUser['name']
  262. );
  263. }
  264. return $aResult;
  265. }
  266. /**
  267. * Cart Processing Methods
  268. */
  269. public function actionAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount)
  270. {
  271. $aResult = $this->getObjectCart()->serviceAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount);
  272. echoJson($aResult);
  273. }
  274. /**
  275. * Isn't used yet.
  276. */
  277. public function actionDeleteFromCart($iSellerId, $iModuleId, $iItemId)
  278. {
  279. $aResult = $this->getObjectCart()->serviceDeleteFromCart($iSellerId, $iModuleId, $iItemId);
  280. echoJson($aResult);
  281. }
  282. /**
  283. * Isn't used yet.
  284. */
  285. public function actionEmptyCart($iSellerId)
  286. {
  287. $aResult = $this->getObjectCart()->serviceDeleteFromCart($iSellerId);
  288. echoJson($aResult);
  289. }
  290. public function actionSubscribe()
  291. {
  292. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  293. $sSellerProvider = bx_process_input(bx_get('seller_provider'));
  294. $iModuleId = bx_process_input(bx_get('module_id'), BX_DATA_INT);
  295. $iItemId = bx_process_input(bx_get('item_id'), BX_DATA_INT);
  296. $iItemCount = bx_process_input(bx_get('item_count'), BX_DATA_INT);
  297. if(empty($iItemCount))
  298. $iItemCount = 1;
  299. $aResult = $this->getObjectSubscriptions()->serviceSubscribe($iSellerId, $sSellerProvider, $iModuleId, $iItemId, $iItemCount);
  300. $bRedirect = !empty($aResult['redirect']);
  301. if(!empty($aResult['popup'])) {
  302. $sContent = '';
  303. $sContent .= $this->_oTemplate->displayCartJs(BX_PAYMENT_TYPE_RECURRING, $iSellerId);
  304. $sContent .= !empty($aResult['popup']['html']) ? $aResult['popup']['html'] : $aResult['popup'];
  305. return $this->_oTemplate->displayPageCodeResponse($sContent, false, true);
  306. }
  307. if(!empty($aResult['code']))
  308. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  309. if(!empty($aResult['message']) && !$bRedirect)
  310. return $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  311. if($bRedirect) {
  312. header('Location: ' . $aResult['redirect']);
  313. exit;
  314. }
  315. }
  316. public function actionSubscribeJson()
  317. {
  318. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  319. $sSellerProvider = bx_process_input(bx_get('seller_provider'));
  320. $iModuleId = bx_process_input(bx_get('module_id'), BX_DATA_INT);
  321. $iItemId = bx_process_input(bx_get('item_id'), BX_DATA_INT);
  322. $iItemCount = bx_process_input(bx_get('item_count'), BX_DATA_INT);
  323. if(empty($iItemCount))
  324. $iItemCount = 1;
  325. $sRedirect = bx_process_input(bx_get('redirect'));
  326. $aResult = $this->getObjectSubscriptions()->serviceSubscribe($iSellerId, $sSellerProvider, $iModuleId, $iItemId, $iItemCount, $sRedirect);
  327. echoJson($aResult);
  328. }
  329. public function actionSubscriptionGetDetails($iId)
  330. {
  331. $aResult = $this->_oTemplate->displaySubscriptionGetDetails($iId);
  332. echoJson($aResult);
  333. }
  334. public function actionSubscriptionChangeDetails($iId)
  335. {
  336. $aResult = $this->_oTemplate->displaySubscriptionChangeDetails($iId);
  337. echoJson($aResult);
  338. }
  339. public function actionSubscriptionGetBilling($iId)
  340. {
  341. $aResult = $this->_oTemplate->displaySubscriptionGetBilling($iId);
  342. echoJson($aResult);
  343. }
  344. public function actionSubscriptionChangeBilling($iId)
  345. {
  346. $aResult = $this->_oTemplate->displaySubscriptionChangeBilling($iId);
  347. echoJson($aResult);
  348. }
  349. public function actionSubscriptionCancelation($iId)
  350. {
  351. $aResult = array('code' => 1, 'message' => _t('_bx_payment_err_cannot_perform'));
  352. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => $iId));
  353. if(empty($aPending) && !is_array($aPending))
  354. return echoJson($aResult);
  355. $aSubscription = $this->_oDb->getSubscription(array('type' => 'pending_id', 'pending_id' => $iId));
  356. if(empty($aSubscription) && !is_array($aSubscription))
  357. return echoJson($aResult);
  358. $oRecipient = BxDolProfile::getInstance((int)$aPending['seller_id']);
  359. if(!$oRecipient)
  360. return echoJson($aResult);
  361. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate($this->_oConfig->getPrefix('general') . 'cancelation_request', array(
  362. 'sibscription_id' => $aSubscription['subscription_id'],
  363. 'sibscription_customer' => $aSubscription['customer_id'],
  364. 'sibscription_date' => bx_time_js($aSubscription['date'], BX_FORMAT_DATE, true)
  365. ), 0, (int)$aPending['client_id']);
  366. $sEmail = '';
  367. $oProvider = $this->getObjectProvider($aPending['provider'], $aPending['seller_id']);
  368. if($oProvider !== false && $oProvider->isActive())
  369. $sEmail = $oProvider->getOption('cancellation_email');
  370. if(empty($sEmail))
  371. $sEmail = $oRecipient->getAccountObject()->getEmail();
  372. if(!sendMail($sEmail, $aTemplate['Subject'], $aTemplate['Body'], 0, array(), BX_EMAIL_SYSTEM))
  373. return echoJson($aResult);
  374. echoJson(array('code' => 0, 'message' => _t('_bx_payment_msg_cancelation_request_sent')));
  375. }
  376. /**
  377. * Payment Processing Methods
  378. */
  379. public function actionInitializeCheckout($sType)
  380. {
  381. if(!$this->isLogged())
  382. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  383. if(bx_get('seller_id') !== false && bx_get('provider') !== false && bx_get('items') !== false) {
  384. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  385. $sProvider = bx_process_input(bx_get('provider'));
  386. $aItems = bx_process_input(bx_get('items'));
  387. $mixedResult = $this->serviceInitializeCheckout(BX_PAYMENT_TYPE_SINGLE, $iSellerId, $sProvider, $aItems);
  388. if($mixedResult !== true)
  389. return $this->_oTemplate->displayPageCodeError($mixedResult);
  390. }
  391. header('Location: ' . $this->_oConfig->getUrl('URL_CART'));
  392. exit;
  393. }
  394. /**
  395. * @page service Service Calls
  396. * @section bx_payment Payment
  397. * @subsection bx_payment-purchase_processing Purchase Processing
  398. * @subsubsection bx_payment-initialize_checkout initialize_checkout
  399. *
  400. * @code bx_srv('bx_payment', 'initialize_checkout', [...]); @endcode
  401. *
  402. * Initialize the checkout process.
  403. *
  404. * @param $sType string value with payment type (single or recurring).
  405. * @param $iSellerId integer value with seller ID.
  406. * @param $sProvider string value with payment provider name.
  407. * @param $aItems (optional) an array with items to be purchased.
  408. * @param $sRedirect (optional) string value with redirect URL if it's needed.
  409. * @return the result depends on the payment provider which is used for processing or represented as string value with error message if something is wrong.
  410. *
  411. * @see BxPaymentModule::serviceInitializeCheckout
  412. */
  413. /**
  414. * @ref bx_payment-initialize_checkout "initialize_checkout"
  415. */
  416. public function serviceInitializeCheckout($sType, $iSellerId, $sProvider, $aItems = array(), $sRedirect = '')
  417. {
  418. if(!is_array($aItems))
  419. $aItems = array($aItems);
  420. $iSellerId = (int)$iSellerId;
  421. if($iSellerId == BX_PAYMENT_EMPTY_ID)
  422. return $this->_sLangsPrefix . 'err_unknown_vendor';
  423. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  424. if($oProvider === false || !$oProvider->isActive())
  425. return $this->_sLangsPrefix . 'err_incorrect_provider';
  426. $aInfo = $this->getObjectCart()->getInfo($sType, $this->_iUserId, $iSellerId, $aItems);
  427. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  428. return $this->_sLangsPrefix . 'err_empty_order';
  429. /*
  430. * Process FREE (price = 0) items for LOGGED IN members
  431. * WITHOUT processing via payment provider.
  432. */
  433. $bProcessedFree = false;
  434. $sKeyPriceSingle = $this->_oConfig->getKey('KEY_ARRAY_PRICE_SINGLE');
  435. $sKeyPriceRecurring = $this->_oConfig->getKey('KEY_ARRAY_PRICE_RECURRING');
  436. foreach($aInfo['items'] as $iIndex => $aItem)
  437. if((int)$aInfo['client_id'] != 0 && (float)$aItem[$sKeyPriceSingle] == 0 && (float)$aItem[$sKeyPriceRecurring] == 0) {
  438. $aItemInfo = $this->callRegisterCartItem((int)$aItem['module_id'], array($aInfo['client_id'], $aInfo['vendor_id'], $aItem['id'], $aItem['quantity'], $this->_oConfig->getLicense()));
  439. if(is_array($aItemInfo) && !empty($aItemInfo))
  440. $bProcessedFree = true;
  441. $aInfo['items_count'] -= 1;
  442. unset($aInfo['items'][$iIndex]);
  443. $sCartItems = $this->_oDb->getCartItems($aInfo['client_id']);
  444. $sCartItems = trim(preg_replace("'" . $this->_oConfig->descriptorA2S(array($aInfo['vendor_id'], $aItem['module_id'], $aItem['id'], $aItem['quantity'])) . ":?'", "", $sCartItems), ":");
  445. $this->_oDb->setCartItems($aInfo['client_id'], $sCartItems);
  446. }
  447. if(empty($aInfo['items']))
  448. return $this->_sLangsPrefix . ($bProcessedFree ? 'msg_successfully_processed_free' : 'err_empty_order');
  449. $iPendingId = $this->_oDb->insertOrderPending($this->_iUserId, $sType, $sProvider, $aInfo);
  450. if(empty($iPendingId))
  451. return $this->_sLangsPrefix . 'err_access_db';
  452. /*
  453. * Perform Join WITHOUT processing via payment provider
  454. * if a client ISN'T logged in and has only ONE FREE item in the card.
  455. */
  456. if((int)$aInfo['client_id'] == 0 && (int)$aInfo['items_count'] == 1) {
  457. reset($aInfo['items']);
  458. $aItem = current($aInfo['items']);
  459. if(!empty($aItem) && $this->_oConfig->getPrice($sType, $aItem)) {
  460. $this->_oDb->updateOrderPending($iPendingId, array(
  461. 'order' => $this->_oConfig->getLicense(),
  462. 'error_code' => '1',
  463. 'error_msg' => ''
  464. ));
  465. $this->getObjectJoin()->performJoin($iPendingId);
  466. }
  467. }
  468. return $oProvider->initializeCheckout($iPendingId, $aInfo, $sRedirect);
  469. }
  470. public function actionFinalizeCheckout($sProvider, $mixedVendorId = "")
  471. {
  472. $aData = &$_REQUEST;
  473. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  474. if($oProvider === false || !$oProvider->isActive())
  475. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  476. $aResult = $oProvider->finalizeCheckout($aData);
  477. if((int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS)
  478. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  479. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$aResult['pending_id']));
  480. $bTypeRecurring = $aPending['type'] == BX_PAYMENT_TYPE_RECURRING;
  481. if($bTypeRecurring)
  482. $this->registerSubscription($aPending, array(
  483. 'customer_id' => $aResult['customer_id'],
  484. 'subscription_id' => $aResult['subscription_id']
  485. ));
  486. $this->onPaymentRegisterBefore($aPending);
  487. //--- Check "Pay Before Join" situation
  488. if((int)$aPending['client_id'] == 0)
  489. $this->getObjectJoin()->performJoin((int)$aPending['id'], isset($aResult['client_name']) ? $aResult['client_name'] : '', isset($aResult['client_email']) ? $aResult['client_email'] : '');
  490. //--- Register payment for purchased items in associated modules
  491. if(!empty($aResult['paid']) || ($bTypeRecurring && !empty($aResult['trial'])))
  492. $this->registerPayment($aPending);
  493. bx_alert($this->getName(), 'finalize_checkout', 0, bx_get_logged_profile_id(), array(
  494. 'pending' => $aPending,
  495. 'transactions' => $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id'])),
  496. 'provider' => $oProvider,
  497. 'message' => &$aResult['message'],
  498. ));
  499. if($oProvider->needRedirect()) {
  500. header('Location: ' . $oProvider->getReturnUrl());
  501. exit;
  502. }
  503. if(!empty($aResult['redirect'])) {
  504. header('Location: ' . base64_decode(urldecode($aResult['redirect'])));
  505. exit;
  506. }
  507. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  508. }
  509. public function actionFinalizedCheckout($sProvider, $mixedVendorId = "")
  510. {
  511. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  512. if($oProvider === false || !$oProvider->isActive())
  513. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  514. $aResult = $oProvider->finalizedCheckout();
  515. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  516. }
  517. public function actionNotify($sProvider, $mixedVendorId = "")
  518. {
  519. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  520. if($oProvider === false || !$oProvider->isActive())
  521. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  522. $oProvider->notify();
  523. }
  524. public function onProfileJoin($iProfileId)
  525. {
  526. $this->getObjectJoin()->onProfileJoin($iProfileId);
  527. }
  528. public function onProfileDelete($iProfileId)
  529. {
  530. $this->_oDb->onProfileDelete($iProfileId);
  531. }
  532. public function isAllowedPurchase($aItem, $bPerform = false)
  533. {
  534. $iUserId = (int)$this->getProfileId();
  535. $aItemInfo = $this->callGetCartItem($aItem['module_id'], array($aItem['item_id']));
  536. if(empty($aItemInfo))
  537. return false;
  538. if(isAdmin())
  539. return true;
  540. $aCheckResult = checkActionModule($iUserId, 'purchase', $this->getName(), $bPerform);
  541. if($aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  542. return true;
  543. return $aCheckResult[CHECK_ACTION_MESSAGE];
  544. }
  545. public function isAllowedSell($aItem, $bPerform = false)
  546. {
  547. $iUserId = (int)$this->getProfileId();
  548. if(!$iUserId)
  549. return false;
  550. $aItemInfo = $this->callGetCartItem($aItem['module_id'], array($aItem['item_id']));
  551. if(empty($aItemInfo))
  552. return false;
  553. if(isAdmin())
  554. return true;
  555. $aCheckResult = checkActionModule($iUserId, 'sell', $this->getName(), $bPerform);
  556. if((int)$aItemInfo['author_id'] == $iUserId && $aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  557. return true;
  558. return $aCheckResult[CHECK_ACTION_MESSAGE];
  559. }
  560. public function checkData($iClientId, $iSellerId, $iModuleId, $iItemId, $iItemCount)
  561. {
  562. $CNF = &$this->_oConfig->CNF;
  563. if($iSellerId == BX_PAYMENT_EMPTY_ID || empty($iModuleId) || empty($iItemId) || empty($iItemCount))
  564. return array('code' => 1, 'message' => _t($CNF['T']['ERR_WRONG_DATA']));
  565. $iClientId = $this->getProfileId();
  566. if(empty($iClientId)) {
  567. $sLoginUrl = BxDolPermalinks::getInstance()->permalink('page.php?i=login');
  568. return array('code' => 2, 'eval' => 'window.open("' . $sLoginUrl . '", "_self");');
  569. }
  570. $mixedResult = $this->isAllowedPurchase(array('module_id' => $iModuleId, 'item_id' => $iItemId));
  571. if($mixedResult !== true) {
  572. if(is_string($mixedResult) && !empty($mixedResult))
  573. return array('code' => 2, 'message' => $mixedResult);
  574. else
  575. return array('code' => 1, 'message' => _t($CNF['T']['ERR_WRONG_DATA']));
  576. }
  577. if($iClientId == $iSellerId)
  578. return array('code' => 3, 'message' => _t($CNF['T']['ERR_SELF_PURCHASE']));
  579. $aSeller = $this->getVendorInfo($iSellerId);
  580. if(!$aSeller['active'])
  581. return array('code' => 4, 'message' => _t($CNF['T']['ERR_INACTIVE_VENDOR']));
  582. return true;
  583. }
  584. public function registerPayment($mixedPending)
  585. {
  586. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  587. if(empty($aPending) || !is_array($aPending))
  588. return false;
  589. $sType = $aPending['type'];
  590. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  591. if($bTypeSingle && (int)$aPending['processed'] == 1)
  592. return true;
  593. $iClientId = (int)$aPending['client_id'];
  594. $sLicense = $this->_oConfig->getLicense();
  595. $sCartItems = '';
  596. if($bTypeSingle)
  597. $sCartItems = $this->_oDb->getCartItems($iClientId);
  598. $bResult = false;
  599. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  600. foreach($aItems as $aItem) {
  601. $sMethod = $bTypeSingle ? 'callRegisterCartItem' : 'callRegisterSubscriptionItem';
  602. $aItemInfo = $this->$sMethod((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order'], $sLicense));
  603. if(empty($aItemInfo) || !is_array($aItemInfo))
  604. continue;
  605. $this->_oDb->insertOrderProcessed(array(
  606. 'pending_id' => $aPending['id'],
  607. 'client_id' => $aPending['client_id'],
  608. 'seller_id' => $aPending['seller_id'],
  609. 'module_id' => $aItem['module_id'],
  610. 'item_id' => $aItem['item_id'],
  611. 'item_count' => $aItem['item_count'],
  612. 'amount' => $aItem['item_count'] * $this->_oConfig->getPrice($sType, $aItemInfo),
  613. 'license' => $sLicense,
  614. ));
  615. if($bTypeSingle)
  616. $sCartItems = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aItem) . ":?'", "", $sCartItems), ":");
  617. $bResult = true;
  618. }
  619. if($bTypeSingle)
  620. $this->_oDb->setCartItems($iClientId, $sCartItems);
  621. if($bResult) {
  622. $this->_oDb->updateOrderPending($aPending['id'], array('processed' => 1));
  623. $this->onPaymentRegister($aPending);
  624. }
  625. return $bResult;
  626. }
  627. public function refundPayment($mixedPending)
  628. {
  629. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  630. if(empty($aPending) || !is_array($aPending))
  631. return false;
  632. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  633. $iCanceled = 0;
  634. $aOrders = $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id']));
  635. foreach($aOrders as $aOrder) {
  636. $sMethod = $bTypeSingle ? 'callUnregisterCartItem' : 'callUnregisterSubscriptionItem';
  637. $bResult = $this->$sMethod((int)$aOrder['module_id'], array($aOrder['client_id'], $aOrder['seller_id'], $aOrder['item_id'], $aOrder['item_count'], $aPending['order'], $aOrder['license']));
  638. if(!$bResult)
  639. continue;
  640. if($this->_oDb->deleteOrderProcessed($aOrder['id']))
  641. $iCanceled++;
  642. }
  643. if($iCanceled != count($aOrders))
  644. return false;
  645. $bResult = $this->_oDb->deleteOrderPending($aPending['id']);
  646. if($bResult)
  647. $this->onPaymentRefund($aPending);
  648. return $bResult;
  649. }
  650. public function registerSubscription($aPending, $aParams = array())
  651. {
  652. $this->_oDb->insertSubscription(array(
  653. 'pending_id' => $aPending['id'],
  654. 'customer_id' => $aParams['customer_id'],
  655. 'subscription_id' => $aParams['subscription_id']
  656. ));
  657. $this->onSubscriptionCreate($aPending);
  658. }
  659. public function updateSubscription($aPending, $aParams = array())
  660. {
  661. $this->_oDb->updateSubscription($aParams, array(
  662. 'pending_id' => $aPending['id']
  663. ));
  664. $this->onSubscriptionUpdate($aPending);
  665. }
  666. public function cancelSubscription($mixedPending)
  667. {
  668. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  669. if(empty($aPending) || !is_array($aPending) || $aPending['type'] != BX_PAYMENT_TYPE_RECURRING)
  670. return false;
  671. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  672. foreach($aItems as $aItem)
  673. $this->callCancelSubscriptionItem((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order']));
  674. $this->onSubscriptionCancel($aPending);
  675. }
  676. public function onPaymentRegisterBefore($aPending, $aResult = array())
  677. {
  678. //--- 'System' -> 'Before Register Payment' for Alerts Engine ---//
  679. bx_alert('system', 'before_register_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  680. //--- 'System' -> 'Before Register Payment' for Alerts Engine ---//
  681. }
  682. public function onPaymentRegister($aPending, $aResult = array())
  683. {
  684. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  685. if($bTypeSingle) {
  686. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  687. foreach($aItems as $aItem)
  688. $this->isAllowedPurchase(array('module_id' => $aItem['module_id'], 'item_id' => $aItem['item_id']), true);
  689. }
  690. //--- 'System' -> 'Register Payment' for Alerts Engine ---//
  691. bx_alert('system', 'register_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  692. //--- 'System' -> 'Register Payment' for Alerts Engine ---//
  693. }
  694. public function onPaymentRefund($aPending, $aResult = array())
  695. {
  696. //--- 'System' -> 'Refund Payment' for Alerts Engine ---//
  697. bx_alert('system', 'refund_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  698. //--- 'System' -> 'Refund Payment' for Alerts Engine ---//
  699. }
  700. public function onSubscriptionCreate($aPending, $aResult = array())
  701. {
  702. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  703. $this->isAllowedPurchase(array('module_id' => $aItems[0]['module_id'], 'item_id' => $aItems[0]['item_id']), true);
  704. //--- 'System' -> 'Create Subscription' for Alerts Engine ---//
  705. bx_alert('system', 'create_subscription', 0, $aPending['client_id'], array('pending' => $aPending));
  706. //--- 'System' -> 'Create Subscription' for Alerts Engine ---//
  707. }
  708. public function onSubscriptionUpdate($aPending, $aResult = array())
  709. {
  710. //--- 'System' -> 'Update Subscription' for Alerts Engine ---//
  711. bx_alert('system', 'update_subscription', 0, $aPending['client_id'], array('pending' => $aPending));
  712. //--- 'System' -> 'Update Subscription' for Alerts Engine ---//
  713. }
  714. public function onSubscriptionCancel($aPending, $aResult = array())
  715. {
  716. //--- 'System' -> 'Cancel Subscription' for Alerts Engine ---//
  717. bx_alert('system', 'cancel_subscription', 0, $aPending['client_id'], array('pending' => $aPending));
  718. //--- 'System' -> 'Cancel Subscription' for Alerts Engine ---//
  719. }
  720. public function setSiteSubmenu($sSubmenu, $sSelModule, $sSelName)
  721. {
  722. $oSiteSubmenu = BxDolMenu::getObjectInstance('sys_site_submenu');
  723. if(!$oSiteSubmenu)
  724. return;
  725. $sModuleSubmenu = $this->_oConfig->getObject($sSubmenu);
  726. $oModuleSubmenu = BxDolMenu::getObjectInstance($sModuleSubmenu);
  727. if(!$oModuleSubmenu)
  728. return;
  729. $oSiteSubmenu->setObjectSubmenu($sModuleSubmenu);
  730. $oModuleSubmenu->setSelected($sSelModule, $sSelName);
  731. }
  732. }
  733. /** @} */