BxPaymentModule.php 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955
  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_RESULT_SUCCESS', 0);
  16. /*
  17. * Subscriptions: statuses.
  18. */
  19. define('BX_PAYMENT_SBS_STATUS_SCHEDULED', 'scheduled');
  20. define('BX_PAYMENT_SBS_STATUS_TRIAL', 'trial');
  21. define('BX_PAYMENT_SBS_STATUS_ACTIVE', 'active');
  22. define('BX_PAYMENT_SBS_STATUS_UNPAID', 'unpaid');
  23. define('BX_PAYMENT_SBS_STATUS_PAUSED', 'paused');
  24. define('BX_PAYMENT_SBS_STATUS_CANCELED', 'canceled');
  25. define('BX_PAYMENT_SBS_STATUS_UNKNOWN', 'unknown');
  26. /*
  27. * Subscriptions: period units.
  28. */
  29. define('BX_PAYMENT_SBS_PU_YEAR', 'year');
  30. define('BX_PAYMENT_SBS_PU_MONTH', 'month');
  31. define('BX_PAYMENT_SBS_PU_WEEK', 'week');
  32. define('BX_PAYMENT_SBS_PU_DAY', 'day');
  33. define('BX_PAYMENT_SBS_PU_HOUR', 'hour');
  34. define('BX_PAYMENT_SBS_PU_MINUTE', 'minute');
  35. /*
  36. * Invoice: statuses.
  37. */
  38. define('BX_PAYMENT_INV_STATUS_UNPAID', 'unpaid');
  39. define('BX_PAYMENT_INV_STATUS_PAID', 'paid');
  40. define('BX_PAYMENT_INV_STATUS_OVERDUE', 'overdue');
  41. /**
  42. * Payment module by BoonEx
  43. *
  44. * This module is needed to work with payment providers and organize the process
  45. * of some item purchasing. Shopping Cart and Orders Manager are included.
  46. *
  47. * Integration notes:
  48. * To integrate your module with this one, you need:
  49. * 1. Get 'Add To Cart' button using serviceGetAddToCartLink service.
  50. * 2. Add info about your module in the 'bx_pmt_modules' table.
  51. * 3. Realize the following service methods in your Module class.
  52. * a. serviceGetItems($iSellerId) - Is used in Orders Administration to get all products of the requested seller(vendor).
  53. * b. serviceGetCartItem($iClientId, $iItemId) - Is used in Shopping Cart to get one product by specified id.
  54. * c. serviceRegisterCartItem($iClientId, $iSellerId, $iItemId, $iItemCount, $sOrderId) - Register purchased product.
  55. * d. serviceUnregisterCartItem($iClientId, $iSellerId, $iItemId, $iItemCount, $sOrderId) - Unregister the product purchased earlier.
  56. * @see You may see an example of integration in Membership module.
  57. *
  58. *
  59. * Profile's Wall:
  60. * no spy events
  61. *
  62. *
  63. *
  64. * Spy:
  65. * no spy events
  66. *
  67. *
  68. *
  69. * Memberships/ACL:
  70. * Doesn't depend on user's membership.
  71. *
  72. *
  73. *
  74. * Service methods:
  75. *
  76. * Is used to get "Add to cart" link for some item(s) in your module.
  77. * @see BxPmtModule::serviceGetAddToCartLink
  78. * BxDolService::call('payment', 'get_add_to_cart_link', array($iSellerId, $mixedModuleId, $iItemId, $iItemCount));
  79. *
  80. * Check transaction(s) in database which satisty all conditions.
  81. * @see BxPmtModule::serviceGetOrdersInfo
  82. * BxDolService::call('payment', 'get_orders_info', array($aConditions), 'Orders');
  83. *
  84. * Get total count of items in Shopping Cart.
  85. * @see BxPmtModule::serviceGetCartItemsCount
  86. * BxDolService::call('payment', 'get_cart_items_count', array($iUserId, $iOldCount));
  87. * @note is needed for internal usage(integration with member tool bar).
  88. *
  89. * Get Shopping cart content.
  90. * @see BxPmtModule::serviceGetCartItems
  91. * BxDolService::call('payment', 'get_cart_items');
  92. * @note is needed for internal usage(integration with member tool bar).
  93. *
  94. *
  95. * Alerts:
  96. * no alerts available
  97. *
  98. */
  99. class BxPaymentModule extends BxBaseModPaymentModule
  100. {
  101. protected $_iUserId;
  102. protected $_aOrderTypes;
  103. function __construct($aModule)
  104. {
  105. parent::__construct($aModule);
  106. $this->_iUserId = $this->getProfileId();
  107. $this->_aOrderTypes = array(
  108. BX_PAYMENT_ORDERS_TYPE_PENDING,
  109. BX_PAYMENT_ORDERS_TYPE_PROCESSED,
  110. BX_PAYMENT_ORDERS_TYPE_SUBSCRIPTION,
  111. BX_PAYMENT_ORDERS_TYPE_HISTORY
  112. );
  113. }
  114. /**
  115. * Manage Orders Methods
  116. */
  117. public function actionGetClients()
  118. {
  119. $sTerm = bx_get('term');
  120. $aResult = BxDolService::call('system', 'profiles_search', array($sTerm), 'TemplServiceProfiles');
  121. echoJson($aResult);
  122. }
  123. public function actionGetItems($sType, $iModuleId)
  124. {
  125. $iSellerId = $this->getProfileId();
  126. $aItems = $this->callGetCartItems((int)$iModuleId, array($iSellerId));
  127. echoJson(array(
  128. 'code' => 0,
  129. 'eval' => $this->_oConfig->getJsObject('processed') . '.onSelectModule(oData);',
  130. 'data' => $this->_oTemplate->displayItems($sType, $aItems)
  131. ));
  132. }
  133. public function actionGetFilterValuesItem($iSellerId, $iModuleId)
  134. {
  135. $sItems = '<option value="">' . _t('_bx_payment_txt_all_items') . '</option>';
  136. if(empty($iSellerId) || empty($iModuleId))
  137. return echoJson(array('code' => 1, 'content' => $sItems));
  138. $aItems = $this->callGetCartItems((int)$iModuleId, array($iSellerId));
  139. $this->_oConfig->sortByColumn('title', $aItems);
  140. foreach($aItems as $aItem)
  141. $sItems .= '<option value="' . $aItem['id'] . '">' . $aItem['title'] . '</option>';
  142. echoJson(array('code' => 0, 'content' => $sItems));
  143. }
  144. public function serviceGetSafeServices()
  145. {
  146. $a = parent::serviceGetSafeServices();
  147. return array_merge($a, array (
  148. 'GetBlockJoin' => 'BxPaymentJoin',
  149. 'GetBlockCarts' => 'BxPaymentCart',
  150. 'GetBlockCart' => 'BxPaymentCart',
  151. 'GetBlockCartHistory' => 'BxPaymentCart',
  152. 'GetBlockListMy' => 'BxPaymentSubscriptions',
  153. 'GetBlockHistory' => 'BxPaymentSubscriptions',
  154. ));
  155. }
  156. /**
  157. * @page service Service Calls
  158. * @section bx_payment Payment
  159. * @subsection bx_payment-purchase_processing Purchase Processing
  160. * @subsubsection bx_payment-get_modules_with_payments get_modules_with_payments
  161. *
  162. * @code bx_srv('bx_payment', 'get_modules_with_payments', []); @endcode
  163. *
  164. * Get modules with payments functionality
  165. *
  166. * @return array with modules names
  167. *
  168. * @see BxPaymentModule::serviceGetModulesWithPayments
  169. */
  170. /**
  171. * @ref bx_payment-get_modules_with_payments "get_modules_with_payments"
  172. */
  173. public function serviceGetModulesWithPayments()
  174. {
  175. return $this->_oDb->getModulesWithPayments();
  176. }
  177. /**
  178. * @page service Service Calls
  179. * @section bx_payment Payment
  180. * @subsection bx_payment-purchase_processing Purchase Processing
  181. * @subsubsection bx_payment-is_credits_only is_credits_only
  182. *
  183. * @code bx_srv('bx_payment', 'is_credits_only'); @endcode
  184. *
  185. * Check whether the 'Credits Only' mode is enabled or not.
  186. *
  187. * @return boolean value determining the result of checking.
  188. *
  189. * @see BxPaymentModule::serviceIsCreditsOnly
  190. */
  191. /**
  192. * @ref bx_payment-is_credits_only "is_credits_only"
  193. */
  194. public function serviceIsCreditsOnly()
  195. {
  196. return $this->_oConfig->isCreditsOnly();
  197. }
  198. /**
  199. * @page service Service Calls
  200. * @section bx_payment Payment
  201. * @subsection bx_payment-purchase_processing Purchase Processing
  202. * @subsubsection bx_payment-is_accepting_payments is_accepting_payments
  203. *
  204. * @code bx_srv('bx_payment', 'is_accepting_payments', [...]); @endcode
  205. *
  206. * Check whether the specified vendor has a configured payment provider or not.
  207. *
  208. * @param $iVendorId integer value with vendor ID.
  209. * @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.
  210. * @return boolean value determining the result of checking.
  211. *
  212. * @see BxPaymentModule::serviceIsAcceptingPayments
  213. */
  214. /**
  215. * @ref bx_payment-is_accepting_payments "is_accepting_payments"
  216. */
  217. public function serviceIsAcceptingPayments($iVendorId, $sPaymentType = '')
  218. {
  219. $bResult = false;
  220. switch($sPaymentType) {
  221. case BX_PAYMENT_TYPE_SINGLE:
  222. $aProvidersCart = $this->_oDb->getVendorInfoProvidersSingle($iVendorId);
  223. $bResult = !empty($aProvidersCart);
  224. break;
  225. case BX_PAYMENT_TYPE_RECURRING:
  226. $aProvidersSubscription = $this->_oDb->getVendorInfoProvidersRecurring($iVendorId);
  227. $bResult = !empty($aProvidersSubscription);
  228. break;
  229. default:
  230. $aProviders = $this->_oDb->getVendorInfoProviders($iVendorId);
  231. $bResult = !empty($aProviders);
  232. }
  233. return $bResult;
  234. }
  235. /**
  236. * @deprecated since version 11.0.0
  237. *
  238. * @see BxPaymentModule::serviceIsProviderOptions
  239. */
  240. public function serviceIsPaymentProvider($iVendorId, $sVendorProvider, $sPaymentType = '')
  241. {
  242. return $this->serviceIsProviderOptions($iVendorId, $sVendorProvider, $sPaymentType);
  243. }
  244. /**
  245. * @deprecated since version 11.0.0
  246. *
  247. * @see BxPaymentModule::serviceGetProviderOptions
  248. */
  249. public function serviceGetPaymentProvider($iVendorId, $sVendorProvider, $sPaymentType = '')
  250. {
  251. return $this->serviceGetProviderOptions($iVendorId, $sVendorProvider, $sPaymentType);
  252. }
  253. /**
  254. * @page service Service Calls
  255. * @section bx_payment Payment
  256. * @subsection bx_payment-purchase_processing Purchase Processing
  257. * @subsubsection bx_payment-is_provider_options is_provider_options
  258. *
  259. * @code bx_srv('bx_payment', 'is_provider_options', [...]); @endcode
  260. *
  261. * Check whether the specified vendor has configured the specified payment provider or not.
  262. *
  263. * @param $iVendorId integer value with vendor ID.
  264. * @param $sVendorProvider string value with payment provider name.
  265. * @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.
  266. * @return boolean value determining the result of checking.
  267. *
  268. * @see BxPaymentModule::serviceIsProviderOptions
  269. */
  270. /**
  271. * @ref bx_payment-is_provider_options "is_provider_options"
  272. */
  273. public function serviceIsProviderOptions($iVendorId, $sVendorProvider, $sPaymentType = '')
  274. {
  275. $aProvider = $this->serviceGetProviderOptions($iVendorId, $sVendorProvider, $sPaymentType);
  276. return $aProvider !== false;
  277. }
  278. /**
  279. * @page service Service Calls
  280. * @section bx_payment Payment
  281. * @subsection bx_payment-purchase_processing Purchase Processing
  282. * @subsubsection bx_payment-get_provider_options get_provider_options
  283. *
  284. * @code bx_srv('bx_payment', 'get_provider_options', [...]); @endcode
  285. *
  286. * Get configuration settings for the payment provider entered by the specified vendor.
  287. *
  288. * @param $iVendorId integer value with vendor ID.
  289. * @param $sVendorProvider string value with payment provider name.
  290. * @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.
  291. * @return an array with special format describing the payment provider or false value if something is wrong.
  292. *
  293. * @see BxPaymentModule::serviceGetProviderOptions
  294. */
  295. /**
  296. * @ref bx_payment-get_provider_options "get_provider_options"
  297. */
  298. public function serviceGetProviderOptions($iVendorId, $sVendorProvider, $sPaymentType = '')
  299. {
  300. $aProviders = array();
  301. switch($sPaymentType) {
  302. case BX_PAYMENT_TYPE_SINGLE:
  303. $aProviders = $this->_oDb->getVendorInfoProvidersSingle($iVendorId);
  304. break;
  305. case BX_PAYMENT_TYPE_RECURRING:
  306. $aProviders = $this->_oDb->getVendorInfoProvidersRecurring($iVendorId);
  307. break;
  308. default:
  309. $aProviders = $this->_oDb->getVendorInfoProviders($iVendorId);
  310. }
  311. return !empty($aProviders) && !empty($aProviders[$sVendorProvider]) && is_array(($aProviders[$sVendorProvider])) ? $aProviders[$sVendorProvider] : false;
  312. }
  313. /**
  314. * @page service Service Calls
  315. * @section bx_payment Payment
  316. * @subsection bx_payment-other Other
  317. * @subsubsection bx_payment-get_options_default_currency_code get_options_default_currency_code
  318. *
  319. * @code bx_srv('bx_payment', 'get_options_default_currency_code', [...]); @endcode
  320. *
  321. * Get an array with available currencies. Is used in forms.
  322. *
  323. * @return an array with available currencies represented as key => value pairs.
  324. *
  325. * @see BxPaymentModule::serviceGetOptionsDefaultCurrencyCode
  326. */
  327. /**
  328. * @ref bx_payment-get_options_default_currency_code "get_options_default_currency_code"
  329. */
  330. public function serviceGetOptionsDefaultCurrencyCode()
  331. {
  332. $CNF = &$this->_oConfig->CNF;
  333. $aCurrencies = BxDolForm::getDataItems($CNF['OBJECT_FORM_PRELISTS_CURRENCIES']);
  334. $aResult = array();
  335. foreach($aCurrencies as $sKey => $sValue)
  336. $aResult[] = array(
  337. 'key' => $sKey,
  338. 'value' => $sValue
  339. );
  340. return $aResult;
  341. }
  342. /**
  343. * @page service Service Calls
  344. * @section bx_payment Payment
  345. * @subsection bx_payment-other Other
  346. * @subsubsection bx_payment-get_options_site_admin get_options_site_admin
  347. *
  348. * @code bx_srv('bx_payment', 'get_options_site_admin', [...]); @endcode
  349. *
  350. * 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.
  351. *
  352. * @return an array with profiles represented as key => value pairs.
  353. *
  354. * @see BxPaymentModule::serviceGetOptionsSiteAdmin
  355. */
  356. /**
  357. * @ref bx_payment-get_options_site_admin "get_options_site_admin"
  358. */
  359. public function serviceGetOptionsSiteAdmin()
  360. {
  361. $aResult = array(
  362. array('key' => '', 'value' => _t('_Select_one'))
  363. );
  364. $aIds = $this->_oDb->getAdminsIds();
  365. foreach($aIds as $iId) {
  366. $aUser = $this->getProfileInfo($iId);
  367. $aResult[] = array(
  368. 'key' => $iId,
  369. 'value' => $aUser['name']
  370. );
  371. }
  372. return $aResult;
  373. }
  374. public function serviceGetMenuAddonManageTools()
  375. {
  376. return array(
  377. 'counter1_value' => (int)$this->_oDb->getInvoices(array('type' => 'status', 'status' => BX_PAYMENT_INV_STATUS_PAID, 'count' => true)),
  378. 'counter1_caption' => _t('_bx_payment_menu_item_title_admt_addon_counter1_caption'),
  379. 'counter2_value' => (int)$this->_oDb->getInvoices(array('type' => 'status', 'status' => BX_PAYMENT_INV_STATUS_OVERDUE, 'count' => true)),
  380. 'counter2_caption' => _t('_bx_payment_menu_item_title_admt_addon_counter2_caption'),
  381. 'counter3_value' => (int)$this->_oDb->getInvoices(array('type' => 'all_count'))
  382. );
  383. }
  384. public function serviceGetBlockCheckoutOffline()
  385. {
  386. $CNF = &$this->_oConfig->CNF;
  387. $oBuyer = BxDolProfile::getInstance();
  388. if(!$oBuyer)
  389. return MsgBox(_t('_bx_payment_err_required_login'));
  390. $iSeller = (int)bx_get('seller');
  391. $oSeller = BxDolProfile::getInstance($iSeller);
  392. if(!$oSeller)
  393. return MsgBox(_t('_bx_payment_err_unknown_vendor'));
  394. $aData = array(
  395. 'seller' => $iSeller,
  396. 'currency' => array(
  397. 'code' => bx_process_input(bx_get('currency_code')),
  398. 'sign' => bx_process_input(bx_get('currency_sign')),
  399. ),
  400. 'amount' => (float)bx_get('amount'),
  401. 'return_url' => bx_process_input(bx_get('return_url')),
  402. );
  403. if(empty($aData['currency']['code']))
  404. $aData['currency']['code'] = $this->_oConfig->getDefaultCurrencyCode();
  405. if(empty($aData['currency']['sign']))
  406. $aData['currency']['sign'] = $this->_oConfig->getDefaultCurrencySign();
  407. $sItems = '';
  408. $iItemsCount = (int)bx_get('items_count');
  409. for($i = 0; $i < $iItemsCount; $i++) {
  410. $aItem = array(
  411. 'title' => bx_process_input(bx_get('item_title_' . $i)),
  412. 'quantity' => (int)bx_get('item_quantity_' . $i)
  413. );
  414. $sItems .= _t('_bx_payment_txt_checkout_item', $aItem['title'], $aItem['quantity']);
  415. $aData['items'][] = $aItem;
  416. }
  417. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate($this->_oConfig->getPrefix('general') . 'checkout_offline', array(
  418. 'profile_name' => $oBuyer->getDisplayName(),
  419. 'profile_link' => $oBuyer->getUrl(),
  420. 'items' => $sItems,
  421. 'amount' => $aData['currency']['sign'] . sprintf("%.2f", (float)($aData['amount'])),
  422. 'date' => bx_time_js(time(), BX_FORMAT_DATE, true),
  423. 'pending_orders_link' => $this->getObjectOrders()->serviceGetPendingOrdersUrl()
  424. ), 0, $iSeller);
  425. $sEmail = '';
  426. $oProvider = $this->getObjectProvider($CNF['OBJECT_PP_OFFLINE'], $iSeller);
  427. if($oProvider !== false && $oProvider->isActive())
  428. $sEmail = $oProvider->getOption('checkout_email');
  429. if(empty($sEmail))
  430. $sEmail = $oBuyer->getAccountObject()->getEmail();
  431. if(!sendMail($sEmail, $aTemplate['Subject'], $aTemplate['Body'], 0, array(), BX_EMAIL_SYSTEM))
  432. return MsgBox(_t('_bx_payment_err_cannot_perform'));
  433. return $this->_oTemplate->displayBlockCheckoutOffline($oBuyer, $oSeller, $aData);
  434. }
  435. /**
  436. * Cart Processing Methods
  437. */
  438. public function actionAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount, $sCustom = '')
  439. {
  440. if(empty($sCustom) && bx_get('custom') !== false)
  441. $sCustom = bx_process_input(bx_get('custom'));
  442. $aCustom = array();
  443. if(!empty($sCustom)) {
  444. $aCustom = unserialize(base64_decode($sCustom));
  445. if(empty($aCustom) || !is_array($aCustom))
  446. $aCustom = array();
  447. }
  448. $aResult = $this->getObjectCart()->serviceAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount, $aCustom);
  449. echoJson($aResult);
  450. }
  451. /**
  452. * Isn't used yet.
  453. */
  454. public function actionDeleteFromCart($iSellerId, $iModuleId, $iItemId)
  455. {
  456. echoJson($this->getObjectCart()->serviceDeleteFromCart($iSellerId, $iModuleId, $iItemId));
  457. }
  458. /**
  459. * Isn't used yet.
  460. */
  461. public function actionEmptyCart($iSellerId)
  462. {
  463. echoJson($this->getObjectCart()->serviceDeleteFromCart($iSellerId));
  464. }
  465. public function actionSubscribe()
  466. {
  467. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  468. $sSellerProvider = bx_process_input(bx_get('seller_provider'));
  469. $iModuleId = bx_process_input(bx_get('module_id'), BX_DATA_INT);
  470. $iItemId = bx_process_input(bx_get('item_id'), BX_DATA_INT);
  471. $iItemCount = bx_process_input(bx_get('item_count'), BX_DATA_INT);
  472. if(empty($iItemCount))
  473. $iItemCount = 1;
  474. $sRedirect = bx_process_input(bx_get('redirect'));
  475. $sCustom = bx_process_input(bx_get('custom'));
  476. $aCustom = array();
  477. if(!empty($sCustom)) {
  478. $aCustom = unserialize(base64_decode($sCustom));
  479. if(empty($aCustom) || !is_array($aCustom))
  480. $aCustom = array();
  481. }
  482. $aResult = $this->getObjectSubscriptions()->serviceSubscribe($iSellerId, $sSellerProvider, $iModuleId, $iItemId, $iItemCount, $sRedirect, $aCustom);
  483. $bRedirect = !empty($aResult['redirect']);
  484. if(!empty($aResult['popup'])) {
  485. $sContent = '';
  486. $sContent .= $this->_oTemplate->displayCartJs(BX_PAYMENT_TYPE_RECURRING, $iSellerId);
  487. $sContent .= !empty($aResult['popup']['html']) ? $aResult['popup']['html'] : $aResult['popup'];
  488. return $this->_oTemplate->displayPageCodeResponse($sContent, false, true);
  489. }
  490. if(!empty($aResult['code']))
  491. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  492. if(!empty($aResult['message']) && !$bRedirect)
  493. return $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  494. if($bRedirect) {
  495. header('Location: ' . $aResult['redirect']);
  496. exit;
  497. }
  498. }
  499. public function actionSubscribeJson()
  500. {
  501. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  502. $sSellerProvider = bx_process_input(bx_get('seller_provider'));
  503. $iModuleId = bx_process_input(bx_get('module_id'), BX_DATA_INT);
  504. $iItemId = bx_process_input(bx_get('item_id'), BX_DATA_INT);
  505. $iItemCount = bx_process_input(bx_get('item_count'), BX_DATA_INT);
  506. if(empty($iItemCount))
  507. $iItemCount = 1;
  508. $sItemAddons = '';
  509. if(bx_get('item_addons') !== false) {
  510. $sItemAddons = bx_process_input(bx_get('item_addons'));
  511. if(is_array($sItemAddons))
  512. $sItemAddons = $this->_oConfig->a2s($sItemAddons);
  513. }
  514. $sRedirect = bx_process_input(bx_get('redirect'));
  515. $sCustom = bx_process_input(bx_get('custom'));
  516. $aCustom = array();
  517. if(!empty($sCustom)) {
  518. $aCustom = unserialize(base64_decode($sCustom));
  519. if(empty($aCustom) || !is_array($aCustom))
  520. $aCustom = array();
  521. }
  522. echoJson($this->getObjectSubscriptions()->serviceSubscribeWithAddons($iSellerId, $sSellerProvider, $iModuleId, $iItemId, $iItemCount, $sItemAddons, $sRedirect, $aCustom));
  523. }
  524. public function actionSubscriptionGetDetails($iId)
  525. {
  526. echoJson($this->_oTemplate->displaySubscriptionGetDetails($iId));
  527. }
  528. public function actionSubscriptionChangeDetails($iId)
  529. {
  530. echoJson($this->_oTemplate->displaySubscriptionChangeDetails($iId));
  531. }
  532. public function actionSubscriptionGetBilling($iId)
  533. {
  534. echoJson($this->_oTemplate->displaySubscriptionGetBilling($iId));
  535. }
  536. public function actionSubscriptionChangeBilling($iId)
  537. {
  538. echoJson($this->_oTemplate->displaySubscriptionChangeBilling($iId));
  539. }
  540. public function actionSubscriptionCancelation($iId)
  541. {
  542. $aResult = array('code' => 1, 'message' => _t('_bx_payment_err_cannot_perform'));
  543. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => $iId));
  544. if(empty($aPending) || !is_array($aPending))
  545. return echoJson($aResult);
  546. $aSubscription = $this->_oDb->getSubscription(array('type' => 'pending_id', 'pending_id' => $iId));
  547. if(empty($aSubscription) || !is_array($aSubscription))
  548. return echoJson($aResult);
  549. $oRecipient = BxDolProfile::getInstance((int)$aPending['seller_id']);
  550. if(!$oRecipient)
  551. return echoJson($aResult);
  552. $mixedResult = $this->isAllowedManage($aPending);
  553. if($mixedResult !== true)
  554. return echoJson(array('code' => 2, 'message' => $mixedResult));
  555. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate($this->_oConfig->getPrefix('general') . 'cancelation_request', array(
  556. 'sibscription_id' => $aSubscription['subscription_id'],
  557. 'sibscription_customer' => $aSubscription['customer_id'],
  558. 'sibscription_date' => bx_time_js($aSubscription['date_add'], BX_FORMAT_DATE, true)
  559. ), 0, (int)$aPending['client_id']);
  560. $sEmail = '';
  561. $oProvider = $this->getObjectProvider($aPending['provider'], $aPending['seller_id']);
  562. if($oProvider !== false && $oProvider->isActive())
  563. $sEmail = $oProvider->getOption('cancellation_email');
  564. if(empty($sEmail))
  565. $sEmail = $oRecipient->getAccountObject()->getEmail();
  566. if(!sendMail($sEmail, $aTemplate['Subject'], $aTemplate['Body'], 0, array(), BX_EMAIL_SYSTEM))
  567. return echoJson($aResult);
  568. echoJson(array('code' => 0, 'message' => _t('_bx_payment_msg_cancelation_request_sent')));
  569. }
  570. public function actionSubscriptionCancel($iId, $mixedGridObject = false)
  571. {
  572. $aResult = array('code' => 1, 'message' => _t('_bx_payment_err_cannot_perform'));
  573. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => $iId));
  574. if(empty($aPending) || !is_array($aPending))
  575. return echoJson($aResult);
  576. $mixedResult = $this->isAllowedManage($aPending);
  577. if($mixedResult !== true)
  578. return echoJson(array('code' => 2, 'message' => $mixedResult));
  579. if(!$this->getObjectSubscriptions()->cancel($iId))
  580. return echoJson($aResult);
  581. if(empty($mixedGridObject) && bx_get('grid') !== false)
  582. $mixedGridObject = bx_process_input(bx_get('grid'));
  583. if(!empty($mixedGridObject) && $aPending['client_id'] == $this->getProfileId()) {
  584. $oGrid = BxDolGrid::getObjectInstance($mixedGridObject, $this->_oTemplate);
  585. $oGrid->addQueryParam('client_id', $aPending['client_id']);
  586. return echoJson(array('object' => $mixedGridObject, 'grid' => $oGrid->getCode(false), 'blink' => array($iId)));
  587. }
  588. else
  589. return echoJson(array('code' => 0, 'message' => _t('_bx_payment_msg_successfully_performed')));
  590. }
  591. /**
  592. * Payment Processing Methods
  593. */
  594. public function actionAuthorizeCheckout($sType)
  595. {
  596. if(!$this->isLogged())
  597. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  598. if(bx_get('seller_id') === false || bx_get('provider') === false || bx_get('items') === false)
  599. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_wrong_data');
  600. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  601. $sProvider = bx_process_input(bx_get('provider'));
  602. $aItems = bx_process_input(bx_get('items'));
  603. $mixedResult = $this->serviceAuthorizeCheckout($sType, $iSellerId, $sProvider, $aItems);
  604. if(is_string($mixedResult))
  605. return $this->_oTemplate->displayPageCodeError($mixedResult);
  606. if(is_array($mixedResult) && !empty($mixedResult['redirect'])) {
  607. header('Location: ' . $mixedResult['redirect']);
  608. exit;
  609. }
  610. return $this->_oTemplate->displayPageCodeResponse($this->_sLangsPrefix . 'msg_successfully_performed');
  611. }
  612. public function actionCaptureAuthorizedCheckout($sType)
  613. {
  614. $iProfileId = bx_get_logged_profile_id();
  615. if(!$iProfileId)
  616. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  617. $sOrderAuth = '';
  618. if(($sOrderAuth = bx_get('order')) !== false)
  619. $sOrderAuth = bx_process_input($sOrderAuth);
  620. if(empty($sOrderAuth))
  621. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_empty_order');
  622. $aPending = $this->_oDb->getOrderPending(['type' => 'order', 'order' => $sOrderAuth]);
  623. if(empty($aPending) || !is_array($aPending))
  624. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_empty_order');
  625. if((int)$aPending['seller_id'] != $iProfileId)
  626. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_wrong_vendor');
  627. $mixedResult = $this->serviceCaptureAuthorizedCheckout($sType, $sOrderAuth);
  628. if(is_string($mixedResult))
  629. return $this->_oTemplate->displayPageCodeError($mixedResult);
  630. if(!empty($mixedResult['redirect'])) {
  631. header('Location: ' . base64_decode(urldecode($mixedResult['redirect'])));
  632. exit;
  633. }
  634. return $this->_oTemplate->displayPageCodeResponse($mixedResult['message']);
  635. }
  636. public function actionInitializeCheckout($sType)
  637. {
  638. if(!$this->isLogged())
  639. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  640. if(bx_get('seller_id') !== false && bx_get('provider') !== false && bx_get('items') !== false) {
  641. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  642. $sProvider = bx_process_input(bx_get('provider'));
  643. $aItems = bx_process_input(bx_get('items'));
  644. $mixedResult = $this->serviceInitializeCheckout(BX_PAYMENT_TYPE_SINGLE, $iSellerId, $sProvider, $aItems);
  645. if($mixedResult !== true)
  646. return $this->_oTemplate->displayPageCodeError($mixedResult);
  647. }
  648. header('Location: ' . $this->_oConfig->getUrl('URL_CART'));
  649. exit;
  650. }
  651. public function actionInitializeCheckoutJson($sType)
  652. {
  653. if(!$this->isLogged())
  654. return echoJson(['code' => 1, 'message' => _t($this->_sLangsPrefix . 'err_required_login')]);
  655. if(bx_get('seller_id') !== false && bx_get('provider') !== false && bx_get('items') !== false) {
  656. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  657. $sProvider = bx_process_input(bx_get('provider'));
  658. $aItems = bx_process_input(bx_get('items'));
  659. $mixedResult = $this->serviceInitializeCheckout(BX_PAYMENT_TYPE_SINGLE, $iSellerId, $sProvider, $aItems);
  660. if($mixedResult === false)
  661. return echoJson(['code' => 2, 'message' => _t($this->_sLangsPrefix . 'err_cannot_perform')]);
  662. if(is_string($mixedResult))
  663. return echoJson(['code' => 3, 'message' => $mixedResult]);
  664. else if(is_array($mixedResult))
  665. return echoJson($mixedResult);
  666. }
  667. return echoJson(['code' => 0, 'redirect' => $this->_oConfig->getUrl('URL_CART')]);
  668. }
  669. /**
  670. * @page service Service Calls
  671. * @section bx_payment Payment
  672. * @subsection bx_payment-purchase_processing Purchase Processing
  673. * @subsubsection bx_payment-authorize_checkout authorize_checkout
  674. *
  675. * @code bx_srv('bx_payment', 'authorize_checkout', [...]); @endcode
  676. *
  677. * Authorize order for future checkout.
  678. *
  679. * @param $sType string value with payment type (single or recurring).
  680. * @param $iSellerId integer value with seller ID.
  681. * @param $sProvider string value with payment provider name.
  682. * @param $aItems (optional) an array with items to be purchased.
  683. * @param $sRedirect (optional) string value with redirect URL if it's needed.
  684. * @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.
  685. *
  686. * @see BxPaymentModule::serviceAuthorizeCheckout
  687. */
  688. /**
  689. * @ref bx_payment-authorize_checkout "authorize_checkout"
  690. */
  691. public function serviceAuthorizeCheckout($sType, $iSellerId, $sProvider, $aItems = [], $sRedirect = '')
  692. {
  693. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  694. $bTypeRecurring = $sType == BX_PAYMENT_TYPE_RECURRING;
  695. if(!is_array($aItems))
  696. $aItems = [$aItems];
  697. $iSellerId = (int)$iSellerId;
  698. if($iSellerId == BX_PAYMENT_EMPTY_ID)
  699. return $this->_sLangsPrefix . 'err_unknown_vendor';
  700. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  701. if($oProvider === false || !$oProvider->isActive())
  702. return $this->_sLangsPrefix . 'err_incorrect_provider';
  703. $aInfo = $this->getObjectCart()->getInfo($sType, $this->_iUserId, $iSellerId, $aItems);
  704. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  705. return $this->_sLangsPrefix . 'err_empty_order';
  706. $this->alert('before_authorize', 0, $this->_iUserId, array(
  707. 'client_id' => $this->_iUserId,
  708. 'seller_id' => $iSellerId,
  709. 'type' => &$sType,
  710. 'provider' => &$sProvider,
  711. 'cart_info' => &$aInfo,
  712. ));
  713. $iPendingId = $this->_oDb->insertOrderPending($this->_iUserId, $sType, $sProvider, $aInfo);
  714. if(empty($iPendingId))
  715. return $this->_sLangsPrefix . 'err_access_db';
  716. return $oProvider->authorizeCheckout($iPendingId, $aInfo, $sRedirect);
  717. }
  718. /**
  719. * @page service Service Calls
  720. * @section bx_payment Payment
  721. * @subsection bx_payment-purchase_processing Purchase Processing
  722. * @subsubsection bx_payment-capture_authorized_checkout capture_authorized_checkout
  723. *
  724. * @code bx_srv('bx_payment', 'capture_authorized_checkout', [...]); @endcode
  725. *
  726. * Capture funds for previously authorized order.
  727. *
  728. * @param $sType string value with payment type (single or recurring).
  729. * @param $sOrderAuth string value with order's authorization ID.
  730. * @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.
  731. *
  732. * @see BxPaymentModule::serviceCaptureAuthorizedCheckout
  733. */
  734. /**
  735. * @ref bx_payment-capture_authorized_checkout "capture_authorized_checkout"
  736. */
  737. public function serviceCaptureAuthorizedCheckout($sType, $sOrderAuth, $sRedirect = '')
  738. {
  739. $aPending = $this->_oDb->getOrderPending(['type' => 'order', 'order' => $sOrderAuth]);
  740. if(empty($aPending) || !is_array($aPending))
  741. return $this->_sLangsPrefix . 'err_empty_order';
  742. if((int)$aPending['processed'] != 0)
  743. return $this->_sLangsPrefix . 'err_already_processed';
  744. $iClientId = (int)$aPending['client_id'];
  745. $iSellerId = (int)$aPending['seller_id'];
  746. $sProvider = $aPending['provider'];
  747. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  748. if($oProvider === false || !$oProvider->isActive())
  749. return $this->_sLangsPrefix . 'err_incorrect_provider';
  750. $aInfo = $this->getObjectCart()->getInfo($sType, $iClientId, $iSellerId, $aPending['items']);
  751. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  752. return $this->_sLangsPrefix . 'err_empty_order';
  753. $this->alert('before_capture_authorized', 0, $iClientId, array(
  754. 'order_auth' => $sOrderAuth,
  755. 'client_id' => $iClientId,
  756. 'seller_id' => $iSellerId,
  757. 'type' => &$sType,
  758. 'provider' => &$sProvider,
  759. 'cart_info' => &$aInfo,
  760. ));
  761. $aResult = $oProvider->captureAuthorizedCheckout($sOrderAuth, $aPending, $aInfo, $sRedirect);
  762. if((int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS)
  763. return $aResult['message'];
  764. //--- Get updated pending order
  765. $aPending = $this->_oDb->getOrderPending(['type' => 'id', 'id' => $aResult['pending_id']]);
  766. //--- Register payment for purchased items in associated modules
  767. if(isset($aResult['paid']) && $aResult['paid'])
  768. $this->registerPayment($aPending);
  769. $this->alert('finalize_checkout', 0, bx_get_logged_profile_id(), array(
  770. 'pending' => $aPending,
  771. 'transactions' => $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id'])),
  772. 'provider' => $oProvider,
  773. 'message' => &$aResult['message'],
  774. 'result' => &$aResult,
  775. ));
  776. if(empty($aResult['redirect']) && $oProvider->needRedirect())
  777. $aResult['redirect'] = $oProvider->getReturnUrl();
  778. return $aResult;
  779. }
  780. /**
  781. * @page service Service Calls
  782. * @section bx_payment Payment
  783. * @subsection bx_payment-purchase_processing Purchase Processing
  784. * @subsubsection bx_payment-initialize_checkout initialize_checkout
  785. *
  786. * @code bx_srv('bx_payment', 'initialize_checkout', [...]); @endcode
  787. *
  788. * Initialize the checkout process.
  789. *
  790. * @param $sType string value with payment type (single or recurring).
  791. * @param $iSellerId integer value with seller ID.
  792. * @param $sProvider string value with payment provider name.
  793. * @param $aItems (optional) an array with items to be purchased.
  794. * @param $sRedirect (optional) string value with redirect URL if it's needed.
  795. * @param $aCustom (optional) array with custom data to attach to a payment.
  796. * @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.
  797. *
  798. * @see BxPaymentModule::serviceInitializeCheckout
  799. */
  800. /**
  801. * @ref bx_payment-initialize_checkout "initialize_checkout"
  802. */
  803. public function serviceInitializeCheckout($sType, $iSellerId, $sProvider, $aItems = array(), $sRedirect = '', $aCustoms = array())
  804. {
  805. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  806. $bTypeRecurring = $sType == BX_PAYMENT_TYPE_RECURRING;
  807. if(!is_array($aItems))
  808. $aItems = array($aItems);
  809. $iSellerId = (int)$iSellerId;
  810. if($iSellerId == BX_PAYMENT_EMPTY_ID)
  811. return $this->_sLangsPrefix . 'err_unknown_vendor';
  812. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  813. if($oProvider === false || !$oProvider->isActive())
  814. return $this->_sLangsPrefix . 'err_incorrect_provider';
  815. $aInfo = $this->getObjectCart()->getInfo($sType, $this->_iUserId, $iSellerId, $aItems);
  816. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  817. return $this->_sLangsPrefix . 'err_empty_order';
  818. /*
  819. * Process FREE (price = 0) items for LOGGED IN members
  820. * WITHOUT processing via payment provider.
  821. * Note. This section isn't used for now!
  822. */
  823. $bProcessedFree = false;
  824. $sKeyPriceSingle = $this->_oConfig->getKey('KEY_ARRAY_PRICE_SINGLE');
  825. $sKeyPriceRecurring = $this->_oConfig->getKey('KEY_ARRAY_PRICE_RECURRING');
  826. foreach($aInfo['items'] as $iIndex => $aItem) {
  827. if((int)$aInfo['client_id'] == 0)
  828. continue;
  829. //--- For Single time payments.
  830. if($bTypeSingle && (float)$aItem[$sKeyPriceSingle] == 0) {
  831. $aCart = $this->_oDb->getCartContent($aInfo['client_id']);
  832. $aCartCustoms = !empty($aCart['customs']) ? unserialize($aCart['customs']) : array();
  833. $aCartItem = array($aInfo['vendor_id'], $aItem['module_id'], $aItem['id'], $aItem['quantity']);
  834. $aCartItemCustom = $this->_oConfig->pullCustom($aCartItem, $aCartCustoms);
  835. $aItemInfo = $this->callRegisterCartItem((int)$aItem['module_id'], array($aInfo['client_id'], $aInfo['vendor_id'], $aItem['id'], $aItem['quantity'], $this->_oConfig->getLicense(), $aCartItemCustom));
  836. if(!empty($aItemInfo) && is_array($aItemInfo)) {
  837. if(!empty($aItemInfo['addons']) && is_array($aItemInfo['addons']))
  838. foreach($aItemInfo['addons'] as $sAddon => $aAddon)
  839. $this->callRegisterCartItem((int)$aAddon['module_id'], array($aInfo['client_id'], $aInfo['vendor_id'], $aAddon['id'], $aAddon['quantity'], $this->_oConfig->getLicense(), $aCartItemCustom));
  840. $bProcessedFree = true;
  841. }
  842. $aInfo['items_count'] -= 1;
  843. unset($aInfo['items'][$iIndex]);
  844. $aCart['items'] = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aCartItem) . ":?'", "", $aCart['items']), ":");
  845. $this->_oDb->setCartItems($aInfo['client_id'], $aCart['items'], $aCartCustoms);
  846. }
  847. //--- For Recurring payments.
  848. if($bTypeRecurring && (float)$aItem[$sKeyPriceRecurring] == 0) {
  849. //TODO: Process FREE subscription here, if such situation will be possible.
  850. }
  851. }
  852. if(empty($aInfo['items']))
  853. return $this->_sLangsPrefix . ($bProcessedFree ? 'msg_successfully_processed_free' : 'err_empty_order');
  854. if($bTypeSingle && (empty($aCustoms) || !is_array($aCustoms))) {
  855. $aCart = $this->_oDb->getCartContent($aInfo['client_id']);
  856. $aCartCustoms = !empty($aCart['customs']) ? unserialize($aCart['customs']) : array();
  857. $aCustoms = array();
  858. foreach($aInfo['items'] as $aItem) {
  859. $sCartItem = $this->_oConfig->descriptorA2S(array($aItem['author_id'], $aItem['module_id'], $aItem['id']));
  860. $aCartItemCustom = $this->_oConfig->getCustom($sCartItem, $aCartCustoms);
  861. $this->_oConfig->putCustom($sCartItem, $aCartItemCustom, $aCustoms);
  862. }
  863. }
  864. $this->alert('before_pending', 0, bx_get_logged_profile_id(), array(
  865. 'client_id' => $this->_iUserId,
  866. 'seller_id' => $iSellerId,
  867. 'type' => &$sType,
  868. 'provider' => &$sProvider,
  869. 'cart_info' => &$aInfo,
  870. 'custom' => &$aCustoms,
  871. ));
  872. $iPendingId = $this->_oDb->insertOrderPending($this->_iUserId, $sType, $sProvider, $aInfo, $aCustoms);
  873. if(empty($iPendingId))
  874. return $this->_sLangsPrefix . 'err_access_db';
  875. /*
  876. * Perform Join WITHOUT processing via payment provider
  877. * if a client ISN'T logged in and has only ONE FREE item in the card.
  878. * Note. This section isn't used for now because only a member can purchase!
  879. */
  880. if((int)$aInfo['client_id'] == 0 && (int)$aInfo['items_count'] == 1) {
  881. reset($aInfo['items']);
  882. $aItem = current($aInfo['items']);
  883. if(!empty($aItem) && $this->_oConfig->getPrice($sType, $aItem)) {
  884. $this->_oDb->updateOrderPending($iPendingId, array(
  885. 'order' => $this->_oConfig->getLicense(),
  886. 'error_code' => '1',
  887. 'error_msg' => ''
  888. ));
  889. $this->getObjectJoin()->performJoin($iPendingId);
  890. }
  891. }
  892. return $oProvider->initializeCheckout($iPendingId, $aInfo, $sRedirect);
  893. }
  894. public function actionFinalizeCheckout($sProvider, $mixedVendorId = "")
  895. {
  896. $aData = &$_REQUEST;
  897. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  898. if($oProvider === false || !$oProvider->isActive())
  899. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  900. $aResult = $oProvider->finalizeCheckout($aData);
  901. if((int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS)
  902. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  903. $aPending = $this->_oDb->getOrderPending(['type' => 'id', 'id' => (int)$aResult['pending_id']]);
  904. $bTypeRecurring = $aPending['type'] == BX_PAYMENT_TYPE_RECURRING;
  905. $bAuthorized = isset($aResult['authorized']) && $aResult['authorized'];
  906. $bPaid = isset($aResult['paid']) && $aResult['paid'];
  907. $bTrial = isset($aResult['trial']) && $aResult['trial'];
  908. //--- Register subscription
  909. if($bTypeRecurring) {
  910. $sStatus = BX_PAYMENT_SBS_STATUS_UNPAID;
  911. if($bPaid)
  912. $sStatus = BX_PAYMENT_SBS_STATUS_ACTIVE;
  913. else if($bTrial)
  914. $sStatus = BX_PAYMENT_SBS_STATUS_TRIAL;
  915. $aSubscription = array(
  916. 'customer_id' => $aResult['customer_id'],
  917. 'subscription_id' => $aResult['subscription_id'],
  918. 'status' => $sStatus
  919. );
  920. if(!$this->getObjectSubscriptions()->register($aPending, $aSubscription))
  921. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_already_registered');
  922. }
  923. $this->onPaymentRegisterBefore($aPending);
  924. //--- Check "Pay Before Join" situation
  925. if((int)$aPending['client_id'] == 0)
  926. $this->getObjectJoin()->performJoin((int)$aPending['id'], isset($aResult['client_name']) ? $aResult['client_name'] : '', isset($aResult['client_email']) ? $aResult['client_email'] : '');
  927. //--- Authorize order for selected items in associated modules
  928. if($bAuthorized)
  929. $this->authorizePayment($aPending);
  930. //--- Register payment for purchased items in associated modules
  931. if($bPaid || ($bTypeRecurring && $bTrial))
  932. $this->registerPayment($aPending);
  933. //--- Get updated pending order
  934. $aPending = $this->_oDb->getOrderPending(['type' => 'id', 'id' => $aPending['id']]);
  935. $this->alert('finalize_checkout', 0, bx_get_logged_profile_id(), array(
  936. 'pending' => $aPending,
  937. 'transactions' => $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id'])),
  938. 'provider' => $oProvider,
  939. 'message' => &$aResult['message'],
  940. 'result' => &$aResult,
  941. ));
  942. if($oProvider->needRedirect()) {
  943. header('Location: ' . $oProvider->getReturnUrl());
  944. exit;
  945. }
  946. if(!empty($aResult['redirect'])) {
  947. header('Location: ' . base64_decode(urldecode($aResult['redirect'])));
  948. exit;
  949. }
  950. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  951. }
  952. public function actionFinalizedCheckout($sProvider, $mixedVendorId = "")
  953. {
  954. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  955. if($oProvider === false || !$oProvider->isActive())
  956. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  957. $aResult = $oProvider->finalizedCheckout();
  958. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  959. }
  960. public function actionNotify($sProvider, $mixedVendorId = "")
  961. {
  962. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  963. if($oProvider === false || !$oProvider->isActive())
  964. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  965. $oProvider->notify();
  966. }
  967. /**
  968. * The method is needed to pass direct action calls to necessary Payment Provider.
  969. */
  970. public function actionCall($sProvider, $sAction, $mixedVendorId = BX_PAYMENT_EMPTY_ID)
  971. {
  972. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  973. if($oProvider === false)
  974. BxDolRequest::methodNotFound($sAction, $this->getName());
  975. $sMethod = 'action' . bx_gen_method_name($sAction);
  976. if(!method_exists($oProvider, $sMethod))
  977. BxDolRequest::methodNotFound($sAction, $this->getName());
  978. return call_user_func_array(array($oProvider, $sMethod), array_slice(func_get_args(), 2));
  979. }
  980. public function onProfileJoin($iProfileId)
  981. {
  982. $this->getObjectJoin()->onProfileJoin($iProfileId);
  983. }
  984. public function onProfileDelete($iProfileId)
  985. {
  986. //--- Cancel subscriptions
  987. $aSubscriptions = $this->_oDb->getSubscription(['type' => 'mixed_ext', 'conditions' => ['client_id' => $iProfileId]]);
  988. if(!empty($aSubscriptions) && is_array($aSubscriptions))
  989. foreach($aSubscriptions as $aSubscription)
  990. $this->getObjectSubscriptions()->cancel($aSubscription['pending_id']);
  991. //--- Clean DB
  992. $this->_oDb->onProfileDelete($iProfileId);
  993. }
  994. public function isAllowedPurchase($aItem, $bPerform = false)
  995. {
  996. $iUserId = (int)$this->getProfileId();
  997. $aItemInfo = $this->callGetCartItem((int)$aItem['module_id'], array($aItem['item_id'], isset($aItem['custom']) ? $aItem['custom'] : array()));
  998. if(empty($aItemInfo))
  999. return false;
  1000. if(isAdmin())
  1001. return true;
  1002. $aCheckResult = checkActionModule($iUserId, 'purchase', $this->getName(), $bPerform);
  1003. if($aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  1004. return true;
  1005. return $aCheckResult[CHECK_ACTION_MESSAGE];
  1006. }
  1007. public function isAllowedSell($aItem, $bPerform = false)
  1008. {
  1009. $iUserId = (int)$this->getProfileId();
  1010. if(!$iUserId)
  1011. return false;
  1012. $aItemInfo = $this->callGetCartItem((int)$aItem['module_id'], array($aItem['item_id']));
  1013. if(empty($aItemInfo))
  1014. return false;
  1015. if(isAdmin())
  1016. return true;
  1017. $aCheckResult = checkActionModule($iUserId, 'sell', $this->getName(), $bPerform);
  1018. if((int)$aItemInfo['author_id'] == $iUserId && $aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  1019. return true;
  1020. return $aCheckResult[CHECK_ACTION_MESSAGE];
  1021. }
  1022. public function isAllowedManage($aPending, $bPerform = false)
  1023. {
  1024. $iUserId = (int)$this->getProfileId();
  1025. if($iUserId == $aPending['client_id'] || $iUserId == $aPending['seller_id'] || isAdmin())
  1026. return true;
  1027. $aCheckResult = checkActionModule($iUserId, 'manage any purchase', $this->getName(), $bPerform);
  1028. if($aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  1029. return true;
  1030. return $aCheckResult[CHECK_ACTION_MESSAGE];
  1031. }
  1032. public function isAllowedManageInvoices($bPerform = false)
  1033. {
  1034. if(BxDolAcl::getInstance()->isMemberLevelInSet(array(MEMBERSHIP_ID_MODERATOR, MEMBERSHIP_ID_ADMINISTRATOR)) || isAdmin())
  1035. return true;
  1036. return _t('_sys_txt_access_denied');
  1037. }
  1038. public function checkData($iClientId, $iSellerId, $iModuleId, $iItemId, $iItemCount, $aCustom = array())
  1039. {
  1040. $CNF = &$this->_oConfig->CNF;
  1041. if($iSellerId == BX_PAYMENT_EMPTY_ID || empty($iModuleId) || empty($iItemId) || empty($iItemCount))
  1042. return array('code' => 1, 'message' => _t($CNF['T']['ERR_WRONG_DATA']));
  1043. $iClientId = $this->getProfileId();
  1044. if(empty($iClientId)) {
  1045. $sLoginUrl = BxDolPermalinks::getInstance()->permalink('page.php?i=login');
  1046. return array('code' => 2, 'eval' => 'window.open("' . $sLoginUrl . '", "_self");');
  1047. }
  1048. $mixedResult = $this->isAllowedPurchase(array('module_id' => $iModuleId, 'item_id' => $iItemId, 'custom' => $aCustom));
  1049. if($mixedResult !== true) {
  1050. if(is_string($mixedResult) && !empty($mixedResult))
  1051. return array('code' => 2, 'message' => $mixedResult);
  1052. else
  1053. return array('code' => 1, 'message' => _t($CNF['T']['ERR_WRONG_DATA']));
  1054. }
  1055. if($iClientId == $iSellerId)
  1056. return array('code' => 3, 'message' => _t($CNF['T']['ERR_SELF_PURCHASE']));
  1057. $aSeller = $this->getVendorInfo($iSellerId);
  1058. if(!$aSeller['active'])
  1059. return array('code' => 4, 'message' => _t($CNF['T']['ERR_INACTIVE_VENDOR']));
  1060. return true;
  1061. }
  1062. public function authorizePayment($mixedPending)
  1063. {
  1064. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(['type' => 'id', 'id' => (int)$mixedPending]);
  1065. if(empty($aPending) || !is_array($aPending))
  1066. return false;
  1067. $sType = $aPending['type'];
  1068. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  1069. if((int)$aPending['authorized'] == 1)
  1070. return true;
  1071. $iClientId = (int)$aPending['client_id'];
  1072. $aCart = array();
  1073. if($bTypeSingle)
  1074. $aCart = $this->_oDb->getCartContent($iClientId);
  1075. $bResult = false;
  1076. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  1077. foreach($aItems as $aItem) {
  1078. $sItem = $this->_oConfig->descriptorA2S([$aItem['vendor_id'], $aItem['module_id'], $aItem['item_id']]);
  1079. $sMethod = $bTypeSingle ? 'callAuthorizeCartItem' : 'callAuthorizeSubscriptionItem';
  1080. $aItemInfo = $this->$sMethod((int)$aItem['module_id'], [$aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order']]);
  1081. if(empty($aItemInfo) || !is_array($aItemInfo))
  1082. continue;
  1083. if($bTypeSingle)
  1084. $aCart['items'] = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aItem) . ":?'", "", $aCart['items']), ":");
  1085. $bResult = true;
  1086. }
  1087. if($bResult) {
  1088. $this->_oDb->updateOrderPending($aPending['id'], ['authorized' => 1]);
  1089. $this->onPaymentAuthorize($aPending);
  1090. }
  1091. return $bResult;
  1092. }
  1093. public function registerPayment($mixedPending)
  1094. {
  1095. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  1096. if(empty($aPending) || !is_array($aPending))
  1097. return false;
  1098. $sType = $aPending['type'];
  1099. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  1100. if($bTypeSingle && (int)$aPending['processed'] == 1)
  1101. return true;
  1102. $iClientId = (int)$aPending['client_id'];
  1103. $sLicense = $this->_oConfig->getLicense();
  1104. $aCustoms = !empty($aPending['customs']) ? unserialize($aPending['customs']) : array();
  1105. $aCart = array();
  1106. if($bTypeSingle) {
  1107. $aCart = $this->_oDb->getCartContent($iClientId);
  1108. $aCart['customs'] = !empty($aCart['customs']) ? unserialize($aCart['customs']) : array();
  1109. }
  1110. $bResult = false;
  1111. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  1112. foreach($aItems as $aItem) {
  1113. $sItem = $this->_oConfig->descriptorA2S(array($aItem['vendor_id'], $aItem['module_id'], $aItem['item_id']));
  1114. $aItemCustom = $this->_oConfig->getCustom($sItem, $aCustoms);
  1115. $sMethod = $bTypeSingle ? 'callRegisterCartItem' : 'callRegisterSubscriptionItem';
  1116. $aItemInfo = $this->$sMethod((int)$aItem['module_id'], array($aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order'], $sLicense, $aItemCustom));
  1117. if(empty($aItemInfo) || !is_array($aItemInfo))
  1118. continue;
  1119. $this->_oDb->insertOrderProcessed(array(
  1120. 'pending_id' => $aPending['id'],
  1121. 'client_id' => $aPending['client_id'],
  1122. 'seller_id' => $aPending['seller_id'],
  1123. 'author_id' => $aItem['vendor_id'],
  1124. 'module_id' => (int)$aItem['module_id'],
  1125. 'item_id' => (int)$aItem['item_id'],
  1126. 'item_count' => (int)$aItem['item_count'],
  1127. 'amount' => (int)$aItem['item_count'] * $this->_oConfig->getPrice($sType, $aItemInfo),
  1128. 'license' => $sLicense,
  1129. ));
  1130. if($bTypeSingle) {
  1131. $this->_oConfig->pullCustom($sItem, $aCart['customs']);
  1132. $aCart['items'] = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aItem) . ":?'", "", $aCart['items']), ":");
  1133. }
  1134. $bResult = true;
  1135. }
  1136. if($bTypeSingle)
  1137. $this->_oDb->setCartItems($iClientId, $aCart['items'], $aCart['customs']);
  1138. if($bResult) {
  1139. $this->_oDb->updateOrderPending($aPending['id'], array('processed' => 1));
  1140. $this->onPaymentRegister($aPending);
  1141. }
  1142. return $bResult;
  1143. }
  1144. public function refundPayment($mixedPending)
  1145. {
  1146. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  1147. if(empty($aPending) || !is_array($aPending))
  1148. return false;
  1149. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  1150. $iCanceled = 0;
  1151. $aOrders = $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id']));
  1152. foreach($aOrders as $aOrder) {
  1153. $sMethod = $bTypeSingle ? 'callUnregisterCartItem' : 'callUnregisterSubscriptionItem';
  1154. $bResult = $this->$sMethod((int)$aOrder['module_id'], array($aOrder['client_id'], $aOrder['seller_id'], $aOrder['item_id'], $aOrder['item_count'], $aPending['order'], $aOrder['license']));
  1155. if(!$bResult)
  1156. continue;
  1157. if($this->_oDb->deleteOrderProcessed($aOrder['id']))
  1158. $iCanceled++;
  1159. }
  1160. if($iCanceled != count($aOrders))
  1161. return false;
  1162. $bResult = $this->_oDb->deleteOrderPending($aPending['id']);
  1163. if($bResult)
  1164. $this->onPaymentRefund($aPending);
  1165. return $bResult;
  1166. }
  1167. /**
  1168. * @deprecated since version 12.0.0
  1169. *
  1170. * @use BxPaymentSubscriptions::register instead.
  1171. */
  1172. public function registerSubscription($aPending, $aParams = array())
  1173. {
  1174. return $this->getObjectSubscriptions()->register($aPending, $aParams);
  1175. }
  1176. /**
  1177. * @deprecated since version 12.0.0
  1178. *
  1179. * @use BxPaymentSubscriptions::cancelLocal instead.
  1180. */
  1181. public function cancelSubscription($mixedPending)
  1182. {
  1183. return $this->getObjectSubscriptions()->cancelLocal($mixedPending);
  1184. }
  1185. public function processCommissions()
  1186. {
  1187. if(!defined('BX_DOL_CRON_EXECUTE'))
  1188. return;
  1189. $CNF = &$this->_oConfig->CNF;
  1190. if((int)date('j') == $this->_oConfig->getInvoiceIssueDay())
  1191. $this->_invoicesIssue();
  1192. $this->_invoicesCheck();
  1193. }
  1194. protected function _invoicesIssue()
  1195. {
  1196. $CNF = &$this->_oConfig->CNF;
  1197. $sInvoiceNameMask = 'INV-%d-%d-%d';
  1198. $iMonth = date('m');
  1199. $iYear = date('Y');
  1200. $iPeriodStart = mktime(0, 0, 0, $iMonth-1, 1, $iYear);
  1201. $iPeriodEnd = mktime(23, 59, 59, $iMonth, 0, $iYear);
  1202. $iDateIssue = time();
  1203. $iDateDue = $iDateIssue + 86400 * $this->_oConfig->getInvoiceLifetime();
  1204. $aCommissionsInfo = array();
  1205. $aAclLevels = BxDolAcl::getInstance()->getMemberships(false, true, false, true);
  1206. foreach($aAclLevels as $iAclLevelId => $sAclLevelTitle)
  1207. $aCommissionsInfo[$iAclLevelId] = $this->_oDb->getCommissions(array('type' => 'acl_id', 'acl_id' => $iAclLevelId));
  1208. $iMainSellerId = $this->_oConfig->getSiteAdmin();
  1209. $aVendors = $this->_oDb->getOrderProcessed(array('type' => 'income', 'period_start' => $iPeriodStart, 'period_end' => $iPeriodEnd));
  1210. foreach($aVendors as $aVendor) {
  1211. $iVendorId = (int)$aVendor['id'];
  1212. if($iVendorId == $iMainSellerId)
  1213. continue;
  1214. $aInvoice = $this->_oDb->getInvoices(array('type' => 'committent_id', 'committent_id' => $iVendorId, 'period_start' => $iPeriodStart, 'period_end' => $iPeriodEnd));
  1215. if(!empty($aInvoice) && is_array($aInvoice))
  1216. continue;
  1217. $aVendorAcl = BxDolAcl::getInstance()->getMemberMembershipInfo($iVendorId);
  1218. $aCommissions = $aCommissionsInfo[$aVendorAcl['id']];
  1219. $fCommission = 0;
  1220. foreach($aCommissions as $aCommission) {
  1221. if((float)$aCommission['percentage'] > 0)
  1222. $fCommission += (float)$aVendor['amount'] * (float)$aCommission['percentage'] / 100;
  1223. if((float)$aCommission['installment'] > 0)
  1224. $fCommission += (float)$aCommission['installment'];
  1225. }
  1226. $this->alert('calculate_commission', 0, 0, array(
  1227. 'vendor' => $aVendor,
  1228. 'commissions' => $aCommissions,
  1229. 'override_result' => &$fCommission,
  1230. ));
  1231. $this->_oDb->insertInvoice(array(
  1232. 'name' => sprintf($sInvoiceNameMask, $iMainSellerId, $iVendorId, $this->_oDb->getInvoices(array(
  1233. 'type' => 'index',
  1234. 'commissionaire_id' => $iMainSellerId,
  1235. 'committent_id' => $iVendorId
  1236. ))),
  1237. 'commissionaire_id' => $iMainSellerId,
  1238. 'committent_id' => $iVendorId,
  1239. 'amount' => $fCommission,
  1240. 'period_start' => $iPeriodStart,
  1241. 'period_end' => $iPeriodEnd,
  1242. 'date_issue' => $iDateIssue,
  1243. 'date_due' => $iDateDue,
  1244. 'status' => BX_PAYMENT_INV_STATUS_UNPAID
  1245. ));
  1246. }
  1247. }
  1248. protected function _invoicesCheck()
  1249. {
  1250. $CNF = &$this->_oConfig->CNF;
  1251. $sPrefix = $this->_oConfig->getPrefix('general');
  1252. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  1253. //--- Process expiring invoices.
  1254. $aInvoices = $this->_oDb->getInvoices(array('type' => 'expiring'));
  1255. if(!empty($aInvoices) && is_array($aInvoices))
  1256. foreach($aInvoices as $aInvoice) {
  1257. if((int)$aInvoice['ntf_exp'] > 0)
  1258. continue;
  1259. $oCommittent = BxDolProfile::getInstance($aInvoice['committent_id']);
  1260. if(!$oCommittent)
  1261. continue;
  1262. $bResult = sendMailTemplate($sPrefix . 'expiring_notification_committent', 0, (int)$aInvoice['committent_id'], array(
  1263. 'invoice' => $aInvoice['name'],
  1264. 'days' => $this->_oConfig->getInvoiceExpirationNotify(),
  1265. 'period_start' => $this->_oConfig->formatDate($aInvoice['period_start']),
  1266. 'period_end' => $this->_oConfig->formatDate($aInvoice['period_end']),
  1267. 'date_issue' => $this->_oConfig->formatDateTime($aInvoice['date_issue']),
  1268. 'date_due' => $this->_oConfig->formatDateTime($aInvoice['date_due']),
  1269. ), BX_EMAIL_NOTIFY, true);
  1270. if($bResult)
  1271. $this->_oDb->updateInvoice($aInvoice['id'], array('ntf_exp' => 1));
  1272. }
  1273. //--- Process overdue invoices.
  1274. $aInvoices = $this->_oDb->getInvoices(array('type' => 'overdue'));
  1275. if(!empty($aInvoices) && is_array($aInvoices))
  1276. foreach($aInvoices as $aInvoice) {
  1277. if((int)$aInvoice['ntf_due'] > 0 && $aInvoice['status'] == BX_PAYMENT_INV_STATUS_OVERDUE)
  1278. continue;
  1279. $oCommittent = BxDolProfile::getInstance($aInvoice['committent_id']);
  1280. if(!$oCommittent)
  1281. continue;
  1282. $bResult = sendMailTemplate($sPrefix . 'overdue_notification_committent', 0, (int)$aInvoice['committent_id'], array(
  1283. 'invoice' => $aInvoice['name'],
  1284. 'period_start' => $this->_oConfig->formatDate($aInvoice['period_start']),
  1285. 'period_end' => $this->_oConfig->formatDate($aInvoice['period_end']),
  1286. 'date_issue' => $this->_oConfig->formatDateTime($aInvoice['date_issue']),
  1287. 'date_due' => $this->_oConfig->formatDateTime($aInvoice['date_due']),
  1288. ), BX_EMAIL_NOTIFY, true);
  1289. $this->_oDb->updateInvoice($aInvoice['id'], array(
  1290. 'status' => BX_PAYMENT_INV_STATUS_OVERDUE,
  1291. 'ntf_due' => $bResult ? 1 : 0
  1292. ));
  1293. }
  1294. }
  1295. public function processTimeTracker()
  1296. {
  1297. if(!defined('BX_DOL_CRON_EXECUTE'))
  1298. return;
  1299. $aSubscriptions = $this->_oDb->getSubscription(array(
  1300. 'type' => 'time_tracker',
  1301. 'status_active' => BX_PAYMENT_SBS_STATUS_ACTIVE,
  1302. 'status_trial' => BX_PAYMENT_SBS_STATUS_TRIAL,
  1303. 'status_unpaid' => BX_PAYMENT_SBS_STATUS_UNPAID,
  1304. 'pay_attempts_max' => $this->_oConfig->getPayAttemptsMax(),
  1305. 'pay_attempts_interval' => $this->_oConfig->getPayAttemptsInterval()
  1306. ));
  1307. if(empty($aSubscriptions) || !is_array($aSubscriptions))
  1308. return;
  1309. foreach($aSubscriptions as $aSubscription) {
  1310. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$aSubscription['pending_id']));
  1311. if(empty($aPending) || !is_array($aPending) || $aPending['type'] != BX_PAYMENT_TYPE_RECURRING) {
  1312. $this->log($aSubscription, 'Time Tracker', 'Cannot process subscription.');
  1313. continue;
  1314. }
  1315. $oProvider = $this->getObjectProvider($aPending['provider'], $aPending['seller_id']);
  1316. if($oProvider === false || !$oProvider->isActive() || !method_exists($oProvider, 'makePayment')) {
  1317. $this->log($aSubscription, 'Time Tracker', 'Payment provider unavailable or incorrect.');
  1318. continue;
  1319. }
  1320. if(($mixedResult = $oProvider->makePayment($aPending)) !== true) {
  1321. $this->log($aSubscription, 'Time Tracker', 'Payment cannot be processed.' . (!empty($mixedResult['message']) ? ' ' . $mixedResult['message'] : ''));
  1322. continue;
  1323. }
  1324. if(!$this->getObjectSubscriptions()->prolong($aPending)) {
  1325. $this->log($aSubscription, 'Time Tracker', 'Cannot prolong subscription.');
  1326. continue;
  1327. }
  1328. if(!$this->registerPayment($aPending)) {
  1329. $this->log($aSubscription, 'Time Tracker', 'Cannot register payment.');
  1330. continue;
  1331. }
  1332. }
  1333. }
  1334. public function onPaymentRegisterBefore($aPending, $aResult = [])
  1335. {
  1336. $this->alert('before_register_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  1337. }
  1338. public function onPaymentAuthorize($aPending, $aResult = [])
  1339. {
  1340. $this->alert('authorize_payment', 0, $aPending['client_id'], ['pending' => $aPending]);
  1341. }
  1342. public function onPaymentRegister($aPending, $aResult = [])
  1343. {
  1344. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  1345. if($bTypeSingle) {
  1346. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  1347. foreach($aItems as $aItem)
  1348. $this->isAllowedPurchase(['module_id' => $aItem['module_id'], 'item_id' => $aItem['item_id']], true);
  1349. }
  1350. $this->alert('register_payment', 0, $aPending['client_id'], ['pending' => $aPending]);
  1351. }
  1352. public function onPaymentRefund($aPending, $aResult = [])
  1353. {
  1354. $this->alert('refund_payment', 0, $aPending['client_id'], ['pending' => $aPending]);
  1355. }
  1356. public function onSubscriptionCreate($aPending, $aSubscription, $aResult = [])
  1357. {
  1358. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  1359. $this->isAllowedPurchase(['module_id' => $aItems[0]['module_id'], 'item_id' => $aItems[0]['item_id']], true);
  1360. $this->alert('create_subscription', 0, $aPending['client_id'], [
  1361. 'pending' => $aPending,
  1362. 'subscription' => $aSubscription
  1363. ]);
  1364. }
  1365. public function onSubscriptionProlong($aPending, $aSubscription, $aResult = [])
  1366. {
  1367. $this->alert('prolong_subscription', 0, $aPending['client_id'], [
  1368. 'pending' => $aPending,
  1369. 'subscription' => $aSubscription
  1370. ]);
  1371. }
  1372. public function onSubscriptionOverdue($aPending, $aSubscription, $aResult = [])
  1373. {
  1374. $this->alert('overdue_subscription', 0, $aPending['client_id'], [
  1375. 'pending' => $aPending,
  1376. 'subscription' => $aSubscription
  1377. ]);
  1378. }
  1379. public function onSubscriptionCancel($aPending, $aSubscription, $aResult = [])
  1380. {
  1381. $this->alert('cancel_subscription', 0, $aPending['client_id'], [
  1382. 'pending' => $aPending,
  1383. 'subscription' => $aSubscription
  1384. ]);
  1385. }
  1386. public function setSiteSubmenu($sSubmenu, $sSelModule, $sSelName)
  1387. {
  1388. $oSiteSubmenu = BxDolMenu::getObjectInstance('sys_site_submenu');
  1389. if(!$oSiteSubmenu)
  1390. return;
  1391. $sModuleSubmenu = $this->_oConfig->getObject($sSubmenu);
  1392. $oModuleSubmenu = BxDolMenu::getObjectInstance($sModuleSubmenu);
  1393. if(!$oModuleSubmenu)
  1394. return;
  1395. $oSiteSubmenu->setObjectSubmenu($sModuleSubmenu);
  1396. $oModuleSubmenu->setSelected($sSelModule, $sSelName);
  1397. }
  1398. public function getProviderButtonJs($aCartItem, $aProvider, $sRedirect = '', $aCustom = array())
  1399. {
  1400. $aButtonJs = array();
  1401. $iClientId = $this->getProfileId();
  1402. $sItemAddons = '';
  1403. if(count($aCartItem) == 5)
  1404. $sItemAddons = array_pop($aCartItem);
  1405. list($iSellerId, $iModuleId, $iItemId, $iItemCount) = $aCartItem;
  1406. $oProvider = $this->getObjectProvider($aProvider['name'], $iSellerId);
  1407. if($oProvider !== false && method_exists($oProvider, 'getButtonRecurring')) {
  1408. $aParams = array(
  1409. 'sObjNameCart' => $this->_oConfig->getJsObject('cart'),
  1410. 'iSellerId' => $iSellerId,
  1411. 'iModuleId' => $iModuleId,
  1412. 'iItemId' => $iItemId,
  1413. 'iItemCount' => $iItemCount,
  1414. 'sItemAddons' => $sItemAddons,
  1415. 'sRedirect' => $sRedirect,
  1416. 'sCustom' => base64_encode(serialize($aCustom))
  1417. );
  1418. $aCartInfo = $this->getObjectCart()->getInfo(BX_PAYMENT_TYPE_RECURRING, $iClientId, $iSellerId, $this->_oConfig->descriptorA2S($aCartItem));
  1419. if(!empty($aCartInfo['items_price']) && !empty($aCartInfo['items']) && is_array($aCartInfo['items'])) {
  1420. $aItem = array_shift($aCartInfo['items']);
  1421. $aParams = array_merge($aParams, array(
  1422. 'iAmount' => (int)round(100 * (float)$aCartInfo['items_price']),
  1423. 'sItemName' => $aItem['name'],
  1424. 'sItemTitle' => $aItem['title']
  1425. ));
  1426. }
  1427. $aButtonJs = $oProvider->getButtonRecurringJs($iClientId, $iSellerId, $aParams);
  1428. }
  1429. if(empty($aButtonJs) || !is_array($aButtonJs))
  1430. $aButtonJs = $this->getObjectSubscriptions()->serviceGetSubscribeJs($iSellerId, $aProvider['name'], $iModuleId, $iItemId, $iItemCount, $sRedirect, $aCustom);
  1431. return $aButtonJs;
  1432. }
  1433. /**
  1434. * Integration with itslef which is needed to pay an invoice.
  1435. */
  1436. /**
  1437. * @page service Service Calls
  1438. * @section bx_payment Payment
  1439. * @subsection bx_payment-payments Payments
  1440. * @subsubsection bx_payment-get_payment_data get_payment_data
  1441. *
  1442. * @code bx_srv('bx_payment', 'get_payment_data', [...]); @endcode
  1443. *
  1444. * Get an array with module's description. Is needed for payments processing module.
  1445. *
  1446. * @return an array with module's description.
  1447. *
  1448. * @see BxPaymentModule::serviceGetPaymentData
  1449. */
  1450. /**
  1451. * @ref bx_payment-get_payment_data "get_payment_data"
  1452. */
  1453. public function serviceGetPaymentData()
  1454. {
  1455. return $this->_aModule;
  1456. }
  1457. /**
  1458. * @page service Service Calls
  1459. * @section bx_payment Payment
  1460. * @subsection bx_payment-payments Payments
  1461. * @subsubsection bx_payment-get_cart_item get_cart_item
  1462. *
  1463. * @code bx_srv('bx_payment', 'get_cart_item', [...]); @endcode
  1464. *
  1465. * Get an array with prodict's description. Is used in Shopping Cart in payments processing module.
  1466. *
  1467. * @param $mixedItemId product's ID or Unique Name.
  1468. * @return an array with prodict's description. Empty array is returned if something is wrong.
  1469. *
  1470. * @see BxPaymentModule::serviceGetCartItem
  1471. */
  1472. /**
  1473. * @ref bx_payment-get_cart_item "get_cart_item"
  1474. */
  1475. public function serviceGetCartItem($mixedItemId)
  1476. {
  1477. $CNF = &$this->_oConfig->CNF;
  1478. if(!$mixedItemId)
  1479. return array();
  1480. if(is_numeric($mixedItemId))
  1481. $aItem = $this->_oDb->getInvoices(array('type' => 'id', 'id' => (int)$mixedItemId));
  1482. else
  1483. $aItem = $this->_oDb->getInvoices(array('type' => 'name', 'name' => $mixedItemId));
  1484. if(empty($aItem) || !is_array($aItem))
  1485. return array();
  1486. $oCommissionaire = BxDolProfile::getInstanceMagic($aItem['commissionaire_id']);
  1487. return array (
  1488. 'id' => $aItem['id'],
  1489. 'author_id' => $aItem['commissionaire_id'],
  1490. 'name' => $aItem['name'],
  1491. 'title' => _t('_bx_payment_txt_invoice_title', $aItem['name'], $oCommissionaire->getDisplayName()),
  1492. 'description' => _t('_bx_payment_txt_invoice_description', bx_process_output($aItem['period_start'], BX_DATA_DATE_TS_UTC), bx_process_output($aItem['period_end'], BX_DATA_DATE_TS_UTC)),
  1493. 'url' => '',
  1494. 'price_single' => $aItem['amount'],
  1495. 'price_recurring' => '',
  1496. 'period_recurring' => 0,
  1497. 'period_unit_recurring' => '',
  1498. 'trial_recurring' => ''
  1499. );
  1500. }
  1501. /**
  1502. * @page service Service Calls
  1503. * @section bx_payment Payment
  1504. * @subsection bx_payment-payments Payments
  1505. * @subsubsection bx_payment-get_cart_items get_cart_items
  1506. *
  1507. * @code bx_srv('bx_payment', 'get_cart_items', [...]); @endcode
  1508. *
  1509. * Get an array with prodicts' descriptions by seller. Is used in Manual Order Processing in payments processing module.
  1510. *
  1511. * @param $iCommissionaireId commissionaire ID.
  1512. * @return an array with prodicts' descriptions. Empty array is returned if something is wrong or seller doesn't have any products.
  1513. *
  1514. * @see BxPaymentModule::serviceGetCartItems
  1515. */
  1516. /**
  1517. * @ref bx_payment-get_cart_items "get_cart_items"
  1518. */
  1519. public function serviceGetCartItems($iCommissionaireId)
  1520. {
  1521. $CNF = &$this->_oConfig->CNF;
  1522. $iCommissionaireId = (int)$iCommissionaireId;
  1523. if(empty($iCommissionaireId))
  1524. return array();
  1525. $sCommissionaireName = BxDolProfile::getInstanceMagic($iCommissionaireId)->getDisplayName();
  1526. $aItems = $this->_oDb->getInvoices(array('type' => 'commissionaire_id', 'commissionaire_id' => $iCommissionaireId));
  1527. $aResult = array();
  1528. foreach($aItems as $aItem)
  1529. $aResult[] = array(
  1530. 'id' => $aItem['id'],
  1531. 'author_id' => $aItem['commissionaire_id'],
  1532. 'name' => $aItem['name'],
  1533. 'title' => _t('_bx_payment_txt_invoice_title', $aItem['name'], $sCommissionaireName),
  1534. 'description' => _t('_bx_payment_txt_invoice_description', bx_process_output($aItem['period_start'], BX_DATA_DATE_TS_UTC), bx_process_output($aItem['period_end'], BX_DATA_DATE_TS_UTC)),
  1535. 'url' => '',
  1536. 'price_single' => $aItem['amount'],
  1537. 'price_recurring' => '',
  1538. 'period_recurring' => 0,
  1539. 'period_unit_recurring' => '',
  1540. 'trial_recurring' => ''
  1541. );
  1542. return $aResult;
  1543. }
  1544. /**
  1545. * @page service Service Calls
  1546. * @section bx_payment Payment
  1547. * @subsection bx_payment-payments Payments
  1548. * @subsubsection bx_payment-register_cart_item register_cart_item
  1549. *
  1550. * @code bx_srv('bx_payment', 'register_cart_item', [...]); @endcode
  1551. *
  1552. * Register a processed single time payment inside the Payment module. Is called with payment processing module after the payment was registered there.
  1553. *
  1554. * @param $iClientId client ID.
  1555. * @param $iSellerId seller ID
  1556. * @param $iItemId item ID.
  1557. * @param $iItemCount the number of purchased items.
  1558. * @param $sOrder order number received from payment provider (PayPal, Stripe, etc)
  1559. * @param $sLicense license number genereted with payment processing module for internal usage
  1560. * @return an array with purchased prodict's description. Empty array is returned if something is wrong.
  1561. *
  1562. * @see BxPaymentModule::serviceRegisterCartItem
  1563. */
  1564. /**
  1565. * @ref bx_payment-register_cart_item "register_cart_item"
  1566. */
  1567. public function serviceRegisterCartItem($iClientId, $iSellerId, $iItemId, $iItemCount, $sOrder, $sLicense)
  1568. {
  1569. $CNF = &$this->_oConfig->CNF;
  1570. $aItem = $this->serviceGetCartItem($iItemId);
  1571. if(empty($aItem) || !is_array($aItem))
  1572. return array();
  1573. if(!$this->_oDb->updateInvoice($iItemId, array('status' => BX_PAYMENT_INV_STATUS_PAID)))
  1574. return array();
  1575. $this->alert('invoice_marked_as_paid', 0, false, array(
  1576. 'product_id' => $iItemId,
  1577. 'profile_id' => $iClientId,
  1578. 'order' => $sOrder,
  1579. 'license' => $sLicense,
  1580. 'type' => BX_PAYMENT_TYPE_SINGLE,
  1581. 'count' => $iItemCount,
  1582. 'duration' => '',
  1583. 'trial' => ''
  1584. ));
  1585. return $aItem;
  1586. }
  1587. /**
  1588. * @page service Service Calls
  1589. * @section bx_payment Payment
  1590. * @subsection bx_payment-payments Payments
  1591. * @subsubsection bx_payment-unregister_cart_item unregister_cart_item
  1592. *
  1593. * @code bx_srv('bx_payment', 'unregister_cart_item', [...]); @endcode
  1594. *
  1595. * Unregister an earlier processed single time payment inside the Payment module. Is called with payment processing module after the payment was unregistered there.
  1596. *
  1597. * @param $iClientId client ID.
  1598. * @param $iSellerId seller ID
  1599. * @param $iItemId item ID.
  1600. * @param $iItemCount the number of purchased items.
  1601. * @param $sOrder order number received from payment provider (PayPal, Stripe, etc)
  1602. * @param $sLicense license number genereted with payment processing module for internal usage
  1603. * @return boolean value determining where the payment was unregistered or not.
  1604. *
  1605. * @see BxPaymentModule::serviceUnregisterCartItem
  1606. */
  1607. /**
  1608. * @ref bx_payment-unregister_cart_item "unregister_cart_item"
  1609. */
  1610. public function serviceUnregisterCartItem($iClientId, $iSellerId, $iItemId, $iItemCount, $sOrder, $sLicense)
  1611. {
  1612. if(!$this->_oDb->updateInvoice($iItemId, array('status' => BX_PAYMENT_INV_STATUS_UNPAID)))
  1613. return false;
  1614. $this->alert('invoice_marked_as_unpaid', 0, false, array(
  1615. 'product_id' => $iItemId,
  1616. 'profile_id' => $iClientId,
  1617. 'order' => $sOrder,
  1618. 'license' => $sLicense,
  1619. 'type' => BX_PAYMENT_TYPE_SINGLE,
  1620. 'count' => $iItemCount
  1621. ));
  1622. return true;
  1623. }
  1624. }
  1625. /** @} */