BxPaymentProviderPayPalApi.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. /*
  12. * 1. Set up server-side SDK:
  13. * https://developer.paypal.com/docs/business/checkout/server-side-api-calls/set-up-sdk/
  14. *
  15. * 2. Orders API
  16. * https://developer.paypal.com/docs/api/orders/v2
  17. *
  18. * 2.1. Checkout SDK in GitHUB
  19. * https://github.com/paypal/Checkout-PHP-SDK/
  20. *
  21. * 3. Subscriptions:
  22. * https://developer.paypal.com/docs/subscriptions/
  23. * https://developer.paypal.com/docs/business/subscriptions/
  24. *
  25. * 3.1. API
  26. * https://developer.paypal.com/docs/api/subscriptions/v1
  27. * https://developer.paypal.com/docs/api/catalog-products/v1
  28. *
  29. * 3.2. Integration
  30. * https://developer.paypal.com/docs/subscriptions/integrate/
  31. *
  32. * 3.3 WebHooks
  33. * https://developer.paypal.com/docs/api-basics/notifications/webhooks/rest/
  34. *
  35. * 4. Authorize Intent and Capture Authorized:
  36. * https://github.com/paypal/Checkout-PHP-SDK/tree/develop/samples
  37. *
  38. */
  39. use PayPalHttp\HttpException;
  40. use PayPalCheckoutSdk\Core\PayPalHttpClient;
  41. use PayPalCheckoutSdk\Core\SandboxEnvironment;
  42. use PayPalCheckoutSdk\Core\ProductionEnvironment;
  43. use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
  44. use PayPalCheckoutSdk\Orders\OrdersGetRequest;
  45. use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
  46. use PayPalCheckoutSdk\Orders\OrdersAuthorizeRequest;
  47. use PayPalCheckoutSdk\Payments\AuthorizationsCaptureRequest;
  48. define('PP_API_MODE_LIVE', 1);
  49. define('PP_API_MODE_TEST', 2);
  50. define('PP_API_MODE_DEFAULT', PP_API_MODE_LIVE);
  51. define('PP_API_SBS_STATUS_APPROVAL_PENDING', 'APPROVAL_PENDING');
  52. define('PP_API_SBS_STATUS_APPROVED', 'APPROVED');
  53. define('PP_API_SBS_STATUS_ACTIVE', 'ACTIVE');
  54. class BxPaymentProviderPayPalApi extends BxBaseModPaymentProvider implements iBxBaseModPaymentProvider
  55. {
  56. protected $_oSession;
  57. protected $_sSessionKeyOrder;
  58. protected $_sSessionKeySubscription;
  59. protected $_bCheckAmount;
  60. protected $_iMode;
  61. protected $_sEndpoint;
  62. protected $_sToken;
  63. function __construct($aConfig)
  64. {
  65. $this->MODULE = 'bx_payment';
  66. parent::__construct($aConfig);
  67. $this->_oSession = BxDolSession::getInstance();
  68. $this->_sSessionKeyOrder = $this->MODULE . '_' . $this->_sPrefix . 'order';
  69. $this->_sSessionKeySubscription = $this->MODULE . '_' . $this->_sPrefix . 'subscription';
  70. $this->_bCheckAmount = true;
  71. $this->_iMode = (int)$this->getOption('mode');
  72. $this->_sEndpoint = 'https://api-m' . ($this->_iMode == PP_API_MODE_TEST ? '.sandbox' : '') . '.paypal.com/';
  73. }
  74. public function authorizeCheckout($iPendingId, $aCartInfo)
  75. {
  76. if(empty($aCartInfo['items']) || !is_array($aCartInfo['items']))
  77. return $this->_sLangsPrefix . 'err_empty_items';
  78. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  79. if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
  80. return $this->_sLangsPrefix . 'err_already_processed';
  81. switch($aPending['type']) {
  82. case BX_PAYMENT_TYPE_SINGLE:
  83. $mixedResult = $this->_createOrder($iPendingId, $aCartInfo, ['intent' => 'authorize']);
  84. if($mixedResult === false)
  85. return $this->_sLangsPrefix . 'err_cannot_perform';
  86. $this->_setSessionOrder($mixedResult['order']);
  87. return [
  88. 'code' => BX_PAYMENT_RESULT_SUCCESS,
  89. 'redirect' => $mixedResult['redirect']
  90. ];
  91. case BX_PAYMENT_TYPE_RECURRING:
  92. return $this->_sLangsPrefix . 'err_not_supported';
  93. }
  94. }
  95. public function captureAuthorizedCheckout($sOrderAuth, $mixedPending, $aInfo)
  96. {
  97. $aPending = is_array($mixedPending) ? $mixedPending : $this->_oModule->_oDb->getOrderPending(['type' => 'id', 'id' => (int)$mixedPending]);
  98. if(empty($aPending) || !is_array($aPending))
  99. return ['code' => 2, 'message' => $this->_sLangsPrefix . 'err_empty_order'];
  100. $mixedResult = false;
  101. switch($aPending['type']) {
  102. case BX_PAYMENT_TYPE_SINGLE:
  103. $mixedResult = $this->_captureAuthorization($sOrderAuth);
  104. if($mixedResult === false)
  105. return ['code' => 3, 'message' => $this->_sLangsPrefix . 'err_cannot_perform'];
  106. break;
  107. case BX_PAYMENT_TYPE_RECURRING:
  108. return ['code' => 1, 'message' => $this->_sLangsPrefix . 'err_not_supported'];
  109. }
  110. $aResult = [
  111. 'code' => BX_PAYMENT_RESULT_SUCCESS,
  112. 'message' => $this->_sLangsPrefix . 'pp_api_msg_captured',
  113. 'pending_id' => $aPending['id'],
  114. 'paid' => true
  115. ];
  116. //--- Update pending transaction
  117. $this->_oModule->_oDb->updateOrderPending($aResult['pending_id'], [
  118. 'order' => $mixedResult['order'],
  119. 'error_code' => $aResult['code'],
  120. 'error_msg' => _t($aResult['message']),
  121. ]);
  122. return $aResult;
  123. }
  124. public function initializeCheckout($iPendingId, $aCartInfo)
  125. {
  126. if(empty($aCartInfo['items']) || !is_array($aCartInfo['items']))
  127. return $this->_sLangsPrefix . 'err_empty_items';
  128. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  129. if(!empty($aPending['order']) || !empty($aPending['error_code']) || !empty($aPending['error_msg']) || (int)$aPending['processed'] != 0)
  130. return $this->_sLangsPrefix . 'err_already_processed';
  131. switch($aPending['type']) {
  132. case BX_PAYMENT_TYPE_SINGLE:
  133. $mixedResult = $this->_createOrder($iPendingId, $aCartInfo);
  134. if($mixedResult === false)
  135. return $this->_sLangsPrefix . 'err_cannot_perform';
  136. $this->_setSessionOrder($mixedResult['order']);
  137. header("Location: " . $mixedResult['redirect']);
  138. exit;
  139. case BX_PAYMENT_TYPE_RECURRING:
  140. $mixedResult = $this->_createSubscription($iPendingId, $aCartInfo);
  141. if(is_string($mixedResult))
  142. return $mixedResult;
  143. $this->_setSessionSubscription($mixedResult['subscription']);
  144. return array(
  145. 'code' => 0,
  146. 'redirect' => $mixedResult['redirect'],
  147. );
  148. }
  149. }
  150. public function finalizeCheckout(&$aData)
  151. {
  152. $sMethod = '_finalizeCheckout' . bx_gen_method_name(!empty($aData['subscription_id']) && !empty('ba_token') ? BX_PAYMENT_TYPE_RECURRING : BX_PAYMENT_TYPE_SINGLE);
  153. $aResult = $this->$sMethod($aData);
  154. if(!isset($aResult['code']) || (int)$aResult['code'] != BX_PAYMENT_RESULT_SUCCESS) {
  155. $this->log($aResult, 'Finalize Checkout Failed:', BX_LOG_ERR);
  156. $this->log($aData, 'Finalize Checkout Input:', BX_LOG_ERR);
  157. }
  158. return $aResult;
  159. }
  160. public function notify()
  161. {
  162. $iResult = $this->_processEvent();
  163. http_response_code($iResult);
  164. }
  165. public function getClientId()
  166. {
  167. return $this->getOption($this->_getMode() . '_client_id');
  168. }
  169. public function getSecret()
  170. {
  171. return $this->getOption($this->_getMode() . '_secret');
  172. }
  173. public function getMenuItemsActionsRecurring($iClientId, $iVendorId, $aParams = array())
  174. {
  175. return [];
  176. }
  177. public function cancelRecurring($iPendingId, $sCustomerId, $sSubscriptionId)
  178. {
  179. return $this->_cancelSubscription($sSubscriptionId);
  180. }
  181. protected function _finalizeCheckoutSingle(&$aData)
  182. {
  183. $sOrder = '';
  184. if(!empty($aData['token']))
  185. $sOrder = bx_process_input($aData['token']);
  186. if(empty($sOrder))
  187. $sOrder = $this->_getSessionOrder();
  188. if(empty($sOrder))
  189. return['code' => 1, 'message' => $this->_sLangsPrefix . 'err_empty_order'];
  190. $aOrder = $this->_getOrder($sOrder);
  191. if(empty($aOrder) || !is_array($aOrder))
  192. return ['code' => 1, 'message' => $this->_sLangsPrefix . 'err_empty_order'];
  193. $sMessage = '';
  194. $bAuthorized = $bPaid = false;
  195. switch($aOrder['intent']) {
  196. case 'authorize':
  197. $mixedResult = $this->_authorizeOrder($sOrder);
  198. if($mixedResult === false)
  199. return ['code' => 2, 'message' => $this->_sLangsPrefix . 'pp_api_err_cannot_authorize'];
  200. $sMessage = $this->_sLangsPrefix . 'pp_api_msg_authorized';
  201. $bAuthorized = true;
  202. break;
  203. case 'capture':
  204. $mixedResult = $this->_captureOrder($sOrder);
  205. if($mixedResult === false)
  206. return ['code' => 2, 'message' => $this->_sLangsPrefix . 'pp_api_err_cannot_capture'];
  207. $sMessage = $this->_sLangsPrefix . 'pp_api_msg_captured';
  208. $bPaid = true;
  209. break;
  210. }
  211. $aResult = [
  212. 'code' => BX_PAYMENT_RESULT_SUCCESS,
  213. 'message' => $sMessage,
  214. 'pending_id' => $mixedResult['pending_id'],
  215. 'client_name' => _t($this->_sLangsPrefix . 'txt_buyer_name_mask', $mixedResult['client_first_name'], $mixedResult['client_last_name']),
  216. 'client_email' => $mixedResult['client_email'],
  217. 'authorized' => $bAuthorized,
  218. 'paid' => $bPaid
  219. ];
  220. //--- Update pending transaction
  221. $this->_oModule->_oDb->updateOrderPending($aResult['pending_id'], [
  222. 'order' => $mixedResult['order'],
  223. 'error_code' => $aResult['code'],
  224. 'error_msg' => _t($aResult['message']),
  225. ]);
  226. return $aResult;
  227. }
  228. protected function _finalizeCheckoutRecurring(&$aData)
  229. {
  230. $sSubscription = '';
  231. if(!empty($aData['subscription_id']))
  232. $sSubscription = bx_process_input($aData['subscription_id']);
  233. if(empty($sSubscription))
  234. $sSubscription = $this->_getSessionSubscription();
  235. if(empty($sSubscription))
  236. return array('code' => 1, 'message' => $this->_sLangsPrefix . 'pp_api_err_no_subscription');
  237. $aSubscription = $this->_getSubscription($sSubscription);
  238. if(empty($aSubscription) || !in_array($aSubscription['status'], array(PP_API_SBS_STATUS_APPROVAL_PENDING, PP_API_SBS_STATUS_APPROVED, PP_API_SBS_STATUS_ACTIVE)))
  239. return array('code' => 2, 'message' => $this->_sLangsPrefix . 'pp_api_err_no_subscription');
  240. $aSubscriber = $this->_getClientInfo($aSubscription['subscriber']);
  241. list($bPaid, $bTrial) = $this->_getBillingStatus($aSubscription['billing_info']);
  242. $aResult = array(
  243. 'code' => BX_PAYMENT_RESULT_SUCCESS,
  244. 'message' => $this->_sLangsPrefix . 'pp_api_msg_subscribed',
  245. 'pending_id' => $aSubscription['custom_id'],
  246. 'customer_id' => $aSubscription['subscriber']['payer_id'],
  247. 'subscription_id' => $sSubscription,
  248. 'client_name' => _t($this->_sLangsPrefix . 'txt_buyer_name_mask', $aSubscriber['client_first_name'], $aSubscriber['client_last_name']),
  249. 'client_email' => $aSubscriber['client_email'],
  250. 'trial' => $bTrial,
  251. );
  252. if($aSubscription['status'] == PP_API_SBS_STATUS_APPROVAL_PENDING)
  253. $aResult = array_merge($aResult, array(
  254. 'code' => 3,
  255. 'message' => $this->_sLangsPrefix . 'pp_api_err_subscription_not_confirmed'
  256. ));
  257. //--- Update pending transaction
  258. $this->_oModule->_oDb->updateOrderPending($aResult['pending_id'], array(
  259. 'order' => $sSubscription,
  260. 'error_code' => $aResult['code'],
  261. 'error_msg' => _t($aResult['message'])
  262. ));
  263. return $aResult;
  264. }
  265. /**
  266. * Methods which use common HTTPS calls to process Recurring time payments.
  267. */
  268. protected function _createSubscription($iPendingId, $aCartInfo, $sReturnType = 'approve')
  269. {
  270. $aItem = array_shift($aCartInfo['items']);
  271. if(empty($aItem) || !is_array($aItem))
  272. return $this->_sLangsPrefix . 'pp_api_err_no_item';
  273. $aItem['price_currency'] = $aCartInfo['vendor_currency_code'];
  274. $aProduct = $this->_getProduct($aItem['name']);
  275. if(empty($aProduct)) {
  276. $aProduct = $this->_createProduct($aItem);
  277. if($aProduct === false)
  278. return $this->_sLangsPrefix . 'err_cannot_perform';
  279. }
  280. $aProductPlan = [];
  281. $aPlans = $this->_getPlans($aProduct['id']);
  282. if(!$this->_validateProduct($aItem, $aProduct, $aPlans))
  283. return $this->_sLangsPrefix . 'pp_api_err_wrong_item';
  284. if(!empty($aPlans))
  285. foreach($aPlans as $aPlan)
  286. if(strcmp($aPlan['name'], $aItem['name']) == 0) {
  287. $aProductPlan = $aPlan;
  288. break;
  289. }
  290. if(empty($aProductPlan) || !is_array($aProductPlan)) {
  291. $aProductPlan = $this->_createPlan($aProduct['id'], $aItem);
  292. if($aProductPlan === false)
  293. return $this->_sLangsPrefix . 'err_cannot_perform';
  294. }
  295. $mixedResult = $this->_apiCallAuthorized($this->_sEndpoint . 'v1/billing/subscriptions', array(
  296. 'plan_id' => $aProductPlan['id'],
  297. 'custom_id' => $iPendingId,
  298. 'application_context' => array(
  299. 'cancel_url' => $aItem['url'],
  300. 'return_url' => $this->getReturnDataUrl($aCartInfo['vendor_id'])
  301. )
  302. ));
  303. if($mixedResult === false || empty($mixedResult['id']) || empty($mixedResult['links'])) {
  304. $this->log($mixedResult, 'Create Subscription:', BX_LOG_ERR);
  305. return $this->_sLangsPrefix . 'err_cannot_perform';
  306. }
  307. $mixedLink = false;
  308. foreach($mixedResult['links'] as $aLink)
  309. if($aLink['rel'] == $sReturnType) {
  310. $mixedLink = $aLink['href'];
  311. break;
  312. }
  313. return array(
  314. 'subscription' => $mixedResult['id'],
  315. 'redirect' => $mixedLink
  316. );
  317. }
  318. protected function _getSubscription($sSubscriptionId)
  319. {
  320. $mixedResult = $this->_apiCallAuthorized($this->_sEndpoint . 'v1/billing/subscriptions/' . $sSubscriptionId, array(), array(), 'get');
  321. if($mixedResult === false || !isset($mixedResult['id'])) {
  322. $this->log($mixedResult, 'Get Subscription:', BX_LOG_ERR);
  323. return array();
  324. }
  325. return $mixedResult;
  326. }
  327. protected function _cancelSubscription($sSubscriptionId)
  328. {
  329. list($sCode, $sResponse) = $this->_apiCallAuthorized($this->_sEndpoint . 'v1/billing/subscriptions/' . $sSubscriptionId . '/cancel', [
  330. 'reason' => 'Not needed anymore'
  331. ], [], 'post-json', true);
  332. if($sCode != 204) {
  333. $this->log($sResponse, 'Cancel Subscription:', BX_LOG_ERR);
  334. return false;
  335. }
  336. return true;
  337. }
  338. protected function _createProduct($aItem)
  339. {
  340. if(empty($aItem['description']))
  341. $aItem['description'] = _t('_bx_payment_txt_payment_description', getParam('site_title'));
  342. $aItem['description'] = strmaxtextlen($aItem['description'], 60, '...');
  343. $mixedResult = $this->_apiCallAuthorized($this->_sEndpoint . 'v1/catalogs/products', array(
  344. 'id' => $aItem['name'],
  345. 'name' => $aItem['title'],
  346. 'description' => $aItem['description'],
  347. 'type' => 'DIGITAL',
  348. 'home_url' => $aItem['url'],
  349. ), array(
  350. 'PayPal-Request-Id: bx_prod_' . $aItem['name']
  351. ));
  352. if($mixedResult === false || !isset($mixedResult['id'])) {
  353. $this->log($mixedResult, 'Create Product:', BX_LOG_ERR);
  354. return false;
  355. }
  356. return $mixedResult;
  357. }
  358. protected function _getProduct($sProductId)
  359. {
  360. $mixedResult = $this->_apiCallAuthorized($this->_sEndpoint . 'v1/catalogs/products/' . $sProductId, array(), array(), 'get');
  361. if($mixedResult === false || !isset($mixedResult['id'])) {
  362. $this->log($mixedResult, 'Get Product:', BX_LOG_ERR);
  363. return array();
  364. }
  365. return $mixedResult;
  366. }
  367. protected function _validateProduct($aItem, $aProduct, $aPlans)
  368. {
  369. //--- by date creation.
  370. if(isset($aItem['added'], $aProduct['create_time']) && $aItem['added'] > strtotime($aProduct['create_time']))
  371. return false;
  372. return true;
  373. }
  374. protected function _createPlan($sProductId, $aItem)
  375. {
  376. $aCycles = array();
  377. $sIntervalUnit = $this->_getIntervalUnit($aItem['period_unit_recurring']);
  378. if($sIntervalUnit === false)
  379. return false;
  380. $iSequence = 1;
  381. $iTrial = $this->_oModule->_oConfig->getTrial(BX_PAYMENT_TYPE_RECURRING, $aItem);
  382. if(!empty($iTrial))
  383. $aCycles[] = array(
  384. 'frequency' => array(
  385. 'interval_unit' => $this->_getIntervalUnit(BX_PAYMENT_SBS_PU_DAY),
  386. 'interval_count' => $iTrial
  387. ),
  388. 'tenure_type' => 'TRIAL',
  389. 'sequence' => $iSequence++,
  390. 'total_cycles' => 1,
  391. );
  392. $aCycles[] = array(
  393. 'frequency' => array(
  394. 'interval_unit' => $sIntervalUnit,
  395. 'interval_count' => (int)$aItem['period_recurring']
  396. ),
  397. 'tenure_type' => 'REGULAR',
  398. 'sequence' => $iSequence,
  399. 'total_cycles' => 0,
  400. 'pricing_scheme' => array(
  401. 'fixed_price' => array(
  402. 'value' => $this->_oModule->_oConfig->getPrice(BX_PAYMENT_TYPE_RECURRING, $aItem),
  403. 'currency_code' => $aItem['price_currency']
  404. )
  405. )
  406. );
  407. $mixedResult = $this->_apiCallAuthorized($this->_sEndpoint . 'v1/billing/plans', array(
  408. 'product_id' => $sProductId,
  409. 'name' => $aItem['name'],
  410. 'description' => $aItem['title'],
  411. 'billing_cycles' => $aCycles,
  412. 'payment_preferences' => array(
  413. 'auto_bill_outstanding' => true,
  414. 'setup_fee' => array(
  415. 'value' => 0,
  416. 'currency_code' => $aItem['price_currency']
  417. ),
  418. 'setup_fee_failure_action' => 'CONTINUE',
  419. 'payment_failure_threshold' => 3
  420. ),
  421. ), array(
  422. 'PayPal-Request-Id: bx_plan_' . $aItem['name']
  423. ));
  424. if($mixedResult === false || !isset($mixedResult['id'])) {
  425. $this->log($mixedResult, 'Create Plan:', BX_LOG_ERR);
  426. return false;
  427. }
  428. return $mixedResult;
  429. }
  430. protected function _getPlan($sPlanId)
  431. {
  432. $mixedResult = $this->_apiCallAuthorized($this->_sEndpoint . 'v1/billing/plans/' . $sPlanId, array(), array(), 'get');
  433. if($mixedResult === false || !isset($mixedResult['id'])) {
  434. $this->log($mixedResult, 'Get Plan:', BX_LOG_ERR);
  435. return array();
  436. }
  437. return $mixedResult;
  438. }
  439. protected function _getPlans($sProductId, $iStart = false, $iPerPage = false)
  440. {
  441. $aParams = array(
  442. 'product_id' => $sProductId,
  443. );
  444. if($iStart !== false)
  445. $aParams['page'] = (int)$iStart >= 1 && (int)$iStart <= 100000 ? $iStart : 1;
  446. if($iPerPage !== false)
  447. $aParams['page_size'] = (int)$iPerPage >= 1 && (int)$iPerPage <= 20 ? $iPerPage : 20;
  448. $mixedResult = $this->_apiCallAuthorized($this->_sEndpoint . 'v1/billing/plans', $aParams, array(), 'get');
  449. if(empty($mixedResult) || !is_array($mixedResult) || !isset($mixedResult['plans'])) {
  450. $this->log($mixedResult, 'Get Plans:', BX_LOG_ERR);
  451. return array();
  452. }
  453. return $mixedResult['plans'];
  454. }
  455. protected function _getToken()
  456. {
  457. $mixedResult = $this->_apiCallAuthorize($this->_sEndpoint . 'v1/oauth2/token', [
  458. 'grant_type' => 'client_credentials'
  459. ], [
  460. 'user' => $this->getClientId(),
  461. 'password' => $this->getSecret()
  462. ]);
  463. if($mixedResult === false || empty($mixedResult['access_token'])) {
  464. $this->log($mixedResult, 'Get Token:', BX_LOG_ERR);
  465. return false;
  466. }
  467. return $mixedResult['access_token'];
  468. }
  469. protected function _apiCallAuthorize($sEndpoint, $aParams = [], $aBasicAuth = [], $sMethod = 'post')
  470. {
  471. $sResponse = $this->_apiCall($sEndpoint, $aParams, [], $sMethod, $aBasicAuth);
  472. return !empty($sResponse) ? json_decode($sResponse, true) : false;
  473. }
  474. protected function _apiCallAuthorized($sEndpoint, $aParams = [], $aHeaders = [], $sMethod = 'post-json', $bRawResponse = false)
  475. {
  476. if(!$this->_sToken)
  477. $this->_sToken = $this->_getToken();
  478. $aHeaders = array_merge([
  479. 'Authorization: Bearer ' . $this->_sToken,
  480. 'Prefer: return=representation'
  481. ], $aHeaders);
  482. $sHttpCode = $bRawResponse ? true : null;
  483. $sResponse = $this->_apiCall($sEndpoint, $aParams, $aHeaders, $sMethod, [], $sHttpCode);
  484. if($bRawResponse)
  485. return [$sHttpCode, $sResponse];
  486. return !empty($sResponse) ? json_decode($sResponse, true) : false;
  487. }
  488. protected function _apiCall($sEndpoint, $aParams = [], $aHeaders = [], $sMethod = 'post-json', $aBasicAuth = [], &$sHttpCode = null)
  489. {
  490. $aHeaders = array_merge([
  491. 'Accept: application/json',
  492. 'Content-Type: application/json'
  493. ], $aHeaders);
  494. return bx_file_get_contents($sEndpoint, $aParams, $sMethod, $aHeaders, $sHttpCode, $aBasicAuth);
  495. }
  496. protected function _getIntervalUnit($sPeriodUnit)
  497. {
  498. $aIntervalUnits = array(
  499. BX_PAYMENT_SBS_PU_DAY => 'DAY',
  500. BX_PAYMENT_SBS_PU_WEEK => 'WEEK',
  501. BX_PAYMENT_SBS_PU_MONTH => 'MONTH',
  502. BX_PAYMENT_SBS_PU_YEAR => 'YEAR'
  503. );
  504. return isset($aIntervalUnits[$sPeriodUnit]) ? $aIntervalUnits[$sPeriodUnit] : false;
  505. }
  506. /**
  507. * Methods which use 'Checkout SDK' to process Single time payments.
  508. */
  509. protected function _getClient()
  510. {
  511. $sClientId = $this->getClientId();
  512. $sSecret = $this->getSecret();
  513. if($this->_iMode == PP_API_MODE_LIVE)
  514. $oEnvironment = new ProductionEnvironment($sClientId, $sSecret);
  515. else
  516. $oEnvironment = new SandboxEnvironment($sClientId, $sSecret);
  517. return new PayPalHttpClient($oEnvironment);
  518. }
  519. protected function _createOrder($iPendingId, $aCartInfo, $aParams = [])
  520. {
  521. $sReturnType = isset($aParams['return_type']) ? $aParams['return_type'] : 'approve';
  522. $aItems = array();
  523. foreach($aCartInfo['items'] as $aItem)
  524. $aItems[] = array(
  525. 'name' => $aItem['title'],
  526. 'unit_amount' => array(
  527. 'value' => sprintf("%.2f", $this->_oModule->_oConfig->getPrice(BX_PAYMENT_TYPE_SINGLE, $aItem)),
  528. 'currency_code' => $aCartInfo['vendor_currency_code']
  529. ),
  530. 'quantity' => $aItem['quantity']
  531. );
  532. $sItemsPrice = sprintf("%.2f", round($aCartInfo['items_price'], 2));
  533. $oRequest = new OrdersCreateRequest();
  534. $oRequest->prefer('return=representation');
  535. $oRequest->body = array(
  536. 'intent' => isset($aParams['intent']) ? strtoupper($aParams['intent']) : 'CAPTURE',
  537. 'purchase_units' => array(
  538. array(
  539. 'reference_id' => $iPendingId,
  540. 'amount' => array(
  541. 'currency_code' => $aCartInfo['vendor_currency_code'],
  542. 'value' => $sItemsPrice,
  543. 'breakdown' => array(
  544. 'item_total' => array(
  545. 'currency_code' => $aCartInfo['vendor_currency_code'],
  546. 'value' => $sItemsPrice,
  547. )
  548. )
  549. ),
  550. 'items' => $aItems
  551. )
  552. ),
  553. 'application_context' => array(
  554. 'cancel_url' => $this->_oModule->getObjectCart()->serviceGetCartUrl($aCartInfo['vendor_id']),
  555. 'return_url' => $this->getReturnDataUrl($aCartInfo['vendor_id'])
  556. )
  557. );
  558. try {
  559. $oResponse = $this->_getClient()->execute($oRequest);
  560. if($oResponse->statusCode != 201)
  561. return false;
  562. $mixedLink = false;
  563. foreach($oResponse->result->links as $oLink)
  564. if($oLink->rel == $sReturnType) {
  565. $mixedLink = $oLink->href;
  566. break;
  567. }
  568. return array(
  569. 'order' => $oResponse->result->id,
  570. 'redirect' => $mixedLink,
  571. );
  572. }
  573. catch (HttpException $oException) {
  574. return $this->_processException('Create Order Error: ', $oException);
  575. }
  576. }
  577. protected function _getOrder($sOrderId)
  578. {
  579. $oRequest = new OrdersGetRequest($sOrderId);
  580. try {
  581. $oResponse = $this->_getClient()->execute($oRequest);
  582. if($oResponse->statusCode != 200 || strcmp(strtolower($oResponse->result->status), 'approved') != 0)
  583. return false;
  584. $oPurchase = current($oResponse->result->purchase_units);
  585. return array_merge(array(
  586. 'id' => $oResponse->result->id,
  587. 'intent' => strtolower($oResponse->result->intent),
  588. 'pending_id' => (int)$oPurchase->reference_id,
  589. ), $this->_getClientInfo($oResponse->result->payer));
  590. }
  591. catch (HttpException $oException) {
  592. return $this->_processException('Get Order Error: ', $oException);
  593. }
  594. }
  595. protected function _authorizeOrder($sOrderId)
  596. {
  597. $oRequest = new OrdersAuthorizeRequest($sOrderId);
  598. try {
  599. $oResponse = $this->_getClient()->execute($oRequest);
  600. if($oResponse->statusCode != 201 || strcmp(strtolower($oResponse->result->status), 'completed') != 0)
  601. return false;
  602. $oPurchase = current($oResponse->result->purchase_units);
  603. $oAuthorization = current($oPurchase->payments->authorizations);
  604. return array_merge(array(
  605. 'pending_id' => (int)$oPurchase->reference_id,
  606. 'order' => $oAuthorization->id,
  607. ), $this->_getClientInfo($oResponse->result->payer));
  608. }
  609. catch (HttpException $oException) {
  610. return $this->_processException('Authorize Order Error: ', $oException);
  611. }
  612. }
  613. protected function _captureOrder($sOrderId)
  614. {
  615. $oRequest = new OrdersCaptureRequest($sOrderId);
  616. try {
  617. $oResponse = $this->_getClient()->execute($oRequest);
  618. if($oResponse->statusCode != 201 || strcmp(strtolower($oResponse->result->status), 'completed') != 0)
  619. return false;
  620. $oPurchase = current($oResponse->result->purchase_units);
  621. $oCapture = current($oPurchase->payments->captures);
  622. return array_merge(array(
  623. 'pending_id' => (int)$oPurchase->reference_id,
  624. 'order' => $oCapture->id,
  625. ), $this->_getClientInfo($oResponse->result->payer));
  626. }
  627. catch (HttpException $oException) {
  628. return $this->_processException('Capture Order Error: ', $oException);
  629. }
  630. }
  631. protected function _captureAuthorization($sAuthorizationId)
  632. {
  633. $oRequest = new AuthorizationsCaptureRequest($sAuthorizationId);
  634. try {
  635. $oResponse = $this->_getClient()->execute($oRequest);
  636. if($oResponse->statusCode != 201 || strcmp(strtolower($oResponse->result->status), 'completed') != 0)
  637. return false;
  638. return [
  639. 'order' => $oResponse->result->id
  640. ];
  641. }
  642. catch (HttpException $oException) {
  643. return $this->_processException('Capture Authorization Error: ', $oException);
  644. }
  645. }
  646. protected function _processException($sMessage, &$oException)
  647. {
  648. $sDescription = '';
  649. $aError = [];
  650. $sMethod = 'getJsonBody';
  651. if(method_exists($oException, $sMethod)) {
  652. $aError = $oException->getJsonBody();
  653. if(isset($aError['error']['message']))
  654. $sDescription = $aError['error']['message'];
  655. }
  656. if(empty($sDescription))
  657. $sDescription = $oException->getMessage();
  658. $this->log($sMessage . $sDescription, '', BX_LOG_ERR);
  659. if(!empty($aError))
  660. $this->log($aError, '', BX_LOG_ERR);
  661. return false;
  662. }
  663. /**
  664. * Methods to process WebHooks
  665. */
  666. protected function _processEvent()
  667. {
  668. $sInput = @file_get_contents("php://input");
  669. $aEvent = json_decode($sInput, true);
  670. if(empty($aEvent) || !is_array($aEvent))
  671. return 404;
  672. $sType = $aEvent['event_type'];
  673. if(!in_array($sType, array('PAYMENT.SALE.COMPLETED', 'PAYMENT.CAPTURE.REFUNDED', 'BILLING.SUBSCRIPTION.CANCELLED')))
  674. return 200;
  675. $this->log($aEvent, 'Webhooks: ' . (!empty($sType) ? $sType : ''), BX_LOG_INFO);
  676. $sMethod = '_processEvent' . bx_gen_method_name(strtolower($sType), array('.', '_', '-'));
  677. if(!method_exists($this, $sMethod))
  678. return 200;
  679. return $this->$sMethod($aEvent) ? 200 : 403;
  680. }
  681. protected function _processEventPaymentSaleCompleted($aEvent)
  682. {
  683. $mixedResult = $this->_getEventData($aEvent);
  684. if($mixedResult === false)
  685. return false;
  686. list($aPending, $aEventData) = $mixedResult;
  687. $fChargeAmount = (float)$aEventData['amount']['total'];
  688. $sChargeCurrency = strtoupper($aEventData['amount']['currency']);
  689. if($this->_bCheckAmount && ((float)$aPending['amount'] != $fChargeAmount || strcasecmp($this->_oModule->_oConfig->getDefaultCurrencyCode(), $sChargeCurrency) !== 0))
  690. return false;
  691. if($aPending['type'] == BX_PAYMENT_TYPE_RECURRING)
  692. $this->_oModule->getObjectSubscriptions()->prolong($aPending);
  693. return $this->_oModule->registerPayment($aPending);
  694. }
  695. protected function _processEventPaymentCaptureRefunded($aEvent)
  696. {
  697. $mixedResult = $this->_getEventData($aEvent);
  698. if($mixedResult === false)
  699. return false;
  700. list($aPending, $aEventData) = $mixedResult;
  701. return $this->_oModule->refundPayment($aPending);
  702. }
  703. protected function _processEventBillingSubscriptionCancelled($aEvent)
  704. {
  705. $mixedResult = $this->_getEventData($aEvent);
  706. if($mixedResult === false)
  707. return false;
  708. list($aPending, $aEventData) = $mixedResult;
  709. return $this->_oModule->getObjectSubscriptions()->cancelLocal($aPending);
  710. }
  711. protected function _getEventData($aEvent)
  712. {
  713. if(empty($aEvent['resource']) || !is_array($aEvent['resource']))
  714. return false;
  715. $aData = $aEvent['resource'];
  716. if(empty($aData['billing_agreement_id']))
  717. return false;
  718. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'order', 'order' => $aData['billing_agreement_id']));
  719. if(empty($aPending) || !is_array($aPending))
  720. return false;
  721. return array($aPending, $aData);
  722. }
  723. /**
  724. * Common methods for internal usage.
  725. */
  726. protected function _getMode()
  727. {
  728. if(empty($this->_iMode))
  729. $this->_iMode = (int)$this->getOption('mode');
  730. $aModeI2S = array(
  731. PP_API_MODE_LIVE => 'live',
  732. PP_API_MODE_TEST => 'test'
  733. );
  734. return isset($aModeI2S[$this->_iMode]) ? $aModeI2S[$this->_iMode] : $aModeI2S[PP_API_MODE_DEFAULT];
  735. }
  736. protected function _getSessionOrder()
  737. {
  738. return $this->_oSession->getUnsetValue($this->_sSessionKeyOrder);
  739. }
  740. protected function _setSessionOrder($sValue)
  741. {
  742. $this->_oSession->setValue($this->_sSessionKeyOrder, $sValue);
  743. }
  744. protected function _getSessionSubscription()
  745. {
  746. return $this->_oSession->getUnsetValue($this->_sSessionKeySubscription);
  747. }
  748. protected function _setSessionSubscription($sValue)
  749. {
  750. $this->_oSession->setValue($this->_sSessionKeySubscription, $sValue);
  751. }
  752. /**
  753. * Retrieve 'Client Info' from a 'getSubscription' call's response.
  754. */
  755. protected function _getClientInfo($mixedClient)
  756. {
  757. $_sName = 'name';
  758. $_sFirst = 'given_name';
  759. $_sLast = 'surname';
  760. $_sEmail = 'email_address';
  761. $aResult = [];
  762. if(is_object($mixedClient))
  763. $aResult = [
  764. 'client_first_name' => $mixedClient->$_sName->$_sFirst,
  765. 'client_last_name' => $mixedClient->$_sName->$_sLast,
  766. 'client_email' => $mixedClient->$_sEmail,
  767. ];
  768. else
  769. $aResult = [
  770. 'client_first_name' => $mixedClient[$_sName][$_sFirst],
  771. 'client_last_name' => $mixedClient[$_sName][$_sLast],
  772. 'client_email' => $mixedClient[$_sEmail],
  773. ];
  774. return $aResult;
  775. }
  776. /**
  777. * Retrieve 'Billing Status' from a 'getSubscription' call's response.
  778. */
  779. protected function _getBillingStatus($mixedBillingInfo)
  780. {
  781. $bTrial = $bPaid = false;
  782. $_sCycles = 'cycle_executions';
  783. $_sCycleType = 'tenure_type';
  784. $_sCyclesCompleted = 'cycles_completed';
  785. $_sCyclesTotal = 'total_cycles';
  786. $bByObject = is_object($mixedBillingInfo);
  787. $aCycles = $bByObject ? $mixedBillingInfo->$_sCycles : $mixedBillingInfo[$_sCycles];
  788. if(empty($aCycles) || !is_array($aCycles))
  789. return [$bPaid, $bTrial];
  790. foreach($aCycles as $mixedCycle) {
  791. $sCycleType = $bByObject ? $mixedCycle->$_sCycleType : $mixedCycle[$_sCycleType];
  792. $iCyclesCompleted = $bByObject ? $mixedCycle->$_sCyclesCompleted : (int)$mixedCycle[$_sCyclesCompleted];
  793. $iCyclesTotal = $bByObject ? $mixedCycle->$_sCyclesTotal : (int)$mixedCycle[$_sCyclesTotal];
  794. switch($sCycleType) {
  795. case 'TRIAL':
  796. $bTrial = $iCyclesCompleted <= $iCyclesTotal;
  797. break;
  798. case 'REGULAR':
  799. if($iCyclesCompleted == 0)
  800. break;
  801. $bPaid = true;
  802. $bTrial = false;
  803. break 2;
  804. }
  805. }
  806. return [$bPaid, $bTrial];
  807. }
  808. }
  809. /** @} */