BxPaymentModule.php 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130
  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. if(is_string($aItems))
  938. $aItems = $this->_oConfig->descriptorsM2A($aItems, true);
  939. $mixedResult = $this->serviceInitializeCheckout($sType, $iSellerId, $sProvider, $aItems, $sRedirect, $aCustoms);
  940. if(is_string($mixedResult))
  941. return [bx_api_get_msg($mixedResult)];
  942. if(is_array($mixedResult)) {
  943. if(($sRedirect = $mixedResult['redirect'] ?? false))
  944. return ['url' => $sRedirect];
  945. if(($sMsg = $mixedResult['message'] ?? false))
  946. return [bx_api_get_msg($sMsg)];
  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. /** @} */