BxPaymentModule.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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_TYPE_SINGLE', 'single');
  12. define('BX_PAYMENT_TYPE_RECURRING', 'recurring');
  13. define('BX_PAYMENT_ORDERS_TYPE_PENDING', 'pending');
  14. define('BX_PAYMENT_ORDERS_TYPE_PROCESSED', 'processed');
  15. define('BX_PAYMENT_ORDERS_TYPE_SUBSCRIPTION', 'subscription');
  16. define('BX_PAYMENT_ORDERS_TYPE_HISTORY', 'history');
  17. define('BX_PAYMENT_EMPTY_ID', 0);
  18. define('BX_PAYMENT_RESULT_SUCCESS', 0);
  19. /**
  20. * Payment module by BoonEx
  21. *
  22. * This module is needed to work with payment providers and organize the process
  23. * of some item purchasing. Shopping Cart and Orders Manager are included.
  24. *
  25. * Integration notes:
  26. * To integrate your module with this one, you need:
  27. * 1. Get 'Add To Cart' button using serviceGetAddToCartLink service.
  28. * 2. Add info about your module in the 'bx_pmt_modules' table.
  29. * 3. Realize the following service methods in your Module class.
  30. * a. serviceGetItems($iSellerId) - Is used in Orders Administration to get all products of the requested seller(vendor).
  31. * b. serviceGetCartItem($iClientId, $iItemId) - Is used in Shopping Cart to get one product by specified id.
  32. * c. serviceRegisterCartItem($iClientId, $iSellerId, $iItemId, $iItemCount, $sOrderId) - Register purchased product.
  33. * d. serviceUnregisterCartItem($iClientId, $iSellerId, $iItemId, $iItemCount, $sOrderId) - Unregister the product purchased earlier.
  34. * @see You may see an example of integration in Membership module.
  35. *
  36. *
  37. * Profile's Wall:
  38. * no spy events
  39. *
  40. *
  41. *
  42. * Spy:
  43. * no spy events
  44. *
  45. *
  46. *
  47. * Memberships/ACL:
  48. * Doesn't depend on user's membership.
  49. *
  50. *
  51. *
  52. * Service methods:
  53. *
  54. * Is used to get "Add to cart" link for some item(s) in your module.
  55. * @see BxPmtModule::serviceGetAddToCartLink
  56. * BxDolService::call('payment', 'get_add_to_cart_link', array($iSellerId, $mixedModuleId, $iItemId, $iItemCount));
  57. *
  58. * Check transaction(s) in database which satisty all conditions.
  59. * @see BxPmtModule::serviceGetTransactionsInfo
  60. * BxDolService::call('payment', 'get_transactions_info', array($aConditions));
  61. *
  62. * Get total count of items in Shopping Cart.
  63. * @see BxPmtModule::serviceGetCartItemsCount
  64. * BxDolService::call('payment', 'get_cart_items_count', array($iUserId, $iOldCount));
  65. * @note is needed for internal usage(integration with member tool bar).
  66. *
  67. * Get Shopping cart content.
  68. * @see BxPmtModule::serviceGetCartItems
  69. * BxDolService::call('payment', 'get_cart_items');
  70. * @note is needed for internal usage(integration with member tool bar).
  71. *
  72. *
  73. * Alerts:
  74. * no alerts available
  75. *
  76. */
  77. class BxPaymentModule extends BxBaseModPaymentModule
  78. {
  79. protected $_iUserId;
  80. protected $_aOrderTypes;
  81. function __construct($aModule)
  82. {
  83. parent::__construct($aModule);
  84. $this->_iUserId = $this->getProfileId();
  85. $this->_aOrderTypes = array(
  86. BX_PAYMENT_ORDERS_TYPE_PENDING,
  87. BX_PAYMENT_ORDERS_TYPE_PROCESSED,
  88. BX_PAYMENT_ORDERS_TYPE_SUBSCRIPTION,
  89. BX_PAYMENT_ORDERS_TYPE_HISTORY
  90. );
  91. }
  92. /**
  93. * Manage Orders Methods
  94. */
  95. public function actionGetClients()
  96. {
  97. $sTerm = bx_get('term');
  98. $aResult = BxDolService::call('system', 'profiles_search', array($sTerm), 'TemplServiceProfiles');
  99. echoJson($aResult);
  100. }
  101. public function actionGetItems($sType, $iModuleId)
  102. {
  103. $iSellerId = $this->getProfileId();
  104. $aItems = $this->callGetCartItems((int)$iModuleId, array($iSellerId));
  105. $aResult = array('code' => 0);
  106. if(is_array($aItems) && !empty($aItems))
  107. $aResult['data'] = $this->_oTemplate->displayItems($sType, $aItems);
  108. echoJson($aResult);
  109. }
  110. /**
  111. * Payment Details Methods
  112. */
  113. public function serviceGetOptionsSiteAdmin()
  114. {
  115. $aResult = array(
  116. array('key' => '', 'value' => _t('_Select_one'))
  117. );
  118. $aIds = $this->_oDb->getAdminsIds();
  119. foreach($aIds as $iId) {
  120. $aUser = $this->getProfileInfo($iId);
  121. $aResult[] = array(
  122. 'key' => $iId,
  123. 'value' => $aUser['name']
  124. );
  125. }
  126. return $aResult;
  127. }
  128. /**
  129. * Check transaction(s) in database which satisty all conditions.
  130. *
  131. * @param array $aConditions an array of pears('key' => 'value'). Available keys are the following:
  132. * a. license - internal license (string)
  133. * b. client_id - client's ID (integer)
  134. * c. seller_id - seller's ID (integer)
  135. * d. module_id - modules's where the purchased product is located. (integer)
  136. * e. item_id - item id in the database. (integer)
  137. * f. date - the date when the payment was processed(UNIXTIME STAMP)
  138. *
  139. * @return array of transactions. Each transaction has full info(client ID, seller ID, external transaction ID, date and so on)
  140. */
  141. public function serviceGetTransactionsInfo($aConditions)
  142. {
  143. return $this->_oDb->getOrderProcessed(array('type' => 'mixed', 'conditions' => $aConditions));
  144. }
  145. /**
  146. * Cart Processing Methods
  147. */
  148. public function actionAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount)
  149. {
  150. $aResult = $this->getObjectCart()->serviceAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount);
  151. echoJson($aResult);
  152. }
  153. /**
  154. * Isn't used yet.
  155. */
  156. public function actionDeleteFromCart($iSellerId, $iModuleId, $iItemId)
  157. {
  158. $aResult = $this->getObjectCart()->serviceDeleteFromCart($iSellerId, $iModuleId, $iItemId);
  159. echoJson($aResult);
  160. }
  161. /**
  162. * Isn't used yet.
  163. */
  164. public function actionEmptyCart($iSellerId)
  165. {
  166. $aResult = $this->getObjectCart()->serviceDeleteFromCart($iSellerId);
  167. echoJson($aResult);
  168. }
  169. public function actionSubscribe()
  170. {
  171. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  172. $sSellerProvider = bx_process_input(bx_get('seller_provider'));
  173. $iModuleId = bx_process_input(bx_get('module_id'), BX_DATA_INT);
  174. $iItemId = bx_process_input(bx_get('item_id'), BX_DATA_INT);
  175. $iItemCount = bx_process_input(bx_get('item_count'), BX_DATA_INT);
  176. if(empty($iItemCount))
  177. $iItemCount = 1;
  178. $aResult = $this->getObjectCart()->serviceSubscribe($iSellerId, $sSellerProvider, $iModuleId, $iItemId, $iItemCount);
  179. if($aResult['code'] != 0)
  180. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  181. if(empty($aResult['redirect']) && !empty($aResult['message']))
  182. return $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  183. header('Location: ' . $aResult['redirect']);
  184. exit;
  185. }
  186. public function actionSubscribeJson()
  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. echoJson($aResult);
  197. }
  198. /**
  199. * Payment Processing Methods
  200. */
  201. public function actionInitializeCheckout($sType)
  202. {
  203. if(!$this->isLogged())
  204. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  205. if(bx_get('seller_id') !== false && bx_get('provider') !== false && bx_get('items') !== false) {
  206. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  207. $sProvider = bx_process_input(bx_get('provider'));
  208. $aItems = bx_process_input(bx_get('items'));
  209. $mixedResult = $this->serviceInitializeCheckout(BX_PAYMENT_TYPE_SINGLE, $iSellerId, $sProvider, $aItems);
  210. if($mixedResult !== true)
  211. return $this->_oTemplate->displayPageCodeError($mixedResult);
  212. }
  213. header('Location: ' . $this->_oConfig->getUrl('URL_CART'));
  214. exit;
  215. }
  216. public function serviceInitializeCheckout($sType, $iSellerId, $sProvider, $aItems = array())
  217. {
  218. if(!is_array($aItems))
  219. $aItems = array($aItems);
  220. $iSellerId = (int)$iSellerId;
  221. if($iSellerId == BX_PAYMENT_EMPTY_ID)
  222. return $this->_sLangsPrefix . 'err_unknown_vendor';
  223. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  224. if($oProvider === false || !$oProvider->isActive())
  225. return $this->_sLangsPrefix . 'err_incorrect_provider';
  226. $aInfo = $this->getObjectCart()->getInfo($sType, $this->_iUserId, $iSellerId, $aItems);
  227. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  228. return $this->_sLangsPrefix . 'err_empty_order';
  229. /*
  230. * Process FREE (price = 0) items for LOGGED IN members
  231. * WITHOUT processing via payment provider.
  232. */
  233. $bProcessedFree = false;
  234. $sKeyPriceSingle = $this->_oConfig->getKey('KEY_ARRAY_PRICE_SINGLE');
  235. $sKeyPriceRecurring = $this->_oConfig->getKey('KEY_ARRAY_PRICE_RECURRING');
  236. foreach($aInfo['items'] as $iIndex => $aItem)
  237. if((int)$aInfo['client_id'] != 0 && (float)$aItem[$sKeyPriceSingle] == 0 && (float)$aItem[$sKeyPriceRecurring] == 0) {
  238. $aItemInfo = $this->callRegisterCartItem((int)$aItem['module_id'], array($aInfo['client_id'], $aInfo['vendor_id'], $aItem['id'], $aItem['quantity'], $this->_oConfig->getLicense()));
  239. if(is_array($aItemInfo) && !empty($aItemInfo))
  240. $bProcessedFree = true;
  241. $aInfo['items_count'] -= 1;
  242. unset($aInfo['items'][$iIndex]);
  243. $sCartItems = $this->_oDb->getCartItems($aInfo['client_id']);
  244. $sCartItems = trim(preg_replace("'" . $this->_oConfig->descriptorA2S(array($aInfo['vendor_id'], $aItem['module_id'], $aItem['id'], $aItem['quantity'])) . ":?'", "", $sCartItems), ":");
  245. $this->_oDb->setCartItems($aInfo['client_id'], $sCartItems);
  246. }
  247. if(empty($aInfo['items']))
  248. return $this->_sLangsPrefix . ($bProcessedFree ? 'msg_successfully_processed_free' : 'err_empty_order');
  249. $iPendingId = $this->_oDb->insertOrderPending($this->_iUserId, $sType, $sProvider, $aInfo);
  250. if(empty($iPendingId))
  251. return $this->_sLangsPrefix . 'err_access_db';
  252. /*
  253. * Perform Join WITHOUT processing via payment provider
  254. * if a client ISN'T logged in and has only ONE FREE item in the card.
  255. */
  256. if((int)$aInfo['client_id'] == 0 && (int)$aInfo['items_count'] == 1) {
  257. reset($aInfo['items']);
  258. $aItem = current($aInfo['items']);
  259. if(!empty($aItem) && $this->_oConfig->getPrice($sType, $aItem)) {
  260. $this->_oDb->updateOrderPending($iPendingId, array(
  261. 'order' => $this->_oConfig->getLicense(),
  262. 'error_code' => '1',
  263. 'error_msg' => ''
  264. ));
  265. $this->getObjectJoin()->performJoin($iPendingId);
  266. }
  267. }
  268. return $oProvider->initializeCheckout($iPendingId, $aInfo);
  269. }
  270. public function actionFinalizeCheckout($sProvider, $mixedVendorId = "")
  271. {
  272. $aData = &$_REQUEST;
  273. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  274. if($oProvider === false || !$oProvider->isActive())
  275. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  276. $aResult = $oProvider->finalizeCheckout($aData);
  277. if((int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS)
  278. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  279. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$aResult['pending_id']));
  280. //--- Check "Pay Before Join" situation
  281. if((int)$aPending['client_id'] == 0)
  282. $this->getObjectJoin()->performJoin((int)$aPending['id'], isset($aResult['client_name']) ? $aResult['client_name'] : '', isset($aResult['client_email']) ? $aResult['client_email'] : '');
  283. //--- Register payment for purchased items in associated modules
  284. if(!empty($aResult['paid']))
  285. $this->registerPayment($aPending);
  286. if($oProvider->needRedirect()) {
  287. header('Location: ' . $oProvider->getReturnUrl());
  288. exit;
  289. }
  290. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  291. }
  292. public function actionFinalizedCheckout($sProvider, $mixedVendorId = "")
  293. {
  294. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  295. if($oProvider === false || !$oProvider->isActive())
  296. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  297. $aResult = $oProvider->finalizedCheckout();
  298. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  299. }
  300. public function actionNotify($sProvider, $mixedVendorId = "")
  301. {
  302. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  303. if($oProvider === false || !$oProvider->isActive())
  304. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  305. $oProvider->notify();
  306. }
  307. public function onProfileJoin($iProfileId)
  308. {
  309. $this->getObjectJoin()->onProfileJoin($iProfileId);
  310. }
  311. public function onProfileDelete($iProfileId)
  312. {
  313. $this->_oDb->onProfileDelete($iProfileId);
  314. }
  315. public function isAllowedSell($aItem, $bPerform = false)
  316. {
  317. $iUserId = (int)$this->getProfileId();
  318. if(!$iUserId)
  319. return false;
  320. $aItemInfo = $this->callGetCartItem($aItem['module_id'], array($aItem['item_id']));
  321. if(empty($aItemInfo))
  322. return false;
  323. if(isAdmin())
  324. return true;
  325. $aCheckResult = checkActionModule($iUserId, 'sell', $this->getName(), $bPerform);
  326. if((int)$aItemInfo['author_id'] == $iUserId && $aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  327. return true;
  328. return $aCheckResult[CHECK_ACTION_MESSAGE];
  329. }
  330. public function registerPayment($mixedPending)
  331. {
  332. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  333. if(empty($aPending) || !is_array($aPending))
  334. return false;
  335. if((int)$aPending['processed'] == 1)
  336. return true;
  337. $sType = $aPending['type'];
  338. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  339. $iClientId = (int)$aPending['client_id'];
  340. $sLicense = $this->_oConfig->getLicense();
  341. $sCartItems = '';
  342. if($bTypeSingle)
  343. $sCartItems = $this->_oDb->getCartItems($iClientId);
  344. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  345. foreach($aItems as $aItem) {
  346. $sMethod = $bTypeSingle ? 'callRegisterCartItem' : 'callRegisterSubscriptionItem';
  347. $aItemInfo = $this->$sMethod((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order'], $sLicense));
  348. if(empty($aItemInfo) || !is_array($aItemInfo))
  349. continue;
  350. $this->_oDb->insertOrderProcessed(array(
  351. 'pending_id' => $aPending['id'],
  352. 'client_id' => $aPending['client_id'],
  353. 'seller_id' => $aPending['seller_id'],
  354. 'module_id' => $aItem['module_id'],
  355. 'item_id' => $aItem['item_id'],
  356. 'item_count' => $aItem['item_count'],
  357. 'amount' => $aItem['item_count'] * $this->_oConfig->getPrice($sType, $aItemInfo),
  358. 'license' => $sLicense,
  359. ));
  360. if($bTypeSingle)
  361. $sCartItems = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aItem) . ":?'", "", $sCartItems), ":");
  362. }
  363. if($bTypeSingle)
  364. $this->_oDb->setCartItems($iClientId, $sCartItems);
  365. $bResult = $this->_oDb->updateOrderPending($aPending['id'], array('processed' => 1));
  366. if($bResult) {
  367. //--- 'System' -> 'Register Payment' for Alerts Engine ---//
  368. bx_import('BxDolAlerts');
  369. $oZ = new BxDolAlerts('system', 'register_payment', 0, $iClientId, array('pending' => $aPending));
  370. $oZ->alert();
  371. //--- 'System' -> 'Register Payment' for Alerts Engine ---//
  372. }
  373. return $bResult;
  374. }
  375. public function refundPayment($mixedPending)
  376. {
  377. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  378. if(empty($aPending) || !is_array($aPending))
  379. return false;
  380. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  381. $iCanceled = 0;
  382. $aOrders = $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id']));
  383. foreach($aOrders as $aOrder) {
  384. $sMethod = $bTypeSingle ? 'callUnregisterCartItem' : 'callUnregisterSubscriptionItem';
  385. $bResult = $this->$sMethod((int)$aOrder['module_id'], array($aOrder['client_id'], $aOrder['seller_id'], $aOrder['item_id'], $aOrder['item_count'], $aPending['order'], $aOrder['license']));
  386. if(!$bResult)
  387. continue;
  388. if($this->_oDb->deleteOrderProcessed($aOrder['id']))
  389. $iCanceled++;
  390. }
  391. if($iCanceled != count($aOrders))
  392. return false;
  393. return $this->_oDb->deleteOrderPending($aPending['id']);
  394. }
  395. public function cancelSubscription($mixedPending)
  396. {
  397. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  398. if(empty($aPending) || !is_array($aPending) || $aPending['type'] != BX_PAYMENT_TYPE_RECURRING)
  399. return false;
  400. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  401. foreach($aItems as $aItem)
  402. $this->callCancelSubscriptionItem((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order']));
  403. }
  404. }
  405. /** @} */