BxPaymentModule.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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($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($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. echoJson($aResult);
  180. }
  181. /**
  182. * Payment Processing Methods
  183. */
  184. public function actionInitializeCheckout($sType)
  185. {
  186. if(!$this->isLogged())
  187. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  188. if(bx_get('seller_id') !== false && bx_get('provider') !== false && bx_get('items') !== false) {
  189. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  190. $sProvider = bx_process_input(bx_get('provider'));
  191. $aItems = bx_process_input(bx_get('items'));
  192. $mixedResult = $this->serviceInitializeCheckout(BX_PAYMENT_TYPE_SINGLE, $iSellerId, $sProvider, $aItems);
  193. if($mixedResult !== true)
  194. return $this->_oTemplate->displayPageCodeError($mixedResult);
  195. }
  196. header('Location: ' . $this->_oConfig->getUrl('URL_CART'));
  197. exit;
  198. }
  199. public function serviceInitializeCheckout($sType, $iSellerId, $sProvider, $aItems = array())
  200. {
  201. if(!is_array($aItems))
  202. $aItems = array($aItems);
  203. $iSellerId = (int)$iSellerId;
  204. if($iSellerId == BX_PAYMENT_EMPTY_ID)
  205. return $this->_sLangsPrefix . 'err_unknown_vendor';
  206. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  207. if($oProvider === false || !$oProvider->isActive())
  208. return $this->_sLangsPrefix . 'err_incorrect_provider';
  209. $aInfo = $this->getObjectCart()->getInfo($sType, $this->_iUserId, $iSellerId, $aItems);
  210. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  211. return $this->_sLangsPrefix . 'err_empty_order';
  212. /*
  213. * Process FREE (price = 0) items for LOGGED IN members
  214. * WITHOUT processing via payment provider.
  215. */
  216. $bProcessedFree = false;
  217. $sKeyPriceSingle = $this->_oConfig->getKey('KEY_ARRAY_PRICE_SINGLE');
  218. $sKeyPriceRecurring = $this->_oConfig->getKey('KEY_ARRAY_PRICE_RECURRING');
  219. foreach($aInfo['items'] as $iIndex => $aItem)
  220. if((int)$aInfo['client_id'] != 0 && (float)$aItem[$sKeyPriceSingle] == 0 && (float)$aItem[$sKeyPriceRecurring] == 0) {
  221. $aItemInfo = $this->callRegisterCartItem((int)$aItem['module_id'], array($aInfo['client_id'], $aInfo['vendor_id'], $aItem['id'], $aItem['quantity'], $this->_oConfig->getLicense()));
  222. if(is_array($aItemInfo) && !empty($aItemInfo))
  223. $bProcessedFree = true;
  224. $aInfo['items_count'] -= 1;
  225. unset($aInfo['items'][$iIndex]);
  226. $sCartItems = $this->_oDb->getCartItems($aInfo['client_id']);
  227. $sCartItems = trim(preg_replace("'" . $this->_oConfig->descriptorA2S(array($aInfo['vendor_id'], $aItem['module_id'], $aItem['id'], $aItem['quantity'])) . ":?'", "", $sCartItems), ":");
  228. $this->_oDb->setCartItems($aInfo['client_id'], $sCartItems);
  229. }
  230. if(empty($aInfo['items']))
  231. return $this->_sLangsPrefix . ($bProcessedFree ? 'msg_successfully_processed_free' : 'err_empty_order');
  232. $iPendingId = $this->_oDb->insertOrderPending($this->_iUserId, $sType, $sProvider, $aInfo);
  233. if(empty($iPendingId))
  234. return $this->_sLangsPrefix . 'err_access_db';
  235. /*
  236. * Perform Join WITHOUT processing via payment provider
  237. * if a client ISN'T logged in and has only ONE FREE item in the card.
  238. */
  239. if((int)$aInfo['client_id'] == 0 && (int)$aInfo['items_count'] == 1) {
  240. reset($aInfo['items']);
  241. $aItem = current($aInfo['items']);
  242. if(!empty($aItem) && $this->_oConfig->getPrice($sType, $aItem)) {
  243. $this->_oDb->updateOrderPending($iPendingId, array(
  244. 'order' => $this->_oConfig->getLicense(),
  245. 'error_code' => '1',
  246. 'error_msg' => ''
  247. ));
  248. $this->getObjectJoin()->performJoin($iPendingId);
  249. }
  250. }
  251. return $oProvider->initializeCheckout($iPendingId, $aInfo);
  252. }
  253. public function actionFinalizeCheckout($sProvider, $mixedVendorId = "")
  254. {
  255. $aData = &$_REQUEST;
  256. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  257. if($oProvider === false || !$oProvider->isActive())
  258. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  259. $aResult = $oProvider->finalizeCheckout($aData);
  260. if((int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS)
  261. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  262. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$aResult['pending_id']));
  263. //--- Check "Pay Before Join" situation
  264. if((int)$aPending['client_id'] == 0)
  265. $this->getObjectJoin()->performJoin((int)$aPending['id'], isset($aResult['client_name']) ? $aResult['client_name'] : '', isset($aResult['client_email']) ? $aResult['client_email'] : '');
  266. //--- Register payment for purchased items in associated modules
  267. if(!empty($aResult['paid']))
  268. $this->registerPayment($aPending);
  269. if($oProvider->needRedirect()) {
  270. header('Location: ' . $oProvider->getReturnUrl());
  271. exit;
  272. }
  273. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  274. }
  275. public function actionFinalizedCheckout($sProvider, $mixedVendorId = "")
  276. {
  277. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  278. if($oProvider === false || !$oProvider->isActive())
  279. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  280. $aResult = $oProvider->finalizedCheckout();
  281. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  282. }
  283. public function actionNotify($sProvider, $mixedVendorId = "")
  284. {
  285. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  286. if($oProvider === false || !$oProvider->isActive())
  287. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  288. $oProvider->notify();
  289. }
  290. public function onProfileJoin($iProfileId)
  291. {
  292. $this->getObjectJoin()->onProfileJoin($iProfileId);
  293. }
  294. public function onProfileDelete($iProfileId)
  295. {
  296. $this->_oDb->onProfileDelete($iProfileId);
  297. }
  298. public function isAllowedSell($aItem, $bPerform = false)
  299. {
  300. $iUserId = (int)$this->getProfileId();
  301. if(!$iUserId)
  302. return false;
  303. $aItemInfo = $this->callGetCartItem($aItem['module_id'], array($aItem['item_id']));
  304. if(empty($aItemInfo))
  305. return false;
  306. if(isAdmin())
  307. return true;
  308. $aCheckResult = checkActionModule($iUserId, 'sell', $this->getName(), $bPerform);
  309. if((int)$aItemInfo['author_id'] == $iUserId && $aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  310. return true;
  311. return $aCheckResult[CHECK_ACTION_MESSAGE];
  312. }
  313. public function registerPayment($mixedPending)
  314. {
  315. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  316. if(empty($aPending) || !is_array($aPending))
  317. return false;
  318. if((int)$aPending['processed'] == 1)
  319. return true;
  320. $sType = $aPending['type'];
  321. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  322. $iClientId = (int)$aPending['client_id'];
  323. $sLicense = $this->_oConfig->getLicense();
  324. $sCartItems = '';
  325. if($bTypeSingle)
  326. $sCartItems = $this->_oDb->getCartItems($iClientId);
  327. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  328. foreach($aItems as $aItem) {
  329. $sMethod = $bTypeSingle ? 'callRegisterCartItem' : 'callRegisterSubscriptionItem';
  330. $aItemInfo = $this->$sMethod((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order'], $sLicense));
  331. if(empty($aItemInfo) || !is_array($aItemInfo))
  332. continue;
  333. $this->_oDb->insertOrderProcessed(array(
  334. 'pending_id' => $aPending['id'],
  335. 'client_id' => $aPending['client_id'],
  336. 'seller_id' => $aPending['seller_id'],
  337. 'module_id' => $aItem['module_id'],
  338. 'item_id' => $aItem['item_id'],
  339. 'item_count' => $aItem['item_count'],
  340. 'amount' => $aItem['item_count'] * $this->_oConfig->getPrice($sType, $aItemInfo),
  341. 'license' => $sLicense,
  342. ));
  343. if($bTypeSingle)
  344. $sCartItems = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aItem) . ":?'", "", $sCartItems), ":");
  345. }
  346. if($bTypeSingle)
  347. $this->_oDb->setCartItems($iClientId, $sCartItems);
  348. return $this->_oDb->updateOrderPending($aPending['id'], array('processed' => 1));
  349. }
  350. public function refundPayment($mixedPending)
  351. {
  352. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  353. if(empty($aPending) || !is_array($aPending))
  354. return false;
  355. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  356. $iCanceled = 0;
  357. $aOrders = $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id']));
  358. foreach($aOrders as $aOrder) {
  359. $sMethod = $bTypeSingle ? 'callUnregisterCartItem' : 'callUnregisterSubscriptionItem';
  360. $bResult = $this->$sMethod((int)$aOrder['module_id'], array($aOrder['client_id'], $aOrder['seller_id'], $aOrder['item_id'], $aOrder['item_count'], $aPending['order'], $aOrder['license']));
  361. if(!$bResult)
  362. continue;
  363. if($this->_oDb->deleteOrderProcessed($aOrder['id']))
  364. $iCanceled++;
  365. }
  366. if($iCanceled != count($aOrders))
  367. return false;
  368. return $this->_oDb->deleteOrderPending($aPending['id']);
  369. }
  370. public function cancelSubscription($mixedPending)
  371. {
  372. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  373. if(empty($aPending) || !is_array($aPending) || $aPending['type'] != BX_PAYMENT_TYPE_RECURRING)
  374. return false;
  375. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  376. foreach($aItems as $aItem)
  377. $this->callCancelSubscriptionItem((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order']));
  378. }
  379. }
  380. /** @} */