BxStripeConnectModule.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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(BX_DIRECTORY_PATH_PLUGINS . 'stripe/init.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 BxBaseModConnectModule
  17. {
  18. function __construct(&$aModule)
  19. {
  20. parent::__construct($aModule);
  21. $this->_oConfig->init($this->_oDb);
  22. }
  23. /**
  24. * @page service Service Calls
  25. * @section bx_stripe_connect Stripe Connect
  26. * @subsection bx_stripe_connect-other Other
  27. * @subsubsection bx_stripe_connect-get_options_mode get_options_mode
  28. *
  29. * @code bx_srv('bx_stripe_connect', 'get_options_mode', [...]); @endcode
  30. *
  31. * Get an array with available modes. Is used in forms.
  32. *
  33. * @return an array with available modes represented as key => value pairs.
  34. *
  35. * @see BxStripeConnectModule::serviceGetOptionsMode
  36. */
  37. /**
  38. * @ref bx_stripe_connect-get_options_mode "get_options_mode"
  39. */
  40. public function serviceGetOptionsMode()
  41. {
  42. return array(
  43. BX_STRIPE_CONNECT_MODE_LIVE => _t('_bx_stripe_connect_option_mode_live'),
  44. BX_STRIPE_CONNECT_MODE_TEST => _t('_bx_stripe_connect_option_mode_test'),
  45. );
  46. }
  47. /**
  48. * @page service Service Calls
  49. * @section bx_stripe_connect Stripe Connect
  50. * @subsection bx_stripe_connect-other Other
  51. * @subsubsection bx_stripe_connect-get_options_api_scope get_options_api_scope
  52. *
  53. * @code bx_srv('bx_stripe_connect', 'get_options_api_scope', [...]); @endcode
  54. *
  55. * Get an array with available API scopes. Is used in forms.
  56. *
  57. * @return an array with available scopes represented as key => value pairs.
  58. *
  59. * @see BxStripeConnectModule::serviceGetOptionsApiScope
  60. */
  61. /**
  62. * @ref bx_stripe_connect-get_options_api_scope "get_options_api_scope"
  63. */
  64. public function serviceGetOptionsApiScope()
  65. {
  66. return array(
  67. 'read_only' => _t('_bx_stripe_connect_option_api_scope_read_only'),
  68. 'read_write' => _t('_bx_stripe_connect_option_api_scope_read_write'),
  69. );
  70. }
  71. /**
  72. * @page service Service Calls
  73. * @section bx_stripe_connect Stripe Connect
  74. * @subsection bx_stripe_connect-other Other
  75. * @subsubsection bx_stripe_connect-get_options_pmode_single get_options_pmode_single
  76. *
  77. * @code bx_srv('bx_stripe_connect', 'get_options_pmode_single', [...]); @endcode
  78. *
  79. * Get an array with available processing modes for single time payments. Is used in forms.
  80. *
  81. * @return an array with available modes represented as key => value pairs.
  82. *
  83. * @see BxStripeConnectModule::serviceGetOptionsPmodeSingle
  84. */
  85. /**
  86. * @ref bx_stripe_connect-get_options_pmode_single "get_options_pmode_single"
  87. */
  88. public function serviceGetOptionsPmodeSingle()
  89. {
  90. return array(
  91. BX_STRIPE_CONNECT_PMODE_DIRECT => _t('_bx_stripe_connect_option_pmode_direct'),
  92. BX_STRIPE_CONNECT_PMODE_PLATFORM => _t('_bx_stripe_connect_option_pmode_platform'),
  93. );
  94. }
  95. /**
  96. * @page service Service Calls
  97. * @section bx_stripe_connect Stripe Connect
  98. * @subsection bx_stripe_connect-other Other
  99. * @subsubsection bx_stripe_connect-get_options_pmode_recurring get_options_pmode_recurring
  100. *
  101. * @code bx_srv('bx_stripe_connect', 'get_options_pmode_recurring', [...]); @endcode
  102. *
  103. * Get an array with available processing modes for recurring payments. Is used in forms.
  104. * Note. Subscriptions (recurring payments) do not currently support the Platform mode.
  105. *
  106. * @return an array with available modes represented as key => value pairs.
  107. *
  108. * @see BxStripeConnectModule::serviceGetOptionsPmodeRecurring
  109. */
  110. /**
  111. * @ref bx_stripe_connect-get_options_pmode_recurring "get_options_pmode_recurring"
  112. */
  113. public function serviceGetOptionsPmodeRecurring()
  114. {
  115. return array(
  116. BX_STRIPE_CONNECT_PMODE_DIRECT => _t('_bx_stripe_connect_option_pmode_direct'),
  117. );
  118. }
  119. /**
  120. * @page service Service Calls
  121. * @section bx_stripe_connect Stripe Connect
  122. * @subsection bx_stripe_connect-page_blocks Page Blocks
  123. * @subsubsection bx_stripe_connect-get_block_connect get_block_connect
  124. *
  125. * @code bx_srv('bx_stripe_connect', 'get_block_connect', [...]); @endcode
  126. *
  127. * Get page block with necessary info and actions to connect/disconnect.
  128. *
  129. * @return HTML string with block content to display on the site, all necessary CSS and JS files are automatically added to the HEAD section of the site HTML.
  130. *
  131. * @see BxStripeConnectModule::serviceGetBlockConnect
  132. */
  133. /**
  134. * @ref bx_stripe_connect-get_block_connect "get_block_connect"
  135. */
  136. public function serviceGetBlockConnect()
  137. {
  138. return $this->_oTemplate->displayBlockConnect();
  139. }
  140. public function actionDelete()
  141. {
  142. $sError = _t('_bx_stripe_connect_err_perform');
  143. $iId = (int)bx_get('id');
  144. if(empty($iId))
  145. return echoJson(array('code' => 1, 'message' => $sError));
  146. if(!$this->deleteAccount($iId))
  147. return echoJson(array('code' => 2, 'message' => $sError));
  148. echoJson(array('code' => 0, 'id' => $iId, 'reload' => 1));
  149. }
  150. public function actionResult()
  151. {
  152. if(bx_get('error') !== false)
  153. $this->_oTemplate->displayErrorOccured(bx_process_input(bx_get('error_description')));
  154. $mixedResult = $this->createAccount(bx_process_input(bx_get('code')));
  155. if($mixedResult !== true)
  156. $this->_oTemplate->displayErrorOccured($mixedResult);
  157. $this->_oTemplate->displayMsg('_bx_stripe_connect_msg_connected', true);
  158. }
  159. public function actionNotify()
  160. {
  161. $iResult = $this->_processEvent();
  162. http_response_code($iResult);
  163. }
  164. public function createAccount($sCode)
  165. {
  166. $CNF = $this->_oConfig->CNF;
  167. $oResult = $this->_request($CNF['URL_API_TOKEN'], array(
  168. 'client_secret' => $this->_oConfig->getApiSecretKey(),
  169. 'code' => $sCode,
  170. 'grant_type' => 'authorization_code'
  171. ));
  172. if(!empty($oResult->error))
  173. return bx_process_input($oResult->error_description);
  174. $bResult = $this->_oDb->insertAccount(array(
  175. 'author' => bx_get_logged_profile_id(),
  176. 'added' => time(),
  177. 'user_id' => $oResult->stripe_user_id,
  178. 'public_key' => $oResult->stripe_publishable_key,
  179. 'access_token' => $oResult->access_token,
  180. 'refresh_token' => $oResult->refresh_token
  181. ));
  182. return $bResult ? $bResult : _t('_bx_stripe_connect_err_perform');
  183. }
  184. public function deleteAccount($iId)
  185. {
  186. $CNF = $this->_oConfig->CNF;
  187. $aAccount = $this->_oDb->getAccount(array('type' => 'id', 'id' => $iId));
  188. if(empty($aAccount) || !is_array($aAccount))
  189. return false;
  190. $oResult = $this->_request($CNF['URL_API_DEAUTHORIZE'], array(
  191. 'client_id' => $this->_oConfig->getApiId(),
  192. 'client_secret' => $this->_oConfig->getApiSecretKey(),
  193. 'stripe_user_id' => $aAccount['user_id'],
  194. ));
  195. if(!empty($oResult->error))
  196. return false;
  197. return $this->_oDb->deleteAccount(array('id' => $iId));
  198. }
  199. public function processAlertStripeGetButton($iObject, $iSender, $aParams)
  200. {
  201. if(empty($aParams['type']))
  202. return false;
  203. $sType = $aParams['type'];
  204. $sPayMode = $this->_oConfig->getPayMode($sType);
  205. switch($sType) {
  206. case BX_PAYMENT_TYPE_SINGLE:
  207. if($sPayMode == BX_STRIPE_CONNECT_PMODE_PLATFORM)
  208. $aParams['public_key'] = $this->_oConfig->getApiPublicKey();
  209. break;
  210. case BX_PAYMENT_TYPE_RECURRING:
  211. //TODO: Perform necessary actions here !WHEN! 'Platform' mode will be available for recurring payments.
  212. break;
  213. }
  214. return !empty($aParams['public_key']);
  215. }
  216. public function processAlertStripeCreateCustomer($iObject, $iSender, $aParams)
  217. {
  218. if(empty($aParams['type']) || empty($aParams['customer_params']['card']))
  219. return false;
  220. $sPayMode = $this->_oConfig->getPayMode($aParams['type']);
  221. try {
  222. switch($sPayMode) {
  223. case BX_STRIPE_CONNECT_PMODE_DIRECT:
  224. /*
  225. * Do nothing in this case because a Customer
  226. * should be created in Connected Stripe account.
  227. */
  228. break;
  229. case BX_STRIPE_CONNECT_PMODE_PLATFORM:
  230. \Stripe\Stripe::setApiKey($this->_oConfig->getApiSecretKey());
  231. $aParams['customer_object'] = \Stripe\Customer::create($aParams['customer_params']);
  232. break;
  233. }
  234. }
  235. catch (Exception $oException) {
  236. $aParams['customer_object'] = null;
  237. return $this->_processException('Create Customer Error: ', $oException);
  238. }
  239. return !empty($aParams['customer_object']);
  240. }
  241. public function processAlertStripeRetrieveCustomer($iObject, $iSender, $aParams)
  242. {
  243. if(empty($aParams['type']) || empty($aParams['customer_id']))
  244. return false;
  245. $sPayMode = $this->_oConfig->getPayMode($aParams['type']);
  246. try {
  247. switch($sPayMode) {
  248. case BX_STRIPE_CONNECT_PMODE_DIRECT:
  249. /*
  250. * Do nothing in this case because a Customer
  251. * should be retreived from Connected Stripe account.
  252. */
  253. break;
  254. case BX_STRIPE_CONNECT_PMODE_PLATFORM:
  255. \Stripe\Stripe::setApiKey($this->_oConfig->getApiSecretKey());
  256. $aParams['customer_object'] = \Stripe\Customer::retrieve($aParams['customer_id']);
  257. break;
  258. }
  259. }
  260. catch (Exception $oException) {
  261. $aParams['customer_object'] = null;
  262. return $this->_processException('Retrieve Customer Error: ', $oException);
  263. }
  264. return !empty($aParams['customer_object']);
  265. }
  266. public function processAlertStripeCreateCharge($iObject, $iSender, $aParams)
  267. {
  268. if(empty($iObject) || empty($aParams['charge_params']['amount']))
  269. return false;
  270. $aAccount = $this->_getAccount($iObject, BX_PAYMENT_TYPE_SINGLE);
  271. if($aAccount === false)
  272. return false;
  273. $sPayMode = $this->_oConfig->getPayMode(BX_PAYMENT_TYPE_SINGLE);
  274. $aParams['charge_params']['application_fee'] = $this->_oConfig->getFee(BX_PAYMENT_TYPE_SINGLE, (float)$aParams['charge_params']['amount']);
  275. \Stripe\Stripe::setApiKey($this->_oConfig->getApiSecretKey());
  276. try {
  277. switch($sPayMode) {
  278. case BX_STRIPE_CONNECT_PMODE_DIRECT:
  279. $aParams['charge_object'] = \Stripe\Charge::create($aParams['charge_params'], array('stripe_account' => $aAccount['user_id']));
  280. break;
  281. case BX_STRIPE_CONNECT_PMODE_PLATFORM:
  282. $aParams['charge_params']['destination'] = $aAccount['user_id'];
  283. $aParams['charge_object'] = \Stripe\Charge::create($aParams['charge_params']);
  284. break;
  285. }
  286. }
  287. catch (Exception $oException) {
  288. $aParams['charge_object'] = null;
  289. return $this->_processException('Create Charge Error: ', $oException);
  290. }
  291. return !empty($aParams['charge_object']);
  292. }
  293. public function processAlertStripeRetrieveCharge($iObject, $iSender, $aParams)
  294. {
  295. if(empty($aParams['charge_id']))
  296. return false;
  297. $sPayMode = $this->_oConfig->getPayMode(BX_PAYMENT_TYPE_SINGLE);
  298. try {
  299. switch($sPayMode) {
  300. case BX_STRIPE_CONNECT_PMODE_DIRECT:
  301. /*
  302. * Do nothing in this case because a Charge
  303. * should be stored on Connected Stripe account.
  304. */
  305. break;
  306. case BX_STRIPE_CONNECT_PMODE_PLATFORM:
  307. \Stripe\Stripe::setApiKey($this->_oConfig->getApiSecretKey());
  308. $aParams['charge_object'] = \Stripe\Charge::retrieve($aParams['charge_id']);
  309. break;
  310. }
  311. }
  312. catch (Exception $oException) {
  313. $aParams['charge_object'] = null;
  314. return $this->_processException('Retrieve Customer Error: ', $oException);
  315. }
  316. return !empty($aParams['charge_object']);
  317. }
  318. public function processAlertStripeCreateSubscription($iObject, $iSender, $aParams)
  319. {
  320. if(empty($iObject) || empty($aParams['subscription_params']['plan']))
  321. return false;
  322. $aAccount = $this->_getAccount($iObject, BX_PAYMENT_TYPE_RECURRING);
  323. if($aAccount === false)
  324. return false;
  325. $aParams['subscription_params']['application_fee_percent'] = $this->_oConfig->getFee(BX_PAYMENT_TYPE_RECURRING);
  326. \Stripe\Stripe::setApiKey($this->_oConfig->getApiSecretKey());
  327. try {
  328. $aParams['subscription_object'] = $aParams['customer']->subscriptions->create($aParams['subscription_params'], array('stripe_account' => $aAccount['user_id']));
  329. }
  330. catch (Exception $oException) {
  331. $aParams['subscription_object'] = null;
  332. return $this->_processException('Create Subscription Error: ', $oException);
  333. }
  334. return !empty($aParams['subscription_object']);
  335. }
  336. protected function _request($sUrl, $aParams = array())
  337. {
  338. $sResult = '';
  339. if(!function_exists('curl_init'))
  340. return false;
  341. $rConnect = curl_init();
  342. curl_setopt($rConnect, CURLOPT_URL, $sUrl);
  343. curl_setopt($rConnect, CURLOPT_HEADER, 0);
  344. curl_setopt($rConnect, CURLOPT_RETURNTRANSFER, 1);
  345. curl_setopt($rConnect, CURLOPT_FOLLOWLOCATION, 1);
  346. curl_setopt($rConnect, CURLOPT_POST, 1);
  347. curl_setopt($rConnect, CURLOPT_POSTFIELDS, http_build_query($aParams));
  348. if(bx_mb_strpos($sUrl, 'https') !== false) {
  349. curl_setopt($rConnect, CURLOPT_SSL_VERIFYPEER, 0);
  350. curl_setopt($rConnect, CURLOPT_SSL_VERIFYHOST, 0);
  351. }
  352. $sResult = curl_exec($rConnect);
  353. curl_close($rConnect);
  354. return json_decode($sResult);
  355. }
  356. protected function _processEvent()
  357. {
  358. $sInput = @file_get_contents("php://input");
  359. $aEvent = json_decode($sInput, true);
  360. if(empty($aEvent) || !is_array($aEvent))
  361. return 404;
  362. $sType = $aEvent['type'];
  363. if(!in_array($sType, array('account.application.deauthorized')))
  364. return 200;
  365. $this->_log('Webhooks: ' . (!empty($sType) ? $sType : ''));
  366. $this->_log($aEvent);
  367. $sMethod = '_processEvent' . bx_gen_method_name($sType, array('.', '_', '-'));
  368. if(!method_exists($this, $sMethod))
  369. return 200;
  370. return $this->$sMethod($aEvent) ? 200 : 403;
  371. }
  372. protected function _processEventAccountApplicationDeauthorized(&$aEvent)
  373. {
  374. $CNF = $this->_oConfig->CNF;
  375. $sApiId = bx_process_input($aEvent['data']['object']['id']);
  376. if(strcmp($sApiId, $this->_oConfig->getApiId()) != 0)
  377. return false;
  378. $sUserId = bx_process_input($aEvent['user_id']);
  379. if(empty($sUserId))
  380. return false;
  381. return $this->_oDb->deleteAccount(array('user_id' => $sUserId));
  382. }
  383. protected function _processException($sMessage, &$oException)
  384. {
  385. $aError = $oException->getJsonBody();
  386. $sMessage = $aError['error']['message'];
  387. if(empty($sMessage))
  388. $sMessage = $oException->getMessage();
  389. $this->_log($sMessage . $aError['error']['message']);
  390. $this->_log($aError);
  391. return false;
  392. }
  393. protected function _getAccount($iPending, $sType)
  394. {
  395. $aPending = BxDolPayments::getInstance()->getPendingOrdersInfo(array('id' => $iPending));
  396. if(!empty($aPending) && is_array($aPending) && count($aPending) == 1)
  397. $aPending = array_shift($aPending);
  398. if(empty($aPending) || !is_array($aPending) || $aPending['type'] != $sType)
  399. return false;
  400. $iSeller = (int)$aPending['seller_id'];
  401. $oSeller = BxDolProfile::getInstance($iSeller);
  402. if(!$oSeller)
  403. return false;
  404. $aAccount = $this->_oDb->getAccount(array('type' => 'author', 'author' => $iSeller));
  405. if(empty($aAccount) || !is_array($aAccount))
  406. return false;
  407. return $aAccount;
  408. }
  409. protected function _log($sContents)
  410. {
  411. try {
  412. $sFile = $this->_oConfig->getLogFile();
  413. if(empty($sFile))
  414. $sFile = dirname(__FILE__) . "/bx_stripe_connect.log";
  415. file_put_contents($sFile, date('m-d H:i:s') . ": ", FILE_APPEND);
  416. if (is_array($sContents))
  417. $sContents = var_export($sContents, true);
  418. else if (is_object($sContents))
  419. $sContents = json_encode($sContents);
  420. file_put_contents($sFile, $sContents . "\n", FILE_APPEND);
  421. }
  422. catch (Exception $oException) {
  423. echo "Error: " . $oException->getMessage();
  424. }
  425. }
  426. }
  427. /** @} */