BxPaymentProviderBitPay.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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('BP_STATUS_NEW', 'new');
  12. define('BP_STATUS_PAID', 'paid');
  13. define('BP_STATUS_CONFIRMED', 'confirmed');
  14. define('BP_STATUS_COMPLETE', 'complete');
  15. define('BP_STATUS_EXPIRED', 'expired');
  16. define('BP_STATUS_INVALID', 'invalid');
  17. define('BP_SPEED_HIGH', 'high');
  18. define('BP_SPEED_MEDIUM', 'medium');
  19. define('BP_SPEED_LOW', 'low');
  20. class BxPaymentProviderBitPay extends BxBaseModPaymentProvider implements iBxBaseModPaymentProvider
  21. {
  22. function __construct($aConfig)
  23. {
  24. $this->MODULE = 'bx_payment';
  25. parent::__construct($aConfig);
  26. $this->_initializeOptions();
  27. }
  28. public function initializeCheckout($iPendingId, $aCartInfo)
  29. {
  30. $this->aBpOptions['redirectURL'] .= $aCartInfo['vendor_id'];
  31. $this->aBpOptions['notificationURL'] .= $aCartInfo['vendor_id'];
  32. $this->aBpOptions['notificationURL'] = bx_append_url_params($this->aBpOptions['notificationURL'], array('bxssl' => 1));
  33. switch ($aCartInfo['vendor_currency_code']) {
  34. case 'USD':
  35. case 'EUR':
  36. case 'BTC':
  37. $this->aBpOptions['currency'] = $aCartInfo['vendor_currency_code'];
  38. }
  39. $aPosData = array(
  40. 'vnd' => (string)$aCartInfo['vendor_id'],
  41. 'clt' => (string)$aCartInfo['client_id'],
  42. 'pnd' => (string)$iPendingId
  43. );
  44. $aOptions = array(
  45. 'itemDesc' => 'Payment to ' . $aCartInfo['vendor_profile_name']
  46. );
  47. $aResponse = $this->createInvoice($iPendingId, (float)$aCartInfo['items_price'], $aPosData, $aOptions);
  48. if(!empty($aResponse['error']))
  49. return _t(is_array($aResponse['error']) ? $aResponse['error']['message'] : $aResponse['error']);
  50. header('Location: ' . $aResponse['url']);
  51. exit;
  52. }
  53. public function finalizeCheckout(&$aData)
  54. {
  55. $aData = $this->_verifyNotification();
  56. if($aData === false)
  57. return array('code' => 2, 'message' => _t('_payment_bp_err_no_data_given'));
  58. if(empty($this->_aOptions) && isset($aData['posData']['d']['pnd'])) {
  59. $this->_aOptions = $this->getOptionsByPending($aData['posData']['d']['pnd']);
  60. if(empty($this->_aOptions))
  61. return array('code' => 3, 'message' => _t('_payment_bp_err_no_vendor_given'));
  62. $this->_initializeOptions();
  63. }
  64. $aPosData = $this->_verifyPosData($aData['posData']);
  65. if($aPosData === false)
  66. return array('code' => 4, 'message' => _t('_payment_bp_err_incorrect_data'));
  67. //--- Update pending transaction ---//
  68. $sStatus = $aData['status'];
  69. $sMessage = '';
  70. $sResult = $this->_verifyAmount($aPosData, $aData['price']);
  71. if($sResult === false) {
  72. $sStatus = BP_STATUS_INVALID;
  73. $sMessage = _t('_payment_bp_err_wrong_amount');
  74. }
  75. $iPendingId = (int)$aPosData['pnd'];
  76. $sOrderId = Bx_process_input($aData['id']);
  77. $this->_oModule->_oDb->updateOrderPending($iPendingId, array(
  78. 'order' => $sOrderId,
  79. 'error_code' => $sStatus,
  80. 'error_msg' => $sMessage
  81. ));
  82. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  83. if((int)$aPending['processed'] != 0)
  84. return array('code' => 6, 'message' => _t('_payment_bp_err_already_processed'));
  85. //--- Process purchased items in the database if STATUS became CONFIRMED (HIGH and MEDIUM speed), COMPLETE (LOW speed)
  86. $sSpeed = $this->aBpOptions['transactionSpeed'];
  87. if(!((in_array($sSpeed, array(BP_SPEED_HIGH, BP_SPEED_MEDIUM)) && $sStatus == BP_STATUS_CONFIRMED) || ($sSpeed == BP_SPEED_LOW && $sStatus == BP_STATUS_COMPLETE)))
  88. return array('code' => 7, 'message' => _t('_payment_bp_err_no_confirmation_given'));
  89. return array(
  90. 'code' => BX_PAYMENT_RESULT_SUCCESS,
  91. 'message' => '',
  92. 'pending_id' => $iPendingId,
  93. 'paid' => true
  94. );
  95. }
  96. public function finalizedCheckout()
  97. {
  98. return array(
  99. 'message' => _t('_payment_bp_msg_checkout_finished')
  100. );
  101. }
  102. /**
  103. *
  104. * Creates BitPay invoice via Bitpay::curl.
  105. *
  106. * @param string $orderId, string $price, string $posData, array $options
  107. * @return array $response
  108. * @throws Exception $e
  109. *
  110. */
  111. public function createInvoice($orderId, $price, $posData, $options = array()) {
  112. // $orderId: Used to display an orderID to the buyer. In the account summary view, this value is used to
  113. // identify a ledger entry if present. Maximum length is 100 characters.
  114. //
  115. // $price: by default, $price is expressed in the currency you set in Bitpay::aOptions['currency'].
  116. //
  117. // $posData: this field is included in status updates or requests to get an invoice. It is intended to be used by
  118. // the merchant to uniquely identify an order associated with an invoice in their system. Aside from that, Bit-Pay does
  119. // not use the data in this field. The data in this field can be anything that is meaningful to the merchant.
  120. // Maximum length is 100 characters.
  121. //
  122. // Note: Using the posData hash option will APPEND the hash to the posData field and could push you over the 100
  123. // character limit.
  124. //
  125. // $options keys can include any of:
  126. // 'itemDesc', 'itemCode', 'notificationEmail', 'notificationURL', 'redirectURL', 'apiKey'
  127. // 'currency', 'physical', 'fullNotifications', 'transactionSpeed', 'buyerName',
  128. // 'buyerAddress1', 'buyerAddress2', 'buyerCity', 'buyerState', 'buyerZip', 'buyerEmail', 'buyerPhone'
  129. //
  130. // If a given option is not provided here, the value of that option will default to what is found in Bitpay::aOptions
  131. try {
  132. $options = array_merge($this->aBpOptions, $options); // $options override any options found in Bitpay::aOptions
  133. $pos = array('d' => $posData);
  134. if ($this->aBpOptions['verifyPos'])
  135. $pos['h'] = $this->_hash(serialize($posData), $options['apiKey']);
  136. $options['posData'] = json_encode($pos);
  137. if(strlen($options['posData']) > 100)
  138. return array('error' => '_payment_bp_err_posdata_exceed_limit');
  139. $options['orderID'] = $orderId;
  140. $options['price'] = $price;
  141. $postOptions = array('orderID', 'itemDesc', 'itemCode', 'notificationEmail', 'notificationURL', 'redirectURL',
  142. 'posData', 'price', 'currency', 'physical', 'fullNotifications', 'transactionSpeed', 'buyerName',
  143. 'buyerAddress1', 'buyerAddress2', 'buyerCity', 'buyerState', 'buyerZip', 'buyerEmail', 'buyerPhone');
  144. foreach($postOptions as $o) {
  145. if (array_key_exists($o, $options))
  146. $post[$o] = $options[$o];
  147. }
  148. $post = json_encode($post);
  149. $response = $this->_curl('https://bitpay.com/api/invoice/', $options['apiKey'], $post);
  150. if($this->aBpOptions['useLogging']) {
  151. $this->log('Create Invoice: ');
  152. $this->log('-- Data: ' . $post);
  153. $this->log('Response: ');
  154. $this->log($response);
  155. }
  156. return $response;
  157. }
  158. catch (Exception $e) {
  159. if($this->aBpOptions['useLogging'])
  160. $this->log('Error: ' . $e->getMessage());
  161. return array('error' => $e->getMessage());
  162. }
  163. }
  164. /**
  165. *
  166. * Retrieves an invoice from BitPay. $options can include 'apiKey'
  167. *
  168. * @param string $invoiceId, boolean $apiKey
  169. * @return mixed $json
  170. * @throws Exception $e
  171. *
  172. */
  173. public function getInvoice($invoiceId, $apiKey=false) {
  174. try {
  175. if (!$apiKey)
  176. $apiKey = $this->aBpOptions['apiKey'];
  177. $response = $this->_curl('https://bitpay.com/api/invoice/'.$invoiceId, $apiKey);
  178. if (is_string($response))
  179. return $response; // error
  180. $response['posData'] = json_decode($response['posData'], true);
  181. $response['posData'] = $response['posData']['d'];
  182. return $response;
  183. }
  184. catch (Exception $e) {
  185. if($this->aBpOptions['useLogging'])
  186. $this->log('Error: ' . $e->getMessage());
  187. return 'Error: ' . $e->getMessage();
  188. }
  189. }
  190. /**
  191. *
  192. * Retrieves a list of all supported currencies
  193. * and returns associative array.
  194. *
  195. * @param none
  196. * @return array $currencies
  197. * @throws Exception $e
  198. *
  199. */
  200. function getCurrencyList() {
  201. $currencies = array();
  202. $rate_url = 'https://bitpay.com/api/rates';
  203. try {
  204. $clist = json_decode(file_get_contents($rate_url),true);
  205. foreach($clist as $key => $value)
  206. $currencies[$value['code']] = $value['name'];
  207. return $currencies;
  208. }
  209. catch (Exception $e) {
  210. if($this->aBpOptions['useLogging'])
  211. $this->log('Error: ' . $e->getMessage());
  212. return 'Error: ' . $e->getMessage();
  213. }
  214. }
  215. /**
  216. *
  217. * Retrieves the current rate based on $code.
  218. * The default code us USD, so calling the
  219. * function without a parameter will return
  220. * the current BTC/USD price.
  221. *
  222. * @param string $code
  223. * @return string $rate
  224. * @throws Exception $e
  225. *
  226. */
  227. public function getRate($code = 'USD') {
  228. $rate_url = 'https://bitpay.com/api/rates';
  229. try {
  230. $clist = json_decode(file_get_contents($rate_url),true);
  231. foreach($clist as $key => $value) {
  232. if($value['code'] == $code)
  233. $rate = number_format($value['rate'], 2, '.', '');
  234. }
  235. return $rate;
  236. }
  237. catch (Exception $e) {
  238. if($this->aBpOptions['useLogging'])
  239. $this->log('Error: ' . $e->getMessage());
  240. return 'Error: ' . $e->getMessage();
  241. }
  242. }
  243. protected function _initializeOptions() {
  244. // REQUIRED Api key you created at bitpay.com
  245. $this->aBpOptions['apiKey'] = $this->getOption('api_key');
  246. // whether to verify POS data by hashing above api key. If set to false, you should
  247. // have some way of verifying that callback data comes from bitpay.com
  248. // note: this option can only be changed here. It cannot be set dynamically.
  249. $this->aBpOptions['verifyPos'] = true;
  250. // email where invoice update notifications should be sent
  251. $this->aBpOptions['notificationEmail'] = $this->getOption('notification_email');
  252. // url where bit-pay server should send update notifications. See API doc for more details.
  253. // example: $bpNotificationUrl = 'http://www.example.com/callback.php';
  254. $this->aBpOptions['notificationURL'] = $this->_oModule->_oConfig->getUrl('URL_RETURN_DATA', array(), true) . $this->_sName . '/';
  255. // url where the customer should be directed to after paying for the order
  256. // example: $bpNotificationUrl = 'http://www.example.com/confirmation.php';
  257. $this->aBpOptions['redirectURL'] = BX_DOL_URL_ROOT . $this->_oModule->_oConfig->getBaseUri() . 'act_checkout_finished/' . $this->_sName . '/';
  258. // This is the currency used for the price setting. A list of other pricing
  259. // currencies supported is found at bitpay.com
  260. $this->aBpOptions['currency'] = 'BTC';
  261. // Indicates whether anything is to be shipped with the order
  262. // (if false, the buyer will be informed that nothing is to be shipped)
  263. $this->aBpOptions['physical'] = false;
  264. // If set to false, then notificaitions are only
  265. // sent when an invoice is confirmed (according the the
  266. // transactionSpeed setting). If set to true, then a notification
  267. // will be sent on every status change
  268. $this->aBpOptions['fullNotifications'] = $this->getOption('full_notifications') == 'on';
  269. // transaction speed: low/medium/high. See API docs for more details.
  270. $this->aBpOptions['transactionSpeed'] = $this->getOption('transaction_speed');
  271. // Change to 'true' if you would like automatic logging of invoices and errors.
  272. // Otherwise you will have to call the bpLog function manually to log any information.
  273. $this->aBpOptions['useLogging'] = true;
  274. }
  275. /**
  276. *
  277. * Call from your notification handler to convert $_POST data to an object containing invoice data
  278. *
  279. * @param boolean $apiKey
  280. * @return mixed $json
  281. * @throws Exception $e
  282. *
  283. */
  284. protected function _verifyNotification() {
  285. try {
  286. $this->log('Notification received: ' . date("m.d.y H:i:s"));
  287. $post = file_get_contents("php://input");
  288. if(!$post) {
  289. $this->log('Error: No post data');
  290. return false;
  291. }
  292. $json = json_decode($post, true);
  293. $this->log('-- Data: ' . $post);
  294. $this->log($json);
  295. if(is_string($json))
  296. return false;
  297. if(!array_key_exists('posData', $json)) {
  298. $this->log('Error: No posData');
  299. return false;
  300. }
  301. $json['posData'] = json_decode($json['posData'], true);
  302. if(empty($json['posData']) || !is_array($json['posData'])) {
  303. $this->log('Error: Empty posData');
  304. return false;
  305. }
  306. return $json;
  307. }
  308. catch (Exception $e) {
  309. if($this->aBpOptions['useLogging'])
  310. $this->log('Error: ' . $e->getMessage());
  311. return false;
  312. }
  313. }
  314. /**
  315. *
  316. * Call from your notification handler to verify posData
  317. *
  318. * @param array $aPosData
  319. * @return boolean
  320. *
  321. */
  322. protected function _verifyPosData($aPosData) {
  323. if(!$this->aBpOptions['verifyPos']) {
  324. if(empty($aPosData['d']) || !is_array($aPosData['d'])) {
  325. $this->log('Error: Payment data cannot be found.');
  326. return false;
  327. }
  328. return $aPosData['d'];
  329. }
  330. if($this->_hash(serialize($aPosData['d']), $this->aBpOptions['apiKey']) != $aPosData['h']) {
  331. $this->log('Error: Authentication failed (bad posData hash).');
  332. return false;
  333. }
  334. return $aPosData['d'];
  335. }
  336. protected function _verifyAmount($aPosData, $fAmount) {
  337. $iPendingId = (int)$aPosData['pnd'];
  338. $aPending = $this->_oModule->_oDb->getOrderPending(array('type' => 'id', 'id' => $iPendingId));
  339. if(empty($aPending) || !is_array($aPending) || $fAmount != (float)$aPending['amount'])
  340. return false;
  341. return true;
  342. }
  343. /**
  344. *
  345. * Decodes JSON response and returns
  346. * associative array.
  347. *
  348. * @param string $response
  349. * @return array $arrResponse
  350. * @throws Exception $e
  351. *
  352. */
  353. protected function _decodeResponse($response) {
  354. try {
  355. if (empty($response) || !(is_string($response)))
  356. return array('error' => 'BxPmtBitPay::_decodeResponse expects a string parameter.');
  357. return json_decode($response, true);
  358. }
  359. catch (Exception $e) {
  360. if($this->aBpOptions['useLogging'])
  361. $this->log('Error: ' . $e->getMessage());
  362. return array('error' => $e->getMessage());
  363. }
  364. }
  365. /**
  366. *
  367. * Generates a base64 encoded keyed hash.
  368. *
  369. * @param string $data, string $key
  370. * @return string $hmac
  371. * @throws Exception $e
  372. *
  373. */
  374. protected function _hash($data, $key) {
  375. try {
  376. $hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE));
  377. return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
  378. }
  379. catch (Exception $e) {
  380. if($this->aBpOptions['useLogging'])
  381. $this->log('Error: ' . $e->getMessage());
  382. return 'Error: ' . $e->getMessage();
  383. }
  384. }
  385. /**
  386. *
  387. * Handles post/get to BitPay via curl.
  388. *
  389. * @param string $url, string $apiKey, boolean $post
  390. * @return mixed $response
  391. * @throws Exception $e
  392. *
  393. */
  394. protected function _curl($url, $apiKey, $post = false) {
  395. if(!isset($url) || trim($url) == '' || !isset($apiKey) || trim($apiKey) == '') {
  396. // Invalid parameter specified
  397. if($this->aBpOptions['useLogging'])
  398. $this->log('Error: You must supply non-empty url and apiKey parameters.');
  399. return array('error' => 'You must supply non-empty url and apiKey parameters.');
  400. }
  401. try {
  402. $curl = curl_init();
  403. $length = 0;
  404. if ($post) {
  405. curl_setopt($curl, CURLOPT_POST, 1);
  406. curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
  407. $length = strlen($post);
  408. }
  409. $uname = base64_encode($apiKey);
  410. if($uname) {
  411. $header = array(
  412. 'Content-Type: application/json',
  413. 'Content-Length: ' . $length,
  414. 'Authorization: Basic ' . $uname,
  415. );
  416. curl_setopt($curl, CURLOPT_URL, $url);
  417. curl_setopt($curl, CURLOPT_PORT, 443);
  418. curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  419. curl_setopt($curl, CURLOPT_TIMEOUT, 10);
  420. curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
  421. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1); // verify certificate
  422. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // check existence of CN and verify that it matches hostname
  423. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  424. curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);
  425. curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);
  426. $responseString = curl_exec($curl);
  427. if($responseString == false) {
  428. $response = array('error' => curl_error($curl));
  429. if($this->aBpOptions['useLogging'])
  430. $this->log('Error: ' . curl_error($curl));
  431. }
  432. else {
  433. $response = json_decode($responseString, true);
  434. if (!$response) {
  435. $response = array('error' => 'invalid json: '.$responseString);
  436. if($this->aBpOptions['useLogging'])
  437. $this->log('Error - Invalid JSON: ' . $responseString);
  438. }
  439. }
  440. curl_close($curl);
  441. return $response;
  442. }
  443. else {
  444. curl_close($curl);
  445. if($this->aBpOptions['useLogging'])
  446. $this->log('Invalid data found in apiKey value passed to Bitpay::curl method. (Failed: base64_encode(apikey))');
  447. return array('error' => 'Invalid data found in apiKey value passed to Bitpay::curl method. (Failed: base64_encode(apikey))');
  448. }
  449. }
  450. catch (Exception $e) {
  451. @curl_close($curl);
  452. if($this->aBpOptions['useLogging'])
  453. $this->log('Error: ' . $e->getMessage());
  454. return array('error' => $e->getMessage());
  455. }
  456. }
  457. }
  458. /** @} */