BxPaymentModule.php 84 KB

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