BxPaymentModule.php 84 KB

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