BxPaymentModule.php 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020
  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. public function serviceGetOptionsPersonalCurrencyCode()
  343. {
  344. return array_merge([[
  345. 'key' => '',
  346. 'value' => _t('_bx_payment_gc_currency_code_default')
  347. ]], $this->serviceGetOptionsDefaultCurrencyCode());
  348. }
  349. /**
  350. * @page service Service Calls
  351. * @section bx_payment Payment
  352. * @subsection bx_payment-other Other
  353. * @subsubsection bx_payment-get_options_site_admin get_options_site_admin
  354. *
  355. * @code bx_srv('bx_payment', 'get_options_site_admin', [...]); @endcode
  356. *
  357. * 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.
  358. *
  359. * @return an array with profiles represented as key => value pairs.
  360. *
  361. * @see BxPaymentModule::serviceGetOptionsSiteAdmin
  362. */
  363. /**
  364. * @ref bx_payment-get_options_site_admin "get_options_site_admin"
  365. */
  366. public function serviceGetOptionsSiteAdmin()
  367. {
  368. $aResult = array(
  369. array('key' => '', 'value' => _t('_Select_one'))
  370. );
  371. $aIds = $this->_oDb->getAdminsIds();
  372. foreach($aIds as $iId) {
  373. $aUser = $this->getProfileInfo($iId);
  374. $aResult[] = array(
  375. 'key' => $iId,
  376. 'value' => $aUser['name']
  377. );
  378. }
  379. return $aResult;
  380. }
  381. public function serviceGetMenuAddonManageTools()
  382. {
  383. return array(
  384. 'counter1_value' => (int)$this->_oDb->getInvoices(array('type' => 'status', 'status' => BX_PAYMENT_INV_STATUS_PAID, 'count' => true)),
  385. 'counter1_caption' => _t('_bx_payment_menu_item_title_admt_addon_counter1_caption'),
  386. 'counter2_value' => (int)$this->_oDb->getInvoices(array('type' => 'status', 'status' => BX_PAYMENT_INV_STATUS_OVERDUE, 'count' => true)),
  387. 'counter2_caption' => _t('_bx_payment_menu_item_title_admt_addon_counter2_caption'),
  388. 'counter3_value' => (int)$this->_oDb->getInvoices(array('type' => 'all_count'))
  389. );
  390. }
  391. public function serviceGetBlockCheckoutOffline()
  392. {
  393. $CNF = &$this->_oConfig->CNF;
  394. $oBuyer = BxDolProfile::getInstance();
  395. if(!$oBuyer)
  396. return MsgBox(_t('_bx_payment_err_required_login'));
  397. $iSeller = (int)bx_get('seller');
  398. $oSeller = BxDolProfile::getInstance($iSeller);
  399. if(!$oSeller)
  400. return MsgBox(_t('_bx_payment_err_unknown_vendor'));
  401. $aData = array(
  402. 'seller' => $iSeller,
  403. 'currency' => array(
  404. 'code' => bx_process_input(bx_get('currency_code')),
  405. 'sign' => bx_process_input(bx_get('currency_sign')),
  406. ),
  407. 'amount' => (float)bx_get('amount'),
  408. 'return_url' => bx_process_input(bx_get('return_url')),
  409. );
  410. if(empty($aData['currency']['code']))
  411. $aData['currency']['code'] = $this->_oConfig->getDefaultCurrencyCode();
  412. if(empty($aData['currency']['sign']))
  413. $aData['currency']['sign'] = $this->_oConfig->getDefaultCurrencySign();
  414. $sItems = '';
  415. $iItemsCount = (int)bx_get('items_count');
  416. for($i = 0; $i < $iItemsCount; $i++) {
  417. $aItem = array(
  418. 'title' => bx_process_input(bx_get('item_title_' . $i)),
  419. 'quantity' => (int)bx_get('item_quantity_' . $i)
  420. );
  421. $sItems .= _t('_bx_payment_txt_checkout_item', $aItem['title'], $aItem['quantity']);
  422. $aData['items'][] = $aItem;
  423. }
  424. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate($this->_oConfig->getPrefix('general') . 'checkout_offline', array(
  425. 'profile_name' => $oBuyer->getDisplayName(),
  426. 'profile_link' => $oBuyer->getUrl(),
  427. 'items' => $sItems,
  428. 'amount' => $aData['currency']['sign'] . sprintf("%.2f", (float)($aData['amount'])),
  429. 'date' => bx_time_js(time(), BX_FORMAT_DATE, true),
  430. 'pending_orders_link' => $this->getObjectOrders()->serviceGetPendingOrdersUrl()
  431. ), 0, $iSeller);
  432. $sEmail = '';
  433. $oProvider = $this->getObjectProvider($CNF['OBJECT_PP_OFFLINE'], $iSeller);
  434. if($oProvider !== false && $oProvider->isActive())
  435. $sEmail = $oProvider->getOption('checkout_email');
  436. if(empty($sEmail))
  437. $sEmail = $oBuyer->getAccountObject()->getEmail();
  438. if(!sendMail($sEmail, $aTemplate['Subject'], $aTemplate['Body'], 0, array(), BX_EMAIL_SYSTEM))
  439. return MsgBox(_t('_bx_payment_err_cannot_perform'));
  440. return $this->_oTemplate->displayBlockCheckoutOffline($oBuyer, $oSeller, $aData);
  441. }
  442. /**
  443. * Cart Processing Methods
  444. */
  445. public function actionAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount, $sCustom = '')
  446. {
  447. if(empty($sCustom) && bx_get('custom') !== false)
  448. $sCustom = bx_process_input(bx_get('custom'));
  449. $aCustom = array();
  450. if(!empty($sCustom)) {
  451. $aCustom = unserialize(base64_decode($sCustom));
  452. if(empty($aCustom) || !is_array($aCustom))
  453. $aCustom = array();
  454. }
  455. $aResult = $this->getObjectCart()->serviceAddToCart($iSellerId, $iModuleId, $iItemId, $iItemCount, $aCustom);
  456. echoJson($aResult);
  457. }
  458. /**
  459. * Isn't used yet.
  460. */
  461. public function actionDeleteFromCart($iSellerId, $iModuleId, $iItemId)
  462. {
  463. echoJson($this->getObjectCart()->serviceDeleteFromCart($iSellerId, $iModuleId, $iItemId));
  464. }
  465. /**
  466. * Isn't used yet.
  467. */
  468. public function actionEmptyCart($iSellerId)
  469. {
  470. echoJson($this->getObjectCart()->serviceDeleteFromCart($iSellerId));
  471. }
  472. public function actionSubscribe()
  473. {
  474. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  475. $sSellerProvider = bx_process_input(bx_get('seller_provider'));
  476. $iModuleId = bx_process_input(bx_get('module_id'), BX_DATA_INT);
  477. $iItemId = bx_process_input(bx_get('item_id'), BX_DATA_INT);
  478. $iItemCount = bx_process_input(bx_get('item_count'), BX_DATA_INT);
  479. if(empty($iItemCount))
  480. $iItemCount = 1;
  481. $sRedirect = bx_process_input(bx_get('redirect'));
  482. $sCustom = bx_process_input(bx_get('custom'));
  483. $aCustom = array();
  484. if(!empty($sCustom)) {
  485. $aCustom = unserialize(base64_decode($sCustom));
  486. if(empty($aCustom) || !is_array($aCustom))
  487. $aCustom = array();
  488. }
  489. $aResult = $this->getObjectSubscriptions()->serviceSubscribe($iSellerId, $sSellerProvider, $iModuleId, $iItemId, $iItemCount, $sRedirect, $aCustom);
  490. $bRedirect = !empty($aResult['redirect']);
  491. if(!empty($aResult['popup'])) {
  492. $sContent = '';
  493. $sContent .= $this->_oTemplate->displayCartJs(BX_PAYMENT_TYPE_RECURRING, $iSellerId);
  494. $sContent .= !empty($aResult['popup']['html']) ? $aResult['popup']['html'] : $aResult['popup'];
  495. return $this->_oTemplate->displayPageCodeResponse($sContent, false, true);
  496. }
  497. if(!empty($aResult['code']))
  498. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  499. if(!empty($aResult['message']) && !$bRedirect)
  500. return $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  501. if($bRedirect) {
  502. header('Location: ' . $aResult['redirect']);
  503. exit;
  504. }
  505. }
  506. public function actionSubscribeJson()
  507. {
  508. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  509. $sSellerProvider = bx_process_input(bx_get('seller_provider'));
  510. $iModuleId = bx_process_input(bx_get('module_id'), BX_DATA_INT);
  511. $iItemId = bx_process_input(bx_get('item_id'), BX_DATA_INT);
  512. $iItemCount = bx_process_input(bx_get('item_count'), BX_DATA_INT);
  513. if(empty($iItemCount))
  514. $iItemCount = 1;
  515. $sItemAddons = '';
  516. if(bx_get('item_addons') !== false) {
  517. $sItemAddons = bx_process_input(bx_get('item_addons'));
  518. if(is_array($sItemAddons))
  519. $sItemAddons = $this->_oConfig->a2s($sItemAddons);
  520. }
  521. $sRedirect = bx_process_input(bx_get('redirect'));
  522. $sCustom = bx_process_input(bx_get('custom'));
  523. $aCustom = array();
  524. if(!empty($sCustom)) {
  525. $aCustom = unserialize(base64_decode($sCustom));
  526. if(empty($aCustom) || !is_array($aCustom))
  527. $aCustom = array();
  528. }
  529. echoJson($this->getObjectSubscriptions()->serviceSubscribeWithAddons($iSellerId, $sSellerProvider, $iModuleId, $iItemId, $iItemCount, $sItemAddons, $sRedirect, $aCustom));
  530. }
  531. public function actionSubscriptionGetDetails($iId)
  532. {
  533. echoJson($this->_oTemplate->displaySubscriptionGetDetails($iId));
  534. }
  535. public function actionSubscriptionChangeDetails($iId)
  536. {
  537. echoJson($this->_oTemplate->displaySubscriptionChangeDetails($iId));
  538. }
  539. public function actionSubscriptionGetBilling($iId)
  540. {
  541. echoJson($this->_oTemplate->displaySubscriptionGetBilling($iId));
  542. }
  543. public function actionSubscriptionChangeBilling($iId)
  544. {
  545. echoJson($this->_oTemplate->displaySubscriptionChangeBilling($iId));
  546. }
  547. public function actionSubscriptionCancelation($iId)
  548. {
  549. $aResult = array('code' => 1, 'message' => _t('_bx_payment_err_cannot_perform'));
  550. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => $iId));
  551. if(empty($aPending) || !is_array($aPending))
  552. return echoJson($aResult);
  553. $aSubscription = $this->_oDb->getSubscription(array('type' => 'pending_id', 'pending_id' => $iId));
  554. if(empty($aSubscription) || !is_array($aSubscription))
  555. return echoJson($aResult);
  556. $oRecipient = BxDolProfile::getInstance((int)$aPending['seller_id']);
  557. if(!$oRecipient)
  558. return echoJson($aResult);
  559. $mixedResult = $this->isAllowedManage($aPending);
  560. if($mixedResult !== true)
  561. return echoJson(array('code' => 2, 'message' => $mixedResult));
  562. $aTemplate = BxDolEmailTemplates::getInstance()->parseTemplate($this->_oConfig->getPrefix('general') . 'cancelation_request', array(
  563. 'sibscription_id' => $aSubscription['subscription_id'],
  564. 'sibscription_customer' => $aSubscription['customer_id'],
  565. 'sibscription_date' => bx_time_js($aSubscription['date_add'], BX_FORMAT_DATE, true)
  566. ), 0, (int)$aPending['client_id']);
  567. $sEmail = '';
  568. $oProvider = $this->getObjectProvider($aPending['provider'], $aPending['seller_id']);
  569. if($oProvider !== false && $oProvider->isActive())
  570. $sEmail = $oProvider->getOption('cancellation_email');
  571. if(empty($sEmail))
  572. $sEmail = $oRecipient->getAccountObject()->getEmail();
  573. if(!sendMail($sEmail, $aTemplate['Subject'], $aTemplate['Body'], 0, array(), BX_EMAIL_SYSTEM))
  574. return echoJson($aResult);
  575. echoJson(array('code' => 0, 'message' => _t('_bx_payment_msg_cancelation_request_sent')));
  576. }
  577. public function actionSubscriptionCancel($iId, $mixedGridObject = false)
  578. {
  579. $aResult = array('code' => 1, 'message' => _t('_bx_payment_err_cannot_perform'));
  580. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => $iId));
  581. if(empty($aPending) || !is_array($aPending))
  582. return echoJson($aResult);
  583. $mixedResult = $this->isAllowedManage($aPending);
  584. if($mixedResult !== true)
  585. return echoJson(array('code' => 2, 'message' => $mixedResult));
  586. if(!$this->getObjectSubscriptions()->cancel($iId))
  587. return echoJson($aResult);
  588. if(empty($mixedGridObject) && bx_get('grid') !== false)
  589. $mixedGridObject = bx_process_input(bx_get('grid'));
  590. if(!empty($mixedGridObject) && $aPending['client_id'] == $this->getProfileId()) {
  591. $oGrid = BxDolGrid::getObjectInstance($mixedGridObject, $this->_oTemplate);
  592. $oGrid->addQueryParam('client_id', $aPending['client_id']);
  593. return echoJson(array('object' => $mixedGridObject, 'grid' => $oGrid->getCode(false), 'blink' => array($iId)));
  594. }
  595. else
  596. return echoJson(array('code' => 0, 'message' => _t('_bx_payment_msg_successfully_performed')));
  597. }
  598. /**
  599. * Payment Processing Methods
  600. */
  601. public function actionAuthorizeCheckout($sType)
  602. {
  603. if(!$this->isLogged())
  604. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  605. if(bx_get('seller_id') === false || bx_get('provider') === false || bx_get('items') === false)
  606. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_wrong_data');
  607. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  608. $sProvider = bx_process_input(bx_get('provider'));
  609. $aItems = bx_process_input(bx_get('items'));
  610. $mixedResult = $this->serviceAuthorizeCheckout($sType, $iSellerId, $sProvider, $aItems);
  611. if(is_string($mixedResult))
  612. return $this->_oTemplate->displayPageCodeError($mixedResult);
  613. if(is_array($mixedResult) && !empty($mixedResult['redirect'])) {
  614. header('Location: ' . $mixedResult['redirect']);
  615. exit;
  616. }
  617. return $this->_oTemplate->displayPageCodeResponse($this->_sLangsPrefix . 'msg_successfully_performed');
  618. }
  619. public function actionCaptureAuthorizedCheckout($sType)
  620. {
  621. $iProfileId = bx_get_logged_profile_id();
  622. if(!$iProfileId)
  623. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  624. $sOrderAuth = '';
  625. if(($sOrderAuth = bx_get('order')) !== false)
  626. $sOrderAuth = bx_process_input($sOrderAuth);
  627. if(empty($sOrderAuth))
  628. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_empty_order');
  629. $aPending = $this->_oDb->getOrderPending(['type' => 'order', 'order' => $sOrderAuth]);
  630. if(empty($aPending) || !is_array($aPending))
  631. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_empty_order');
  632. if((int)$aPending['seller_id'] != $iProfileId)
  633. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_wrong_vendor');
  634. $mixedResult = $this->serviceCaptureAuthorizedCheckout($sType, $sOrderAuth);
  635. if(is_string($mixedResult))
  636. return $this->_oTemplate->displayPageCodeError($mixedResult);
  637. if(!empty($mixedResult['redirect'])) {
  638. header('Location: ' . base64_decode(urldecode($mixedResult['redirect'])));
  639. exit;
  640. }
  641. return $this->_oTemplate->displayPageCodeResponse($mixedResult['message']);
  642. }
  643. public function actionInitializeCheckout($sType)
  644. {
  645. if(!$this->isLogged())
  646. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_required_login');
  647. if(bx_get('seller_id') !== false && bx_get('provider') !== false && bx_get('items') !== false) {
  648. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  649. $sProvider = bx_process_input(bx_get('provider'));
  650. $aItems = bx_process_input(bx_get('items'));
  651. $mixedResult = $this->serviceInitializeCheckout(BX_PAYMENT_TYPE_SINGLE, $iSellerId, $sProvider, $aItems);
  652. if($mixedResult !== true)
  653. return $this->_oTemplate->displayPageCodeError($mixedResult);
  654. }
  655. header('Location: ' . $this->_oConfig->getUrl('URL_CART'));
  656. exit;
  657. }
  658. public function actionInitializeCheckoutJson($sType)
  659. {
  660. if(!$this->isLogged())
  661. return echoJson(['code' => 1, 'message' => _t($this->_sLangsPrefix . 'err_required_login')]);
  662. if(bx_get('seller_id') !== false && bx_get('provider') !== false && bx_get('items') !== false) {
  663. $iSellerId = bx_process_input(bx_get('seller_id'), BX_DATA_INT);
  664. $sProvider = bx_process_input(bx_get('provider'));
  665. $aItems = bx_process_input(bx_get('items'));
  666. $mixedResult = $this->serviceInitializeCheckout(BX_PAYMENT_TYPE_SINGLE, $iSellerId, $sProvider, $aItems);
  667. if($mixedResult === false)
  668. return echoJson(['code' => 2, 'message' => _t($this->_sLangsPrefix . 'err_cannot_perform')]);
  669. if(is_string($mixedResult))
  670. return echoJson(['code' => 3, 'message' => $mixedResult]);
  671. else if(is_array($mixedResult))
  672. return echoJson($mixedResult);
  673. }
  674. return echoJson(['code' => 0, 'redirect' => $this->_oConfig->getUrl('URL_CART')]);
  675. }
  676. /**
  677. * @page service Service Calls
  678. * @section bx_payment Payment
  679. * @subsection bx_payment-purchase_processing Purchase Processing
  680. * @subsubsection bx_payment-authorize_checkout authorize_checkout
  681. *
  682. * @code bx_srv('bx_payment', 'authorize_checkout', [...]); @endcode
  683. *
  684. * Authorize order for future checkout.
  685. *
  686. * @param $sType string value with payment type (single or recurring).
  687. * @param $iSellerId integer value with seller ID.
  688. * @param $sProvider string value with payment provider name.
  689. * @param $aItems (optional) an array with items to be purchased.
  690. * @param $sRedirect (optional) string value with redirect URL if it's needed.
  691. * @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.
  692. *
  693. * @see BxPaymentModule::serviceAuthorizeCheckout
  694. */
  695. /**
  696. * @ref bx_payment-authorize_checkout "authorize_checkout"
  697. */
  698. public function serviceAuthorizeCheckout($sType, $iSellerId, $sProvider, $aItems = [], $sRedirect = '')
  699. {
  700. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  701. $bTypeRecurring = $sType == BX_PAYMENT_TYPE_RECURRING;
  702. if(!is_array($aItems))
  703. $aItems = [$aItems];
  704. $iSellerId = (int)$iSellerId;
  705. if($iSellerId == BX_PAYMENT_EMPTY_ID)
  706. return $this->_sLangsPrefix . 'err_unknown_vendor';
  707. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  708. if($oProvider === false || !$oProvider->isActive())
  709. return $this->_sLangsPrefix . 'err_incorrect_provider';
  710. $aInfo = $this->getObjectCart()->getInfo($sType, $this->_iUserId, $iSellerId, $aItems);
  711. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  712. return $this->_sLangsPrefix . 'err_empty_order';
  713. $this->alert('before_authorize', 0, $this->_iUserId, array(
  714. 'client_id' => $this->_iUserId,
  715. 'seller_id' => $iSellerId,
  716. 'type' => &$sType,
  717. 'provider' => &$sProvider,
  718. 'cart_info' => &$aInfo,
  719. ));
  720. $iPendingId = $this->_oDb->insertOrderPending($this->_iUserId, $sType, $sProvider, $aInfo);
  721. if(empty($iPendingId))
  722. return $this->_sLangsPrefix . 'err_access_db';
  723. return $oProvider->authorizeCheckout($iPendingId, $aInfo, $sRedirect);
  724. }
  725. /**
  726. * @page service Service Calls
  727. * @section bx_payment Payment
  728. * @subsection bx_payment-purchase_processing Purchase Processing
  729. * @subsubsection bx_payment-capture_authorized_checkout capture_authorized_checkout
  730. *
  731. * @code bx_srv('bx_payment', 'capture_authorized_checkout', [...]); @endcode
  732. *
  733. * Capture funds for previously authorized order.
  734. *
  735. * @param $sType string value with payment type (single or recurring).
  736. * @param $sOrderAuth string value with order's authorization ID.
  737. * @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.
  738. *
  739. * @see BxPaymentModule::serviceCaptureAuthorizedCheckout
  740. */
  741. /**
  742. * @ref bx_payment-capture_authorized_checkout "capture_authorized_checkout"
  743. */
  744. public function serviceCaptureAuthorizedCheckout($sType, $sOrderAuth, $sRedirect = '')
  745. {
  746. $aPending = $this->_oDb->getOrderPending(['type' => 'order', 'order' => $sOrderAuth]);
  747. if(empty($aPending) || !is_array($aPending))
  748. return $this->_sLangsPrefix . 'err_empty_order';
  749. if((int)$aPending['processed'] != 0)
  750. return $this->_sLangsPrefix . 'err_already_processed';
  751. $iClientId = (int)$aPending['client_id'];
  752. $iSellerId = (int)$aPending['seller_id'];
  753. $sProvider = $aPending['provider'];
  754. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  755. if($oProvider === false || !$oProvider->isActive())
  756. return $this->_sLangsPrefix . 'err_incorrect_provider';
  757. $aInfo = $this->getObjectCart()->getInfo($sType, $iClientId, $iSellerId, $aPending['items']);
  758. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  759. return $this->_sLangsPrefix . 'err_empty_order';
  760. $this->alert('before_capture_authorized', 0, $iClientId, array(
  761. 'order_auth' => $sOrderAuth,
  762. 'client_id' => $iClientId,
  763. 'seller_id' => $iSellerId,
  764. 'type' => &$sType,
  765. 'provider' => &$sProvider,
  766. 'cart_info' => &$aInfo,
  767. ));
  768. $aResult = $oProvider->captureAuthorizedCheckout($sOrderAuth, $aPending, $aInfo, $sRedirect);
  769. if((int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS)
  770. return $aResult['message'];
  771. //--- Get updated pending order
  772. $aPending = $this->_oDb->getOrderPending(['type' => 'id', 'id' => $aResult['pending_id']]);
  773. //--- Register payment for purchased items in associated modules
  774. if(isset($aResult['paid']) && $aResult['paid'])
  775. $this->registerPayment($aPending);
  776. $this->alert('finalize_checkout', 0, bx_get_logged_profile_id(), array(
  777. 'pending' => $aPending,
  778. 'transactions' => $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id'])),
  779. 'provider' => $oProvider,
  780. 'message' => &$aResult['message'],
  781. 'result' => &$aResult,
  782. ));
  783. if(empty($aResult['redirect']) && $oProvider->needRedirect())
  784. $aResult['redirect'] = $oProvider->getReturnUrl();
  785. return $aResult;
  786. }
  787. /**
  788. * @page service Service Calls
  789. * @section bx_payment Payment
  790. * @subsection bx_payment-purchase_processing Purchase Processing
  791. * @subsubsection bx_payment-initialize_checkout initialize_checkout
  792. *
  793. * @code bx_srv('bx_payment', 'initialize_checkout', [...]); @endcode
  794. *
  795. * Initialize the checkout process.
  796. *
  797. * @param $sType string value with payment type (single or recurring).
  798. * @param $iSellerId integer value with seller ID.
  799. * @param $sProvider string value with payment provider name.
  800. * @param $aItems (optional) an array with items to be purchased.
  801. * @param $sRedirect (optional) string value with redirect URL if it's needed.
  802. * @param $aCustom (optional) array with custom data to attach to a payment.
  803. * @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.
  804. *
  805. * @see BxPaymentModule::serviceInitializeCheckout
  806. */
  807. /**
  808. * @ref bx_payment-initialize_checkout "initialize_checkout"
  809. */
  810. public function serviceInitializeCheckout($sType, $iSellerId, $sProvider, $aItems = array(), $sRedirect = '', $aCustoms = array())
  811. {
  812. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  813. $bTypeRecurring = $sType == BX_PAYMENT_TYPE_RECURRING;
  814. if(!is_array($aItems))
  815. $aItems = array($aItems);
  816. $iSellerId = (int)$iSellerId;
  817. if($iSellerId == BX_PAYMENT_EMPTY_ID)
  818. return $this->_sLangsPrefix . 'err_unknown_vendor';
  819. $oProvider = $this->getObjectProvider($sProvider, $iSellerId);
  820. if($oProvider === false || !$oProvider->isActive())
  821. return $this->_sLangsPrefix . 'err_incorrect_provider';
  822. $aInfo = $this->getObjectCart()->getInfo($sType, $this->_iUserId, $iSellerId, $aItems);
  823. if(empty($aInfo) || $aInfo['vendor_id'] == BX_PAYMENT_EMPTY_ID || empty($aInfo['items']))
  824. return $this->_sLangsPrefix . 'err_empty_order';
  825. /*
  826. * Process FREE (price = 0) items for LOGGED IN members
  827. * WITHOUT processing via payment provider.
  828. * Note. This section isn't used for now!
  829. */
  830. $bProcessedFree = false;
  831. $sKeyPriceSingle = $this->_oConfig->getKey('KEY_ARRAY_PRICE_SINGLE');
  832. $sKeyPriceRecurring = $this->_oConfig->getKey('KEY_ARRAY_PRICE_RECURRING');
  833. foreach($aInfo['items'] as $iIndex => $aItem) {
  834. if((int)$aInfo['client_id'] == 0)
  835. continue;
  836. //--- For Single time payments.
  837. if($bTypeSingle && (float)$aItem[$sKeyPriceSingle] == 0) {
  838. $aCart = $this->_oDb->getCartContent($aInfo['client_id']);
  839. $aCartCustoms = !empty($aCart['customs']) ? unserialize($aCart['customs']) : array();
  840. $aCartItem = array($aInfo['vendor_id'], $aItem['module_id'], $aItem['id'], $aItem['quantity']);
  841. $aCartItemCustom = $this->_oConfig->pullCustom($aCartItem, $aCartCustoms);
  842. $aItemInfo = $this->callRegisterCartItem((int)$aItem['module_id'], array($aInfo['client_id'], $aInfo['vendor_id'], $aItem['id'], $aItem['quantity'], $this->_oConfig->getLicense(), $aCartItemCustom));
  843. if(!empty($aItemInfo) && is_array($aItemInfo)) {
  844. if(!empty($aItemInfo['addons']) && is_array($aItemInfo['addons']))
  845. foreach($aItemInfo['addons'] as $sAddon => $aAddon)
  846. $this->callRegisterCartItem((int)$aAddon['module_id'], array($aInfo['client_id'], $aInfo['vendor_id'], $aAddon['id'], $aAddon['quantity'], $this->_oConfig->getLicense(), $aCartItemCustom));
  847. $bProcessedFree = true;
  848. }
  849. $aInfo['items_count'] -= 1;
  850. unset($aInfo['items'][$iIndex]);
  851. $aCart['items'] = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aCartItem) . ":?'", "", $aCart['items']), ":");
  852. $this->_oDb->setCartItems($aInfo['client_id'], $aCart['items'], $aCartCustoms);
  853. }
  854. //--- For Recurring payments.
  855. if($bTypeRecurring && (float)$aItem[$sKeyPriceRecurring] == 0) {
  856. //TODO: Process FREE subscription here, if such situation will be possible.
  857. }
  858. }
  859. if(empty($aInfo['items']))
  860. return $this->_sLangsPrefix . ($bProcessedFree ? 'msg_successfully_processed_free' : 'err_empty_order');
  861. if($bTypeSingle && (empty($aCustoms) || !is_array($aCustoms))) {
  862. $aCart = $this->_oDb->getCartContent($aInfo['client_id']);
  863. $aCartCustoms = !empty($aCart['customs']) ? unserialize($aCart['customs']) : array();
  864. $aCustoms = array();
  865. foreach($aInfo['items'] as $aItem) {
  866. $sCartItem = $this->_oConfig->descriptorA2S(array($aItem['author_id'], $aItem['module_id'], $aItem['id']));
  867. $aCartItemCustom = $this->_oConfig->getCustom($sCartItem, $aCartCustoms);
  868. $this->_oConfig->putCustom($sCartItem, $aCartItemCustom, $aCustoms);
  869. }
  870. }
  871. $this->alert('before_pending', 0, bx_get_logged_profile_id(), array(
  872. 'client_id' => $this->_iUserId,
  873. 'seller_id' => $iSellerId,
  874. 'type' => &$sType,
  875. 'provider' => &$sProvider,
  876. 'cart_info' => &$aInfo,
  877. 'custom' => &$aCustoms,
  878. ));
  879. $iPendingId = $this->_oDb->insertOrderPending($this->_iUserId, $sType, $sProvider, $aInfo, $aCustoms);
  880. if(empty($iPendingId))
  881. return $this->_sLangsPrefix . 'err_access_db';
  882. /*
  883. * Perform Join WITHOUT processing via payment provider
  884. * if a client ISN'T logged in and has only ONE FREE item in the card.
  885. * Note. This section isn't used for now because only a member can purchase!
  886. */
  887. if((int)$aInfo['client_id'] == 0 && (int)$aInfo['items_count'] == 1) {
  888. reset($aInfo['items']);
  889. $aItem = current($aInfo['items']);
  890. if(!empty($aItem) && $this->_oConfig->getPrice($sType, $aItem)) {
  891. $this->_oDb->updateOrderPending($iPendingId, array(
  892. 'order' => $this->_oConfig->getLicense(),
  893. 'error_code' => '1',
  894. 'error_msg' => ''
  895. ));
  896. $this->getObjectJoin()->performJoin($iPendingId);
  897. }
  898. }
  899. return $oProvider->initializeCheckout($iPendingId, $aInfo, $sRedirect);
  900. }
  901. public function actionFinalizeCheckout($sProvider, $mixedVendorId = "")
  902. {
  903. $aData = &$_REQUEST;
  904. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  905. if($oProvider === false || !$oProvider->isActive())
  906. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  907. $aResult = $oProvider->finalizeCheckout($aData);
  908. if((int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS)
  909. return $this->_oTemplate->displayPageCodeError($aResult['message']);
  910. $aPending = $this->_oDb->getOrderPending(['type' => 'id', 'id' => (int)$aResult['pending_id']]);
  911. $bTypeRecurring = $aPending['type'] == BX_PAYMENT_TYPE_RECURRING;
  912. $bAuthorized = isset($aResult['authorized']) && $aResult['authorized'];
  913. $bPaid = isset($aResult['paid']) && $aResult['paid'];
  914. $bTrial = isset($aResult['trial']) && $aResult['trial'];
  915. //--- Register subscription
  916. if($bTypeRecurring) {
  917. $sStatus = BX_PAYMENT_SBS_STATUS_UNPAID;
  918. if($bPaid)
  919. $sStatus = BX_PAYMENT_SBS_STATUS_ACTIVE;
  920. else if($bTrial)
  921. $sStatus = BX_PAYMENT_SBS_STATUS_TRIAL;
  922. $aSubscription = array(
  923. 'customer_id' => $aResult['customer_id'],
  924. 'subscription_id' => $aResult['subscription_id'],
  925. 'status' => $sStatus
  926. );
  927. if(!$this->getObjectSubscriptions()->register($aPending, $aSubscription))
  928. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_already_registered');
  929. }
  930. $this->onPaymentRegisterBefore($aPending);
  931. //--- Check "Pay Before Join" situation
  932. if((int)$aPending['client_id'] == 0)
  933. $this->getObjectJoin()->performJoin((int)$aPending['id'], isset($aResult['client_name']) ? $aResult['client_name'] : '', isset($aResult['client_email']) ? $aResult['client_email'] : '');
  934. //--- Authorize order for selected items in associated modules
  935. if($bAuthorized)
  936. $this->authorizePayment($aPending);
  937. //--- Register payment for purchased items in associated modules
  938. if($bPaid || ($bTypeRecurring && $bTrial))
  939. $this->registerPayment($aPending);
  940. //--- Get updated pending order
  941. $aPending = $this->_oDb->getOrderPending(['type' => 'id', 'id' => $aPending['id']]);
  942. $this->alert('finalize_checkout', 0, bx_get_logged_profile_id(), array(
  943. 'pending' => $aPending,
  944. 'transactions' => $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id'])),
  945. 'provider' => $oProvider,
  946. 'message' => &$aResult['message'],
  947. 'result' => &$aResult,
  948. ));
  949. if($oProvider->needRedirect()) {
  950. header('Location: ' . $oProvider->getReturnUrl());
  951. exit;
  952. }
  953. if(!empty($aResult['redirect'])) {
  954. header('Location: ' . base64_decode(urldecode($aResult['redirect'])));
  955. exit;
  956. }
  957. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  958. }
  959. public function actionFinalizedCheckout($sProvider, $mixedVendorId = "")
  960. {
  961. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  962. if($oProvider === false || !$oProvider->isActive())
  963. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  964. $aResult = $oProvider->finalizedCheckout();
  965. $this->_oTemplate->displayPageCodeResponse($aResult['message']);
  966. }
  967. public function actionNotify($sProvider, $mixedVendorId = "")
  968. {
  969. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  970. if($oProvider === false || !$oProvider->isActive())
  971. return $this->_oTemplate->displayPageCodeError($this->_sLangsPrefix . 'err_incorrect_provider');
  972. $oProvider->notify();
  973. }
  974. /**
  975. * The method is needed to pass direct action calls to necessary Payment Provider.
  976. */
  977. public function actionCall($sProvider, $sAction, $mixedVendorId = BX_PAYMENT_EMPTY_ID)
  978. {
  979. $oProvider = $this->getObjectProvider($sProvider, $mixedVendorId);
  980. if($oProvider === false)
  981. BxDolRequest::methodNotFound($sAction, $this->getName());
  982. $sMethod = 'action' . bx_gen_method_name($sAction);
  983. if(!method_exists($oProvider, $sMethod))
  984. BxDolRequest::methodNotFound($sAction, $this->getName());
  985. return call_user_func_array(array($oProvider, $sMethod), array_slice(func_get_args(), 2));
  986. }
  987. public function onProfileJoin($iProfileId)
  988. {
  989. $this->getObjectJoin()->onProfileJoin($iProfileId);
  990. }
  991. public function onProfileDelete($iProfileId)
  992. {
  993. //--- Cancel subscriptions
  994. $aSubscriptions = $this->_oDb->getSubscription(['type' => 'mixed_ext', 'conditions' => ['client_id' => $iProfileId]]);
  995. if(!empty($aSubscriptions) && is_array($aSubscriptions))
  996. foreach($aSubscriptions as $aSubscription)
  997. $this->getObjectSubscriptions()->cancel($aSubscription['pending_id']);
  998. //--- Clean DB
  999. $this->_oDb->onProfileDelete($iProfileId);
  1000. }
  1001. public function isAllowedPurchase($aItem, $bPerform = false)
  1002. {
  1003. $iUserId = (int)$this->getProfileId();
  1004. $aItemInfo = $this->callGetCartItem((int)$aItem['module_id'], array($aItem['item_id'], $iUserId, isset($aItem['custom']) ? $aItem['custom'] : array()));
  1005. if(empty($aItemInfo))
  1006. return false;
  1007. if(isAdmin())
  1008. return true;
  1009. $aCheckResult = checkActionModule($iUserId, 'purchase', $this->getName(), $bPerform);
  1010. if($aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  1011. return true;
  1012. return $aCheckResult[CHECK_ACTION_MESSAGE];
  1013. }
  1014. public function isAllowedSell($aItem, $bPerform = false)
  1015. {
  1016. $iUserId = (int)$this->getProfileId();
  1017. if(!$iUserId)
  1018. return false;
  1019. $aItemInfo = $this->callGetCartItem((int)$aItem['module_id'], array($aItem['item_id'], $iUserId));
  1020. if(empty($aItemInfo))
  1021. return false;
  1022. if(isAdmin())
  1023. return true;
  1024. $aCheckResult = checkActionModule($iUserId, 'sell', $this->getName(), $bPerform);
  1025. if((int)$aItemInfo['author_id'] == $iUserId && $aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  1026. return true;
  1027. return $aCheckResult[CHECK_ACTION_MESSAGE];
  1028. }
  1029. public function isAllowedManage($aPending, $bPerform = false)
  1030. {
  1031. $iUserId = (int)$this->getProfileId();
  1032. if($iUserId == $aPending['client_id'] || $iUserId == $aPending['seller_id'] || isAdmin())
  1033. return true;
  1034. $aCheckResult = checkActionModule($iUserId, 'manage any purchase', $this->getName(), $bPerform);
  1035. if($aCheckResult[CHECK_ACTION_RESULT] == CHECK_ACTION_RESULT_ALLOWED)
  1036. return true;
  1037. return $aCheckResult[CHECK_ACTION_MESSAGE];
  1038. }
  1039. public function isAllowedManageInvoices($bPerform = false)
  1040. {
  1041. if(BxDolAcl::getInstance()->isMemberLevelInSet(array(MEMBERSHIP_ID_MODERATOR, MEMBERSHIP_ID_ADMINISTRATOR)) || isAdmin())
  1042. return true;
  1043. return _t('_sys_txt_access_denied');
  1044. }
  1045. public function checkData($iClientId, $iSellerId, $iModuleId, $iItemId, $iItemCount, $aCustom = array())
  1046. {
  1047. $CNF = &$this->_oConfig->CNF;
  1048. if($iSellerId == BX_PAYMENT_EMPTY_ID || empty($iModuleId) || empty($iItemId) || empty($iItemCount))
  1049. return array('code' => 1, 'message' => _t($CNF['T']['ERR_WRONG_DATA']));
  1050. $iClientId = $this->getProfileId();
  1051. if(empty($iClientId)) {
  1052. $sLoginUrl = BxDolPermalinks::getInstance()->permalink('page.php?i=login');
  1053. return array('code' => 2, 'eval' => 'window.open("' . $sLoginUrl . '", "_self");');
  1054. }
  1055. $mixedResult = $this->isAllowedPurchase(array('module_id' => $iModuleId, 'item_id' => $iItemId, 'custom' => $aCustom));
  1056. if($mixedResult !== true) {
  1057. if(is_string($mixedResult) && !empty($mixedResult))
  1058. return array('code' => 2, 'message' => $mixedResult);
  1059. else
  1060. return array('code' => 1, 'message' => _t($CNF['T']['ERR_WRONG_DATA']));
  1061. }
  1062. if($iClientId == $iSellerId)
  1063. return array('code' => 3, 'message' => _t($CNF['T']['ERR_SELF_PURCHASE']));
  1064. $aSeller = $this->getVendorInfo($iSellerId);
  1065. if(!$aSeller['active'])
  1066. return array('code' => 4, 'message' => _t($CNF['T']['ERR_INACTIVE_VENDOR']));
  1067. return true;
  1068. }
  1069. public function authorizePayment($mixedPending)
  1070. {
  1071. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(['type' => 'id', 'id' => (int)$mixedPending]);
  1072. if(empty($aPending) || !is_array($aPending))
  1073. return false;
  1074. $sType = $aPending['type'];
  1075. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  1076. if((int)$aPending['authorized'] == 1)
  1077. return true;
  1078. $iClientId = (int)$aPending['client_id'];
  1079. $aCart = array();
  1080. if($bTypeSingle)
  1081. $aCart = $this->_oDb->getCartContent($iClientId);
  1082. $bResult = false;
  1083. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  1084. foreach($aItems as $aItem) {
  1085. $sItem = $this->_oConfig->descriptorA2S([$aItem['vendor_id'], $aItem['module_id'], $aItem['item_id']]);
  1086. $sMethod = $bTypeSingle ? 'callAuthorizeCartItem' : 'callAuthorizeSubscriptionItem';
  1087. $aItemInfo = $this->$sMethod((int)$aItem['module_id'], [$aPending['client_id'], $aPending['seller_id'], $aItem['item_id'], $aItem['item_count'], $aPending['order']]);
  1088. if(empty($aItemInfo) || !is_array($aItemInfo))
  1089. continue;
  1090. if($bTypeSingle)
  1091. $aCart['items'] = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aItem) . ":?'", "", $aCart['items']), ":");
  1092. $bResult = true;
  1093. }
  1094. if($bResult) {
  1095. $this->_oDb->updateOrderPending($aPending['id'], ['authorized' => 1]);
  1096. $this->onPaymentAuthorize($aPending);
  1097. }
  1098. return $bResult;
  1099. }
  1100. public function registerPayment($mixedPending)
  1101. {
  1102. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(['type' => 'id', 'id' => (int)$mixedPending]);
  1103. if(empty($aPending) || !is_array($aPending))
  1104. return false;
  1105. $sType = $aPending['type'];
  1106. $bTypeSingle = $sType == BX_PAYMENT_TYPE_SINGLE;
  1107. if($bTypeSingle && (int)$aPending['processed'] == 1)
  1108. return true;
  1109. $iClientId = (int)$aPending['client_id'];
  1110. $iSellerId = (int)$aPending['seller_id'];
  1111. $sLicense = $this->_oConfig->getLicense();
  1112. $aCustoms = !empty($aPending['customs']) ? unserialize($aPending['customs']) : [];
  1113. $aCart = [];
  1114. if($bTypeSingle) {
  1115. $aCart = $this->_oDb->getCartContent($iClientId);
  1116. $aCart['customs'] = !empty($aCart['customs']) ? unserialize($aCart['customs']) : [];
  1117. }
  1118. $bResult = false;
  1119. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  1120. foreach($aItems as $aItem) {
  1121. $sItem = $this->_oConfig->descriptorA2S([$aItem['vendor_id'], $aItem['module_id'], $aItem['item_id']]);
  1122. $aItemCustom = $this->_oConfig->getCustom($sItem, $aCustoms);
  1123. $sMethod = $bTypeSingle ? 'callRegisterCartItem' : 'callRegisterSubscriptionItem';
  1124. $aItemInfo = $this->$sMethod((int)$aItem['module_id'], [$iClientId, $iSellerId, $aItem['item_id'], $aItem['item_count'], $aPending['order'], $sLicense, $aItemCustom]);
  1125. if(empty($aItemInfo) || !is_array($aItemInfo))
  1126. continue;
  1127. $this->_oDb->insertOrderProcessed([
  1128. 'pending_id' => $aPending['id'],
  1129. 'client_id' => $iClientId,
  1130. 'seller_id' => $iSellerId,
  1131. 'author_id' => (int)$aItem['vendor_id'],
  1132. 'module_id' => (int)$aItem['module_id'],
  1133. 'item_id' => (int)$aItem['item_id'],
  1134. 'item_count' => (int)$aItem['item_count'],
  1135. 'amount' => (int)$aItem['item_count'] * $this->_oConfig->getPrice($sType, $aItemInfo),
  1136. 'currency' => $this->getVendorCurrencyCode($iSellerId),
  1137. 'license' => $sLicense,
  1138. ]);
  1139. if($bTypeSingle) {
  1140. $this->_oConfig->pullCustom($sItem, $aCart['customs']);
  1141. $aCart['items'] = trim(preg_replace("'" . $this->_oConfig->descriptorA2S($aItem) . ":?'", "", $aCart['items']), ":");
  1142. }
  1143. $bResult = true;
  1144. }
  1145. if($bTypeSingle)
  1146. $this->_oDb->setCartItems($iClientId, $aCart['items'], $aCart['customs']);
  1147. if($bResult) {
  1148. $this->_oDb->updateOrderPending($aPending['id'], ['processed' => 1]);
  1149. $this->onPaymentRegister($aPending);
  1150. }
  1151. return $bResult;
  1152. }
  1153. public function refundPayment($mixedPending)
  1154. {
  1155. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$mixedPending));
  1156. if(empty($aPending) || !is_array($aPending))
  1157. return false;
  1158. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  1159. $iCanceled = 0;
  1160. $aOrders = $this->_oDb->getOrderProcessed(array('type' => 'pending_id', 'pending_id' => (int)$aPending['id']));
  1161. foreach($aOrders as $aOrder) {
  1162. $sMethod = $bTypeSingle ? 'callUnregisterCartItem' : 'callUnregisterSubscriptionItem';
  1163. $bResult = $this->$sMethod((int)$aOrder['module_id'], array($aOrder['client_id'], $aOrder['seller_id'], $aOrder['item_id'], $aOrder['item_count'], $aPending['order'], $aOrder['license']));
  1164. if(!$bResult)
  1165. continue;
  1166. if($this->_oDb->deleteOrderProcessed($aOrder['id']))
  1167. $iCanceled++;
  1168. }
  1169. if($iCanceled != count($aOrders))
  1170. return false;
  1171. $bResult = $this->_oDb->deleteOrderPending($aPending['id']);
  1172. if($bResult)
  1173. $this->onPaymentRefund($aPending);
  1174. return $bResult;
  1175. }
  1176. /**
  1177. * @deprecated since version 12.0.0
  1178. *
  1179. * @use BxPaymentSubscriptions::register instead.
  1180. */
  1181. public function registerSubscription($aPending, $aParams = array())
  1182. {
  1183. return $this->getObjectSubscriptions()->register($aPending, $aParams);
  1184. }
  1185. /**
  1186. * @deprecated since version 12.0.0
  1187. *
  1188. * @use BxPaymentSubscriptions::cancelLocal instead.
  1189. */
  1190. public function cancelSubscription($mixedPending)
  1191. {
  1192. return $this->getObjectSubscriptions()->cancelLocal($mixedPending);
  1193. }
  1194. public function processCommissions()
  1195. {
  1196. if(!defined('BX_DOL_CRON_EXECUTE'))
  1197. return;
  1198. $CNF = &$this->_oConfig->CNF;
  1199. if((int)date('j') == $this->_oConfig->getInvoiceIssueDay())
  1200. $this->_invoicesIssue();
  1201. $this->_invoicesCheck();
  1202. }
  1203. protected function _invoicesIssue()
  1204. {
  1205. $CNF = &$this->_oConfig->CNF;
  1206. $sInvoiceNameMask = 'INV-%d-%d-%d';
  1207. $iMonth = date('m');
  1208. $iYear = date('Y');
  1209. $iPeriodStart = mktime(0, 0, 0, $iMonth-1, 1, $iYear);
  1210. $iPeriodEnd = mktime(23, 59, 59, $iMonth, 0, $iYear);
  1211. $iDateIssue = time();
  1212. $iDateDue = $iDateIssue + 86400 * $this->_oConfig->getInvoiceLifetime();
  1213. $aCommissionsInfo = array();
  1214. $aAclLevels = BxDolAcl::getInstance()->getMemberships(false, true, false, true);
  1215. foreach($aAclLevels as $iAclLevelId => $sAclLevelTitle)
  1216. $aCommissionsInfo[$iAclLevelId] = $this->_oDb->getCommissions(array('type' => 'acl_id', 'acl_id' => $iAclLevelId));
  1217. $iMainSellerId = $this->_oConfig->getSiteAdmin();
  1218. $aVendors = $this->_oDb->getOrderProcessed(array('type' => 'income', 'period_start' => $iPeriodStart, 'period_end' => $iPeriodEnd));
  1219. foreach($aVendors as $aVendor) {
  1220. $iVendorId = (int)$aVendor['id'];
  1221. if($iVendorId == $iMainSellerId)
  1222. continue;
  1223. $aInvoice = $this->_oDb->getInvoices(array('type' => 'committent_id', 'committent_id' => $iVendorId, 'period_start' => $iPeriodStart, 'period_end' => $iPeriodEnd));
  1224. if(!empty($aInvoice) && is_array($aInvoice))
  1225. continue;
  1226. $aVendorAcl = BxDolAcl::getInstance()->getMemberMembershipInfo($iVendorId);
  1227. $aCommissions = $aCommissionsInfo[$aVendorAcl['id']];
  1228. $fCommission = 0;
  1229. foreach($aCommissions as $aCommission) {
  1230. if((float)$aCommission['percentage'] > 0)
  1231. $fCommission += (float)$aVendor['amount'] * (float)$aCommission['percentage'] / 100;
  1232. if((float)$aCommission['installment'] > 0)
  1233. $fCommission += (float)$aCommission['installment'];
  1234. }
  1235. $this->alert('calculate_commission', 0, 0, array(
  1236. 'vendor' => $aVendor,
  1237. 'commissions' => $aCommissions,
  1238. 'override_result' => &$fCommission,
  1239. ));
  1240. $this->_oDb->insertInvoice(array(
  1241. 'name' => sprintf($sInvoiceNameMask, $iMainSellerId, $iVendorId, $this->_oDb->getInvoices(array(
  1242. 'type' => 'index',
  1243. 'commissionaire_id' => $iMainSellerId,
  1244. 'committent_id' => $iVendorId
  1245. ))),
  1246. 'commissionaire_id' => $iMainSellerId,
  1247. 'committent_id' => $iVendorId,
  1248. 'amount' => $fCommission,
  1249. 'period_start' => $iPeriodStart,
  1250. 'period_end' => $iPeriodEnd,
  1251. 'date_issue' => $iDateIssue,
  1252. 'date_due' => $iDateDue,
  1253. 'status' => BX_PAYMENT_INV_STATUS_UNPAID
  1254. ));
  1255. }
  1256. }
  1257. protected function _invoicesCheck()
  1258. {
  1259. $CNF = &$this->_oConfig->CNF;
  1260. $sPrefix = $this->_oConfig->getPrefix('general');
  1261. $oEmailTemplates = BxDolEmailTemplates::getInstance();
  1262. //--- Process expiring invoices.
  1263. $aInvoices = $this->_oDb->getInvoices(array('type' => 'expiring'));
  1264. if(!empty($aInvoices) && is_array($aInvoices))
  1265. foreach($aInvoices as $aInvoice) {
  1266. if((int)$aInvoice['ntf_exp'] > 0)
  1267. continue;
  1268. $oCommittent = BxDolProfile::getInstance($aInvoice['committent_id']);
  1269. if(!$oCommittent)
  1270. continue;
  1271. $bResult = sendMailTemplate($sPrefix . 'expiring_notification_committent', 0, (int)$aInvoice['committent_id'], array(
  1272. 'invoice' => $aInvoice['name'],
  1273. 'days' => $this->_oConfig->getInvoiceExpirationNotify(),
  1274. 'period_start' => $this->_oConfig->formatDate($aInvoice['period_start']),
  1275. 'period_end' => $this->_oConfig->formatDate($aInvoice['period_end']),
  1276. 'date_issue' => $this->_oConfig->formatDateTime($aInvoice['date_issue']),
  1277. 'date_due' => $this->_oConfig->formatDateTime($aInvoice['date_due']),
  1278. ), BX_EMAIL_NOTIFY, true);
  1279. if($bResult)
  1280. $this->_oDb->updateInvoice($aInvoice['id'], array('ntf_exp' => 1));
  1281. }
  1282. //--- Process overdue invoices.
  1283. $aInvoices = $this->_oDb->getInvoices(array('type' => 'overdue'));
  1284. if(!empty($aInvoices) && is_array($aInvoices))
  1285. foreach($aInvoices as $aInvoice) {
  1286. if((int)$aInvoice['ntf_due'] > 0 && $aInvoice['status'] == BX_PAYMENT_INV_STATUS_OVERDUE)
  1287. continue;
  1288. $oCommittent = BxDolProfile::getInstance($aInvoice['committent_id']);
  1289. if(!$oCommittent)
  1290. continue;
  1291. $bResult = sendMailTemplate($sPrefix . 'overdue_notification_committent', 0, (int)$aInvoice['committent_id'], array(
  1292. 'invoice' => $aInvoice['name'],
  1293. 'period_start' => $this->_oConfig->formatDate($aInvoice['period_start']),
  1294. 'period_end' => $this->_oConfig->formatDate($aInvoice['period_end']),
  1295. 'date_issue' => $this->_oConfig->formatDateTime($aInvoice['date_issue']),
  1296. 'date_due' => $this->_oConfig->formatDateTime($aInvoice['date_due']),
  1297. ), BX_EMAIL_NOTIFY, true);
  1298. $this->_oDb->updateInvoice($aInvoice['id'], array(
  1299. 'status' => BX_PAYMENT_INV_STATUS_OVERDUE,
  1300. 'ntf_due' => $bResult ? 1 : 0
  1301. ));
  1302. }
  1303. }
  1304. public function processTimeTracker()
  1305. {
  1306. if(!defined('BX_DOL_CRON_EXECUTE'))
  1307. return;
  1308. $aSubscriptions = $this->_oDb->getSubscription(array(
  1309. 'type' => 'time_tracker',
  1310. 'status_active' => BX_PAYMENT_SBS_STATUS_ACTIVE,
  1311. 'status_trial' => BX_PAYMENT_SBS_STATUS_TRIAL,
  1312. 'status_unpaid' => BX_PAYMENT_SBS_STATUS_UNPAID,
  1313. 'pay_attempts_max' => $this->_oConfig->getPayAttemptsMax(),
  1314. 'pay_attempts_interval' => $this->_oConfig->getPayAttemptsInterval()
  1315. ));
  1316. if(empty($aSubscriptions) || !is_array($aSubscriptions))
  1317. return;
  1318. foreach($aSubscriptions as $aSubscription) {
  1319. $aPending = $this->_oDb->getOrderPending(array('type' => 'id', 'id' => (int)$aSubscription['pending_id']));
  1320. if(empty($aPending) || !is_array($aPending) || $aPending['type'] != BX_PAYMENT_TYPE_RECURRING) {
  1321. $this->log($aSubscription, 'Time Tracker', 'Cannot process subscription.');
  1322. continue;
  1323. }
  1324. $oProvider = $this->getObjectProvider($aPending['provider'], $aPending['seller_id']);
  1325. if($oProvider === false || !$oProvider->isActive() || !method_exists($oProvider, 'makePayment')) {
  1326. $this->log($aSubscription, 'Time Tracker', 'Payment provider unavailable or incorrect.');
  1327. continue;
  1328. }
  1329. $this->_oDb->updateSubscription(['pay_attempts' => (int)$aSubscription['pay_attempts'] + 1], ['id' => $aSubscription['id']]);
  1330. if(($mixedResult = $oProvider->makePayment($aPending)) !== true) {
  1331. $this->_oDb->updateSubscription(['status' => BX_PAYMENT_SBS_STATUS_UNPAID], ['id' => $aSubscription['id']]);
  1332. $this->log($aSubscription, 'Time Tracker', 'Payment cannot be processed (code: ' . (!empty($mixedResult['code']) ? (int)$mixedResult['code'] : 0) . ').');
  1333. continue;
  1334. }
  1335. if(!$this->getObjectSubscriptions()->prolong($aPending)) {
  1336. $this->log($aSubscription, 'Time Tracker', 'Cannot prolong subscription.');
  1337. continue;
  1338. }
  1339. if(!$this->registerPayment($aPending)) {
  1340. $this->log($aSubscription, 'Time Tracker', 'Cannot register payment.');
  1341. continue;
  1342. }
  1343. }
  1344. }
  1345. public function onPaymentRegisterBefore($aPending, $aResult = [])
  1346. {
  1347. $this->alert('before_register_payment', 0, $aPending['client_id'], array('pending' => $aPending));
  1348. }
  1349. public function onPaymentAuthorize($aPending, $aResult = [])
  1350. {
  1351. $this->alert('authorize_payment', 0, $aPending['client_id'], ['pending' => $aPending]);
  1352. }
  1353. public function onPaymentRegister($aPending, $aResult = [])
  1354. {
  1355. $bTypeSingle = $aPending['type'] == BX_PAYMENT_TYPE_SINGLE;
  1356. if($bTypeSingle) {
  1357. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  1358. foreach($aItems as $aItem)
  1359. $this->isAllowedPurchase(['module_id' => $aItem['module_id'], 'item_id' => $aItem['item_id']], true);
  1360. }
  1361. $this->alert('register_payment', 0, $aPending['client_id'], ['pending' => $aPending]);
  1362. }
  1363. public function onPaymentRefund($aPending, $aResult = [])
  1364. {
  1365. $this->alert('refund_payment', 0, $aPending['client_id'], ['pending' => $aPending]);
  1366. }
  1367. public function onSubscriptionCreate($aPending, $aSubscription, $aResult = [])
  1368. {
  1369. $aItems = $this->_oConfig->descriptorsM2A($aPending['items']);
  1370. $this->isAllowedPurchase(['module_id' => $aItems[0]['module_id'], 'item_id' => $aItems[0]['item_id']], true);
  1371. $this->alert('create_subscription', 0, $aPending['client_id'], [
  1372. 'pending' => $aPending,
  1373. 'subscription' => $aSubscription
  1374. ]);
  1375. }
  1376. public function onSubscriptionProlong($aPending, $aSubscription, $aResult = [])
  1377. {
  1378. $this->alert('prolong_subscription', 0, $aPending['client_id'], [
  1379. 'pending' => $aPending,
  1380. 'subscription' => $aSubscription
  1381. ]);
  1382. }
  1383. public function onSubscriptionOverdue($aPending, $aSubscription, $aResult = [])
  1384. {
  1385. $this->alert('overdue_subscription', 0, $aPending['client_id'], [
  1386. 'pending' => $aPending,
  1387. 'subscription' => $aSubscription
  1388. ]);
  1389. }
  1390. public function onSubscriptionCancel($aPending, $aSubscription, $aResult = [])
  1391. {
  1392. $this->alert('cancel_subscription', 0, $aPending['client_id'], [
  1393. 'pending' => $aPending,
  1394. 'subscription' => $aSubscription
  1395. ]);
  1396. }
  1397. public function setSiteSubmenu($sSubmenu, $sSelModule, $sSelName)
  1398. {
  1399. $oSiteSubmenu = BxDolMenu::getObjectInstance('sys_site_submenu');
  1400. if(!$oSiteSubmenu)
  1401. return;
  1402. $sModuleSubmenu = $this->_oConfig->getObject($sSubmenu);
  1403. $oModuleSubmenu = BxDolMenu::getObjectInstance($sModuleSubmenu);
  1404. if(!$oModuleSubmenu)
  1405. return;
  1406. $oSiteSubmenu->setObjectSubmenu($sModuleSubmenu);
  1407. $oModuleSubmenu->setSelected($sSelModule, $sSelName);
  1408. }
  1409. public function getProviderButtonJs($aCartItem, $aProvider, $sRedirect = '', $aCustom = array())
  1410. {
  1411. $aButtonJs = array();
  1412. $iClientId = $this->getProfileId();
  1413. $sItemAddons = '';
  1414. if(count($aCartItem) == 5)
  1415. $sItemAddons = array_pop($aCartItem);
  1416. list($iSellerId, $iModuleId, $iItemId, $iItemCount) = $aCartItem;
  1417. $oProvider = $this->getObjectProvider($aProvider['name'], $iSellerId);
  1418. if($oProvider !== false && method_exists($oProvider, 'getButtonRecurring')) {
  1419. $aParams = array(
  1420. 'sObjNameCart' => $this->_oConfig->getJsObject('cart'),
  1421. 'iSellerId' => $iSellerId,
  1422. 'iModuleId' => $iModuleId,
  1423. 'iItemId' => $iItemId,
  1424. 'iItemCount' => $iItemCount,
  1425. 'sItemAddons' => $sItemAddons,
  1426. 'sRedirect' => $sRedirect,
  1427. 'sCustom' => base64_encode(serialize($aCustom))
  1428. );
  1429. $aCartInfo = $this->getObjectCart()->getInfo(BX_PAYMENT_TYPE_RECURRING, $iClientId, $iSellerId, $this->_oConfig->descriptorA2S($aCartItem));
  1430. if(!empty($aCartInfo['items_price']) && !empty($aCartInfo['items']) && is_array($aCartInfo['items'])) {
  1431. $aItem = array_shift($aCartInfo['items']);
  1432. $aParams = array_merge($aParams, array(
  1433. 'iAmount' => (int)round(100 * (float)$aCartInfo['items_price']),
  1434. 'sItemName' => $aItem['name'],
  1435. 'sItemTitle' => $aItem['title']
  1436. ));
  1437. }
  1438. $aButtonJs = $oProvider->getButtonRecurringJs($iClientId, $iSellerId, $aParams);
  1439. }
  1440. if(empty($aButtonJs) || !is_array($aButtonJs))
  1441. $aButtonJs = $this->getObjectSubscriptions()->serviceGetSubscribeJs($iSellerId, $aProvider['name'], $iModuleId, $iItemId, $iItemCount, $sRedirect, $aCustom);
  1442. return $aButtonJs;
  1443. }
  1444. /**
  1445. * Integration with itslef which is needed to pay an invoice.
  1446. */
  1447. /**
  1448. * @page service Service Calls
  1449. * @section bx_payment Payment
  1450. * @subsection bx_payment-payments Payments
  1451. * @subsubsection bx_payment-get_payment_data get_payment_data
  1452. *
  1453. * @code bx_srv('bx_payment', 'get_payment_data', [...]); @endcode
  1454. *
  1455. * Get an array with module's description. Is needed for payments processing module.
  1456. *
  1457. * @return an array with module's description.
  1458. *
  1459. * @see BxPaymentModule::serviceGetPaymentData
  1460. */
  1461. /**
  1462. * @ref bx_payment-get_payment_data "get_payment_data"
  1463. */
  1464. public function serviceGetPaymentData()
  1465. {
  1466. return $this->_aModule;
  1467. }
  1468. /**
  1469. * @page service Service Calls
  1470. * @section bx_payment Payment
  1471. * @subsection bx_payment-payments Payments
  1472. * @subsubsection bx_payment-get_cart_item get_cart_item
  1473. *
  1474. * @code bx_srv('bx_payment', 'get_cart_item', [...]); @endcode
  1475. *
  1476. * Get an array with prodict's description. Is used in Shopping Cart in payments processing module.
  1477. *
  1478. * @param $mixedItemId product's ID or Unique Name.
  1479. * @return an array with prodict's description. Empty array is returned if something is wrong.
  1480. *
  1481. * @see BxPaymentModule::serviceGetCartItem
  1482. */
  1483. /**
  1484. * @ref bx_payment-get_cart_item "get_cart_item"
  1485. */
  1486. public function serviceGetCartItem($mixedItemId)
  1487. {
  1488. $CNF = &$this->_oConfig->CNF;
  1489. if(!$mixedItemId)
  1490. return array();
  1491. if(is_numeric($mixedItemId))
  1492. $aItem = $this->_oDb->getInvoices(array('type' => 'id', 'id' => (int)$mixedItemId));
  1493. else
  1494. $aItem = $this->_oDb->getInvoices(array('type' => 'name', 'name' => $mixedItemId));
  1495. if(empty($aItem) || !is_array($aItem))
  1496. return array();
  1497. $oCommissionaire = BxDolProfile::getInstanceMagic($aItem['commissionaire_id']);
  1498. return array (
  1499. 'id' => $aItem['id'],
  1500. 'author_id' => $aItem['commissionaire_id'],
  1501. 'name' => $aItem['name'],
  1502. 'title' => _t('_bx_payment_txt_invoice_title', $aItem['name'], $oCommissionaire->getDisplayName()),
  1503. '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)),
  1504. 'url' => '',
  1505. 'price_single' => $aItem['amount'],
  1506. 'price_recurring' => '',
  1507. 'period_recurring' => 0,
  1508. 'period_unit_recurring' => '',
  1509. 'trial_recurring' => ''
  1510. );
  1511. }
  1512. /**
  1513. * @page service Service Calls
  1514. * @section bx_payment Payment
  1515. * @subsection bx_payment-payments Payments
  1516. * @subsubsection bx_payment-get_cart_items get_cart_items
  1517. *
  1518. * @code bx_srv('bx_payment', 'get_cart_items', [...]); @endcode
  1519. *
  1520. * Get an array with prodicts' descriptions by seller. Is used in Manual Order Processing in payments processing module.
  1521. *
  1522. * @param $iCommissionaireId commissionaire ID.
  1523. * @return an array with prodicts' descriptions. Empty array is returned if something is wrong or seller doesn't have any products.
  1524. *
  1525. * @see BxPaymentModule::serviceGetCartItems
  1526. */
  1527. /**
  1528. * @ref bx_payment-get_cart_items "get_cart_items"
  1529. */
  1530. public function serviceGetCartItems($iCommissionaireId)
  1531. {
  1532. $CNF = &$this->_oConfig->CNF;
  1533. $iCommissionaireId = (int)$iCommissionaireId;
  1534. if(empty($iCommissionaireId))
  1535. return array();
  1536. $sCommissionaireName = BxDolProfile::getInstanceMagic($iCommissionaireId)->getDisplayName();
  1537. $aItems = $this->_oDb->getInvoices(array('type' => 'commissionaire_id', 'commissionaire_id' => $iCommissionaireId));
  1538. $aResult = array();
  1539. foreach($aItems as $aItem)
  1540. $aResult[] = array(
  1541. 'id' => $aItem['id'],
  1542. 'author_id' => $aItem['commissionaire_id'],
  1543. 'name' => $aItem['name'],
  1544. 'title' => _t('_bx_payment_txt_invoice_title', $aItem['name'], $sCommissionaireName),
  1545. '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)),
  1546. 'url' => '',
  1547. 'price_single' => $aItem['amount'],
  1548. 'price_recurring' => '',
  1549. 'period_recurring' => 0,
  1550. 'period_unit_recurring' => '',
  1551. 'trial_recurring' => ''
  1552. );
  1553. return $aResult;
  1554. }
  1555. /**
  1556. * @page service Service Calls
  1557. * @section bx_payment Payment
  1558. * @subsection bx_payment-payments Payments
  1559. * @subsubsection bx_payment-register_cart_item register_cart_item
  1560. *
  1561. * @code bx_srv('bx_payment', 'register_cart_item', [...]); @endcode
  1562. *
  1563. * Register a processed single time payment inside the Payment module. Is called with payment processing module after the payment was registered there.
  1564. *
  1565. * @param $iClientId client ID.
  1566. * @param $iSellerId seller ID
  1567. * @param $iItemId item ID.
  1568. * @param $iItemCount the number of purchased items.
  1569. * @param $sOrder order number received from payment provider (PayPal, Stripe, etc)
  1570. * @param $sLicense license number genereted with payment processing module for internal usage
  1571. * @return an array with purchased prodict's description. Empty array is returned if something is wrong.
  1572. *
  1573. * @see BxPaymentModule::serviceRegisterCartItem
  1574. */
  1575. /**
  1576. * @ref bx_payment-register_cart_item "register_cart_item"
  1577. */
  1578. public function serviceRegisterCartItem($iClientId, $iSellerId, $iItemId, $iItemCount, $sOrder, $sLicense)
  1579. {
  1580. $CNF = &$this->_oConfig->CNF;
  1581. $aItem = $this->serviceGetCartItem($iItemId);
  1582. if(empty($aItem) || !is_array($aItem))
  1583. return array();
  1584. if(!$this->_oDb->updateInvoice($iItemId, array('status' => BX_PAYMENT_INV_STATUS_PAID)))
  1585. return array();
  1586. $this->alert('invoice_marked_as_paid', 0, false, array(
  1587. 'product_id' => $iItemId,
  1588. 'profile_id' => $iClientId,
  1589. 'order' => $sOrder,
  1590. 'license' => $sLicense,
  1591. 'type' => BX_PAYMENT_TYPE_SINGLE,
  1592. 'count' => $iItemCount,
  1593. 'duration' => '',
  1594. 'trial' => ''
  1595. ));
  1596. return $aItem;
  1597. }
  1598. /**
  1599. * @page service Service Calls
  1600. * @section bx_payment Payment
  1601. * @subsection bx_payment-payments Payments
  1602. * @subsubsection bx_payment-unregister_cart_item unregister_cart_item
  1603. *
  1604. * @code bx_srv('bx_payment', 'unregister_cart_item', [...]); @endcode
  1605. *
  1606. * Unregister an earlier processed single time payment inside the Payment module. Is called with payment processing module after the payment was unregistered there.
  1607. *
  1608. * @param $iClientId client ID.
  1609. * @param $iSellerId seller ID
  1610. * @param $iItemId item ID.
  1611. * @param $iItemCount the number of purchased items.
  1612. * @param $sOrder order number received from payment provider (PayPal, Stripe, etc)
  1613. * @param $sLicense license number genereted with payment processing module for internal usage
  1614. * @return boolean value determining where the payment was unregistered or not.
  1615. *
  1616. * @see BxPaymentModule::serviceUnregisterCartItem
  1617. */
  1618. /**
  1619. * @ref bx_payment-unregister_cart_item "unregister_cart_item"
  1620. */
  1621. public function serviceUnregisterCartItem($iClientId, $iSellerId, $iItemId, $iItemCount, $sOrder, $sLicense)
  1622. {
  1623. if(!$this->_oDb->updateInvoice($iItemId, array('status' => BX_PAYMENT_INV_STATUS_UNPAID)))
  1624. return false;
  1625. $this->alert('invoice_marked_as_unpaid', 0, false, array(
  1626. 'product_id' => $iItemId,
  1627. 'profile_id' => $iClientId,
  1628. 'order' => $sOrder,
  1629. 'license' => $sLicense,
  1630. 'type' => BX_PAYMENT_TYPE_SINGLE,
  1631. 'count' => $iItemCount
  1632. ));
  1633. return true;
  1634. }
  1635. public function serviceConvert($fAmount, $sCurrencyFrom, $sCurrencyTo, $fRate = false)
  1636. {
  1637. $sCurrencyDefault = $this->_oConfig->getDefaultCurrencyCode();
  1638. $bFromDefault = strcmp($sCurrencyFrom, $sCurrencyDefault) == 0;
  1639. $bToDefault = strcmp($sCurrencyTo, $sCurrencyDefault) == 0;
  1640. if(!$bFromDefault && !$bToDefault)
  1641. return false;
  1642. if($fRate === false)
  1643. $fRate = $this->_oDb->getCurrencyExchangeRate($bFromDefault ? $sCurrencyTo : $sCurrencyFrom);
  1644. if($fRate === false)
  1645. return false;
  1646. $fRate = (float)$fRate;
  1647. if($bToDefault)
  1648. $fRate = 1/$fRate;
  1649. return $fAmount * $fRate;
  1650. }
  1651. public function updateCurrencyExchangeRates()
  1652. {
  1653. $CNF = &$this->_oConfig->CNF;
  1654. $sApiKey = getParam($CNF['PARAM_CURRENCY_EXCHANGE_API']);
  1655. if(empty($sApiKey))
  1656. return;
  1657. $sCurrency = $this->_oDb->getParam($CNF['PARAM_CURRENCY_CODE'], false);
  1658. $aCurrencies = BxDolForm::getDataItems($CNF['OBJECT_FORM_PRELISTS_CURRENCIES'], false, BX_DATA_VALUES_ADDITIONAL);
  1659. unset($aCurrencies[$sCurrency]);
  1660. $sApiEndpoint = 'https://api.apilayer.com/exchangerates_data/latest';
  1661. $aApiParams = [
  1662. 'symbols' => implode(',', array_keys($aCurrencies)),
  1663. 'base' => $sCurrency
  1664. ];
  1665. $sResponse = bx_file_get_contents($sApiEndpoint, $aApiParams, 'get', [
  1666. 'apikey: ' . $sApiKey
  1667. ]);
  1668. $aResponse = json_decode($sResponse, true);
  1669. if(empty($aResponse['rates']) || !is_array($aResponse['rates']))
  1670. return;
  1671. $this->_oDb->deleteCurrencyExchangeRate($sCurrency);
  1672. foreach($aResponse['rates'] as $sCode => $fRate)
  1673. $this->_oDb->updateCurrencyExchangeRate($sCode, $fRate);
  1674. }
  1675. }
  1676. /** @} */