BxPaymentProviderRecurly.php 10 KB

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