BxPaymentModule.php 39 KB

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