BxPaymentModule.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  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. 'eval' => $this->_oConfig->getJsObject('processed') . '.onSelectModule(oData);',
  106. 'data' => $this->_oTemplate->displayItems($sType, $aItems)
  107. ));
  108. }
  109. /**
  110. * @page service Service Calls
  111. * @section bx_payment Payment
  112. * @subsection bx_payment-purchase_processing Purchase Processing
  113. * @subsubsection bx_payment-is_accepting_payments is_accepting_payments
  114. *
  115. * @code bx_srv('bx_payment', 'is_accepting_payments', [...]); @endcode
  116. *
  117. * Check whether the specified vendor has a configured payment provider or not.
  118. *
  119. * @param $iVendorId integer value with vendor ID.
  120. * @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.
  121. * @return boolean value determining the result of checking.
  122. *
  123. * @see BxPaymentModule::serviceIsAcceptingPayments
  124. */
  125. /**
  126. * @ref bx_payment-is_accepting_payments "is_accepting_payments"
  127. */
  128. public function serviceIsAcceptingPayments($iVendorId, $sPaymentType = '')
  129. {
  130. $bResult = false;
  131. switch($sPaymentType) {
  132. case BX_PAYMENT_TYPE_SINGLE:
  133. $aProvidersCart = $this->_oDb->getVendorInfoProvidersSingle($iVendorId);
  134. $bResult = !empty($aProvidersCart);
  135. break;
  136. case BX_PAYMENT_TYPE_RECURRING:
  137. $aProvidersSubscription = $this->_oDb->getVendorInfoProvidersRecurring($iVendorId);
  138. $bResult = !empty($aProvidersSubscription);
  139. break;
  140. default:
  141. $aProviders = $this->_oDb->getVendorInfoProviders($iVendorId);
  142. $bResult = !empty($aProviders);
  143. }
  144. return $bResult;
  145. }
  146. /**
  147. * @page service Service Calls
  148. * @section bx_payment Payment
  149. * @subsection bx_payment-purchase_processing Purchase Processing
  150. * @subsubsection bx_payment-is_payment_provider is_payment_provider
  151. *
  152. * @code bx_srv('bx_payment', 'is_payment_provider', [...]); @endcode
  153. *
  154. * Check whether the specified vendor has configured the specified payment provider or not.
  155. *
  156. * @param $iVendorId integer value with vendor ID.
  157. * @param $sVendorProvider string value with payment provider name.
  158. * @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.
  159. * @return boolean value determining the result of checking.
  160. *
  161. * @see BxPaymentModule::serviceIsPaymentProvider
  162. */
  163. /**
  164. * @ref bx_payment-is_payment_provider "is_payment_provider"
  165. */
  166. public function serviceIsPaymentProvider($iVendorId, $sVendorProvider, $sPaymentType = '')
  167. {
  168. $aProvider = $this->serviceGetPaymentProvider($iVendorId, $sVendorProvider, $sPaymentType);
  169. return $aProvider !== false;
  170. }
  171. /**
  172. * @page service Service Calls
  173. * @section bx_payment Payment
  174. * @subsection bx_payment-purchase_processing Purchase Processing
  175. * @subsubsection bx_payment-get_payment_provider get_payment_provider
  176. *
  177. * @code bx_srv('bx_payment', 'is_payment_provider', [...]); @endcode
  178. *
  179. * Get configuration settings for the payment provider entered by the specified vendor.
  180. *
  181. * @param $iVendorId integer value with vendor ID.
  182. * @param $sVendorProvider string value with payment provider name.
  183. * @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.
  184. * @return an array with special format describing the payment provider or false value if something is wrong.
  185. *
  186. * @see BxPaymentModule::serviceGetPaymentProvider
  187. */
  188. /**
  189. * @ref bx_payment-get_payment_provider "get_payment_provider"
  190. */
  191. public function serviceGetPaymentProvider($iVendorId, $sVendorProvider, $sPaymentType = '')
  192. {
  193. $aProviders = array();
  194. switch($sPaymentType) {
  195. case BX_PAYMENT_TYPE_SINGLE:
  196. $aProviders = $this->_oDb->getVendorInfoProvidersSingle($iVendorId);
  197. break;
  198. case BX_PAYMENT_TYPE_RECURRING:
  199. $aProviders = $this->_oDb->getVendorInfoProvidersRecurring($iVendorId);
  200. break;
  201. default:
  202. $aProviders = $this->_oDb->getVendorInfoProviders($iVendorId);
  203. }
  204. return !empty($aProviders) && !empty($aProviders[$sVendorProvider]) && is_array(($aProviders[$sVendorProvider])) ? $aProviders[$sVendorProvider] : false;
  205. }
  206. /**
  207. * @page service Service Calls
  208. * @section bx_payment Payment
  209. * @subsection bx_payment-other Other
  210. * @subsubsection bx_payment-get_options_default_currency_code get_options_default_currency_code
  211. *
  212. * @code bx_srv('bx_payment', 'get_options_default_currency_code', [...]); @endcode
  213. *
  214. * Get an array with available currencies. Is used in forms.
  215. *
  216. * @return an array with available currencies represented as key => value pairs.
  217. *
  218. * @see BxPaymentModule::serviceGetOptionsDefaultCurrencyCode
  219. */
  220. /**
  221. * @ref bx_payment-get_options_default_currency_code "get_options_default_currency_code"
  222. */
  223. public function serviceGetOptionsDefaultCurrencyCode()
  224. {
  225. $CNF = &$this->_oConfig->CNF;
  226. $aCurrencies = BxDolForm::getDataItems($CNF['OBJECT_FORM_PRELISTS_CURRENCIES']);
  227. $aResult = array();
  228. foreach($aCurrencies as $sKey => $sValue)
  229. $aResult[] = array(
  230. 'key' => $sKey,
  231. 'value' => $sValue
  232. );
  233. return $aResult;
  234. }
  235. /**
  236. * @page service Service Calls
  237. * @section bx_payment Payment
  238. * @subsection bx_payment-other Other
  239. * @subsubsection bx_payment-get_options_site_admin get_options_site_admin
  240. *
  241. * @code bx_srv('bx_payment', 'get_options_site_admin', [...]); @endcode
  242. *
  243. * 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.
  244. *
  245. * @return an array with profiles represented as key => value pairs.
  246. *
  247. * @see BxPaymentModule::serviceGetOptionsSiteAdmin
  248. */
  249. /**
  250. * @ref bx_payment-get_options_site_admin "get_options_site_admin"
  251. */
  252. public function serviceGetOptionsSiteAdmin()
  253. {
  254. $aResult = array(
  255. array('key' => '', 'value' => _t('_Select_one'))
  256. );
  257. $aIds = $this->_oDb->getAdminsIds();
  258. foreach($aIds as $iId) {
  259. $aUser = $this->getProfileInfo($iId);
  260. $aResult[] = array(
  261. 'key' => $iId,
  262. 'value' => $aUser['name']
  263. );
  264. }
  265. return $aResult;
  266. }
  267. /**
  268. * Cart Processing Methods
  269. */
  270. public function actionAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount, $sCustom = '')
  271. {
  272. if(empty($sCustom) && bx_get('custom') !== false)
  273. $sCustom = bx_process_input(bx_get('custom'));
  274. $aCustom = array();
  275. if(!empty($sCustom)) {
  276. $aCustom = unserialize(base64_decode($sCustom));
  277. if(empty($aCustom) || !is_array($aCustom))
  278. $aCustom = array();
  279. }
  280. $aResult = $this->getObjectCart()->serviceAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount, $aCustom);
  281. echoJson($aResult);
  282. }
  283. /**
  284. * Isn't used yet.
  285. */
  286. public function actionDeleteFromCart($iSellerId, $iModuleId, $iItemId)
  287. {
  288. $aResult = $this->getObjectCart()->serviceDeleteFromCart($iSellerId, $iModuleId, $iItemId);
  289. echoJson($aResult);
  290. }
  291. /**
  292. * Isn't used yet.
  293. */
  294. public function actionEmptyCart($iSellerId)
  295. {
  296. $aResult = $this->getObjectCart()->serviceDeleteFromCart($iSellerId);
  297. echoJson($aResult);
  298. }
  299. public function actionSubscribe()
  300. {
  301. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  302. $sSellerProvider = bx_process_input(bx_get('seller_provider'));
  303. $iModuleId = bx_process_input(bx_get('module_id'), BX_DATA_INT);
  304. $iItemId = bx_process_input(bx_get('item_id'), BX_DATA_INT);
  305. $iItemCount = bx_process_input(bx_get('item_count'), BX_DATA_INT);
  306. if(empty($iItemCount))
  307. $iItemCount = 1;
  308. $sRedirect = bx_process_input(bx_get('redirect'));
  309. $sCustom = bx_process_input(bx_get('custom'));
  310. $aCustom = array();
  311. if(!empty($sCustom)) {
  312. $aCustom = unserialize(base64_decode($sCustom));
  313. if(empty($aCustom) || !is_array($aCustom))
  314. $aCustom = array();
  315. }
  316. $aResult = $this->getObjectSubscriptions()->serviceSubscribe($iSellerId, $sSellerProvider, $iModuleId, $iItemId, $iItemCount, $sRedirect, $aCustom);
  317. $bRedirect = !empty($aResult['redirect']);
  318. if(!empty($aResult['popup'])) {
  319. $sContent = '';
  320. $sContent .= $this->_oTemplate->displayCartJs(BX_PAYMENT_TYPE_RECURRING, $iSellerId);
  321. $sContent .= !empty($aResult['popup']['html']) ? $aResult['popup']['html'] : $aResult['popup'];
  322. return $this->_oTemplate->displayPageCodeResponse($sContent, false, true);
  323. }
  324. if(!empty($aResult['code']))
  325. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  326. if(!empty($aResult['message']) && !$bRedirect)
  327. return $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  328. if($bRedirect) {
  329. header('Location: ' . $aResult['redirect']);
  330. exit;
  331. }
  332. }
  333. public function actionSubscribeJson()
  334. {
  335. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  336. $sSellerProvider = bx_process_input(bx_get('seller_provider'));
  337. $iModuleId = bx_process_input(bx_get('module_id'), BX_DATA_INT);
  338. $iItemId = bx_process_input(bx_get('item_id'), BX_DATA_INT);
  339. $iItemCount = bx_process_input(bx_get('item_count'), BX_DATA_INT);
  340. if(empty($iItemCount))
  341. $iItemCount = 1;
  342. $sRedirect = bx_process_input(bx_get('redirect'));
  343. $sCustom = bx_process_input(bx_get('custom'));
  344. $aCustom = array();
  345. if(!empty($sCustom)) {
  346. $aCustom = unserialize(base64_decode($sCustom));
  347. if(empty($aCustom) || !is_array($aCustom))
  348. $aCustom = array();
  349. }
  350. $aResult = $this->getObjectSubscriptions()->serviceSubscribe($iSellerId, $sSellerProvider, $iModuleId, $iItemId, $iItemCount, $sRedirect, $aCustom);
  351. echoJson($aResult);
  352. }
  353. public function actionSubscriptionGetDetails($iId)
  354. {
  355. $aResult = $this->_oTemplate->displaySubscriptionGetDetails($iId);
  356. echoJson($aResult);
  357. }
  358. public function actionSubscriptionChangeDetails($iId)
  359. {
  360. $aResult = $this->_oTemplate->displaySubscriptionChangeDetails($iId);
  361. echoJson($aResult);
  362. }
  363. public function actionSubscriptionGetBilling($iId)
  364. {
  365. $aResult = $this->_oTemplate->displaySubscriptionGetBilling($iId);
  366. echoJson($aResult);
  367. }
  368. public function actionSubscriptionChangeBilling($iId)
  369. {
  370. $aResult = $this->_oTemplate->displaySubscriptionChangeBilling($iId);
  371. echoJson($aResult);
  372. }
  373. public function actionSubscriptionCancelation($iId)
  374. {
  375. $aResult = array('code' => 1, 'message' => _t('_bx_payment_err_cannot_perform'));
  376. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => $iId));
  377. if(empty($aPending) && !is_array($aPending))
  378. return echoJson($aResult);
  379. $aSubscription = $this->_oDb->getSubscription(array('type' => 'pending_id', 'pending_id' => $iId));
  380. if(empty($aSubscription) && !is_array($aSubscription))
  381. return echoJson($aResult);
  382. $oRecipient = BxDolProfile::getInstance((int)$aPending['seller_id']);
  383. if(!$oRecipient)
  384. return echoJson($aResult);
  385. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate($this->_oConfig->getPrefix('general') . 'cancelation_request', array(
  386. 'sibscription_id' => $aSubscription['subscription_id'],
  387. 'sibscription_customer' => $aSubscription['customer_id'],
  388. 'sibscription_date' => bx_time_js($aSubscription['date'], BX_FORMAT_DATE, true)
  389. ), 0, (int)$aPending['client_id']);
  390. $sEmail = '';
  391. $oProvider = $this->getObjectProvider($aPending['provider'], $aPending['seller_id']);
  392. if($oProvider !== false && $oProvider->isActive())
  393. $sEmail = $oProvider->getOption('cancellation_email');
  394. if(empty($sEmail))
  395. $sEmail = $oRecipient->getAccountObject()->getEmail();
  396. if(!sendMail($sEmail, $aTemplate['Subject'], $aTemplate['Body'], 0, array(), BX_EMAIL_SYSTEM))
  397. return echoJson($aResult);
  398. echoJson(array('code' => 0, 'message' => _t('_bx_payment_msg_cancelation_request_sent')));
  399. }
  400. /**
  401. * Payment Processing Methods
  402. */
  403. public function actionInitializeCheckout($sType)
  404. {
  405. if(!$this->isLogged())
  406. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  407. if(bx_get('seller_id') !== false && bx_get('provider') !== false && bx_get('items') !== false) {
  408. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  409. $sProvider = bx_process_input(bx_get('provider'));
  410. $aItems = bx_process_input(bx_get('items'));
  411. $mixedResult = $this->serviceInitializeCheckout(BX_PAYMENT_TYPE_SINGLE, $iSellerId, $sProvider, $aItems);
  412. if($mixedResult !== true)
  413. return $this->_oTemplate->displayPageCodeError($mixedResult);
  414. }
  415. header('Location: ' . $this->_oConfig->getUrl('URL_CART'));
  416. exit;
  417. }
  418. /**
  419. * @page service Service Calls
  420. * @section bx_payment Payment
  421. * @subsection bx_payment-purchase_processing Purchase Processing
  422. * @subsubsection bx_payment-initialize_checkout initialize_checkout
  423. *
  424. * @code bx_srv('bx_payment', 'initialize_checkout', [...]); @endcode
  425. *
  426. * Initialize the checkout process.
  427. *
  428. * @param $sType string value with payment type (single or recurring).
  429. * @param $iSellerId integer value with seller ID.
  430. * @param $sProvider string value with payment provider name.
  431. * @param $aItems (optional) an array with items to be purchased.
  432. * @param $sRedirect (optional) string value with redirect URL if it's needed.
  433. * @param $aCustom (optional) array with custom data to attach to a payment.
  434. * @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.
  435. *
  436. * @see BxPaymentModule::serviceInitializeCheckout
  437. */
  438. /**
  439. * @ref bx_payment-initialize_checkout "initialize_checkout"
  440. */
  441. public function serviceInitializeCheckout($sType, $iSellerId, $sProvider, $aItems = array(), $sRedirect = '', $aCustoms = array())
  442. {
  443. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  444. $bTypeRecurring = $sType == BX_PAYMENT_TYPE_RECURRING;
  445. if(!is_array($aItems))
  446. $aItems = array($aItems);
  447. $iSellerId = (int)$iSellerId;
  448. if($iSellerId == BX_PAYMENT_EMPTY_ID)
  449. return $this->_sLangsPrefix . 'err_unknown_vendor';
  450. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  451. if($oProvider === false || !$oProvider->isActive())
  452. return $this->_sLangsPrefix . 'err_incorrect_provider';
  453. $aInfo = $this->getObjectCart()->getInfo($sType, $this->_iUserId, $iSellerId, $aItems);
  454. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  455. return $this->_sLangsPrefix . 'err_empty_order';
  456. /*
  457. * Process FREE (price = 0) items for LOGGED IN members
  458. * WITHOUT processing via payment provider.
  459. * Note. This section isn't used for now!
  460. */
  461. $bProcessedFree = false;
  462. $sKeyPriceSingle = $this->_oConfig->getKey('KEY_ARRAY_PRICE_SINGLE');
  463. $sKeyPriceRecurring = $this->_oConfig->getKey('KEY_ARRAY_PRICE_RECURRING');
  464. foreach($aInfo['items'] as $iIndex => $aItem) {
  465. if((int)$aInfo['client_id'] == 0)
  466. continue;
  467. //--- For Single time payments.
  468. if($bTypeSingle && (float)$aItem[$sKeyPriceSingle] == 0) {
  469. $aCart = $this->_oDb->getCartContent($aInfo['client_id']);
  470. $aCartCustoms = !empty($aCart['customs']) ? unserialize($aCart['customs']) : array();
  471. $aCartItem = array($aInfo['vendor_id'], $aItem['module_id'], $aItem['id'], $aItem['quantity']);
  472. $aCartItemCustom = $this->_oConfig->pullCustom($aCartItem, $aCartCustoms);
  473. $aItemInfo = $this->callRegisterCartItem((int)$aItem['module_id'], array($aInfo['client_id'], $aInfo['vendor_id'], $aItem['id'], $aItem['quantity'], $this->_oConfig->getLicense(), $aCartItemCustom));
  474. if(is_array($aItemInfo) && !empty($aItemInfo))
  475. $bProcessedFree = true;
  476. $aInfo['items_count'] -= 1;
  477. unset($aInfo['items'][$iIndex]);
  478. $aCart['items'] = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aCartItem) . ":?'", "", $aCart['items']), ":");
  479. $this->_oDb->setCartItems($aInfo['client_id'], $aCart['items'], $aCartCustoms);
  480. }
  481. //--- For Recurring payments.
  482. if($bTypeRecurring && (float)$aItem[$sKeyPriceRecurring] == 0) {
  483. //TODO: Process FREE subscription here, if such situation will be possible.
  484. }
  485. }
  486. if(empty($aInfo['items']))
  487. return $this->_sLangsPrefix . ($bProcessedFree ? 'msg_successfully_processed_free' : 'err_empty_order');
  488. if($bTypeSingle && (empty($aCustoms) || !is_array($aCustoms))) {
  489. $aCart = $this->_oDb->getCartContent($aInfo['client_id']);
  490. $aCartCustoms = !empty($aCart['customs']) ? unserialize($aCart['customs']) : array();
  491. $aCustoms = array();
  492. foreach($aInfo['items'] as $aItem) {
  493. $sCartItem = $this->_oConfig->descriptorA2S(array($aInfo['vendor_id'], $aItem['module_id'], $aItem['id']));
  494. $aCartItemCustom = $this->_oConfig->getCustom($sCartItem, $aCartCustoms);
  495. $this->_oConfig->putCustom($sCartItem, $aCartItemCustom, $aCustoms);
  496. }
  497. }
  498. $iPendingId = $this->_oDb->insertOrderPending($this->_iUserId, $sType, $sProvider, $aInfo, $aCustoms);
  499. if(empty($iPendingId))
  500. return $this->_sLangsPrefix . 'err_access_db';
  501. /*
  502. * Perform Join WITHOUT processing via payment provider
  503. * if a client ISN'T logged in and has only ONE FREE item in the card.
  504. * Note. This section isn't used for now because only a member can purchase!
  505. */
  506. if((int)$aInfo['client_id'] == 0 && (int)$aInfo['items_count'] == 1) {
  507. reset($aInfo['items']);
  508. $aItem = current($aInfo['items']);
  509. if(!empty($aItem) && $this->_oConfig->getPrice($sType, $aItem)) {
  510. $this->_oDb->updateOrderPending($iPendingId, array(
  511. 'order' => $this->_oConfig->getLicense(),
  512. 'error_code' => '1',
  513. 'error_msg' => ''
  514. ));
  515. $this->getObjectJoin()->performJoin($iPendingId);
  516. }
  517. }
  518. return $oProvider->initializeCheckout($iPendingId, $aInfo, $sRedirect);
  519. }
  520. public function actionFinalizeCheckout($sProvider, $mixedVendorId = "")
  521. {
  522. $aData = &$_REQUEST;
  523. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  524. if($oProvider === false || !$oProvider->isActive())
  525. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  526. $aResult = $oProvider->finalizeCheckout($aData);
  527. if((int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS)
  528. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  529. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$aResult['pending_id']));
  530. $bTypeRecurring = $aPending['type'] == BX_PAYMENT_TYPE_RECURRING;
  531. if($bTypeRecurring)
  532. $this->registerSubscription($aPending, array(
  533. 'customer_id' => $aResult['customer_id'],
  534. 'subscription_id' => $aResult['subscription_id']
  535. ));
  536. $this->onPaymentRegisterBefore($aPending);
  537. //--- Check "Pay Before Join" situation
  538. if((int)$aPending['client_id'] == 0)
  539. $this->getObjectJoin()->performJoin((int)$aPending['id'], isset($aResult['client_name']) ? $aResult['client_name'] : '', isset($aResult['client_email']) ? $aResult['client_email'] : '');
  540. //--- Register payment for purchased items in associated modules
  541. if(!empty($aResult['paid']) || ($bTypeRecurring && !empty($aResult['trial'])))
  542. $this->registerPayment($aPending);
  543. bx_alert($this->getName(), 'finalize_checkout', 0, bx_get_logged_profile_id(), array(
  544. 'pending' => $aPending,
  545. 'transactions' => $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id'])),
  546. 'provider' => $oProvider,
  547. 'message' => &$aResult['message'],
  548. ));
  549. if($oProvider->needRedirect()) {
  550. header('Location: ' . $oProvider->getReturnUrl());
  551. exit;
  552. }
  553. if(!empty($aResult['redirect'])) {
  554. header('Location: ' . base64_decode(urldecode($aResult['redirect'])));
  555. exit;
  556. }
  557. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  558. }
  559. public function actionFinalizedCheckout($sProvider, $mixedVendorId = "")
  560. {
  561. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  562. if($oProvider === false || !$oProvider->isActive())
  563. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  564. $aResult = $oProvider->finalizedCheckout();
  565. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  566. }
  567. public function actionNotify($sProvider, $mixedVendorId = "")
  568. {
  569. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  570. if($oProvider === false || !$oProvider->isActive())
  571. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  572. $oProvider->notify();
  573. }
  574. public function onProfileJoin($iProfileId)
  575. {
  576. $this->getObjectJoin()->onProfileJoin($iProfileId);
  577. }
  578. public function onProfileDelete($iProfileId)
  579. {
  580. $this->_oDb->onProfileDelete($iProfileId);
  581. }
  582. public function isAllowedPurchase($aItem, $bPerform = false)
  583. {
  584. $iUserId = (int)$this->getProfileId();
  585. $aItemInfo = $this->callGetCartItem($aItem['module_id'], array($aItem['item_id']));
  586. if(empty($aItemInfo))
  587. return false;
  588. if(isAdmin())
  589. return true;
  590. $aCheckResult = checkActionModule($iUserId, 'purchase', $this->getName(), $bPerform);
  591. if($aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  592. return true;
  593. return $aCheckResult[CHECK_ACTION_MESSAGE];
  594. }
  595. public function isAllowedSell($aItem, $bPerform = false)
  596. {
  597. $iUserId = (int)$this->getProfileId();
  598. if(!$iUserId)
  599. return false;
  600. $aItemInfo = $this->callGetCartItem($aItem['module_id'], array($aItem['item_id']));
  601. if(empty($aItemInfo))
  602. return false;
  603. if(isAdmin())
  604. return true;
  605. $aCheckResult = checkActionModule($iUserId, 'sell', $this->getName(), $bPerform);
  606. if((int)$aItemInfo['author_id'] == $iUserId && $aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  607. return true;
  608. return $aCheckResult[CHECK_ACTION_MESSAGE];
  609. }
  610. public function checkData($iClientId, $iSellerId, $iModuleId, $iItemId, $iItemCount)
  611. {
  612. $CNF = &$this->_oConfig->CNF;
  613. if($iSellerId == BX_PAYMENT_EMPTY_ID || empty($iModuleId) || empty($iItemId) || empty($iItemCount))
  614. return array('code' => 1, 'message' => _t($CNF['T']['ERR_WRONG_DATA']));
  615. $iClientId = $this->getProfileId();
  616. if(empty($iClientId)) {
  617. $sLoginUrl = BxDolPermalinks::getInstance()->permalink('page.php?i=login');
  618. return array('code' => 2, 'eval' => 'window.open("' . $sLoginUrl . '", "_self");');
  619. }
  620. $mixedResult = $this->isAllowedPurchase(array('module_id' => $iModuleId, 'item_id' => $iItemId));
  621. if($mixedResult !== true) {
  622. if(is_string($mixedResult) && !empty($mixedResult))
  623. return array('code' => 2, 'message' => $mixedResult);
  624. else
  625. return array('code' => 1, 'message' => _t($CNF['T']['ERR_WRONG_DATA']));
  626. }
  627. if($iClientId == $iSellerId)
  628. return array('code' => 3, 'message' => _t($CNF['T']['ERR_SELF_PURCHASE']));
  629. $aSeller = $this->getVendorInfo($iSellerId);
  630. if(!$aSeller['active'])
  631. return array('code' => 4, 'message' => _t($CNF['T']['ERR_INACTIVE_VENDOR']));
  632. return true;
  633. }
  634. public function registerPayment($mixedPending)
  635. {
  636. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  637. if(empty($aPending) || !is_array($aPending))
  638. return false;
  639. $sType = $aPending['type'];
  640. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  641. if($bTypeSingle && (int)$aPending['processed'] == 1)
  642. return true;
  643. $iClientId = (int)$aPending['client_id'];
  644. $sLicense = $this->_oConfig->getLicense();
  645. $aCustoms = !empty($aPending['customs']) ? unserialize($aPending['customs']) : array();
  646. $aCart = array();
  647. if($bTypeSingle) {
  648. $aCart = $this->_oDb->getCartContent($iClientId);
  649. $aCart['customs'] = !empty($aCart['customs']) ? unserialize($aCart['customs']) : array();
  650. }
  651. $bResult = false;
  652. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  653. foreach($aItems as $aItem) {
  654. $sItem = $this->_oConfig->descriptorA2S(array($aItem['vendor_id'], $aItem['module_id'], $aItem['item_id']));
  655. $aItemCustom = $this->_oConfig->getCustom($sItem, $aCustoms);
  656. $sMethod = $bTypeSingle ? 'callRegisterCartItem' : 'callRegisterSubscriptionItem';
  657. $aItemInfo = $this->$sMethod((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order'], $sLicense, $aItemCustom));
  658. if(empty($aItemInfo) || !is_array($aItemInfo))
  659. continue;
  660. $this->_oDb->insertOrderProcessed(array(
  661. 'pending_id' => $aPending['id'],
  662. 'client_id' => $aPending['client_id'],
  663. 'seller_id' => $aPending['seller_id'],
  664. 'module_id' => (int)$aItem['module_id'],
  665. 'item_id' => (int)$aItem['item_id'],
  666. 'item_count' => (int)$aItem['item_count'],
  667. 'amount' => (int)$aItem['item_count'] * $this->_oConfig->getPrice($sType, $aItemInfo),
  668. 'license' => $sLicense,
  669. ));
  670. if($bTypeSingle) {
  671. $this->_oConfig->pullCustom($sItem, $aCart['customs']);
  672. $aCart['items'] = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aItem) . ":?'", "", $aCart['items']), ":");
  673. }
  674. $bResult = true;
  675. }
  676. if($bTypeSingle)
  677. $this->_oDb->setCartItems($iClientId, $aCart['items'], $aCart['customs']);
  678. if($bResult) {
  679. $this->_oDb->updateOrderPending($aPending['id'], array('processed' => 1));
  680. $this->onPaymentRegister($aPending);
  681. }
  682. return $bResult;
  683. }
  684. public function refundPayment($mixedPending)
  685. {
  686. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  687. if(empty($aPending) || !is_array($aPending))
  688. return false;
  689. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  690. $iCanceled = 0;
  691. $aOrders = $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id']));
  692. foreach($aOrders as $aOrder) {
  693. $sMethod = $bTypeSingle ? 'callUnregisterCartItem' : 'callUnregisterSubscriptionItem';
  694. $bResult = $this->$sMethod((int)$aOrder['module_id'], array($aOrder['client_id'], $aOrder['seller_id'], $aOrder['item_id'], $aOrder['item_count'], $aPending['order'], $aOrder['license']));
  695. if(!$bResult)
  696. continue;
  697. if($this->_oDb->deleteOrderProcessed($aOrder['id']))
  698. $iCanceled++;
  699. }
  700. if($iCanceled != count($aOrders))
  701. return false;
  702. $bResult = $this->_oDb->deleteOrderPending($aPending['id']);
  703. if($bResult)
  704. $this->onPaymentRefund($aPending);
  705. return $bResult;
  706. }
  707. public function registerSubscription($aPending, $aParams = array())
  708. {
  709. $this->_oDb->insertSubscription(array(
  710. 'pending_id' => $aPending['id'],
  711. 'customer_id' => $aParams['customer_id'],
  712. 'subscription_id' => $aParams['subscription_id']
  713. ));
  714. $this->onSubscriptionCreate($aPending);
  715. }
  716. public function updateSubscription($aPending, $aParams = array())
  717. {
  718. $this->_oDb->updateSubscription($aParams, array(
  719. 'pending_id' => $aPending['id']
  720. ));
  721. $this->onSubscriptionUpdate($aPending);
  722. }
  723. public function cancelSubscription($mixedPending)
  724. {
  725. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  726. if(empty($aPending) || !is_array($aPending) || $aPending['type'] != BX_PAYMENT_TYPE_RECURRING)
  727. return false;
  728. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  729. foreach($aItems as $aItem)
  730. $this->callCancelSubscriptionItem((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order']));
  731. $this->onSubscriptionCancel($aPending);
  732. }
  733. public function onPaymentRegisterBefore($aPending, $aResult = array())
  734. {
  735. //--- 'System' -> 'Before Register Payment' for Alerts Engine ---//
  736. bx_alert('system', 'before_register_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  737. //--- 'System' -> 'Before Register Payment' for Alerts Engine ---//
  738. }
  739. public function onPaymentRegister($aPending, $aResult = array())
  740. {
  741. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  742. if($bTypeSingle) {
  743. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  744. foreach($aItems as $aItem)
  745. $this->isAllowedPurchase(array('module_id' => $aItem['module_id'], 'item_id' => $aItem['item_id']), true);
  746. }
  747. //--- 'System' -> 'Register Payment' for Alerts Engine ---//
  748. bx_alert('system', 'register_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  749. //--- 'System' -> 'Register Payment' for Alerts Engine ---//
  750. }
  751. public function onPaymentRefund($aPending, $aResult = array())
  752. {
  753. //--- 'System' -> 'Refund Payment' for Alerts Engine ---//
  754. bx_alert('system', 'refund_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  755. //--- 'System' -> 'Refund Payment' for Alerts Engine ---//
  756. }
  757. public function onSubscriptionCreate($aPending, $aResult = array())
  758. {
  759. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  760. $this->isAllowedPurchase(array('module_id' => $aItems[0]['module_id'], 'item_id' => $aItems[0]['item_id']), true);
  761. //--- 'System' -> 'Create Subscription' for Alerts Engine ---//
  762. bx_alert('system', 'create_subscription', 0, $aPending['client_id'], array('pending' => $aPending));
  763. //--- 'System' -> 'Create Subscription' for Alerts Engine ---//
  764. }
  765. public function onSubscriptionUpdate($aPending, $aResult = array())
  766. {
  767. //--- 'System' -> 'Update Subscription' for Alerts Engine ---//
  768. bx_alert('system', 'update_subscription', 0, $aPending['client_id'], array('pending' => $aPending));
  769. //--- 'System' -> 'Update Subscription' for Alerts Engine ---//
  770. }
  771. public function onSubscriptionCancel($aPending, $aResult = array())
  772. {
  773. //--- 'System' -> 'Cancel Subscription' for Alerts Engine ---//
  774. bx_alert('system', 'cancel_subscription', 0, $aPending['client_id'], array('pending' => $aPending));
  775. //--- 'System' -> 'Cancel Subscription' for Alerts Engine ---//
  776. }
  777. public function setSiteSubmenu($sSubmenu, $sSelModule, $sSelName)
  778. {
  779. $oSiteSubmenu = BxDolMenu::getObjectInstance('sys_site_submenu');
  780. if(!$oSiteSubmenu)
  781. return;
  782. $sModuleSubmenu = $this->_oConfig->getObject($sSubmenu);
  783. $oModuleSubmenu = BxDolMenu::getObjectInstance($sModuleSubmenu);
  784. if(!$oModuleSubmenu)
  785. return;
  786. $oSiteSubmenu->setObjectSubmenu($sModuleSubmenu);
  787. $oModuleSubmenu->setSelected($sSelModule, $sSelName);
  788. }
  789. }
  790. /** @} */