BxPaymentProviderRecurly.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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('RCRL_MODE_LIVE', 1);
  12. define('RCRL_MODE_TEST', 2);
  13. class BxPaymentProviderRecurly extends BxBaseModPaymentProvider implements iBxBaseModPaymentProvider
  14. {
  15. protected $_aIncludeJs;
  16. protected $_aIncludeCss;
  17. protected $_sFormCard;
  18. protected $_sFormDisplayCardAdd;
  19. protected $_iMode;
  20. protected $_bCheckAmount;
  21. function __construct($aConfig)
  22. {
  23. $this->MODULE = 'bx_payment';
  24. parent::__construct($aConfig);
  25. $this->_aIncludeJs = array(
  26. 'https://js.recurly.com/v4/recurly.js'
  27. );
  28. $this->_aIncludeCss = array(
  29. 'recurly.css'
  30. );
  31. $this->_sFormCard = 'bx_payment_form_rcrl_card';
  32. $this->_sFormDisplayCardAdd = 'bx_payment_form_rcrl_card_add';
  33. $this->_bUseSsl = true;
  34. $this->_bCheckAmount = false; // Disabled for easier processing of discounted subscriptions.
  35. }
  36. public function initOptions($aOptions)
  37. {
  38. parent::initOptions($aOptions);
  39. $this->_iMode = (int)$this->getOption('mode');
  40. }
  41. public function addJsCss()
  42. {
  43. if(!$this->isActive())
  44. return;
  45. $this->_oModule->_oTemplate->addJs($this->_aIncludeJs);
  46. $this->_oModule->_oTemplate->addCss($this->_aIncludeCss);
  47. }
  48. public function initializeCheckout($iPendingId, $aCartInfo)
  49. {
  50. $aItem = array_shift($aCartInfo['items']);
  51. if(empty($aItem) || !is_array($aItem))
  52. return $this->_sLangsPrefix . 'err_empty_items';
  53. $aClient = $this->_oModule->getProfileInfo();
  54. $aVendor = $this->_oModule->getProfileInfo($aCartInfo['vendor_id']);
  55. $mixedResult = $this->createCardForm($iPendingId, $aItem, $aClient, $aVendor);
  56. if($mixedResult === false)
  57. return $this->_sLangsPrefix . 'err_cannot_perform';
  58. return array_merge(array('code' => 0), $mixedResult);
  59. }
  60. public function finalizeCheckout(&$aData)
  61. {
  62. $iPendingId = bx_process_input($aData['pending_id'], BX_DATA_INT);
  63. $sItem = bx_process_input($aData['item']);
  64. $sToken = bx_process_input($aData['token']);
  65. $aClient = array(
  66. 'first_name' => bx_process_input($aData['first_name']),
  67. 'last_name' => bx_process_input($aData['last_name']),
  68. 'email' => bx_process_input($aData['email'])
  69. );
  70. if(empty($sToken) || empty($iPendingId))
  71. return array('code' => 1, 'message' => $this->_sLangsPrefix . 'pp_err_no_data_given');
  72. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  73. if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
  74. return array('code' => 3, 'message' => $this->_sLangsPrefix . 'err_already_processed');
  75. $oSubscription = $this->createSubscription($sToken, $sItem, $aClient);
  76. if($oSubscription === false)
  77. return $this->_sLangsPrefix . 'err_cannot_perform';
  78. /*
  79. * TODO: Need to get subscription ID to save it in DB as Order
  80. */
  81. $sSubscription = '';
  82. $aResult = array(
  83. 'code' => BX_PAYMENT_RESULT_SUCCESS,
  84. 'message' => $this->_sLangsPrefix . 'rcrl_msg_subscribed',
  85. 'pending_id' => $iPendingId,
  86. 'client_name' => _t($this->_sLangsPrefix . 'txt_buyer_name_mask', $aClient['first_name'], $aClient['last_name']),
  87. 'client_email' => $aClient['email'],
  88. 'paid' => false
  89. );
  90. //--- Update pending transaction ---//
  91. $this->_oModule->_oDb->updateOrderPending($iPendingId, array(
  92. 'order' => $sSubscription,
  93. 'error_code' => $aResult['code'],
  94. 'error_msg' => _t($aResult['message'])
  95. ));
  96. return $aResult;
  97. }
  98. public function notify()
  99. {
  100. /*
  101. * TODO: Integrate necessary Webhook events.
  102. */
  103. //$iResult = $this->_processEvent();
  104. //http_response_code($iResult);
  105. }
  106. public function createCardForm($iPendingId, $aItem, $aClient, $aVendor)
  107. {
  108. $oForm = BxDolForm::getObjectInstance($this->_sFormCard, $this->_sFormDisplayCardAdd, $this->_oModule->_oTemplate);
  109. $oForm->aFormAttrs['action'] = bx_append_url_params($this->getReturnDataUrl($aVendor['id']), array(
  110. 'pending_id' => $iPendingId
  111. ));
  112. $oForm->aInputs['pending_id']['value'] = $iPendingId;
  113. $oForm->aInputs['item']['value'] = $aItem['name'];
  114. $aCardFields = array('card_number', 'card_cvv');
  115. foreach($aCardFields as $sCardField) {
  116. $oForm->aInputs[$sCardField]['content'] = $this->_oModule->_oTemplate->parseHtmlByName('rcrl_card_field.html', array(
  117. 'attrs' => bx_convert_array2attrs($oForm->aInputs[$sCardField]['attrs'])
  118. ));
  119. }
  120. $oForm->aInputs['card_expire']['content'] = $this->_oModule->_oTemplate->parseHtmlByName('rcrl_card_field_date.html', array(
  121. 'attrs_month' => bx_convert_array2attrs(array('data-recurly' => 'month')),
  122. 'attrs_year' => bx_convert_array2attrs(array('data-recurly' => 'year'))
  123. ));
  124. $oForm->initChecker();
  125. if($oForm->isSubmittedAndValid()) {
  126. $sFormMethod = $oForm->aFormAttrs['method'];
  127. /*
  128. * TODO: Need to reload form on internal error or update the code to work via this check and then redirect to Finalize.
  129. * Issue with "form reloading". Currently Recurly doesn't allow to "call payment form" multiple times (https://github.com/recurly/recurly-js/issues/239).
  130. */
  131. }
  132. $aTmplConfig = BxTemplConfig::getInstance()->__get('aLessConfig');
  133. $sId = 'bx-payment-rcrl-card-add';
  134. $sTitle = _t($this->_sLangsPrefix . 'popup_title_rcrl_card_add');
  135. $sContent = BxTemplStudioFunctions::getInstance()->popupBox($sId, $sTitle, $this->_oModule->_oTemplate->parseHtmlByName('rcrl_card_popup_add.html', array(
  136. 'public_key' => $this->getOption('api_key_public'),
  137. 'font_family' => $aTmplConfig['bx-font-family'],
  138. 'font_size' => $aTmplConfig['bx-font-size-default'],
  139. 'font_color' => $aTmplConfig['bx-font-color-default'],
  140. 'form_id' => $oForm->aFormAttrs['id'],
  141. 'form' => $oForm->getCode(true),
  142. )));
  143. return array('popup' => array(
  144. 'html' => $sContent,
  145. 'options' => array(
  146. 'closeOnOuterClick' => false,
  147. 'onBeforeShow' => 'bxRecurlyFieldsInit();',
  148. 'onHide' => 'bxRecurlyFieldsDestroy();'
  149. )
  150. ));
  151. }
  152. public function createSubscription($sToken, $sItem, $aClient)
  153. {
  154. $oSubscription = false;
  155. try {
  156. $oSubscription = new Recurly_Subscription();
  157. $oSubscription->plan_code = $sItem;
  158. $oSubscription->account = new Recurly_Account();
  159. $oSubscription->account->account_code = 'pat_smith';
  160. $oSubscription->account->first_name = $aClient['first_name'];
  161. $oSubscription->account->last_name = $aClient['last_name'];
  162. $oSubscription->account->email = $aClient['email'];
  163. $oSubscription->account->billing_info = new Recurly_BillingInfo();
  164. $oSubscription->account->billing_info->token_id = $sToken;
  165. $oSubscription->create();
  166. }
  167. catch (Exception $oException) {
  168. $iError = $oException->getCode();
  169. $sError = $oException->getMessage();
  170. $this->log('Create Subscription Error: ' . $sError . '(' . $iError . ')');
  171. return false;
  172. }
  173. return $oSubscription;
  174. }
  175. public function retrieveSubscription($sSubscriptionId)
  176. {
  177. $oSubscription = null;
  178. try {
  179. }
  180. catch (Exception $oException) {
  181. $iError = $oException->getCode();
  182. $sError = $oException->getMessage();
  183. $this->log('Retrieve Subscription Error: ' . $sError . '(' . $iError . ')');
  184. return false;
  185. }
  186. return $oSubscription;
  187. }
  188. public function deleteSubscription($sSubscriptionId)
  189. {
  190. try {
  191. }
  192. catch (Exception $oException) {
  193. $aError = $oException->getJsonBody();
  194. $this->log('Delete Subscription Error: ' . $aError['error']['message']);
  195. $this->log($aError);
  196. return false;
  197. }
  198. return true;
  199. }
  200. protected function _processEvent()
  201. {
  202. $sInput = @file_get_contents("php://input");
  203. $aEvent = json_decode($sInput, true);
  204. if(empty($aEvent) || !is_array($aEvent))
  205. return 404;
  206. $sType = $aEvent['event_type'];
  207. if(!in_array($sType, array('payment_succeeded', ' payment_refunded', 'subscription_cancelled')))
  208. return 200;
  209. $this->log('Webhooks: ' . (!empty($sType) ? $sType : ''));
  210. $this->log($aEvent);
  211. $sMethod = '_processEvent' . bx_gen_method_name($sType, array('.', '_', '-'));
  212. if(!method_exists($this, $sMethod))
  213. return 200;
  214. return $this->$sMethod($aEvent) ? 200 : 403;
  215. }
  216. protected function _processEventPaymentSucceeded(&$aEvent)
  217. {
  218. $mixedResult = $this->_getData($aEvent, true);
  219. if($mixedResult === false)
  220. return false;
  221. list($aPending, $aTransaction) = $mixedResult;
  222. $fTransactionAmount = (float)$aTransaction['amount'] / 100;
  223. $sTransactionCurrency = strtoupper($aTransaction['currency_code']);
  224. if($this->_bCheckAmount && ((float)$aPending['amount'] != $fTransactionAmount || strcasecmp($this->_oModule->_oConfig->getDefaultCurrencyCode(), $sTransactionCurrency) !== 0))
  225. return false;
  226. return $this->_oModule->registerPayment($aPending);
  227. }
  228. protected function _processEventPaymentRefunded(&$aEvent)
  229. {
  230. $mixedResult = $this->_getData($aEvent);
  231. if($mixedResult === false)
  232. return false;
  233. list($aPending) = $mixedResult;
  234. return $this->_oModule->refundPayment($aPending);
  235. }
  236. protected function _processEventSubscriptionCancelled(&$aEvent)
  237. {
  238. $mixedResult = $this->_getData($aEvent);
  239. if($mixedResult === false)
  240. return false;
  241. list($aPending) = $mixedResult;
  242. return $this->_oModule->getObjectSubscriptions()->cancelLocal($aPending);
  243. }
  244. protected function _getData(&$aEvent, $bWithStatusCheck = false)
  245. {
  246. $aTransaction = $aEvent['content']['transaction'];
  247. if(empty($aTransaction) || ($bWithStatusCheck && $aTransaction['status'] != 'success'))
  248. return false;
  249. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'order', 'order' => $aTransaction['subscription_id']));
  250. if(empty($aPending) || !is_array($aPending))
  251. return false;
  252. return array($aPending, $aTransaction);
  253. }
  254. }
  255. /** @} */