BxStripeConnectModule.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 StripeConnect Stripe Connect
  7. * @ingroup TridentModules
  8. *
  9. * @{
  10. */
  11. require_once('BxStripeConnectApi.php');
  12. define('BX_STRIPE_CONNECT_MODE_LIVE', 'live');
  13. define('BX_STRIPE_CONNECT_MODE_TEST', 'test');
  14. define('BX_STRIPE_CONNECT_PMODE_DIRECT', 'direct');
  15. define('BX_STRIPE_CONNECT_PMODE_PLATFORM', 'platform');
  16. class BxStripeConnectModule extends BxBaseModGeneralModule
  17. {
  18. public function __construct(&$aModule)
  19. {
  20. parent::__construct($aModule);
  21. $this->_oConfig->init($this->_oDb);
  22. }
  23. /**
  24. *
  25. * SERVICE METHODS
  26. *
  27. */
  28. public function serviceGetSafeServices()
  29. {
  30. return array_merge(parent::serviceGetSafeServices(), [
  31. 'AccountSessionCreate' => '',
  32. 'AccountCreate' => '',
  33. 'AccountContinue' => '',
  34. 'AccountDelete' => ''
  35. ]);
  36. }
  37. public function serviceAccountCreate($iId)
  38. {
  39. $CNF = &$this->_oConfig->CNF;
  40. $sError = _t('_bx_stripe_connect_err_perform');
  41. if(empty($iId) || $iId != bx_get_logged_profile_id())
  42. return ['code' => 1, 'message' => $sError];
  43. $oProfile = BxDolProfile::getInstance($iId);
  44. if(!$oProfile)
  45. return ['code' => 1, 'message' => $sError];
  46. $sAccIdField = $CNF['FIELD_' . strtoupper($this->_oConfig->getMode()) . '_ACCOUNT_ID'];
  47. $oApi = BxStripeConnectApi::getInstance();
  48. $oAccount = $oApi->createAccount($oProfile->getAccountObject()->getEmail());
  49. if(!$oAccount)
  50. return ['code' => 1, 'message' => $sError];
  51. $aAccount = $this->_oDb->getAccount(['sample' => 'profile_id', 'profile_id' => $iId]);
  52. if($aAccount && is_array($aAccount))
  53. $this->_oDb->updateAccount([
  54. $sAccIdField => $oAccount->id
  55. ], ['profile_id' => $iId]);
  56. else
  57. $this->_oDb->insertAccount([
  58. 'profile_id' => $iId,
  59. $sAccIdField => $oAccount->id
  60. ]);
  61. $sRefreshLink = $this->_oConfig->getRefreshLink();
  62. $sReturnLink = $this->_oConfig->getReturnLink();
  63. $oAccountLink = $oApi->createAccountLinks($oAccount->id, $sRefreshLink, $sReturnLink);
  64. if(!$oAccountLink)
  65. return ['code' => 1, 'message' => $sError];
  66. return ['code' => 0, 'redirect' => $oAccountLink->url];
  67. }
  68. public function serviceAccountContinue($iId)
  69. {
  70. $CNF = &$this->_oConfig->CNF;
  71. $sError = _t('_bx_stripe_connect_err_perform');
  72. if(empty($iId) || $iId != bx_get_logged_profile_id())
  73. return ['code' => 1, 'message' => $sError];
  74. $sModeUc = strtoupper($this->_oConfig->getMode());
  75. $sAccIdField = $CNF['FIELD_' . $sModeUc . '_ACCOUNT_ID'];
  76. $sAccDetailsField = $CNF['FIELD_' . $sModeUc . '_DETAILS'];
  77. $aAccount = $this->_oDb->getAccount(['sample' => 'profile_id', 'profile_id' => $iId]);
  78. if(empty($aAccount) || !is_array($aAccount) || $aAccount[$sAccIdField] == '')
  79. return ['code' => 1, 'message' => $sError];
  80. if((int)$aAccount[$sAccDetailsField] != 0)
  81. return ['code' => 0];
  82. $sRefreshLink = $this->_oConfig->getRefreshLink();
  83. $sReturnLink = $this->_oConfig->getReturnLink();
  84. $oAccountLink = BxStripeConnectApi::getInstance()->createAccountLinks($aAccount[$sAccIdField], $sRefreshLink, $sReturnLink);
  85. if(!$oAccountLink)
  86. return ['code' => 1, 'message' => $sError];
  87. return ['code' => 0, 'redirect' => $oAccountLink->url];
  88. }
  89. public function serviceAccountDelete($iId)
  90. {
  91. $CNF = &$this->_oConfig->CNF;
  92. $sError = _t('_bx_stripe_connect_err_perform');
  93. if(empty($iId) || $iId != bx_get_logged_profile_id())
  94. return ['code' => 1, 'message' => $sError];
  95. $aAccount = $this->_oDb->getAccount(['sample' => 'profile_id', 'profile_id' => $iId]);
  96. if(empty($aAccount) || !is_array($aAccount))
  97. return ['code' => 1, 'message' => $sError];
  98. $sAccIdField = $CNF['FIELD_' . strtoupper($this->_oConfig->getMode()) . '_ACCOUNT_ID'];
  99. $oAccount = BxStripeConnectApi::getInstance()->deleteAccount($aAccount[$sAccIdField]);
  100. if(!$oAccount || !$oAccount->deleted)
  101. return ['code' => 2, 'message' => _t('_bx_stripe_connect_err_delete')];
  102. $this->_oDb->deleteAccount([
  103. 'profile_id' => $iId,
  104. $sAccIdField => $oAccount->id
  105. ]);
  106. return ['code' => 0, 'reload' => 1];
  107. }
  108. public function serviceAccountSessionCreate($iProfileId)
  109. {
  110. $CNF = &$this->_oConfig->CNF;
  111. if(!$iProfileId || ($iProfileId != $this->_iProfileId && !isAdmin()))
  112. $iProfileId = $this->_iProfileId;
  113. if(!$iProfileId)
  114. return ['code' => 1];
  115. $sModeUc = strtoupper($this->_oConfig->getMode());
  116. $sAccIdField = $CNF['FIELD_' . $sModeUc . '_ACCOUNT_ID'];
  117. $aAccount = $this->_oDb->getAccount(['sample' => 'profile_id', 'profile_id' => $iProfileId]);
  118. if(empty($aAccount) || !is_array($aAccount) || $aAccount[$sAccIdField] == '')
  119. return ['code' => 1];
  120. $oAccountSession = BxStripeConnectApi::getInstance()->createAccountSessions($aAccount[$sAccIdField]);
  121. if(!$oAccountSession)
  122. return ['code' => 1];
  123. return [
  124. 'code' => 0,
  125. 'secret' => $oAccountSession->client_secret
  126. ];
  127. }
  128. /**
  129. * @page service Service Calls
  130. * @section bx_stripe_connect Stripe Connect
  131. * @subsection bx_stripe_connect-other Other
  132. * @subsubsection bx_stripe_connect-get_options_mode get_options_mode
  133. *
  134. * @code bx_srv('bx_stripe_connect', 'get_options_mode', [...]); @endcode
  135. *
  136. * Get an array with available modes. Is used in forms.
  137. *
  138. * @return an array with available modes represented as key => value pairs.
  139. *
  140. * @see BxStripeConnectModule::serviceGetOptionsMode
  141. */
  142. /**
  143. * @ref bx_stripe_connect-get_options_mode "get_options_mode"
  144. */
  145. public function serviceGetOptionsMode()
  146. {
  147. return [
  148. BX_STRIPE_CONNECT_MODE_LIVE => _t('_bx_stripe_connect_option_mode_live'),
  149. BX_STRIPE_CONNECT_MODE_TEST => _t('_bx_stripe_connect_option_mode_test'),
  150. ];
  151. }
  152. /**
  153. * @page service Service Calls
  154. * @section bx_stripe_connect Stripe Connect
  155. * @subsection bx_stripe_connect-other Other
  156. * @subsubsection bx_stripe_connect-get_options_pmode get_options_pmode
  157. *
  158. * @code bx_srv('bx_stripe_connect', 'get_options_pmode', [...]); @endcode
  159. *
  160. * Get an array with available processing modes for payments. Is used in forms.
  161. *
  162. * @return an array with available modes represented as key => value pairs.
  163. *
  164. * @see BxStripeConnectModule::serviceGetOptionsPmode
  165. */
  166. /**
  167. * @ref bx_stripe_connect-get_options_pmode "get_options_pmode"
  168. */
  169. public function serviceGetOptionsPmode()
  170. {
  171. return [
  172. BX_STRIPE_CONNECT_PMODE_DIRECT => _t('_bx_stripe_connect_option_pmode_direct'),
  173. //BX_STRIPE_CONNECT_PMODE_PLATFORM => _t('_bx_stripe_connect_option_pmode_platform'),
  174. ];
  175. }
  176. public function serviceGetOptionValueMode($iVendorId, $aParams = [])
  177. {
  178. return _t('_bx_stripe_connect_option_mode_' . $this->_oConfig->getMode());
  179. }
  180. public function serviceGetOptionValueLiveAccountId($iVendorId, $aParams = [])
  181. {
  182. $CNF = &$this->_oConfig->CNF;
  183. $aAccount = $this->_oDb->getAccount(['sample' => 'profile_id', 'profile_id' => $iVendorId]);
  184. if(empty($aAccount) || !is_array($aAccount))
  185. return '';
  186. return $aAccount[$CNF['FIELD_LIVE_ACCOUNT_ID']];
  187. }
  188. public function serviceGetOptionValueTestAccountId($iVendorId, $aParams = [])
  189. {
  190. $CNF = &$this->_oConfig->CNF;
  191. $aAccount = $this->_oDb->getAccount(['sample' => 'profile_id', 'profile_id' => $iVendorId]);
  192. if(empty($aAccount) || !is_array($aAccount))
  193. return '';
  194. return $aAccount[$CNF['FIELD_TEST_ACCOUNT_ID']];
  195. }
  196. public function serviceGetConnectCode($iVendorId, $aParams = [])
  197. {
  198. return $this->_oTemplate->getConnectCode($iVendorId, $aParams);
  199. }
  200. public function serviceGetBlockPayments()
  201. {
  202. if(!isLogged())
  203. return $this->_bIsApi ? [] : '';
  204. if($this->_bIsApi)
  205. return [bx_api_get_block('stripe_connect', [
  206. 'key' => $this->_oConfig->getApiPublicKey(),
  207. 'embed' => 'payments'
  208. ])];
  209. return $this->_oTemplate->getBlockPayments();
  210. }
  211. /*
  212. * Isn't supported with the current SDK. It's still in Beta mode.
  213. * https://docs.stripe.com/connect/supported-embedded-components/reporting-chart
  214. */
  215. public function serviceGetBlockReportingChart()
  216. {
  217. if(!isLogged())
  218. return $this->_bIsApi ? [] : '';
  219. if($this->_bIsApi)
  220. return [bx_api_get_block('stripe_connect', [
  221. 'key' => $this->_oConfig->getApiPublicKey(),
  222. 'embed' => 'reporting-chart'
  223. ])];
  224. return $this->_oTemplate->getBlockReportingChart();
  225. }
  226. public function serviceGetBlockBalances()
  227. {
  228. if(!isLogged())
  229. return $this->_bIsApi ? [] : '';
  230. if($this->_bIsApi)
  231. return [bx_api_get_block('stripe_connect', [
  232. 'key' => $this->_oConfig->getApiPublicKey(),
  233. 'embed' => 'balances'
  234. ])];
  235. return $this->_oTemplate->getBlockBalances();
  236. }
  237. public function serviceGetBlockNotifications()
  238. {
  239. if(!isLogged())
  240. return $this->_bIsApi ? [] : '';
  241. if($this->_bIsApi)
  242. return [bx_api_get_block('stripe_connect', [
  243. 'key' => $this->_oConfig->getApiPublicKey(),
  244. 'embed' => 'notification-banner'
  245. ])];
  246. return $this->_oTemplate->getBlockNotifications();
  247. }
  248. /**
  249. *
  250. * ACTION METHODS
  251. *
  252. */
  253. public function actionNotify()
  254. {
  255. $iResult = $this->_processEvent();
  256. http_response_code($iResult);
  257. }
  258. public function actionAccountCreate()
  259. {
  260. return echoJson($this->serviceAccountCreate((int)bx_get('id')));
  261. }
  262. public function actionAccountContinue()
  263. {
  264. return echoJson($this->serviceAccountContinue((int)bx_get('id')));
  265. }
  266. public function actionAccountDelete()
  267. {
  268. return echoJson($this->serviceAccountDelete((int)bx_get('id')));
  269. }
  270. public function actionAccountSessionCreate($iProfileId)
  271. {
  272. return echoJson($this->serviceAccountSessionCreate($iProfileId));
  273. }
  274. /**
  275. *
  276. * OTHER METHODS
  277. *
  278. */
  279. public function hasAccount($iVendorId)
  280. {
  281. return $this->_oDb->hasAccount($iVendorId, $this->_oConfig->getMode());
  282. }
  283. public function processAlertStripeV3GetButton($iObject, $iSender, $aParams)
  284. {
  285. $CNF = &$this->_oConfig->CNF;
  286. $iVendorId = 0;
  287. if(empty($aParams['vendor_id']) || ($iVendorId = (int)$aParams['vendor_id']) == $this->_oConfig->getMainSeller())
  288. return false;
  289. $sModeUc = strtoupper($this->_oConfig->getMode());
  290. $sAccIdField = $CNF['FIELD_' . $sModeUc . '_ACCOUNT_ID'];
  291. $aAccount = $this->_oDb->getAccount(['sample' => 'profile_id', 'profile_id' => $iVendorId]);
  292. if(empty($aAccount) || !is_array($aAccount) || empty($aAccount[$sAccIdField]))
  293. return false;
  294. $aParams['public_key'] = $this->_oConfig->getApiPublicKey();
  295. $aParams['connected_account_id'] = $aAccount[$sAccIdField];
  296. return !empty($aParams['public_key']);
  297. }
  298. public function processAlertStripeV3CreateSession($iObject, $iSender, $aParams)
  299. {
  300. $CNF = &$this->_oConfig->CNF;
  301. if(empty($aParams['session_params']))
  302. return false;
  303. try {
  304. $sModeUc = strtoupper($this->_oConfig->getMode());
  305. $sAccIdField = $CNF['FIELD_' . $sModeUc . '_ACCOUNT_ID'];
  306. $iVendorId = (int)$aParams['session_params']['metadata']['vendor'];
  307. if($iVendorId == $this->_oConfig->getMainSeller())
  308. return false;
  309. $aAccount = $this->_oDb->getAccount(['sample' => 'profile_id', 'profile_id' => $iVendorId]);
  310. if(empty($aAccount) || !is_array($aAccount) || empty($aAccount[$sAccIdField]))
  311. return false;
  312. switch($aParams['session_params']['mode']) {
  313. case 'payment':
  314. $fAmount = 0;
  315. foreach($aParams['session_params']['line_items'] as $aLineItem)
  316. $fAmount += (float)$aLineItem['price_data']['unit_amount'] * (int)$aLineItem['quantity'];
  317. if($fAmount && ($fAmount = $this->_oConfig->getFee(BX_PAYMENT_TYPE_SINGLE, $iVendorId, $fAmount))) {
  318. if(!isset($aParams['session_params']['payment_intent_data']))
  319. $aParams['session_params']['payment_intent_data'] = [];
  320. $aParams['session_params']['payment_intent_data']['application_fee_amount'] = $fAmount;
  321. }
  322. break;
  323. case 'subscription':
  324. $fAmount = 0;
  325. foreach($aParams['session_params']['line_items'] as $aLineItem)
  326. $fAmount += (float)$aLineItem['price_data']['unit_amount'] * (int)$aLineItem['quantity'];
  327. if($fAmount && ($fAmount = $this->_oConfig->getFee(BX_PAYMENT_TYPE_RECURRING, $iVendorId, $fAmount))) {
  328. if(!isset($aParams['session_params']['subscription_data']))
  329. $aParams['session_params']['subscription_data'] = [];
  330. $aParams['session_params']['subscription_data']['application_fee_percent'] = $fAmount;
  331. }
  332. break;
  333. }
  334. $aParams['session_object'] = BxStripeConnectApi::getInstance()->getStripe()->checkout->sessions->create($aParams['session_params'], [
  335. 'stripe_account' => $aAccount[$sAccIdField]
  336. ]);
  337. }
  338. catch (Exception $oException) {
  339. $aParams['session_object'] = null;
  340. return $this->_processException('Create Session Error: ', $oException);
  341. }
  342. return !empty($aParams['session_object']);
  343. }
  344. protected function _processEvent()
  345. {
  346. $sInput = @file_get_contents("php://input");
  347. $aEvent = json_decode($sInput, true);
  348. if(empty($aEvent) || !is_array($aEvent))
  349. return 404;
  350. $sType = $aEvent['type'];
  351. if(!in_array($sType, ['account.updated']))
  352. return 200;
  353. $this->_log('Webhooks: ' . (!empty($sType) ? $sType : ''));
  354. $this->_log($aEvent);
  355. $sMethod = '_processEvent' . bx_gen_method_name($sType, array('.', '_', '-'));
  356. if(!method_exists($this, $sMethod))
  357. return 200;
  358. return $this->$sMethod($aEvent) ? 200 : 403;
  359. }
  360. protected function _processEventAccountUpdated(&$aEvent)
  361. {
  362. $CNF = $this->_oConfig->CNF;
  363. $sAccountId = '';
  364. if(!isset($aEvent['data']['object']['id']) || !($sAccountId = bx_process_input($aEvent['data']['object']['id'])))
  365. return false;
  366. $sMode = $this->_oConfig->getMode();
  367. $sAccDetailsField = $CNF['FIELD_' . strtoupper($sMode) . '_DETAILS'];
  368. $aAccount = $this->_oDb->getAccount(['sample' => 'account_id', $sMode . '_account_id' => $sAccountId]);
  369. if((int)$aAccount[$sAccDetailsField] == 0 && $aEvent['data']['object']['details_submitted'])
  370. return $this->_oDb->updateAccount([$sAccDetailsField => 1], [$CNF['FIELD_ID'] => $aAccount[$CNF['FIELD_ID']]]);
  371. return true;
  372. }
  373. protected function _processException($sMessage, &$oException)
  374. {
  375. $aError = $oException->getJsonBody();
  376. $sMessage = $aError['error']['message'];
  377. if(empty($sMessage))
  378. $sMessage = $oException->getMessage();
  379. $this->_log($sMessage . $aError['error']['message']);
  380. $this->_log($aError);
  381. return false;
  382. }
  383. protected function _log($sContents)
  384. {
  385. if (is_array($sContents))
  386. $sContents = var_export($sContents, true);
  387. else if (is_object($sContents))
  388. $sContents = json_encode($sContents);
  389. bx_log('bx_stripe_connect', $sContents, BX_LOG_ERR);
  390. }
  391. }
  392. /** @} */