BxPaymentProviderStripeBasic.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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('STRP_MODE_LIVE', 1);
  12. define('STRP_MODE_TEST', 2);
  13. class BxPaymentProviderStripeBasic extends BxBaseModPaymentProvider
  14. {
  15. protected $_sFormDetails;
  16. protected $_sFormDisplayDetailsEdit;
  17. protected $_sFormCard;
  18. protected $_sFormDisplayCardAdd;
  19. protected $_iMode;
  20. protected $_bCheckAmount;
  21. protected $_bProrate;
  22. protected $_oCustomer;
  23. function __construct($aConfig)
  24. {
  25. $this->MODULE = 'bx_payment';
  26. parent::__construct($aConfig);
  27. $this->_aSbsStatuses = array(
  28. 'incomplete' => BX_PAYMENT_SBS_STATUS_UNPAID,
  29. 'incomplete_expired' => BX_PAYMENT_SBS_STATUS_UNPAID,
  30. 'trialing' => BX_PAYMENT_SBS_STATUS_TRIAL,
  31. 'active' => BX_PAYMENT_SBS_STATUS_ACTIVE,
  32. 'past_due' => BX_PAYMENT_SBS_STATUS_UNPAID,
  33. 'unpaid' => BX_PAYMENT_SBS_STATUS_UNPAID,
  34. 'canceled' => BX_PAYMENT_SBS_STATUS_CANCELED,
  35. );
  36. $this->_sFormDetails = 'bx_payment_form_strp_details';
  37. $this->_sFormDisplayDetailsEdit = 'bx_payment_form_strp_details_edit';
  38. $this->_sFormCard = 'bx_payment_form_strp_card';
  39. $this->_sFormDisplayCardAdd = 'bx_payment_form_strp_card_add';
  40. $this->_bProrate = false;
  41. $this->_aIncludeJs = array(
  42. 'main.js',
  43. );
  44. $this->_aIncludeCss = array(
  45. 'stripe.css'
  46. );
  47. $this->_oCustomer = null;
  48. \Stripe\Stripe::setApiKey($this->_getSecretKey());
  49. }
  50. public function initOptions($aOptions)
  51. {
  52. parent::initOptions($aOptions);
  53. $this->_iMode = (int)$this->getOption('mode');
  54. $this->_bCheckAmount = $this->getOption('check_amount') == 'on';
  55. $this->_bUseSsl = $this->getOption('ssl') == 'on';
  56. }
  57. public function addJsCss()
  58. {
  59. if(!$this->isActive())
  60. return;
  61. $this->_oModule->_oTemplate->addJs($this->_aIncludeJs);
  62. $this->_oModule->_oTemplate->addCss($this->_aIncludeCss);
  63. }
  64. public function getJsObject($aParams = array())
  65. {
  66. $sJsObject = $this->_oModule->_oConfig->getJsObject($this->_sName);
  67. if(isset($aParams['iModuleId'], $aParams['iSellerId'], $aParams['iItemId']))
  68. $sJsObject .= '_' . md5($aParams['iModuleId'] . '-' . $aParams['iSellerId'] . '-' . $aParams['iItemId']);
  69. return $sJsObject;
  70. }
  71. public function notify()
  72. {
  73. $iResult = $this->_processEvent();
  74. http_response_code($iResult);
  75. }
  76. public function getButtonSingle($iClientId, $iVendorId, $aParams = array())
  77. {
  78. $aItems = array();
  79. $aCartInfo = $this->_oModule->getObjectCart()->getInfo(BX_PAYMENT_TYPE_SINGLE, $iClientId, (int)$iVendorId, $aItems);
  80. if(empty($aCartInfo) || !is_array($aCartInfo))
  81. return '';
  82. return $this->_getButton(BX_PAYMENT_TYPE_SINGLE, $iClientId, $iVendorId, array_merge($aParams, array(
  83. 'sVendorName' => _t($this->_sLangsPrefix . 'txt_payment_to', $aCartInfo['vendor_name']),
  84. 'sVendorCurrency' => $aCartInfo['vendor_currency_code'],
  85. 'sVendorIcon' => $aCartInfo['vendor_avatar'],
  86. )));
  87. }
  88. public function getButtonSingleJs($iClientId, $iVendorId, $aParams = array())
  89. {
  90. $aItems = array();
  91. $aCartInfo = $this->_oModule->getObjectCart()->getInfo(BX_PAYMENT_TYPE_SINGLE, $iClientId, (int)$iVendorId, $aItems);
  92. if(empty($aCartInfo) || !is_array($aCartInfo))
  93. return '';
  94. return $this->_getButtonJs(BX_PAYMENT_TYPE_SINGLE, $iClientId, $iVendorId, array_merge($aParams, array(
  95. 'sVendorName' => _t($this->_sLangsPrefix . 'txt_payment_to', $aCartInfo['vendor_name']),
  96. 'sVendorCurrency' => $aCartInfo['vendor_currency_code'],
  97. 'sVendorIcon' => $aCartInfo['vendor_avatar'],
  98. )));
  99. }
  100. public function getButtonRecurring($iClientId, $iVendorId, $aParams = array())
  101. {
  102. $aVendor = $this->_oModule->getVendorInfo((int)$iVendorId);
  103. return $this->_getButton(BX_PAYMENT_TYPE_RECURRING, $iClientId, $iVendorId, array_merge($aParams, array(
  104. 'sVendorName' => _t($this->_sLangsPrefix . 'txt_payment_to', $aVendor['name']),
  105. 'sVendorCurrency' => $aVendor['currency_code'],
  106. 'sVendorIcon' => $aVendor['avatar'],
  107. )));
  108. }
  109. public function getButtonRecurringJs($iClientId, $iVendorId, $aParams = array())
  110. {
  111. $aVendor = $this->_oModule->getVendorInfo((int)$iVendorId);
  112. return $this->_getButtonJs(BX_PAYMENT_TYPE_RECURRING, $iClientId, $iVendorId, array_merge($aParams, array(
  113. 'sVendorName' => _t($this->_sLangsPrefix . 'txt_payment_to', $aVendor['name']),
  114. 'sVendorCurrency' => $aVendor['currency_code'],
  115. 'sVendorIcon' => $aVendor['avatar'],
  116. )));
  117. }
  118. public function getMenuItemsActionsRecurring($iClientId, $iVendorId, $aParams = array())
  119. {
  120. if($this->_bIsApi || empty($aParams['order']))
  121. return [];
  122. $sJsObject = $this->_oModule->_oConfig->getJsObject(BX_PAYMENT_ORDERS_TYPE_SUBSCRIPTION);
  123. $sPrefix = 'bx-payment-strp-';
  124. return array(
  125. array('id' => $sPrefix . 'details', 'name' => $sPrefix . 'details', 'class' => '', 'link' => 'javascript:void(0)', 'onclick' => "javascript:" . $sJsObject . ".getDetails(this, '" . $aParams['id'] . "')", 'target' => '_self', 'title' => _t('_bx_payment_strp_menu_item_title_details')),
  126. array('id' => $sPrefix . 'details_change', 'name' => $sPrefix . 'details_change', 'class' => '', 'link' => 'javascript:void(0)', 'onclick' => "javascript:" . $sJsObject . ".changeDetails(this, '" . $aParams['id'] . "')", 'target' => '_self', 'title' => _t('_bx_payment_strp_menu_item_title_details_change')),
  127. array('id' => $sPrefix . 'billing', 'name' => $sPrefix . 'billing', 'class' => '', 'link' => 'javascript:void(0)', 'onclick' => "javascript:" . $sJsObject . ".getBilling(this, '" . $aParams['id'] . "')", 'target' => '_self', 'title' => _t('_bx_payment_strp_menu_item_title_billing')),
  128. array('id' => $sPrefix . 'billing_change', 'name' => $sPrefix . 'billing_change', 'class' => '', 'link' => 'javascript:void(0)', 'onclick' => "javascript:" . $sJsObject . ".changeBilling(this, '" . $aParams['id'] . "')", 'target' => '_self', 'title' => _t('_bx_payment_strp_menu_item_title_billing_change')),
  129. );
  130. }
  131. public function getDetailsRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
  132. {
  133. $oSubscription = $this->_retrieveSubscription($sCustomerId, $sSubscriptionId);
  134. if($oSubscription === false)
  135. return '';
  136. $aSubscription = $oSubscription->jsonSerialize();
  137. if(empty($aSubscription) || !is_array($aSubscription))
  138. return '';
  139. $sName = '';
  140. if(!empty($aSubscription['plan']['name']))
  141. $sName = $aSubscription['plan']['name'];
  142. else if(!empty($aSubscription['plan']['product'])){
  143. $oProduct = $this->_retrieveProduct($aSubscription['plan']['product']);
  144. if($oProduct !== false)
  145. $sName = $oProduct->name;
  146. }
  147. $sNone = _t('_bx_payment_txt_none');
  148. return $this->_oModule->_oTemplate->parseHtmlByName('strp_details_recurring.html', array(
  149. 'plan' => $sName,
  150. 'cost' => _t('_bx_payment_strp_txt_cost_mask', (int)$aSubscription['plan']['amount'] / 100, $aSubscription['plan']['currency'], $aSubscription['plan']['interval']),
  151. 'status' => $aSubscription['status'],
  152. 'created' => bx_time_js($aSubscription['created'], BX_FORMAT_DATE_TIME, true),
  153. 'started' => !empty($aSubscription['start']) ? bx_time_js($aSubscription['start'], BX_FORMAT_DATE_TIME, true) : $sNone,
  154. 'trial_start' => !empty($aSubscription['trial_start']) ? bx_time_js($aSubscription['trial_start'], BX_FORMAT_DATE_TIME, true) : $sNone,
  155. 'trial_end' => !empty($aSubscription['trial_end']) ? bx_time_js($aSubscription['trial_end'], BX_FORMAT_DATE_TIME, true) : $sNone,
  156. 'cperiod_start' => !empty($aSubscription['current_period_start']) ? bx_time_js($aSubscription['current_period_start'], BX_FORMAT_DATE_TIME, true) : $sNone,
  157. 'cperiod_end' => !empty($aSubscription['current_period_end']) ? bx_time_js($aSubscription['current_period_end'], BX_FORMAT_DATE_TIME, true) : $sNone,
  158. ));
  159. }
  160. public function changeDetailsRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
  161. {
  162. $oForm = BxDolForm::getObjectInstance($this->_sFormDetails, $this->_sFormDisplayDetailsEdit, $this->_oModule->_oTemplate);
  163. $oForm->aFormAttrs['id'] = $this->_oModule->_oConfig->getHtmlIds('subscription', 'form_subscription_change_details');
  164. $oForm->aFormAttrs['action'] = BX_DOL_URL_ROOT . $this->_oModule->_oConfig->getBaseUri() . 'subscription_change_details/' . $iPendingId;
  165. $oForm->aInputs['item_id']['values'] = $this->_getDataChangeDetailsRecurring($iPendingId);
  166. $oForm->initChecker();
  167. if($oForm->isSubmittedAndValid()) {
  168. $aResultError = array('code' => 1, 'message' => _t('_bx_payment_strp_err_details_changed'));
  169. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  170. list($iVendorId, $iModuleId, $iItemId, $iItemCount) = $this->_oModule->_oConfig->descriptorS2A($aPending['items']);
  171. $aItem = $this->_oModule->callGetCartItem($iModuleId, array($oForm->getCleanValue('item_id'), $aPending['client_id']));
  172. if(empty($aItem) || !is_array($aItem))
  173. return $aResultError;
  174. $oSubscription = $this->_retrieveSubscription($sCustomerId, $sSubscriptionId);
  175. if($oSubscription === false)
  176. return $aResultError;
  177. $oSubscription->plan = $aItem['name'];
  178. $oSubscription->prorate = $this->_bProrate;
  179. $oSubscription = $oSubscription->save();
  180. if(strcmp($oSubscription->plan->id, $aItem['name']) !== 0)
  181. return $aResultError;
  182. $sItems = $this->_oModule->_oConfig->descriptorA2S(array($iVendorId, $iModuleId, $aItem['id'], $iItemCount));
  183. if(!$this->_oModule->_oDb->updateOrderPending($iPendingId, array('items' => $sItems)))
  184. return $aResultError;
  185. $this->_oModule->callReregisterSubscriptionItem($iModuleId, array($aPending['client_id'], $aPending['seller_id'], $iItemId, $aItem['id'], $aPending['order']));
  186. return array('code' => 0, 'message' => _t('_bx_payment_strp_msg_details_changed'));
  187. }
  188. return $this->_oModule->_oTemplate->parseHtmlByName('strp_details_change_recuring.html', array(
  189. 'object' => $this->_oModule->_oConfig->getJsObject('subscription'),
  190. 'form' => $oForm->getCode(),
  191. 'form_id' => $oForm->aFormAttrs['id'],
  192. ));
  193. }
  194. public function getBillingRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
  195. {
  196. $aCard = ['brand' => '', 'country' => '', 'funding' => '', 'last4' => '', 'exp_month' => '', 'exp_year' => '', 'cvc_check' => ''];
  197. $oCard = $this->_retrieveCard($sCustomerId);
  198. if($oCard === false && ($oSubscription = $this->_retrieveSubscription($sCustomerId, $sSubscriptionId)) !== false) {
  199. $sPaymentMethodId = $oSubscription->default_payment_method;
  200. if(!empty($sPaymentMethodId) && ($oPaymentMethod = $this->_retrievePaymentMethod($sPaymentMethodId)) !== false)
  201. $oCard = $oPaymentMethod->card;
  202. }
  203. if(!empty($oCard))
  204. $aCard = $oCard->jsonSerialize();
  205. return $this->_oModule->_oTemplate->parseHtmlByName('strp_billing_recurring.html', array(
  206. 'brand' => $aCard['brand'],
  207. 'origin' => $aCard['country'],
  208. 'type' => $aCard['funding'],
  209. 'number' => _t('_bx_payment_strp_txt_card_number_mask', $aCard['last4']),
  210. 'expires' => _t('_bx_payment_strp_txt_card_expires_mask', $aCard['exp_month'], $aCard['exp_year']),
  211. 'cvc' => _t(!empty($aCard['cvc_check']) && strcmp($aCard['cvc_check'], 'pass') === 0 ? '_bx_payment_strp_txt_card_cvc_passed' : '_bx_payment_txt_none'),
  212. ));
  213. }
  214. public function changeBillingRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
  215. {
  216. $oForm = BxDolForm::getObjectInstance($this->_sFormCard, $this->_sFormDisplayCardAdd, $this->_oModule->_oTemplate);
  217. $oForm->aFormAttrs['id'] = $this->_oModule->_oConfig->getHtmlIds('subscription', 'form_subscription_change_billing');
  218. $oForm->aFormAttrs['action'] = BX_DOL_URL_ROOT . $this->_oModule->_oConfig->getBaseUri() . 'subscription_change_billing/' . $iPendingId;
  219. $oForm->initChecker();
  220. if($oForm->isSubmittedAndValid()) {
  221. $aResultError = array('code' => 1, 'message' => _t('_bx_payment_strp_err_billing_changed'));
  222. $aMatch = array();
  223. if(!preg_match('/^([0-9]{2})\D([0-9]{4})$/i', $oForm->getCleanValue('card_expire'), $aMatch))
  224. return $aResultError;
  225. list($iMonth, $iYear) = array_slice($aMatch, 1);
  226. $aToken = $this->_createToken(array(
  227. 'number' => $oForm->getCleanValue('card_number'),
  228. 'exp_month' => $iMonth,
  229. 'exp_year' => $iYear,
  230. 'cvc' => $oForm->getCleanValue('card_cvv')
  231. ));
  232. if(empty($aToken) || !is_array($aToken))
  233. return $aResultError;
  234. $aCard = $this->_createCard(BX_PAYMENT_TYPE_RECURRING, $sCustomerId, $aToken['id']);
  235. if(empty($aCard) || !is_array($aCard))
  236. return $aResultError;
  237. $oCustomer = $this->_retrieveCustomer(BX_PAYMENT_TYPE_RECURRING, $sCustomerId);
  238. if($oCustomer === false)
  239. return $aResultError;
  240. $oCustomer->default_source = $aCard['id'];
  241. $oCustomer->save();
  242. return array('code' => 0, 'message' => _t('_bx_payment_strp_msg_billing_changed'));
  243. }
  244. return $this->_oModule->_oTemplate->parseHtmlByName('strp_billing_change_recuring.html', array(
  245. 'object' => $this->_oModule->_oConfig->getJsObject('subscription'),
  246. 'form' => $oForm->getCode(),
  247. 'form_id' => $oForm->aFormAttrs['id'],
  248. ));
  249. }
  250. public function cancelRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
  251. {
  252. $oSubscription = $this->_cancelSubscription($sCustomerId, $sSubscriptionId);
  253. if($oSubscription === false)
  254. return false;
  255. return true;
  256. }
  257. public function getSubscription($iPendingId, $sCustomerId, $sSubscriptionId)
  258. {
  259. $oSubscription = $this->_retrieveSubscription($sCustomerId, $sSubscriptionId);
  260. if($oSubscription === false)
  261. return array();
  262. $aSubscription = $oSubscription->jsonSerialize();
  263. if(empty($aSubscription) || !is_array($aSubscription))
  264. return array();
  265. $sStatus = isset($this->_aSbsStatuses[$aSubscription['status']]) ? $this->_aSbsStatuses[$aSubscription['status']] : BX_PAYMENT_SBS_STATUS_UNKNOWN;
  266. return array(
  267. 'status' => $sStatus,
  268. 'created' => $aSubscription['created'],
  269. 'started' => !empty($aSubscription['start']) ? $aSubscription['start'] : 0,
  270. 'trial_start' => !empty($aSubscription['trial_start']) ? $aSubscription['trial_start'] : 0,
  271. 'trial_end' => !empty($aSubscription['trial_end']) ? $aSubscription['trial_end'] : 0,
  272. 'cperiod_start' => !empty($aSubscription['current_period_start']) ? $aSubscription['current_period_start'] : 0,
  273. 'cperiod_end' => !empty($aSubscription['current_period_end']) ? $aSubscription['current_period_end'] : 0,
  274. );
  275. }
  276. protected function _getPublicKey()
  277. {
  278. return $this->_iMode == STRP_MODE_LIVE ? $this->getOption('live_pub_key') : $this->getOption('test_pub_key');
  279. }
  280. protected function _getSecretKey()
  281. {
  282. return $this->_iMode == STRP_MODE_LIVE ? $this->getOption('live_sec_key') : $this->getOption('test_sec_key');
  283. }
  284. protected function _retrieveCustomer($sType, $sId)
  285. {
  286. $oCustomer = null;
  287. /**
  288. * @hooks
  289. * @hookdef hook-bx_payment-stripe_retrieve_customer 'bx_payment', 'stripe_retrieve_customer' - hook to override customer data retrieved from payment provider
  290. * - $unit_name - equals `bx_payment`
  291. * - $action - equals `stripe_retrieve_customer`
  292. * - $object_id - not used
  293. * - $sender_id - not used
  294. * - $extra_params - array of additional params with the following array keys:
  295. * - `type` - [string] payment type: single or recurring
  296. * - `customer_id` - [string] by ref, unique customer id, can be overridden in hook processing
  297. * - `customer_object` - [object] by ref, an instance of customer, redurned by payment provider, can be overridden in hook processing
  298. * @hook @ref hook-bx_payment-stripe_retrieve_customer
  299. */
  300. bx_alert($this->_oModule->_oConfig->getName(), $this->_sName . '_retrieve_customer', 0, false, [
  301. 'type' => $sType,
  302. 'customer_id' => &$sId,
  303. 'customer_object' => &$oCustomer,
  304. 'customer_id_ref' => &$sId,
  305. 'customer_object_ref' => &$oCustomer,
  306. ]);
  307. try {
  308. if(empty($oCustomer))
  309. $oCustomer = \Stripe\Customer::retrieve($sId);
  310. }
  311. catch (Exception $oException) {
  312. return $this->_processException('Retrieve Customer Error: ', $oException);
  313. }
  314. return $oCustomer;
  315. }
  316. protected function _retrieveCharge($sId)
  317. {
  318. $oCharge = null;
  319. /**
  320. * @hooks
  321. * @hookdef hook-bx_payment-stripe_retrieve_charge 'bx_payment', 'stripe_retrieve_charge' - hook to override charge data retrieved from payment provider
  322. * - $unit_name - equals `bx_payment`
  323. * - $action - equals `stripe_retrieve_charge`
  324. * - $object_id - not used
  325. * - $sender_id - not used
  326. * - $extra_params - array of additional params with the following array keys:
  327. * - `type` - [string] payment type: single or recurring
  328. * - `charge_id` - [string] by ref, unique charge id, can be overridden in hook processing
  329. * - `charge_object` - [object] by ref, an instance of charge, redurned by payment provider, can be overridden in hook processing
  330. * @hook @ref hook-bx_payment-stripe_retrieve_charge
  331. */
  332. /**
  333. * @hooks
  334. * @hookdef hook-bx_payment-stripe_v3_retrieve_charge 'bx_payment', 'stripe_v3_retrieve_charge' - hook to override charge data retrieved from payment provider
  335. * It's equivalent to @ref hook-bx_payment-stripe_retrieve_charge
  336. * @hook @ref hook-bx_payment-stripe_v3_retrieve_charge
  337. */
  338. bx_alert($this->_oModule->_oConfig->getName(), $this->_sName . '_retrieve_charge', 0, false, [
  339. 'charge_id' => &$sId,
  340. 'charge_object' => &$oCharge,
  341. 'charge_id_ref' => &$sId,
  342. 'charge_object_ref' => &$oCharge,
  343. ]);
  344. try {
  345. if(empty($oCharge))
  346. $oCharge = \Stripe\Charge::retrieve($sId);
  347. }
  348. catch (Exception $oException) {
  349. return $this->_processException('Retrieve Charge Error: ', $oException);
  350. }
  351. return $oCharge;
  352. }
  353. protected function _retrieveSubscription($sCustomerId, $sSubscriptionId)
  354. {
  355. try {
  356. $oCustomer = $this->_retrieveCustomer(BX_PAYMENT_TYPE_RECURRING, $sCustomerId);
  357. $oSubscription = \Stripe\Subscription::retrieve($sSubscriptionId);
  358. }
  359. catch (Exception $oException) {
  360. return $this->_processException('Retrieve Subscription Error: ', $oException);
  361. }
  362. return $oSubscription;
  363. }
  364. protected function _cancelSubscription($sCustomerId, $sSubscriptionId)
  365. {
  366. try {
  367. $oSubscription = $this->_retrieveSubscription($sCustomerId, $sSubscriptionId);
  368. $oSubscription = $oSubscription->cancel();
  369. }
  370. catch (Exception $oException) {
  371. return $this->_processException('Cancel Subscription Error: ', $oException);
  372. }
  373. /**
  374. * @hooks
  375. * @hookdef hook-bx_payment-stripe_cancel_subscription 'bx_payment', 'stripe_cancel_subscription' - hook after a subscription was canceled
  376. * - $unit_name - equals `bx_payment`
  377. * - $action - equals `stripe_cancel_subscription`
  378. * - $object_id - not used
  379. * - $sender_id - not used
  380. * - $extra_params - array of additional params with the following array keys:
  381. * - `subscription_id` - [string] unique subscription id
  382. * - `subscription_object` - [object] an instance of subscription, redurned by payment provider
  383. * @hook @ref hook-bx_payment-stripe_cancel_subscription
  384. */
  385. /**
  386. * @hooks
  387. * @hookdef hook-bx_payment-stripe_v3_cancel_subscription 'bx_payment', 'stripe_v3_cancel_subscription' - hook after a subscription was canceled
  388. * It's equivalent to @ref hook-bx_payment-stripe_cancel_subscription
  389. * @hook @ref hook-bx_payment-stripe_v3_cancel_subscription
  390. */
  391. bx_alert($this->_oModule->_oConfig->getName(), $this->_sName . '_cancel_subscription', 0, false, [
  392. 'subscription_id' => $sSubscriptionId,
  393. 'subscription_object' => &$oSubscription
  394. ]);
  395. return $oSubscription;
  396. }
  397. protected function _retrievePaymentMethod($sPaymentMethodId)
  398. {
  399. return false;
  400. }
  401. protected function _retrieveProduct($sId)
  402. {
  403. $oProduct = null;
  404. /**
  405. * @hooks
  406. * @hookdef hook-bx_payment-stripe_retrieve_product 'bx_payment', 'stripe_retrieve_product' - hook to override product data retrieved from payment provider
  407. * - $unit_name - equals `bx_payment`
  408. * - $action - equals `stripe_retrieve_product`
  409. * - $object_id - not used
  410. * - $sender_id - not used
  411. * - $extra_params - array of additional params with the following array keys:
  412. * - `product_id` - [string] by ref, unique product id, can be overridden in hook processing
  413. * - `product_object` - [object] by ref, an instance of product, redurned by payment provider, can be overridden in hook processing
  414. * @hook @ref hook-bx_payment-stripe_retrieve_product
  415. */
  416. /**
  417. * @hooks
  418. * @hookdef hook-bx_payment-stripe_v3_retrieve_product 'bx_payment', 'stripe_v3_retrieve_product' - hook to override product data retrieved from payment provider
  419. * It's equivalent to @ref hook-bx_payment-stripe_retrieve_product
  420. * @hook @ref hook-bx_payment-stripe_v3_retrieve_product
  421. */
  422. bx_alert($this->_oModule->_oConfig->getName(), $this->_sName . '_retrieve_product', 0, false, [
  423. 'product_id' => &$sId,
  424. 'product_object' => &$oProduct
  425. ]);
  426. if(!empty($oProduct))
  427. return $oProduct;
  428. try {
  429. $oProduct = \Stripe\Product::retrieve($sId);
  430. }
  431. catch (Exception $oException) {
  432. return $this->_processException('Retrieve Product Error: ', $oException);
  433. }
  434. return $oProduct;
  435. }
  436. protected function _listPlans($iLimit = 100)
  437. {
  438. if($iLimit <= 0)
  439. $iLimit = 1;
  440. if($iLimit > 100)
  441. $iLimit = 100;
  442. try {
  443. $oPlans = \Stripe\Plan::all(array('limit' => $iLimit));
  444. }
  445. catch (Exception $oException) {
  446. return $this->_processException('List Plans Error: ', $oException);
  447. }
  448. return $oPlans;
  449. }
  450. protected function _retrieveEvent($sId) {
  451. try {
  452. $oEvent = \Stripe\Event::retrieve($sId);
  453. }
  454. catch (Exception $oException) {
  455. return $this->_processException('Retrieve Event Error: ', $oException);
  456. }
  457. return $oEvent;
  458. }
  459. protected function _processEvent()
  460. {
  461. $sInput = @file_get_contents("php://input");
  462. $aEvent = json_decode($sInput, true);
  463. if(empty($aEvent) || !is_array($aEvent))
  464. return 404;
  465. $sType = $aEvent['type'];
  466. if(!in_array($sType, array('invoice.payment_succeeded', 'charge.refunded', 'customer.subscription.deleted')))
  467. return 200;
  468. $this->log('Webhooks: ' . (!empty($sType) ? $sType : ''), '', BX_LOG_INFO);
  469. $this->log($aEvent, '', BX_LOG_INFO);
  470. $sMethod = '_processEvent' . bx_gen_method_name($sType, array('.', '_', '-'));
  471. if(!method_exists($this, $sMethod))
  472. return 200;
  473. return $this->$sMethod($aEvent) ? 200 : 403;
  474. }
  475. protected function _processEventInvoicePaymentSucceeded(&$aEvent)
  476. {
  477. $mixedResult = $this->_getDataInvoicePaymentSucceeded($aEvent);
  478. if($mixedResult === false)
  479. return false;
  480. list($mixedPending, $aPaid) = $mixedResult;
  481. if(empty($mixedPending) || empty($aPaid))
  482. return false;
  483. $fChargeAmount = (float)$aPaid['amount'] / 100;
  484. $sChargeCurrency = strtoupper($aPaid['currency']);
  485. if(is_string($mixedPending))
  486. return $this->_oModule->_oDb->insertStrpPaymentPending($mixedPending, $fChargeAmount, $sChargeCurrency);
  487. if($this->_bCheckAmount && ((float)$mixedPending['amount'] != $fChargeAmount || strcasecmp($this->_oModule->_oConfig->getDefaultCurrencyCode(), $sChargeCurrency) !== 0))
  488. return false;
  489. if($mixedPending['type'] == BX_PAYMENT_TYPE_RECURRING)
  490. $this->_oModule->getObjectSubscriptions()->prolong($mixedPending);
  491. return $this->_oModule->registerPayment($mixedPending);
  492. }
  493. protected function _processEventChargeRefunded(&$aEvent)
  494. {
  495. $mixedResult = $this->_getData($aEvent);
  496. if($mixedResult === false)
  497. return false;
  498. list($aPending) = $mixedResult;
  499. if(empty($aPending) || !is_array($aPending))
  500. return false;
  501. return $this->_oModule->refundPayment($aPending);
  502. }
  503. protected function _processEventCustomerSubscriptionDeleted(&$aEvent)
  504. {
  505. $mixedResult = $this->_getData($aEvent);
  506. if($mixedResult === false)
  507. return false;
  508. list($aPending) = $mixedResult;
  509. if(empty($aPending) || !is_array($aPending))
  510. return true;
  511. return $this->_oModule->getObjectSubscriptions()->cancelLocal($aPending);
  512. }
  513. protected function _processException($sMessage, &$oException)
  514. {
  515. $aError = $oException->getJsonBody();
  516. $sMessage = $aError['error']['message'];
  517. if(empty($sMessage))
  518. $sMessage = $oException->getMessage();
  519. $this->log($sMessage . $aError['error']['message'], '', BX_LOG_ERR);
  520. $this->log($aError, '', BX_LOG_ERR);
  521. return false;
  522. }
  523. protected function _getData(&$aEvent, $bRetrieve = true)
  524. {
  525. if($bRetrieve)
  526. $oEvent = $this->_retrieveEvent($aEvent['id']);
  527. else
  528. $oEvent = \Stripe\Util\Util::convertToStripeObject($aEvent, array());
  529. if(empty($oEvent))
  530. return false;
  531. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'order', 'order' => $oEvent->data->object->subscription));
  532. $oCharge = $this->_retrieveCharge($oEvent->data->object->charge);
  533. return array($aPending, $oCharge);
  534. }
  535. protected function _getDataInvoicePaymentSucceeded(&$aEvent, $bRetrieve = true)
  536. {
  537. if($bRetrieve)
  538. $oEvent = $this->_retrieveEvent($aEvent['id']);
  539. else
  540. $oEvent = \Stripe\Util\Util::convertToStripeObject($aEvent, array());
  541. if(empty($oEvent))
  542. return false;
  543. /**
  544. * Note. $oEvent->data->object->subscription and $oEvent->data->object->charge
  545. * are checked for backward compatibility.
  546. */
  547. $sSubscriptionId = '';
  548. if(!empty($oEvent->data->object->subscription))
  549. $sSubscriptionId = $oEvent->data->object->subscription;
  550. else if(!empty($oEvent->data->object->parent) && $oEvent->data->object->parent->type == 'subscription_details')
  551. $sSubscriptionId = $oEvent->data->object->parent->subscription_details->subscription;
  552. if(!$sSubscriptionId)
  553. return false;
  554. $aPending = $this->_oModule->_oDb->getOrderPending(['type' => 'order', 'order' => $sSubscriptionId]);
  555. $aPaid = ['amount' => 0, 'currency' => ''];
  556. if(!empty($oEvent->data->object->charge)) {
  557. $oCharge = $this->_retrieveCharge($oEvent->data->object->charge);
  558. if($oCharge)
  559. $aPaid = [
  560. 'amount' => $oCharge->amount,
  561. 'currency' => $oCharge->currency
  562. ];
  563. }
  564. else {
  565. if(!empty($oEvent->data->object->amount_paid))
  566. $aPaid['amount'] = $oEvent->data->object->amount_paid;
  567. if(!empty($oEvent->data->object->currency))
  568. $aPaid['currency'] = $oEvent->data->object->currency;
  569. }
  570. return [!empty($aPending) && is_array($aPending) ? $aPending : $sSubscriptionId, $aPaid];
  571. }
  572. protected function _getDataChangeDetailsRecurring($iPendingId)
  573. {
  574. $aResult = array();
  575. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  576. list($iVendorId, $iModuleId, $iItemId) = $this->_oModule->_oConfig->descriptorS2A($aPending['items']);
  577. if(empty($iModuleId) || empty($iVendorId) || (int)$iVendorId != (int)$aPending['seller_id'])
  578. return $aResult;
  579. $aItems = $this->_oModule->callGetCartItems((int)$iModuleId, array($iVendorId));
  580. if(empty($aItems) || !is_array($aItems))
  581. return $aResult;
  582. $oPlans = $this->_listPlans();
  583. if($oPlans === false)
  584. return $aResult;
  585. $aPlans = $oPlans->jsonSerialize();
  586. if(empty($aPlans) || !is_array($aPlans) || empty($aPlans['data']) || !is_array($aPlans['data']))
  587. return $aResult;
  588. $aPlans = $aPlans['data'];
  589. $aPlanNames = array();
  590. foreach($aPlans as $aPlan)
  591. $aPlanNames[] = $aPlan['id'];
  592. if(empty($aPlanNames) || !is_array($aPlanNames))
  593. return $aResult;
  594. foreach($aItems as $aItem) {
  595. $fPrice = $this->_oModule->_oConfig->getPrice(BX_PAYMENT_TYPE_RECURRING, $aItem);
  596. if($fPrice == 0 || (int)$aItem['id'] == (int)$iItemId || !in_array($aItem['name'], $aPlanNames))
  597. continue;
  598. $aResult[] = array('key' => $aItem['id'], 'value' => $aItem['title']);
  599. }
  600. return $aResult;
  601. }
  602. protected function _getButton($sType, $iClientId, $iVendorId, $aParams = array())
  603. {
  604. list($sJsCode, $sJsMethod) = $this->_getButtonJs($sType, $iClientId, $iVendorId, $aParams);
  605. return $this->_oModule->_oTemplate->parseHtmlByName('strp_button_' . $sType . '.html', array(
  606. 'type' => $sType,
  607. 'caption' => _t($this->_sLangsPrefix . 'strp_txt_checkout_with_' . $sType, $this->_sCaption),
  608. 'onclick' => $sJsMethod,
  609. 'js_object' => $this->_oModule->_oConfig->getJsObject($this->_sName),
  610. 'js_code' => $sJsCode,
  611. ));
  612. }
  613. }
  614. /** @} */