BxPaymentModule.php 83 KB

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