BxPaymentModule.php 81 KB

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