BxPaymentModule.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  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. $mixedResult = $this->isAllowedManage($aPending);
  386. if($mixedResult !== true)
  387. return echoJson(array('code' => 2, 'message' => $mixedResult));
  388. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate($this->_oConfig->getPrefix('general') . 'cancelation_request', array(
  389. 'sibscription_id' => $aSubscription['subscription_id'],
  390. 'sibscription_customer' => $aSubscription['customer_id'],
  391. 'sibscription_date' => bx_time_js($aSubscription['date'], BX_FORMAT_DATE, true)
  392. ), 0, (int)$aPending['client_id']);
  393. $sEmail = '';
  394. $oProvider = $this->getObjectProvider($aPending['provider'], $aPending['seller_id']);
  395. if($oProvider !== false && $oProvider->isActive())
  396. $sEmail = $oProvider->getOption('cancellation_email');
  397. if(empty($sEmail))
  398. $sEmail = $oRecipient->getAccountObject()->getEmail();
  399. if(!sendMail($sEmail, $aTemplate['Subject'], $aTemplate['Body'], 0, array(), BX_EMAIL_SYSTEM))
  400. return echoJson($aResult);
  401. echoJson(array('code' => 0, 'message' => _t('_bx_payment_msg_cancelation_request_sent')));
  402. }
  403. public function actionSubscriptionCancel($iId, $mixedGridObject = false)
  404. {
  405. $aResult = array('code' => 1, 'message' => _t('_bx_payment_err_cannot_perform'));
  406. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => $iId));
  407. if(empty($aPending) || !is_array($aPending))
  408. return echoJson($aResult);
  409. $mixedResult = $this->isAllowedManage($aPending);
  410. if($mixedResult !== true)
  411. return echoJson(array('code' => 2, 'message' => $mixedResult));
  412. if(!$this->getObjectSubscriptions()->cancel($iId))
  413. return echoJson($aResult);
  414. if(empty($mixedGridObject) && bx_get('grid') !== false)
  415. $mixedGridObject = bx_process_input(bx_get('grid'));
  416. if(!empty($mixedGridObject) && $aPending['client_id'] == $this->getProfileId()) {
  417. $oGrid = BxDolGrid::getObjectInstance($mixedGridObject, $this->_oTemplate);
  418. $oGrid->addQueryParam('client_id', $aPending['client_id']);
  419. return echoJson(array('object' => $mixedGridObject, 'grid' => $oGrid->getCode(false), 'blink' => array($iId)));
  420. }
  421. else
  422. return echoJson(array('code' => 0, 'message' => _t('_bx_payment_msg_successfully_performed')));
  423. }
  424. /**
  425. * Payment Processing Methods
  426. */
  427. public function actionInitializeCheckout($sType)
  428. {
  429. if(!$this->isLogged())
  430. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  431. if(bx_get('seller_id') !== false && bx_get('provider') !== false && bx_get('items') !== false) {
  432. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  433. $sProvider = bx_process_input(bx_get('provider'));
  434. $aItems = bx_process_input(bx_get('items'));
  435. $mixedResult = $this->serviceInitializeCheckout(BX_PAYMENT_TYPE_SINGLE, $iSellerId, $sProvider, $aItems);
  436. if($mixedResult !== true)
  437. return $this->_oTemplate->displayPageCodeError($mixedResult);
  438. }
  439. header('Location: ' . $this->_oConfig->getUrl('URL_CART'));
  440. exit;
  441. }
  442. /**
  443. * @page service Service Calls
  444. * @section bx_payment Payment
  445. * @subsection bx_payment-purchase_processing Purchase Processing
  446. * @subsubsection bx_payment-initialize_checkout initialize_checkout
  447. *
  448. * @code bx_srv('bx_payment', 'initialize_checkout', [...]); @endcode
  449. *
  450. * Initialize the checkout process.
  451. *
  452. * @param $sType string value with payment type (single or recurring).
  453. * @param $iSellerId integer value with seller ID.
  454. * @param $sProvider string value with payment provider name.
  455. * @param $aItems (optional) an array with items to be purchased.
  456. * @param $sRedirect (optional) string value with redirect URL if it's needed.
  457. * @param $aCustom (optional) array with custom data to attach to a payment.
  458. * @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.
  459. *
  460. * @see BxPaymentModule::serviceInitializeCheckout
  461. */
  462. /**
  463. * @ref bx_payment-initialize_checkout "initialize_checkout"
  464. */
  465. public function serviceInitializeCheckout($sType, $iSellerId, $sProvider, $aItems = array(), $sRedirect = '', $aCustoms = array())
  466. {
  467. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  468. $bTypeRecurring = $sType == BX_PAYMENT_TYPE_RECURRING;
  469. if(!is_array($aItems))
  470. $aItems = array($aItems);
  471. $iSellerId = (int)$iSellerId;
  472. if($iSellerId == BX_PAYMENT_EMPTY_ID)
  473. return $this->_sLangsPrefix . 'err_unknown_vendor';
  474. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  475. if($oProvider === false || !$oProvider->isActive())
  476. return $this->_sLangsPrefix . 'err_incorrect_provider';
  477. $aInfo = $this->getObjectCart()->getInfo($sType, $this->_iUserId, $iSellerId, $aItems);
  478. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  479. return $this->_sLangsPrefix . 'err_empty_order';
  480. /*
  481. * Process FREE (price = 0) items for LOGGED IN members
  482. * WITHOUT processing via payment provider.
  483. * Note. This section isn't used for now!
  484. */
  485. $bProcessedFree = false;
  486. $sKeyPriceSingle = $this->_oConfig->getKey('KEY_ARRAY_PRICE_SINGLE');
  487. $sKeyPriceRecurring = $this->_oConfig->getKey('KEY_ARRAY_PRICE_RECURRING');
  488. foreach($aInfo['items'] as $iIndex => $aItem) {
  489. if((int)$aInfo['client_id'] == 0)
  490. continue;
  491. //--- For Single time payments.
  492. if($bTypeSingle && (float)$aItem[$sKeyPriceSingle] == 0) {
  493. $aCart = $this->_oDb->getCartContent($aInfo['client_id']);
  494. $aCartCustoms = !empty($aCart['customs']) ? unserialize($aCart['customs']) : array();
  495. $aCartItem = array($aInfo['vendor_id'], $aItem['module_id'], $aItem['id'], $aItem['quantity']);
  496. $aCartItemCustom = $this->_oConfig->pullCustom($aCartItem, $aCartCustoms);
  497. $aItemInfo = $this->callRegisterCartItem((int)$aItem['module_id'], array($aInfo['client_id'], $aInfo['vendor_id'], $aItem['id'], $aItem['quantity'], $this->_oConfig->getLicense(), $aCartItemCustom));
  498. if(is_array($aItemInfo) && !empty($aItemInfo))
  499. $bProcessedFree = true;
  500. $aInfo['items_count'] -= 1;
  501. unset($aInfo['items'][$iIndex]);
  502. $aCart['items'] = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aCartItem) . ":?'", "", $aCart['items']), ":");
  503. $this->_oDb->setCartItems($aInfo['client_id'], $aCart['items'], $aCartCustoms);
  504. }
  505. //--- For Recurring payments.
  506. if($bTypeRecurring && (float)$aItem[$sKeyPriceRecurring] == 0) {
  507. //TODO: Process FREE subscription here, if such situation will be possible.
  508. }
  509. }
  510. if(empty($aInfo['items']))
  511. return $this->_sLangsPrefix . ($bProcessedFree ? 'msg_successfully_processed_free' : 'err_empty_order');
  512. if($bTypeSingle && (empty($aCustoms) || !is_array($aCustoms))) {
  513. $aCart = $this->_oDb->getCartContent($aInfo['client_id']);
  514. $aCartCustoms = !empty($aCart['customs']) ? unserialize($aCart['customs']) : array();
  515. $aCustoms = array();
  516. foreach($aInfo['items'] as $aItem) {
  517. $sCartItem = $this->_oConfig->descriptorA2S(array($aInfo['vendor_id'], $aItem['module_id'], $aItem['id']));
  518. $aCartItemCustom = $this->_oConfig->getCustom($sCartItem, $aCartCustoms);
  519. $this->_oConfig->putCustom($sCartItem, $aCartItemCustom, $aCustoms);
  520. }
  521. }
  522. $iPendingId = $this->_oDb->insertOrderPending($this->_iUserId, $sType, $sProvider, $aInfo, $aCustoms);
  523. if(empty($iPendingId))
  524. return $this->_sLangsPrefix . 'err_access_db';
  525. /*
  526. * Perform Join WITHOUT processing via payment provider
  527. * if a client ISN'T logged in and has only ONE FREE item in the card.
  528. * Note. This section isn't used for now because only a member can purchase!
  529. */
  530. if((int)$aInfo['client_id'] == 0 && (int)$aInfo['items_count'] == 1) {
  531. reset($aInfo['items']);
  532. $aItem = current($aInfo['items']);
  533. if(!empty($aItem) && $this->_oConfig->getPrice($sType, $aItem)) {
  534. $this->_oDb->updateOrderPending($iPendingId, array(
  535. 'order' => $this->_oConfig->getLicense(),
  536. 'error_code' => '1',
  537. 'error_msg' => ''
  538. ));
  539. $this->getObjectJoin()->performJoin($iPendingId);
  540. }
  541. }
  542. return $oProvider->initializeCheckout($iPendingId, $aInfo, $sRedirect);
  543. }
  544. public function actionFinalizeCheckout($sProvider, $mixedVendorId = "")
  545. {
  546. $aData = &$_REQUEST;
  547. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  548. if($oProvider === false || !$oProvider->isActive())
  549. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  550. $aResult = $oProvider->finalizeCheckout($aData);
  551. if((int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS)
  552. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  553. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$aResult['pending_id']));
  554. $bTypeRecurring = $aPending['type'] == BX_PAYMENT_TYPE_RECURRING;
  555. if($bTypeRecurring)
  556. $this->registerSubscription($aPending, array(
  557. 'customer_id' => $aResult['customer_id'],
  558. 'subscription_id' => $aResult['subscription_id']
  559. ));
  560. $this->onPaymentRegisterBefore($aPending);
  561. //--- Check "Pay Before Join" situation
  562. if((int)$aPending['client_id'] == 0)
  563. $this->getObjectJoin()->performJoin((int)$aPending['id'], isset($aResult['client_name']) ? $aResult['client_name'] : '', isset($aResult['client_email']) ? $aResult['client_email'] : '');
  564. //--- Register payment for purchased items in associated modules
  565. if(!empty($aResult['paid']) || ($bTypeRecurring && !empty($aResult['trial'])))
  566. $this->registerPayment($aPending);
  567. bx_alert($this->getName(), 'finalize_checkout', 0, bx_get_logged_profile_id(), array(
  568. 'pending' => $aPending,
  569. 'transactions' => $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id'])),
  570. 'provider' => $oProvider,
  571. 'message' => &$aResult['message'],
  572. ));
  573. if($oProvider->needRedirect()) {
  574. header('Location: ' . $oProvider->getReturnUrl());
  575. exit;
  576. }
  577. if(!empty($aResult['redirect'])) {
  578. header('Location: ' . base64_decode(urldecode($aResult['redirect'])));
  579. exit;
  580. }
  581. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  582. }
  583. public function actionFinalizedCheckout($sProvider, $mixedVendorId = "")
  584. {
  585. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  586. if($oProvider === false || !$oProvider->isActive())
  587. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  588. $aResult = $oProvider->finalizedCheckout();
  589. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  590. }
  591. public function actionNotify($sProvider, $mixedVendorId = "")
  592. {
  593. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  594. if($oProvider === false || !$oProvider->isActive())
  595. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  596. $oProvider->notify();
  597. }
  598. public function onProfileJoin($iProfileId)
  599. {
  600. $this->getObjectJoin()->onProfileJoin($iProfileId);
  601. }
  602. public function onProfileDelete($iProfileId)
  603. {
  604. $this->_oDb->onProfileDelete($iProfileId);
  605. }
  606. public function isAllowedPurchase($aItem, $bPerform = false)
  607. {
  608. $iUserId = (int)$this->getProfileId();
  609. $aItemInfo = $this->callGetCartItem($aItem['module_id'], array($aItem['item_id']));
  610. if(empty($aItemInfo))
  611. return false;
  612. if(isAdmin())
  613. return true;
  614. $aCheckResult = checkActionModule($iUserId, 'purchase', $this->getName(), $bPerform);
  615. if($aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  616. return true;
  617. return $aCheckResult[CHECK_ACTION_MESSAGE];
  618. }
  619. public function isAllowedSell($aItem, $bPerform = false)
  620. {
  621. $iUserId = (int)$this->getProfileId();
  622. if(!$iUserId)
  623. return false;
  624. $aItemInfo = $this->callGetCartItem($aItem['module_id'], array($aItem['item_id']));
  625. if(empty($aItemInfo))
  626. return false;
  627. if(isAdmin())
  628. return true;
  629. $aCheckResult = checkActionModule($iUserId, 'sell', $this->getName(), $bPerform);
  630. if((int)$aItemInfo['author_id'] == $iUserId && $aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  631. return true;
  632. return $aCheckResult[CHECK_ACTION_MESSAGE];
  633. }
  634. public function isAllowedManage($aPending, $bPerform = false)
  635. {
  636. $iUserId = (int)$this->getProfileId();
  637. if($iUserId == $aPending['client_id'] || $iUserId == $aPending['seller_id'] || isAdmin())
  638. return true;
  639. $aCheckResult = checkActionModule($iUserId, 'manage any purchase', $this->getName(), $bPerform);
  640. if($aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  641. return true;
  642. return $aCheckResult[CHECK_ACTION_MESSAGE];
  643. }
  644. public function checkData($iClientId, $iSellerId, $iModuleId, $iItemId, $iItemCount)
  645. {
  646. $CNF = &$this->_oConfig->CNF;
  647. if($iSellerId == BX_PAYMENT_EMPTY_ID || empty($iModuleId) || empty($iItemId) || empty($iItemCount))
  648. return array('code' => 1, 'message' => _t($CNF['T']['ERR_WRONG_DATA']));
  649. $iClientId = $this->getProfileId();
  650. if(empty($iClientId)) {
  651. $sLoginUrl = BxDolPermalinks::getInstance()->permalink('page.php?i=login');
  652. return array('code' => 2, 'eval' => 'window.open("' . $sLoginUrl . '", "_self");');
  653. }
  654. $mixedResult = $this->isAllowedPurchase(array('module_id' => $iModuleId, 'item_id' => $iItemId));
  655. if($mixedResult !== true) {
  656. if(is_string($mixedResult) && !empty($mixedResult))
  657. return array('code' => 2, 'message' => $mixedResult);
  658. else
  659. return array('code' => 1, 'message' => _t($CNF['T']['ERR_WRONG_DATA']));
  660. }
  661. if($iClientId == $iSellerId)
  662. return array('code' => 3, 'message' => _t($CNF['T']['ERR_SELF_PURCHASE']));
  663. $aSeller = $this->getVendorInfo($iSellerId);
  664. if(!$aSeller['active'])
  665. return array('code' => 4, 'message' => _t($CNF['T']['ERR_INACTIVE_VENDOR']));
  666. return true;
  667. }
  668. public function registerPayment($mixedPending)
  669. {
  670. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  671. if(empty($aPending) || !is_array($aPending))
  672. return false;
  673. $sType = $aPending['type'];
  674. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  675. if($bTypeSingle && (int)$aPending['processed'] == 1)
  676. return true;
  677. $iClientId = (int)$aPending['client_id'];
  678. $sLicense = $this->_oConfig->getLicense();
  679. $aCustoms = !empty($aPending['customs']) ? unserialize($aPending['customs']) : array();
  680. $aCart = array();
  681. if($bTypeSingle) {
  682. $aCart = $this->_oDb->getCartContent($iClientId);
  683. $aCart['customs'] = !empty($aCart['customs']) ? unserialize($aCart['customs']) : array();
  684. }
  685. $bResult = false;
  686. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  687. foreach($aItems as $aItem) {
  688. $sItem = $this->_oConfig->descriptorA2S(array($aItem['vendor_id'], $aItem['module_id'], $aItem['item_id']));
  689. $aItemCustom = $this->_oConfig->getCustom($sItem, $aCustoms);
  690. $sMethod = $bTypeSingle ? 'callRegisterCartItem' : 'callRegisterSubscriptionItem';
  691. $aItemInfo = $this->$sMethod((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order'], $sLicense, $aItemCustom));
  692. if(empty($aItemInfo) || !is_array($aItemInfo))
  693. continue;
  694. $this->_oDb->insertOrderProcessed(array(
  695. 'pending_id' => $aPending['id'],
  696. 'client_id' => $aPending['client_id'],
  697. 'seller_id' => $aPending['seller_id'],
  698. 'module_id' => (int)$aItem['module_id'],
  699. 'item_id' => (int)$aItem['item_id'],
  700. 'item_count' => (int)$aItem['item_count'],
  701. 'amount' => (int)$aItem['item_count'] * $this->_oConfig->getPrice($sType, $aItemInfo),
  702. 'license' => $sLicense,
  703. ));
  704. if($bTypeSingle) {
  705. $this->_oConfig->pullCustom($sItem, $aCart['customs']);
  706. $aCart['items'] = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aItem) . ":?'", "", $aCart['items']), ":");
  707. }
  708. $bResult = true;
  709. }
  710. if($bTypeSingle)
  711. $this->_oDb->setCartItems($iClientId, $aCart['items'], $aCart['customs']);
  712. if($bResult) {
  713. $this->_oDb->updateOrderPending($aPending['id'], array('processed' => 1));
  714. $this->onPaymentRegister($aPending);
  715. }
  716. return $bResult;
  717. }
  718. public function refundPayment($mixedPending)
  719. {
  720. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  721. if(empty($aPending) || !is_array($aPending))
  722. return false;
  723. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  724. $iCanceled = 0;
  725. $aOrders = $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id']));
  726. foreach($aOrders as $aOrder) {
  727. $sMethod = $bTypeSingle ? 'callUnregisterCartItem' : 'callUnregisterSubscriptionItem';
  728. $bResult = $this->$sMethod((int)$aOrder['module_id'], array($aOrder['client_id'], $aOrder['seller_id'], $aOrder['item_id'], $aOrder['item_count'], $aPending['order'], $aOrder['license']));
  729. if(!$bResult)
  730. continue;
  731. if($this->_oDb->deleteOrderProcessed($aOrder['id']))
  732. $iCanceled++;
  733. }
  734. if($iCanceled != count($aOrders))
  735. return false;
  736. $bResult = $this->_oDb->deleteOrderPending($aPending['id']);
  737. if($bResult)
  738. $this->onPaymentRefund($aPending);
  739. return $bResult;
  740. }
  741. public function registerSubscription($aPending, $aParams = array())
  742. {
  743. $this->_oDb->insertSubscription(array(
  744. 'pending_id' => $aPending['id'],
  745. 'customer_id' => $aParams['customer_id'],
  746. 'subscription_id' => $aParams['subscription_id']
  747. ));
  748. $this->onSubscriptionCreate($aPending);
  749. }
  750. public function updateSubscription($aPending, $aParams = array())
  751. {
  752. $this->_oDb->updateSubscription($aParams, array(
  753. 'pending_id' => $aPending['id']
  754. ));
  755. $this->onSubscriptionUpdate($aPending);
  756. }
  757. public function cancelSubscription($mixedPending)
  758. {
  759. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  760. if(empty($aPending) || !is_array($aPending) || $aPending['type'] != BX_PAYMENT_TYPE_RECURRING)
  761. return false;
  762. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  763. foreach($aItems as $aItem)
  764. $this->callCancelSubscriptionItem((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order']));
  765. $this->onSubscriptionCancel($aPending);
  766. }
  767. public function onPaymentRegisterBefore($aPending, $aResult = array())
  768. {
  769. //--- 'System' -> 'Before Register Payment' for Alerts Engine ---//
  770. bx_alert('system', 'before_register_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  771. //--- 'System' -> 'Before Register Payment' for Alerts Engine ---//
  772. }
  773. public function onPaymentRegister($aPending, $aResult = array())
  774. {
  775. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  776. if($bTypeSingle) {
  777. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  778. foreach($aItems as $aItem)
  779. $this->isAllowedPurchase(array('module_id' => $aItem['module_id'], 'item_id' => $aItem['item_id']), true);
  780. }
  781. //--- 'System' -> 'Register Payment' for Alerts Engine ---//
  782. bx_alert('system', 'register_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  783. //--- 'System' -> 'Register Payment' for Alerts Engine ---//
  784. }
  785. public function onPaymentRefund($aPending, $aResult = array())
  786. {
  787. //--- 'System' -> 'Refund Payment' for Alerts Engine ---//
  788. bx_alert('system', 'refund_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  789. //--- 'System' -> 'Refund Payment' for Alerts Engine ---//
  790. }
  791. public function onSubscriptionCreate($aPending, $aResult = array())
  792. {
  793. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  794. $this->isAllowedPurchase(array('module_id' => $aItems[0]['module_id'], 'item_id' => $aItems[0]['item_id']), true);
  795. //--- 'System' -> 'Create Subscription' for Alerts Engine ---//
  796. bx_alert('system', 'create_subscription', 0, $aPending['client_id'], array('pending' => $aPending));
  797. //--- 'System' -> 'Create Subscription' for Alerts Engine ---//
  798. }
  799. public function onSubscriptionUpdate($aPending, $aResult = array())
  800. {
  801. //--- 'System' -> 'Update Subscription' for Alerts Engine ---//
  802. bx_alert('system', 'update_subscription', 0, $aPending['client_id'], array('pending' => $aPending));
  803. //--- 'System' -> 'Update Subscription' for Alerts Engine ---//
  804. }
  805. public function onSubscriptionCancel($aPending, $aResult = array())
  806. {
  807. //--- 'System' -> 'Cancel Subscription' for Alerts Engine ---//
  808. bx_alert('system', 'cancel_subscription', 0, $aPending['client_id'], array('pending' => $aPending));
  809. //--- 'System' -> 'Cancel Subscription' for Alerts Engine ---//
  810. }
  811. public function setSiteSubmenu($sSubmenu, $sSelModule, $sSelName)
  812. {
  813. $oSiteSubmenu = BxDolMenu::getObjectInstance('sys_site_submenu');
  814. if(!$oSiteSubmenu)
  815. return;
  816. $sModuleSubmenu = $this->_oConfig->getObject($sSubmenu);
  817. $oModuleSubmenu = BxDolMenu::getObjectInstance($sModuleSubmenu);
  818. if(!$oModuleSubmenu)
  819. return;
  820. $oSiteSubmenu->setObjectSubmenu($sModuleSubmenu);
  821. $oModuleSubmenu->setSelected($sSelModule, $sSelName);
  822. }
  823. }
  824. /** @} */