BxPaymentModule.php 82 KB

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