BxPaymentModule.php 40 KB

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