BxPaymentModule.php 87 KB

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