BxPaymentModule.php 82 KB

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