BxPaymentModule.php 79 KB

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