BxPaymentModule.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
  4. * CC-BY License - http://creativecommons.org/licenses/by/3.0/
  5. *
  6. * @defgroup Payment Payment
  7. * @ingroup TridentModules
  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::serviceGetTransactionsInfo
  58. * BxDolService::call('payment', 'get_transactions_info', array($aConditions));
  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. $aResult = array('code' => 0);
  104. if(is_array($aItems) && !empty($aItems))
  105. $aResult['data'] = $this->_oTemplate->displayItems($sType, $aItems);
  106. echoJson($aResult);
  107. }
  108. /**
  109. * Payment Details Methods
  110. */
  111. public function serviceIsAcceptingPayments($iVendorId, $sPaymentType = '')
  112. {
  113. $bResult = false;
  114. switch($sPaymentType) {
  115. case BX_PAYMENT_TYPE_SINGLE:
  116. $aProvidersCart = $this->_oDb->getVendorInfoProvidersCart($iVendorId);
  117. $bResult = !empty($aProvidersCart);
  118. break;
  119. case BX_PAYMENT_TYPE_RECURRING:
  120. $aProvidersSubscription = $this->_oDb->getVendorInfoProvidersSubscription($iVendorId);
  121. $bResult = !empty($aProvidersSubscription);
  122. break;
  123. default:
  124. $aProvidersCart = $this->_oDb->getVendorInfoProvidersCart($iVendorId);
  125. $aProvidersSubscription = $this->_oDb->getVendorInfoProvidersSubscription($iVendorId);
  126. $bResult = !empty($aProvidersCart) || !empty($aProvidersSubscription);
  127. }
  128. return $bResult;
  129. }
  130. public function serviceGetOptionsSiteAdmin()
  131. {
  132. $aResult = array(
  133. array('key' => '', 'value' => _t('_Select_one'))
  134. );
  135. $aIds = $this->_oDb->getAdminsIds();
  136. foreach($aIds as $iId) {
  137. $aUser = $this->getProfileInfo($iId);
  138. $aResult[] = array(
  139. 'key' => $iId,
  140. 'value' => $aUser['name']
  141. );
  142. }
  143. return $aResult;
  144. }
  145. /**
  146. * Check transaction(s) in database which satisty all conditions.
  147. *
  148. * @param array $aConditions an array of pears('key' => 'value'). Available keys are the following:
  149. * a. license - internal license (string)
  150. * b. client_id - client's ID (integer)
  151. * c. seller_id - seller's ID (integer)
  152. * d. module_id - modules's where the purchased product is located. (integer)
  153. * e. item_id - item id in the database. (integer)
  154. * f. date - the date when the payment was processed(UNIXTIME STAMP)
  155. *
  156. * @return array of transactions. Each transaction has full info(client ID, seller ID, external transaction ID, date and so on)
  157. */
  158. public function serviceGetTransactionsInfo($aConditions)
  159. {
  160. return $this->_oDb->getOrderProcessed(array('type' => 'mixed', 'conditions' => $aConditions));
  161. }
  162. /**
  163. * Cart Processing Methods
  164. */
  165. public function actionAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount)
  166. {
  167. $aResult = $this->getObjectCart()->serviceAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount);
  168. echoJson($aResult);
  169. }
  170. /**
  171. * Isn't used yet.
  172. */
  173. public function actionDeleteFromCart($iSellerId, $iModuleId, $iItemId)
  174. {
  175. $aResult = $this->getObjectCart()->serviceDeleteFromCart($iSellerId, $iModuleId, $iItemId);
  176. echoJson($aResult);
  177. }
  178. /**
  179. * Isn't used yet.
  180. */
  181. public function actionEmptyCart($iSellerId)
  182. {
  183. $aResult = $this->getObjectCart()->serviceDeleteFromCart($iSellerId);
  184. echoJson($aResult);
  185. }
  186. public function actionSubscribe()
  187. {
  188. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  189. $sSellerProvider = bx_process_input(bx_get('seller_provider'));
  190. $iModuleId = bx_process_input(bx_get('module_id'), BX_DATA_INT);
  191. $iItemId = bx_process_input(bx_get('item_id'), BX_DATA_INT);
  192. $iItemCount = bx_process_input(bx_get('item_count'), BX_DATA_INT);
  193. if(empty($iItemCount))
  194. $iItemCount = 1;
  195. $aResult = $this->getObjectCart()->serviceSubscribe($iSellerId, $sSellerProvider, $iModuleId, $iItemId, $iItemCount);
  196. if($aResult['code'] != 0)
  197. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  198. if(empty($aResult['redirect']) && !empty($aResult['message']))
  199. return $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  200. header('Location: ' . $aResult['redirect']);
  201. exit;
  202. }
  203. public function actionSubscribeJson()
  204. {
  205. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  206. $sSellerProvider = bx_process_input(bx_get('seller_provider'));
  207. $iModuleId = bx_process_input(bx_get('module_id'), BX_DATA_INT);
  208. $iItemId = bx_process_input(bx_get('item_id'), BX_DATA_INT);
  209. $iItemCount = bx_process_input(bx_get('item_count'), BX_DATA_INT);
  210. if(empty($iItemCount))
  211. $iItemCount = 1;
  212. $aResult = $this->getObjectCart()->serviceSubscribe($iSellerId, $sSellerProvider, $iModuleId, $iItemId, $iItemCount);
  213. echoJson($aResult);
  214. }
  215. /**
  216. * Payment Processing Methods
  217. */
  218. public function actionInitializeCheckout($sType)
  219. {
  220. if(!$this->isLogged())
  221. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  222. if(bx_get('seller_id') !== false && bx_get('provider') !== false && bx_get('items') !== false) {
  223. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  224. $sProvider = bx_process_input(bx_get('provider'));
  225. $aItems = bx_process_input(bx_get('items'));
  226. $mixedResult = $this->serviceInitializeCheckout(BX_PAYMENT_TYPE_SINGLE, $iSellerId, $sProvider, $aItems);
  227. if($mixedResult !== true)
  228. return $this->_oTemplate->displayPageCodeError($mixedResult);
  229. }
  230. header('Location: ' . $this->_oConfig->getUrl('URL_CART'));
  231. exit;
  232. }
  233. public function serviceInitializeCheckout($sType, $iSellerId, $sProvider, $aItems = array())
  234. {
  235. if(!is_array($aItems))
  236. $aItems = array($aItems);
  237. $iSellerId = (int)$iSellerId;
  238. if($iSellerId == BX_PAYMENT_EMPTY_ID)
  239. return $this->_sLangsPrefix . 'err_unknown_vendor';
  240. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  241. if($oProvider === false || !$oProvider->isActive())
  242. return $this->_sLangsPrefix . 'err_incorrect_provider';
  243. $aInfo = $this->getObjectCart()->getInfo($sType, $this->_iUserId, $iSellerId, $aItems);
  244. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  245. return $this->_sLangsPrefix . 'err_empty_order';
  246. /*
  247. * Process FREE (price = 0) items for LOGGED IN members
  248. * WITHOUT processing via payment provider.
  249. */
  250. $bProcessedFree = false;
  251. $sKeyPriceSingle = $this->_oConfig->getKey('KEY_ARRAY_PRICE_SINGLE');
  252. $sKeyPriceRecurring = $this->_oConfig->getKey('KEY_ARRAY_PRICE_RECURRING');
  253. foreach($aInfo['items'] as $iIndex => $aItem)
  254. if((int)$aInfo['client_id'] != 0 && (float)$aItem[$sKeyPriceSingle] == 0 && (float)$aItem[$sKeyPriceRecurring] == 0) {
  255. $aItemInfo = $this->callRegisterCartItem((int)$aItem['module_id'], array($aInfo['client_id'], $aInfo['vendor_id'], $aItem['id'], $aItem['quantity'], $this->_oConfig->getLicense()));
  256. if(is_array($aItemInfo) && !empty($aItemInfo))
  257. $bProcessedFree = true;
  258. $aInfo['items_count'] -= 1;
  259. unset($aInfo['items'][$iIndex]);
  260. $sCartItems = $this->_oDb->getCartItems($aInfo['client_id']);
  261. $sCartItems = trim(preg_replace("'" . $this->_oConfig->descriptorA2S(array($aInfo['vendor_id'], $aItem['module_id'], $aItem['id'], $aItem['quantity'])) . ":?'", "", $sCartItems), ":");
  262. $this->_oDb->setCartItems($aInfo['client_id'], $sCartItems);
  263. }
  264. if(empty($aInfo['items']))
  265. return $this->_sLangsPrefix . ($bProcessedFree ? 'msg_successfully_processed_free' : 'err_empty_order');
  266. $iPendingId = $this->_oDb->insertOrderPending($this->_iUserId, $sType, $sProvider, $aInfo);
  267. if(empty($iPendingId))
  268. return $this->_sLangsPrefix . 'err_access_db';
  269. /*
  270. * Perform Join WITHOUT processing via payment provider
  271. * if a client ISN'T logged in and has only ONE FREE item in the card.
  272. */
  273. if((int)$aInfo['client_id'] == 0 && (int)$aInfo['items_count'] == 1) {
  274. reset($aInfo['items']);
  275. $aItem = current($aInfo['items']);
  276. if(!empty($aItem) && $this->_oConfig->getPrice($sType, $aItem)) {
  277. $this->_oDb->updateOrderPending($iPendingId, array(
  278. 'order' => $this->_oConfig->getLicense(),
  279. 'error_code' => '1',
  280. 'error_msg' => ''
  281. ));
  282. $this->getObjectJoin()->performJoin($iPendingId);
  283. }
  284. }
  285. return $oProvider->initializeCheckout($iPendingId, $aInfo);
  286. }
  287. public function actionFinalizeCheckout($sProvider, $mixedVendorId = "")
  288. {
  289. $aData = &$_REQUEST;
  290. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  291. if($oProvider === false || !$oProvider->isActive())
  292. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  293. $aResult = $oProvider->finalizeCheckout($aData);
  294. if((int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS)
  295. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  296. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$aResult['pending_id']));
  297. //--- 'System' -> 'Before Register Payment' for Alerts Engine ---//
  298. bx_import('BxDolAlerts');
  299. $oZ = new BxDolAlerts('system', 'before_register_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  300. $oZ->alert();
  301. //--- 'System' -> 'Before Register Payment' for Alerts Engine ---//
  302. //--- Check "Pay Before Join" situation
  303. if((int)$aPending['client_id'] == 0)
  304. $this->getObjectJoin()->performJoin((int)$aPending['id'], isset($aResult['client_name']) ? $aResult['client_name'] : '', isset($aResult['client_email']) ? $aResult['client_email'] : '');
  305. //--- Register payment for purchased items in associated modules
  306. if(!empty($aResult['paid']))
  307. $this->registerPayment($aPending);
  308. if($oProvider->needRedirect()) {
  309. header('Location: ' . $oProvider->getReturnUrl());
  310. exit;
  311. }
  312. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  313. }
  314. public function actionFinalizedCheckout($sProvider, $mixedVendorId = "")
  315. {
  316. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  317. if($oProvider === false || !$oProvider->isActive())
  318. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  319. $aResult = $oProvider->finalizedCheckout();
  320. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  321. }
  322. public function actionNotify($sProvider, $mixedVendorId = "")
  323. {
  324. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  325. if($oProvider === false || !$oProvider->isActive())
  326. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  327. $oProvider->notify();
  328. }
  329. public function onProfileJoin($iProfileId)
  330. {
  331. $this->getObjectJoin()->onProfileJoin($iProfileId);
  332. }
  333. public function onProfileDelete($iProfileId)
  334. {
  335. $this->_oDb->onProfileDelete($iProfileId);
  336. }
  337. public function isAllowedSell($aItem, $bPerform = false)
  338. {
  339. $iUserId = (int)$this->getProfileId();
  340. if(!$iUserId)
  341. return false;
  342. $aItemInfo = $this->callGetCartItem($aItem['module_id'], array($aItem['item_id']));
  343. if(empty($aItemInfo))
  344. return false;
  345. if(isAdmin())
  346. return true;
  347. $aCheckResult = checkActionModule($iUserId, 'sell', $this->getName(), $bPerform);
  348. if((int)$aItemInfo['author_id'] == $iUserId && $aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  349. return true;
  350. return $aCheckResult[CHECK_ACTION_MESSAGE];
  351. }
  352. public function registerPayment($mixedPending)
  353. {
  354. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  355. if(empty($aPending) || !is_array($aPending))
  356. return false;
  357. if((int)$aPending['processed'] == 1)
  358. return true;
  359. $sType = $aPending['type'];
  360. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  361. $iClientId = (int)$aPending['client_id'];
  362. $sLicense = $this->_oConfig->getLicense();
  363. $sCartItems = '';
  364. if($bTypeSingle)
  365. $sCartItems = $this->_oDb->getCartItems($iClientId);
  366. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  367. foreach($aItems as $aItem) {
  368. $sMethod = $bTypeSingle ? 'callRegisterCartItem' : 'callRegisterSubscriptionItem';
  369. $aItemInfo = $this->$sMethod((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order'], $sLicense));
  370. if(empty($aItemInfo) || !is_array($aItemInfo))
  371. continue;
  372. $this->_oDb->insertOrderProcessed(array(
  373. 'pending_id' => $aPending['id'],
  374. 'client_id' => $aPending['client_id'],
  375. 'seller_id' => $aPending['seller_id'],
  376. 'module_id' => $aItem['module_id'],
  377. 'item_id' => $aItem['item_id'],
  378. 'item_count' => $aItem['item_count'],
  379. 'amount' => $aItem['item_count'] * $this->_oConfig->getPrice($sType, $aItemInfo),
  380. 'license' => $sLicense,
  381. ));
  382. if($bTypeSingle)
  383. $sCartItems = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aItem) . ":?'", "", $sCartItems), ":");
  384. }
  385. if($bTypeSingle)
  386. $this->_oDb->setCartItems($iClientId, $sCartItems);
  387. $bResult = $this->_oDb->updateOrderPending($aPending['id'], array('processed' => 1));
  388. if($bResult) {
  389. //--- 'System' -> 'Register Payment' for Alerts Engine ---//
  390. bx_import('BxDolAlerts');
  391. $oZ = new BxDolAlerts('system', 'register_payment', 0, $iClientId, array('pending' => $aPending));
  392. $oZ->alert();
  393. //--- 'System' -> 'Register Payment' for Alerts Engine ---//
  394. }
  395. return $bResult;
  396. }
  397. public function refundPayment($mixedPending)
  398. {
  399. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  400. if(empty($aPending) || !is_array($aPending))
  401. return false;
  402. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  403. $iCanceled = 0;
  404. $aOrders = $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id']));
  405. foreach($aOrders as $aOrder) {
  406. $sMethod = $bTypeSingle ? 'callUnregisterCartItem' : 'callUnregisterSubscriptionItem';
  407. $bResult = $this->$sMethod((int)$aOrder['module_id'], array($aOrder['client_id'], $aOrder['seller_id'], $aOrder['item_id'], $aOrder['item_count'], $aPending['order'], $aOrder['license']));
  408. if(!$bResult)
  409. continue;
  410. if($this->_oDb->deleteOrderProcessed($aOrder['id']))
  411. $iCanceled++;
  412. }
  413. if($iCanceled != count($aOrders))
  414. return false;
  415. return $this->_oDb->deleteOrderPending($aPending['id']);
  416. }
  417. public function cancelSubscription($mixedPending)
  418. {
  419. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  420. if(empty($aPending) || !is_array($aPending) || $aPending['type'] != BX_PAYMENT_TYPE_RECURRING)
  421. return false;
  422. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  423. foreach($aItems as $aItem)
  424. $this->callCancelSubscriptionItem((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order']));
  425. }
  426. }
  427. /** @} */