Compare commits

...

63 Commits

Author SHA1 Message Date
Nicolas Dorier
4c0bf5a5bf
Update README.md 2021-11-08 21:02:40 +09:00
nicolas.dorier
75bd0f95f5
bump version 2021-10-03 10:42:34 +09:00
Nicolas Dorier
d59411a396
Merge pull request #23 from ndeet/patch-1
Fix Lets Encrypt root cert error
2021-10-03 10:40:16 +09:00
Andreas Tasch
16862d2ed6
Fix Lets Encrypt root cert error
@NicolasDorier 

Do not use the custom ca-bundle.crt as it contains outdated certs and there is no obvious reason imo to why even use it at all. Normally the system ssl library is good enough for major SSL certs to work. Maybe Bitpay had some need for self signed certs or something to even do that.

Note: just did edit in the web UI and not delete the ca-bundle.crt file for now.

Context:
https://chat.btcpayserver.org/btcpayserver/pl/cm9itj98hfbr9jgiq4t38hkeuw

including the comments afterwards of another user that tried this fix successfully.

Todo: after merging this somebody needs to do a WooCommerce plugin release, not sure who is in charge of that atm.
2021-10-02 22:52:09 +02:00
Andrew Camilleri
3b161c5d00
Merge pull request #22 from ndeet/allow-any-currency
Allow any currency symbol via overloaded class.
2021-01-29 12:24:57 +01:00
Andrew Camilleri
ca9e77e5df
Merge pull request #21 from ndeet/payment-currencies
Support for payment currencies.
2021-01-29 12:24:28 +01:00
Andreas Tasch
01057e8da8 Make sure to use CurrencyUnrestricted here to not break IPN callback. 2021-01-26 14:22:46 +01:00
Andreas Tasch
5522adcf5e Allow any currency symbol via overloaded class. 2021-01-26 13:28:07 +01:00
Andreas Tasch
c41360a6e2 Support for payment currencies. 2021-01-26 13:24:33 +01:00
nicolas.dorier
7815bc0312
bump ca 2020-07-17 21:07:10 +09:00
nicolas.dorier
79ac751e54 fix version 2019-04-23 16:33:13 +09:00
nicolas.dorier
3e0425497c do not try to clean orderId 2019-04-23 15:35:12 +09:00
Nicolas Dorier
1e08ee7c91
Merge pull request #16 from kakaska/fix-get-invoice-tutorial
Fix getInvoice.php and IPNlogger.php tutorial
2019-02-26 13:44:43 +09:00
kakaska
f04618c667 Fix IPNlogger.php tutorial 2019-02-25 22:27:17 +01:00
kakaska
8b3f1663f1 Fix getInvoice.php tutorial 2019-02-25 19:00:35 +01:00
Nicolas Dorier
43076fdd9b
Merge pull request #12 from psyb0t/fix/remove-null-props-when-creating-invoice
Check body object keys for null value and unset them if found
2019-02-21 18:21:35 +09:00
Ciprian Mandache
79d1f1e51b Check body object keys for null value and unset them if found 2019-02-21 11:07:40 +02:00
Nicolas Dorier
36578f803c
Merge pull request #8 from kakaska/update-readme
Update README.md installation section
2019-02-17 20:34:00 +09:00
kakaska
dbc3aeec94 Update README.md installation section 2019-02-17 11:40:35 +01:00
Nicolas Dorier
c25d3d3c99
Merge pull request #5 from kakaska/empty-btcpay-server-url
Throw BitpayException when BTCPAY server url is empty
2019-02-17 13:16:14 +09:00
Nicolas Dorier
0f0c73fc75 Merge branch 'master' into empty-btcpay-server-url 2019-02-17 13:12:11 +09:00
Nicolas Dorier
c0c1457e0b
Merge pull request #6 from kakaska/fix-unit-tests
Fix remaining unit tests
2019-02-17 13:06:50 +09:00
kakaska
3087e0cb7c Fix tests in ClientTest 2019-02-14 20:02:37 +01:00
kakaska
6dda744064 Fix tests in ItemTest 2019-02-14 19:08:58 +01:00
kakaska
883381aca0 Fix testProcessAndValidate() test in ConfigurationTest 2019-02-14 18:37:50 +01:00
kakaska
58b99f9c4e Fix testSendRequestWithException() test in CurlAdapterTest 2019-02-14 18:34:05 +01:00
kakaska
95f351271b Fix failed testConfigAbleToPersistAndLoadKeys() test in BitpayTest 2019-02-14 18:29:48 +01:00
kakaska
46b4b18eb5 Throw BitpayException when BTCPAY server url is empty 2019-02-14 17:52:17 +01:00
Nicolas Dorier
cc8e0bc689
Merge pull request #4 from kakaska/fix-examples
Fix examples and tutorials
2019-02-15 00:48:09 +09:00
Nicolas Dorier
5ba10b0db8
Merge pull request #3 from kakaska/fix-unit-tests
Remove Network specific unit tests
2019-02-15 00:47:46 +09:00
nicolas.dorier
3a0fe24279 Fix edge case where HTTP code is 0 2019-02-15 00:44:44 +09:00
kakaska
75baef3fd7 Fix tutorials 2019-02-13 14:44:45 +01:00
kakaska
dcf5659f34 Fix examples 2019-02-13 13:46:22 +01:00
kakaska
4aeedbd176 Clean up code and add testSetUri() in RequestTest 2019-02-12 21:44:22 +01:00
kakaska
dc4f186bcc Fix mock configuration in ClientTest 2019-02-12 21:28:20 +01:00
kakaska
ec1d1585e1 Remove 'network' parameter from BitpayTest 2019-02-12 21:14:19 +01:00
kakaska
d669d272da Remove 'network.class' parameter configuration from BitpayExtension class 2019-02-12 21:00:12 +01:00
kakaska
f3563d4675 Remove Network specific unit tests 2019-02-12 20:52:28 +01:00
nicolas.dorier
6396af895d remove getTaxIncluded from IPNLogger 2019-01-31 13:24:08 +09:00
nicolas.dorier
c37068ead7 Remove NetworkAwareInterface, simplify Client.php 2019-01-26 15:23:47 +09:00
nicolas.dorier
f34dba2448 Add taxIncluded field 2019-01-26 13:56:34 +09:00
nicolas.dorier
958fd250ef remove checkPriceFormat 2019-01-26 13:41:25 +09:00
nicolas.dorier
c829bc38be Throw exception if invalid http code 2019-01-26 13:40:34 +09:00
Pieter Poorthuis
d6d1431895 Updated changelog and version number for v2.2.20 2018-03-28 12:30:37 +02:00
Pieter Poorthuis
b88a7f6978 Fixed tests, fixed default timezone issues 2018-03-28 12:27:19 +02:00
Pieter Poorthuis
3f57af89d7 Version update + changelog for 2.2.19 2018-03-08 12:01:25 +01:00
Pieter Poorthuis
8e93c11c49 Fixed wrong token in example 2018-03-08 11:57:00 +01:00
Pieter Poorthuis
70514da027 Improved verbose information in examples 2018-03-08 11:54:05 +01:00
Pieter Poorthuis
83e2e0e678 Added support for BCH fields, set timezone to UTC 2018-03-08 11:49:16 +01:00
Pieter Poorthuis
a94bfe9b79
Merge pull request #259 from IDLOCKED/patch-1
typo fixed.
2018-02-16 09:04:30 +01:00
IDLOCKED
0fe0e36084
typo fixed. 2018-02-16 14:40:41 +09:00
Pieter Poorthuis
71dfd51280 Actually pushed changes for price float to production 2018-01-15 19:55:40 +01:00
Pieter Poorthuis
a67bd2ffb3 Version updates for 2.2.17 2018-01-15 12:29:05 +01:00
Pieter Poorthuis
d0fbfa4e2d Fixed decimal check for currencies without decimals (e.g. HUF) 2018-01-15 12:24:53 +01:00
Pieter Poorthuis
27cd6c5076 Merge branch 'master' of https://github.com/bitpay/php-bitpay-client 2017-12-12 15:55:07 +01:00
Pieter Poorthuis
2efe083ad0 Version 2.2.16 changelog 2017-12-12 15:54:50 +01:00
Pieter Poorthuis
3b03d922f6
Fixed another support article link 2017-12-12 15:44:38 +01:00
Pieter Poorthuis
23f343de31
Updated links to support articles 2017-12-12 15:42:54 +01:00
Pieter Poorthuis
0cc78c32f2 Fixed invoice time handling, added hosted payment page example 2017-12-12 15:24:21 +01:00
Pieter Poorthuis
7a06724b25
Removed deprecated factory methods 2017-12-04 09:22:00 +01:00
Pieter Poorthuis
970dfd8269
Merge pull request #255 from arubacao/patch-3
Update .travis.yml to also test against PHP 7.2
2017-12-01 13:39:01 +01:00
arubacao
8dbac51e39
Update .travis.yml to also test against PHP 7.2 2017-12-01 12:40:20 +01:00
Pieter Poorthuis
34e24646a5 Removed mcrypt from composer, fixed datetime invoice setting issue 2017-11-28 11:12:45 +01:00
53 changed files with 1907 additions and 2593 deletions

View File

@ -6,6 +6,7 @@ php:
- 5.6
- 7.0
- 7.1
- 7.2
install:
- composer install

View File

@ -2,6 +2,46 @@
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [2.2.20] - 2018-03-28
### Fixed
- Fixed failing phpunit tests (#262)
- Fixed DateTime zone issues (#261)
- Fixed $invoice->getPaymentTotals() returns subTotals instead (#264)
## [2.2.19] - 2018-03-08
### Added
- Added support for BCH fields in the invoice: transactionCurrency, amountPaid, exchangeRates, paymentSubtotals, paymentTotals
### Fixed
- Set timezone to UTC (=timezone that BitPay invoices use), to prevent PHP errors when no default timezone is set
### Deprecated
- Deprecated BTC specific fields, as documented at https://bitpay.com/api#resource-Invoices
## [2.2.18] - 2018-01-15
### Fixed
- Pushed actual code changes to GitHub from previous release
## [2.2.17] - 2018-01-15
### Fixed
- Fixed decimal check for currencies without decimals (e.g. HUF)
## [2.2.16] - 2017-12-12
### Fixed
- Fixed invoice time being set in milliseconds, whereas seconds are expected (Issue #256 and #257)
- Removed deprecated factory methods from services.xml
## [2.2.15] - 2017-11-28
### Fixed
- Fixed invoice time being set as numeric instead of datetime object
### Removed
- Removed support for mcrypt (#254)
## [2.2.14] - 2017-09-27
### Fixed
- Fixed token check in get invoices method for public facade calls (#243)

View File

@ -1,3 +1,7 @@
# === Warning ===
This is the old BitPay based PHP client and should be considered deprecated (even though it currently still works). If you are building something from scratch, [use the new Greenfield API](https://github.com/btcpayserver/btcpayserver-greenfield-php).
bitpay/php-bitpay-client
=================
@ -33,8 +37,15 @@ Add to your composer.json file by hand.
...
"require": {
...
"bitpay/php-client": "~2.2"
}
"bitpay/php-client": "dev-master"
},
"repositories": [
...
{
"type": "vcs",
"url": "https://github.com/btcpayserver/php-bitpay-client"
}
],
...
}
```

View File

@ -1 +1 @@
2.2.14
2.2.20

View File

@ -28,7 +28,6 @@
"ext-curl": "*",
"ext-json": "*",
"ext-openssl": "*",
"ext-mcrypt": "*",
"symfony/config": "^2.3 || ^3.0",
"symfony/dependency-injection": "^2.3 || ^3.0"
},

View File

@ -66,16 +66,31 @@ $currency->setCode('USD');
$invoice->setCurrency($currency);
/**
* Create a new client. You can see the example of how to configure this using
* a yml file as well.
* To load up keys that you have previously saved, you need to use the same
* storage engine. You also need to tell it the location of the key you want
* to load.
*/
$bitpay = new \Bitpay\Bitpay(__DIR__ . '/config.yml');
$storageEngine = new \Bitpay\Storage\FilesystemStorage();
$privateKey = $storageEngine->load('/tmp/private.key');
$publicKey = $storageEngine->load('/tmp/public.key');
/**
* Create a new client.
*/
$bitpay = new \Bitpay\Bitpay();
/**
* Create the client that will be used to send requests to BitPay's API
*/
$client = $bitpay->get('client');
$client->setPrivateKey($privateKey);
$client->setPublicKey($publicKey);
/**
* Add your btcpayserver url
*/
$client->setUri('https://btcpay.server/');
/**
* You will need to set the token that was returned when you paired your
* keys.

View File

@ -44,16 +44,14 @@ $private->setHex('662be90968bc659873d723374213fa5bf7a30c24f0f0713aa798eb7daa7230
$public = new \Bitpay\PublicKey();
$public->generate($private);
$network = new \Bitpay\Network\Testnet();
$adapter = new \Bitpay\Client\Adapter\CurlAdapter();
$bitpay = new \Bitpay\Bitpay();
$client = new \Bitpay\Client\Client();
$client->setPrivateKey($private);
$client->setPublicKey($public);
$client->setNetwork($network);
$client->setUri('https://btcpay.server/');
$client->setAdapter($adapter);
$client->createPayout($payout);

View File

@ -7,6 +7,7 @@ require __DIR__ . '/../vendor/autoload.php';
$bitpay = new \Bitpay\Bitpay(__DIR__ . '/config.yml');
$client = $bitpay->get('client');
$client->setUri('https://btcpay.server/');
$currencies = $client->getCurrencies();
/** @var \Bitpay\Currency $currencies[0] **/

View File

@ -7,9 +7,8 @@ require __DIR__ . '/../vendor/autoload.php';
$client = new \Bitpay\Client\Client();
$client->setAdapter(new \Bitpay\Client\Adapter\CurlAdapter());
$client->setNetwork(new \Bitpay\Network\Testnet());
$request = new \Bitpay\Client\Request();
$request->setHost('test.bitpay.com');
$request->setUri('https://btcpay.server/');
$request->setMethod(\Bitpay\Client\Request::METHOD_GET);
$request->setPath('rates/USD');

View File

@ -14,6 +14,14 @@
require __DIR__ . '/../vendor/autoload.php';
/**
* To load up keys that you have previously saved, you need to use the same
* storage engine. You also need to tell it the location of the key you want
* to load.
*/
$storageEngine = new \Bitpay\Storage\FilesystemStorage();
$privateKey = $storageEngine->load('/tmp/bitpay.pri');
$publicKey = $storageEngine->load('/tmp/bitpay.pub');
/**
* Create a new client. You can see the example of how to configure this using
@ -22,7 +30,6 @@ require __DIR__ . '/../vendor/autoload.php';
$bitpay = new \Bitpay\Bitpay(
array(
'bitpay' => array(
'network' => 'testnet', // testnet or livenet, default is livenet
'public_key' => '/tmp/bitpay.pub', //see tutorial/001.php and 002.php
'private_key' => '/tmp/bitpay.pri',
'key_storage' => 'Bitpay\Storage\EncryptedFilesystemStorage',
@ -36,5 +43,12 @@ $bitpay = new \Bitpay\Bitpay(
*/
$client = $bitpay->get('client');
$client->setPrivateKey($privateKey);
$client->setPublicKey($publicKey);
/**
* Add your btcpayserver url
*/
$client->setUri('https://btcpay.server/');
$tokens = $client->getTokens();
print_r($tokens);

View File

@ -5,9 +5,6 @@
require __DIR__ . '/../vendor/autoload.php';
// When running bitpay on your local server
$network = new Bitpay\Network\Customnet("127.0.0.1", 8088, true);
// Customize the curl options
$curl_options = array(
CURLOPT_SSL_VERIFYPEER => false,

View File

@ -28,13 +28,6 @@ $publicKey = $storageEngine->load('/tmp/bitpay.pub');
*/
$client = new \Bitpay\Client\Client();
/**
* The network is either livenet or testnet. You can also create your
* own as long as it implements the NetworkInterface. In this example
* we will use testnet
*/
$network = new \Bitpay\Network\Testnet();
/**
* The adapter is what will make the calls to BitPay and return the response
* from BitPay. This can be updated or changed as long as it implements the
@ -47,7 +40,12 @@ $adapter = new \Bitpay\Client\Adapter\CurlAdapter();
*/
$client->setPrivateKey($privateKey);
$client->setPublicKey($publicKey);
$client->setNetwork($network);
/**
* Add your btcpayserver url
*/
$client->setUri('https://btcpay.server/');
$client->setAdapter($adapter);
/**
@ -79,7 +77,9 @@ try {
* decided that it makes more sense to allow your application to handle
* this exception since each app is different and has different requirements.
*/
echo "Pairing failed. Please check whether you're trying to pair a production pairing code on test.";
echo "Exception occured: " . $e->getMessage().PHP_EOL;
echo "Pairing failed. Please check whether you're trying to pair a production pairing code on test.".PHP_EOL;
$request = $client->getRequest();
$response = $client->getResponse();
/**

View File

@ -17,11 +17,10 @@ $storageEngine = new \Bitpay\Storage\EncryptedFilesystemStorage('YourTopSecretPa
$privateKey = $storageEngine->load('/tmp/bitpay.pri');
$publicKey = $storageEngine->load('/tmp/bitpay.pub');
$client = new \Bitpay\Client\Client();
$network = new \Bitpay\Network\Testnet();
$adapter = new \Bitpay\Client\Adapter\CurlAdapter();
$client->setPrivateKey($privateKey);
$client->setPublicKey($publicKey);
$client->setNetwork($network);
$client->setUri('https://btcpay.server/');
$client->setAdapter($adapter);
// ---------------------------
@ -81,8 +80,10 @@ $invoice
* a customer can view the invoice.
*/
try {
echo "Creating invoice at BitPay now.".PHP_EOL;
$client->createInvoice($invoice);
} catch (\Exception $e) {
echo "Exception occured: " . $e->getMessage().PHP_EOL;
$request = $client->getRequest();
$response = $client->getResponse();
echo (string) $request.PHP_EOL.PHP_EOL.PHP_EOL;
@ -91,3 +92,5 @@ try {
}
echo 'Invoice "'.$invoice->getId().'" created, see '.$invoice->getUrl().PHP_EOL;
echo "Verbose details.".PHP_EOL;
print_r($invoice);

View File

@ -0,0 +1,113 @@
<?php
/**
* Copyright (c) 2014-2017 BitPay
*
* 004 - Hosted payment page: create & display invoice
* For details on displaying invoices, see https://bitpay.com/docs/display-invoice
*
* Requirements:
* - Account on https://test.bitpay.com
* - Basic PHP Knowledge
* - Private and Public keys from 001.php
* - Token value obtained from 002.php
* - A webserver to run the code. Running locally works with firefox, but not with Safari & Chrome
*/
require __DIR__.'/../../vendor/autoload.php';
// See 002.php for explanation
$storageEngine = new \Bitpay\Storage\EncryptedFilesystemStorage('YourTopSecretPassword'); // Password may need to be updated if you changed it
$privateKey = $storageEngine->load('/tmp/bitpay.pri');
$publicKey = $storageEngine->load('/tmp/bitpay.pub');
$client = new \Bitpay\Client\Client();
$adapter = new \Bitpay\Client\Adapter\CurlAdapter();
$client->setPrivateKey($privateKey);
$client->setPublicKey($publicKey);
$client->setUri('https://btcpay.server/');
$client->setAdapter($adapter);
// ---------------------------
/**
* The last object that must be injected is the token object.
*/
$token = new \Bitpay\Token();
$token->setToken('UpdateThisValue'); // UPDATE THIS VALUE
/**
* Token object is injected into the client
*/
$client->setToken($token);
/**
* This is where we will start to create an Invoice object, make sure to check
* the InvoiceInterface for methods that you can use.
*/
$invoice = new \Bitpay\Invoice();
$buyer = new \Bitpay\Buyer();
$buyerEmail = "buyeremail@test.com";
$buyer
->setEmail($buyerEmail);
// Add the buyers info to invoice
$invoice->setBuyer($buyer);
/**
* Item is used to keep track of a few things
*/
$item = new \Bitpay\Item();
$item
->setCode('skuNumber')
->setDescription('General Description of Item')
->setPrice('1.99');
$invoice->setItem($item);
/**
* BitPay supports multiple different currencies. Most shopping cart applications
* and applications in general have defined set of currencies that can be used.
* Setting this to one of the supported currencies will create an invoice using
* the exchange rate for that currency.
*
* @see https://test.bitpay.com/bitcoin-exchange-rates for supported currencies
*/
$invoice->setCurrency(new \Bitpay\Currency('USD'));
// Configure the rest of the invoice
$invoice
->setOrderId('OrderIdFromYourSystem')
// You will receive IPN's at this URL, should be HTTPS for security purposes!
->setNotificationUrl('https://store.example.com/bitpay/callback');
/**
* Updates invoice with new information such as the invoice id and the URL where
* a customer can view the invoice.
*/
try {
$client->createInvoice($invoice);
} catch (\Exception $e) {
$request = $client->getRequest();
$response = $client->getResponse();
echo (string) $request.PHP_EOL.PHP_EOL.PHP_EOL;
echo (string) $response.PHP_EOL.PHP_EOL;
exit(1); // We do not want to continue if something went wrong
}
?>
<html>
<head><title>BitPay - Modal CSS invoice demo</title></head>
<body bgcolor="rgb(21,28,111)" textcolor="rgb(255,255,255)">
<button onclick="openInvoice()">Pay Now</button>
<br><br><br>
For more information about BitPay's modal CSS invoice, please see <a href="https://bitpay.com/docs/display-invoice" target="_blank">https://bitpay.com/docs/display-invoice</a>
</body>
<script src="https://bitpay.com/bitpay.js"> </script>
<script>
function openInvoice() {
var network = "testnet"
if (network == "testnet")
bitpay.setApiUrlPrefix("https://test.bitpay.com")
else
bitpay.setApiUrlPrefix("https://bitpay.com")
bitpay.showInvoice("<?php echo $invoice->getId();?>");
}
</script>
</html>

View File

@ -34,7 +34,7 @@ if (true === empty($ipn)) {
throw new \Exception('Could not decode the JSON payload from BitPay.');
}
if (true === empty($ipn -> id)) {
if (true === empty($ipn->id)) {
fwrite($myfile, $date . " : Error. Invalid Bitpay payment notification message received - did not receive invoice ID.\n");
fclose($myfile);
throw new \Exception('Invalid Bitpay payment notification message received - did not receive invoice ID.');
@ -42,16 +42,20 @@ if (true === empty($ipn -> id)) {
// Now fetch the invoice from BitPay
// This is needed, since the IPN does not contain any authentication
$storageEngine = new \Bitpay\Storage\EncryptedFilesystemStorage('YourTopSecretPassword');
$privateKey = $storageEngine->load('/tmp/bitpay.pri');
$publicKey = $storageEngine->load('/tmp/bitpay.pub');
$client = new \Bitpay\Client\Client();
$network = new \Bitpay\Network\Testnet();
//$network = new \Bitpay\Network\Livenet();
$adapter = new \Bitpay\Client\Adapter\CurlAdapter();
$client->setNetwork($network);
$client->setPrivateKey($privateKey);
$client->setPublicKey($publicKey);
$client->setUri('https://btcpay.server/');
$client->setAdapter($adapter);
$token = new \Bitpay\Token();
$token->setToken('UpdateThisValue'); // UPDATE THIS VALUE
$client->setToken($token);
$token->setFacade('merchant');
/**
* This is where we will fetch the invoice object
@ -62,10 +66,9 @@ $invoiceStatus = $invoice->getStatus();
$invoiceExceptionStatus = $invoice->getExceptionStatus();
$invoicePrice = $invoice->getPrice();
fwrite($myfile, $date . " : IPN received for BitPay invoice ".$invoiceId." . Status = " .$invoiceStatus." / exceptionStatus = " . $invoiceExceptionStatus." Price = ". $invoicePrice. "\n");
fwrite($myfile, $date . " : IPN received for BitPay invoice ".$invoiceId." . Status = " .$invoiceStatus." / exceptionStatus = " . $invoiceExceptionStatus." Price = ". $invoicePrice." Tax Included = ". $taxIncluded."\n");
fwrite($myfile, "Raw IPN: ". $raw_post_data."\n");
//Respond with HTTP 200, so BitPay knows the IPN has been received correctly
//If BitPay receives <> HTTP 200, then BitPay will try to send the IPN again with increasing intervals for two more hours.
header("HTTP/1.1 200 OK");
?>

View File

@ -2,55 +2,59 @@
==========================
## About this tutorial
This tutorial contains four scripts. These scripts allow you to do the following:
This tutorial contains five scripts. These scripts allow you to do the following:
1) Create keys to communicate with BitPay's API
2) Pair your keys to your BitPay merchant account
3) Create BitPay invoices
4) Log IPNs (Instant Payment Notifications or webhooks)
4) Display a BitPay invoice using BitPay's hosted payment page
5) Log Instant Payment Notifications (IPNs, also called webhooks)
Script 001 & 002 need to be executed once, to properly configure your local installation.
Script 003 creates BitPay invoices; this script can be run permanently.
Script 004 is very similar to script 003. The main difference is that script 004 outputs HTML, so you can run this on your webserver.
IPNs will be sent after a BitPay invoice receives a payment. IPNs can be logged or processed with IPNlogger.php
## Getting started
To begin please visit https://test.bitpay.com/dashboard/signup and register for a BitPay merchant test account. Please fill in all questions, so you get a fully working test account.
To begin please visit https://test.bitpay.com/dashboard/signup and register for a BitPay merchant test account. Please fill in all questions, so you get a fully working test account. When filling in the settlement address in your BitPay merchant test account, make sure to fill in a testnet bitcoin address (starting with m or n).
If you are looking for a testnet bitcoin wallet to test with, please visit https://bitpay.com/wallet and
create a new wallet.
If you are looking for a testnet bitcoin wallet to test with, please visit https://bitpay.com/wallet and create a new wallet.
If you need testnet bitcoin please visit a testnet faucet, e.g. https://testnet.coinfaucet.eu/en/ or http://tpfaucet.appspot.com/
For more information about testing, please see https://bitpay.com/docs/testing
Please make sure to use BitPay's latest PHP library (bitpay/php-client)
To install BitPay's latest PHP library, please follow the instructions from https://github.com/bitpay/php-bitpay-client/blob/master/README.md
## Script 1 & 2: configure your local installation
The following two scripts need to be executed once. These scripts will generate your private/public keys and pair them to your BitPay merchant account:
1. 001_generateKeys.php : generates the private/public keys to sign the communication with BitPay. The private/public keys are stored in your filesystem for later usage.
2. 002_pair.php : pairs your private/public keys to your BitPay merchant account. Please make sure to first create a pairing code in your BitPay merchant account (Payment Tools -> Manage API tokens) and put this pairing code in the script. The script returns an API token that should be put put in 003_createInvoice.php, to create invoices permanently.
2. 002_pair.php : pairs your private/public keys to your BitPay merchant account. Please make sure to first create a pairing code in your BitPay merchant account (Payment Tools -> Manage API tokens -> Add new token -> Add token) and put this 7 character pairing code in the script. The script returns an API token that should be put put in 003_createInvoice.php, to create invoices permanently.
These first two scripts need to be executed only once.
## Script 3: create a BitPay invoice
3. 003_createInvoice.php : creates a BitPay invoice. Please make sure to update the script with the API token received from 002_pair.php
This script returns a BitPay invoice object. You can display the invoice by loading the invoice-URL in a web browser. You can pay the invoice with your bitcoin wallet.
This script returns a BitPay invoice object. You can display the invoice by loading the invoice URL in a web browser. You can pay the invoice with your bitcoin wallet.
For more information about paying a BitPay invoice, please see http://help.bitpay.com/paying-with-bitcoin/order-information-and-assistance/how-do-i-pay-a-bitpay-invoice-using-bitcoin
## Script 4: display a BitPay invoice using BitPay's hosted payment page
4. 004_HostedPaymentPage.php : creates a BitPay invoice and returns the HTML to show the invoice. Please make sure to update the script with the API token received from 002_pair.php
This script can be run permanently.
For more information about paying a BitPay invoice, please see https://support.bitpay.com/hc/en-us/articles/203281456-How-do-I-pay-a-BitPay-invoice-
## Script 4: log IPNs
After you've paid the invoice, BitPay will send an IPN to the notificationURL of the invoice. This script should be put on your server and be reachable from the internet. Your should put the URL of IPNLogger.php in 003_createInvoice.php, e.g.:
Script 003_createInvoice.php and 004_HostedPaymentPage.php can be run permanently with the token from 002_pair.php
## Script 5: log Instant Payment Notifications
After you've paid the invoice, BitPay will send an IPN to the notificationURL of the invoice. A script to process the IPN should be put on your server and be reachable from the internet. Your should put the URL of IPNLogger.php in 003_createInvoice.php, e.g.:
```
// You will receive IPN's at this URL, should be HTTPS for security purposes!
$invoice->setNotificationUrl('https://yourserver.com/IPNlogger.php');
```
IPNs can be used by the merchant to update their order status. Please note to use IPNs as a trigger to fetch the BitPay invoice status, since the IPNs are not authenticated.
IPNs can be used by the merchant to update order statuses. Please note to use IPNs as a trigger to fetch the BitPay invoice status, since the IPNs are not authenticated.
For more information about IPNs, please see https://bitpay.com/docs/invoice-callbacks
For more information about IPNs see https://bitpay.com/docs/invoice-callbacks
Examples (c) 2014-2017 BitPay

View File

@ -0,0 +1,44 @@
<?php
/**
* Copyright (c) 2014-2017 BitPay
*
* getInvoice
*
* Requirements:
* - Account on https://test.bitpay.com
* - Baisic PHP Knowledge
* - Private and Public keys from 001.php
* - Token value obtained from 002.php
* - Invoice created
*/
require __DIR__.'/../../vendor/autoload.php';
// Now fetch the invoice from BitPay
$storageEngine = new \Bitpay\Storage\EncryptedFilesystemStorage('YourTopSecretPassword');
$privateKey = $storageEngine->load('/tmp/bitpay.pri');
$publicKey = $storageEngine->load('/tmp/bitpay.pub');
$client = new \Bitpay\Client\Client();
$adapter = new \Bitpay\Client\Adapter\CurlAdapter();
$client->setPrivateKey($privateKey);
$client->setPublicKey($publicKey);
$client->setUri('https://btcpay.server/');
$client->setAdapter($adapter);
$token = new \Bitpay\Token();
$token->setToken('UpdateThisValue'); // UPDATE THIS VALUE
$token->setFacade('merchant');
$client->setToken($token);
/**
* This is where we will fetch the invoice object
*/
$invoice = $client->getInvoice("UpdateThisValue");
$request = $client->getRequest();
$response = $client->getResponse();
echo (string) $request.PHP_EOL.PHP_EOL.PHP_EOL;
echo (string) $response.PHP_EOL.PHP_EOL;
print_r($invoice);

View File

@ -80,8 +80,11 @@ class CurlAdapter implements AdapterInterface
/** @var ResponseInterface */
$response = Response::createFromRawResponse($raw);
// For some unknown reason, on some machine, the status code is equal to 0
// If that's the case, let's just ask to curl the real http code
if ($response->getStatusCode() === 0)
$response->setStatusCode(curl_getinfo($curl, CURLINFO_HTTP_CODE));
curl_close($curl);
return $response;
}
@ -94,14 +97,12 @@ class CurlAdapter implements AdapterInterface
private function getCurlDefaultOptions(RequestInterface $request)
{
return array(
CURLOPT_URL => $request->getUri(),
CURLOPT_PORT => $request->getPort(),
CURLOPT_URL => $request->getFullUri(),
CURLOPT_CUSTOMREQUEST => $request->getMethod(),
CURLOPT_HTTPHEADER => $request->getHeaderFields(),
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => 1,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_CAINFO => __DIR__.'/ca-bundle.crt',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_FRESH_CONNECT => 1,

File diff suppressed because it is too large Load Diff

View File

@ -53,19 +53,13 @@ class Client implements ClientInterface
protected $privateKey;
/**
* @var NetworkInterface
* @var uri
*/
protected $network;
protected $uri;
/**
* The network is either livenet or testnet and tells the client where to
* send the requests.
*
* @param NetworkInterface
*/
public function setNetwork(NetworkInterface $network)
public function setUri($uri)
{
$this->network = $network;
$this->uri = trim($uri);
}
/**
@ -108,6 +102,43 @@ class Client implements ClientInterface
return $this;
}
/**
* @inheritdoc
*/
protected function fillInvoiceData(InvoiceInterface $invoice, $data)
{
# BitPay returns the invoice time in milliseconds. PHP's DateTime object expects the time to be in seconds
$invoiceTime = is_numeric($data['invoiceTime']) ? intval($data['invoiceTime']/1000) : $data['invoiceTime'];
$expirationTime = is_numeric($data['expirationTime']) ? intval($data['expirationTime']/1000) : $data['expirationTime'];
$currentTime = is_numeric($data['currentTime']) ? intval($data['currentTime']/1000) : $data['currentTime'];
$invoiceToken = new \Bitpay\Token();
$invoice
->setToken($invoiceToken->setToken($data['token']))
->setUrl($data['url'])
->setPosData(array_key_exists('posData', $data) ? $data['posData'] : '')
->setStatus($data['status'])
->setBtcPrice(array_key_exists('btcPrice', $data) ? $data['btcPrice'] : '')
->setPrice($data['price'])
->setTaxIncluded($data['taxIncluded'])
->setCurrency(new \Bitpay\CurrencyUnrestricted($data['currency']))
->setOrderId(array_key_exists('orderId', $data) ? $data['orderId'] : '')
->setInvoiceTime($invoiceTime)
->setExpirationTime($expirationTime)
->setCurrentTime($currentTime)
->setId($data['id'])
->setBtcPaid(array_key_exists('btcPaid', $data) ? $data['btcPaid'] : '')
->setAmountPaid(array_key_exists('amountPaid', $data) ? $data['amountPaid'] : '')
->setRate(array_key_exists('rate', $data) ? $data['rate'] : '')
->setExceptionStatus($data['exceptionStatus'])
->setRefundAddresses(array_key_exists('refundAddresses', $data) ? $data['refundAddresses'] : '')
->setTransactionCurrency(array_key_exists('transactionCurrency', $data) ? $data['transactionCurrency'] : null)
->setPaymentTotals(array_key_exists('paymentTotals', $data) ? $data['paymentTotals'] : '')
->setPaymentSubtotals(array_key_exists('paymentSubtotals', $data) ? $data['paymentSubtotals'] : '')
->setExchangeRates(array_key_exists('exchangeRates', $data) ? $data['exchangeRates'] : '');
return $invoice;
}
/**
* @inheritdoc
*/
@ -126,6 +157,7 @@ class Client implements ClientInterface
$body = array(
'price' => $item->getPrice(),
'taxIncluded' => $item->getTaxIncluded(),
'currency' => $currency->getCode(),
'posData' => $invoice->getPosData(),
'notificationURL' => $invoice->getNotificationUrl(),
@ -151,8 +183,15 @@ class Client implements ClientInterface
'guid' => Util::guid(),
'nonce' => Util::nonce(),
'token' => $this->token->getToken(),
'paymentCurrencies' => $invoice->getPaymentCurrencies(),
);
foreach(array_keys($body) as $key) {
if(null === $body[$key]) {
unset($body[$key]);
}
}
$request->setBody(json_encode($body));
$this->addIdentityHeader($request);
$this->addSignatureHeader($request);
@ -168,20 +207,8 @@ class Client implements ClientInterface
throw new \Exception($error_message);
}
$data = $body['data'];
$invoiceToken = new \Bitpay\Token();
$invoice
->setToken($invoiceToken->setToken($data['token']))
->setId($data['id'])
->setUrl($data['url'])
->setStatus($data['status'])
->setBtcPrice($data['btcPrice'])
->setPrice($data['price'])
->setInvoiceTime($data['invoiceTime'])
->setExpirationTime($data['expirationTime'])
->setCurrentTime($data['currentTime'])
->setBtcPaid($data['btcPaid'])
->setRate($data['rate'])
->setExceptionStatus($data['exceptionStatus']);
$invoice = $this->fillInvoiceData($invoice, $data);
return $invoice;
}
@ -508,6 +535,10 @@ class Client implements ClientInterface
throw new \Bitpay\Client\BitpayException($this->response->getStatusCode().": ".$body['error']);
}
if($this->response->getStatusCode() >= 400) {
throw new \Exception('invalid status code: '. $this->response->getStatusCode());
}
$tkn = $body['data'][0];
$createdAt = new \DateTime();
$pairingExpiration = new \DateTime();
@ -574,33 +605,17 @@ class Client implements ClientInterface
}
$data = $body['data'];
$invoice = new \Bitpay\Invoice();
$invoiceToken = new \Bitpay\Token();
$invoice
->setToken($invoiceToken->setToken($data['token']))
->setUrl($data['url'])
->setPosData(array_key_exists('posData', $data) ? $data['posData'] : '')
->setStatus($data['status'])
->setBtcPrice($data['btcPrice'])
->setPrice($data['price'])
->setCurrency(new \Bitpay\Currency($data['currency']))
->setOrderId(array_key_exists('orderId', $data) ? $data['orderId'] : '')
->setInvoiceTime($data['invoiceTime'])
->setExpirationTime($data['expirationTime'])
->setCurrentTime($data['currentTime'])
->setId($data['id'])
->setBtcPaid($data['btcPaid'])
->setRate($data['rate'])
->setExceptionStatus($data['exceptionStatus'])
//->setRefundAddress(array_key_exists('refundAddresses', $data) ? key($data['refundAddresses'][0]) : '');
->setRefundAddresses(array_key_exists('refundAddresses', $data) ? $data['refundAddresses'] : '');
$invoice = $this->fillInvoiceData($invoice, $data);
return $invoice;
}
/**
* @param RequestInterface $request
* @return ResponseInterface
@ -636,15 +651,7 @@ class Client implements ClientInterface
throw new \Exception('Please set your Private Key');
}
if (true == property_exists($this->network, 'isPortRequiredInUrl')) {
if ($this->network->isPortRequiredInUrl === true) {
$url = $request->getUriWithPort();
} else {
$url = $request->getUri();
}
} else {
$url = $request->getUri();
}
$url = $request->getFullUri();
$message = sprintf(
'%s%s',
@ -659,12 +666,16 @@ class Client implements ClientInterface
/**
* @return RequestInterface
*
* @throws BitpayException
*/
protected function createNewRequest()
{
if ($this->uri === null) {
throw new BitpayException('You should provider the url of your BTCPAY server');
}
$request = new Request();
$request->setHost($this->network->getApiHost());
$request->setPort($this->network->getApiPort());
$request->setUri($this->uri);
$this->prepareRequestHeaders($request);
return $request;
@ -689,14 +700,5 @@ class Client implements ClientInterface
protected function checkPriceAndCurrency($price, $currency)
{
$decimalPosition = strpos($price, '.');
if ($decimalPosition == 0) {
$decimalPrecision = 0;
} else {
$decimalPrecision = strlen(substr($price, $decimalPosition + 1));
}
if (($decimalPrecision > 2 && $currency != 'BTC') || $decimalPrecision > 6) {
throw new \Exception('Incorrect price format or currency type.');
}
}
}

View File

@ -25,8 +25,8 @@ interface ClientInterface
*
* @see RFC2616 section 14.43 for User-Agent Format
*/
const NAME = 'BitPay PHP-Client';
const VERSION = '0.0.0';
const NAME = 'BitPay PHP-Client BTCPAY';
const VERSION = '2.2.23';
//public function createApplication(ApplicationInterface $application);
@ -56,6 +56,8 @@ interface ClientInterface
*/
public function getInvoice($invoiceId);
//public function getLedgers();
//public function getLedger(CurrencyInterface $currency);

View File

@ -37,13 +37,6 @@ class Request implements RequestInterface
*/
protected $method;
/**
* This should be something such as `test.bitpay.com` or just `bitpay.com`
*
* @var string
*/
protected $host;
/**
* The path is added to the end of the host
*
@ -51,13 +44,6 @@ class Request implements RequestInterface
*/
protected $path;
/**
* Default is 443 but should be changed by whatever is passed in through the Adapter.
*
* @var integer
*/
protected $port;
/**
*/
public function __construct()
@ -82,7 +68,7 @@ class Request implements RequestInterface
*/
public function __toString()
{
$request = sprintf("%s %s HTTP/1.1\r\n", $this->getMethod(), $this->getUriWithPort());
$request = sprintf("%s %s HTTP/1.1\r\n", $this->getMethod(), $this->getFullUri());
$request .= $this->getHeadersAsString();
$request .= $this->getBody();
@ -97,24 +83,6 @@ class Request implements RequestInterface
return (strtoupper($method) == strtoupper($this->method));
}
/**
* @inheritdoc
*/
public function getPort()
{
return $this->port;
}
/**
* This is called in the Adapter
*
* @inheritdoc
*/
public function setPort($port)
{
$this->port = $port;
}
/**
* @inheritdoc
*/
@ -134,58 +102,34 @@ class Request implements RequestInterface
$this->method = $method;
}
/**
* @inheritdoc
*/
public function getSchema()
{
return 'https';
}
/**
* @inheritdoc
*/
public function getUri()
{
return $this->uri;
}
/**
* @inheritdoc
*/
public function getFullUri()
{
$uriNormalized = rtrim($this->getUri(), '/');
$pathNormalized = ltrim($this->getPath(), '/');
return sprintf(
'%s://%s/%s',
$this->getSchema(),
$this->getHost(),
$this->getPath()
'%s/%s',
$uriNormalized,
$pathNormalized
);
}
/**
* @inheritdoc
*/
public function getUriWithPort()
public function setUri($uri)
{
return sprintf(
'%s://%s:%s/%s',
$this->getSchema(),
$this->getHost(),
$this->getPort(),
$this->getPath()
);
}
/**
* @inheritdoc
*/
public function getHost()
{
return $this->host;
}
/**
* Sets the host for the request
*
* @param string $host
*/
public function setHost($host)
{
$this->host = $host;
$this->uri = $uri;
return $this;
}

View File

@ -24,28 +24,6 @@ interface RequestInterface
*/
public function getMethod();
/**
* Should always return https
*
* @return string
*/
public function getSchema();
/**
* Returns the host to send the request to. The host would be something
* such as `test.bitpay.com` or `bitpay.com`
*
* @return string
*/
public function getHost();
/**
* Returns port to send request on
*
* @return integer
*/
public function getPort();
/**
* example of path is `api/invoice` as this is appended to $host
*
@ -58,7 +36,7 @@ interface RequestInterface
*
* @return string
*/
public function getUri();
public function getFullUri();
/**
* Checks the request to see if the method matches a known value

View File

@ -40,11 +40,6 @@ class Configuration implements ConfigurationInterface
->info('Private Key Filename')
->defaultValue(getenv('HOME').'/.bitpay/api.sin')
->end()
->enumNode('network')
->values(array('livenet', 'testnet'))
->info('Network')
->defaultValue('livenet')
->end()
->enumNode('adapter')
->values(array('curl', 'mock'))
->info('Client Adapter')

View File

@ -1,175 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay\Crypto;
/**
* Wrapper around the Mcrypt PHP Extension
*
* @see http://php.net/manual/en/book.mcrypt.php
*/
class McryptExtension implements CryptoInterface
{
/**
* @inheritdoc
*/
public static function hasSupport()
{
return function_exists('mcrypt_encrypt');
}
/**
* @inheritdoc
*/
public function getAlgos()
{
return mcrypt_list_algorithms();
}
/**
* Returns the inititialization size used for a particular cipher
* type. Returns an integer IV size on success or boolean false
* on failure. If no IV is needed for the cipher type and mode,
* a zero is returned.
*
* @param string $cipher_type
* @return int|bool
*/
public function getIVSize($cipher_type = MCRYPT_TRIPLEDES)
{
$block_mode = 'cbc';
return mcrypt_get_iv_size($cipher_type, $block_mode);
}
/**
* Returns the maximum key size that can be used with a particular
* cipher type. Any key size equal to or less than the returned
* value are legal key sizes. Depending on if the local mycrypt
* extension is linked against 2.2 or 2.3/2.4 the block mode could
* be required, hence the if/else statement.
*
* @param string $cipher_type
* @return int
*/
public function getKeySize($cipher_type = MCRYPT_TRIPLEDES)
{
$block_mode = 'cbc';
$max_key_size = mcrypt_get_key_size($cipher_type);
if ($max_key_size !== false) {
return $max_key_size;
} else {
return mcrypt_get_key_size($cipher_type, $block_mode);
}
}
/**
* Performs an internal self-test on the specified mcrypt algorithm and
* returns either boolean true/false depending on if the self-test passed
* or failed.
*
* @param string $cipher_type
* @return boolean
*/
public function algoSelfTest($cipher_type = MCRYPT_TRIPLEDES)
{
return mcrypt_module_self_test($cipher_type);
}
/**
*
* Encrypts $text based on your $key and $iv. The returned text is
* base-64 encoded to make it easier to work with in various scenarios.
* Default cipher is MCRYPT_TRIPLEDES but you can substitute depending
* on your specific encryption needs.
*
* @param string $text
* @param string $key
* @param string $iv
* @param int $bit_check
* @param string $cipher_type
* @return string $text
* @throws Exception $e
*
*/
public function encrypt($text, $key = '', $iv = '', $bit_check = 8, $cipher_type = MCRYPT_TRIPLEDES)
{
try {
/* Ensure the key & IV is the same for both encrypt & decrypt. */
if (!empty($text) && is_string($text)) {
$text_num = str_split($text, $bit_check);
$text_num = $bit_check - strlen($text_num[count($text_num) - 1]);
for ($i = 0; $i<$text_num; $i++) {
$text = $text.chr($text_num);
}
$cipher = mcrypt_module_open($cipher_type, '', 'cbc', '');
mcrypt_generic_init($cipher, $key, $iv);
$encrypted = mcrypt_generic($cipher, $text);
mcrypt_generic_deinit($cipher);
mcrypt_module_close($cipher);
return base64_encode($encrypted);
} else {
return $text;
}
} catch (\Exception $e) {
throw $e;
}
}
/**
*
* Decrypts $text based on your $key and $iv. Make sure you use the same key
* and initialization vector that you used when encrypting the $text. Default
* cipher is MCRYPT_TRIPLEDES but you can substitute depending on the cipher
* used for encrypting the text - very important.
*
* @param string $encrypted_text
* @param string $key
* @param string $iv
* @param int $bit_check
* @param string $cipher_type
* @return string $text
* @throws Exception $e
*
*/
public function decrypt($encrypted_text, $key = '', $iv = '', $bit_check = 8, $cipher_type = MCRYPT_TRIPLEDES)
{
try {
/* Ensure the key & IV is the same for both encrypt & decrypt. */
if (!empty($encrypted_text)) {
$cipher = mcrypt_module_open($cipher_type, '', 'cbc', '');
mcrypt_generic_init($cipher, $key, $iv);
$decrypted = mdecrypt_generic($cipher, base64_decode($encrypted_text));
mcrypt_generic_deinit($cipher);
$last_char = substr($decrypted, -1);
for ($i = 0; $i < $bit_check; $i++) {
if (chr($i) == $last_char) {
$decrypted = substr($decrypted, 0, strlen($decrypted) - $i);
break;
}
}
mcrypt_module_close($cipher);
return $decrypted;
} else {
return $encrypted_text;
}
} catch (\Exception $e) {
throw $e;
}
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace Bitpay;
class CurrencyUnrestricted extends Currency
{
/**
* Overrides the parent method to allow any currency symbol to be set.
*/
public function setCode($code)
{
$this->code = $code;
return $this;
}
}

View File

@ -30,7 +30,6 @@ class BitpayExtension implements ExtensionInterface
$loader = new XmlFileLoader($container, new FileLocator(__DIR__));
$loader->load('services.xml');
$container->setParameter('network.class', 'Bitpay\Network\\'.ContainerBuilder::camelize($config['network']));
$container->setParameter(
'adapter.class',
'Bitpay\Client\Adapter\\'.ContainerBuilder::camelize($config['adapter']).'Adapter'

View File

@ -1,25 +1,20 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!--
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* @license Copyright 2011-2017 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
-->
<container xmlns="http://symfony.com/schema/dic/services">
<parameters>
<parameter key="network.class">Bitpay\Network\Livenet</parameter>
<parameter key="adapter.class">Bitpay\Client\Adapter\CurlAdapter</parameter>
<parameter key="key_manager.class">Bitpay\KeyManager</parameter>
<parameter key="key_storage.class">Bitpay\Storage\FilesystemStorage</parameter>
</parameters>
<services>
<service id="network" class="%network.class%" />
<service id="adapter" class="%adapter.class%" />
<service id="client" class="Bitpay\Client\Client">
<call method="setNetwork">
<argument type="service" id="network" />
</call>
<call method="setAdapter">
<argument type="service" id="adapter" />
</call>
@ -31,7 +26,7 @@
</call>
</service>
<service id="key_storage" class="%key_storage.class%" public="false">
<service id="key_storage" class="%key_storage.class%">
<argument>%bitpay.key_storage_password%</argument>
</service>
@ -39,11 +34,11 @@
<argument type="service" id="key_storage" />
</service>
<service id="public_key" class="Bitpay\PublicKey" factory-service="key_storage" factory-method="load">
<service id="public_key" class="Bitpay\PublicKey">
<argument>%bitpay.public_key%</argument>
</service>
<service id="private_key" class="Bitpay\PrivateKey" factory-service="key_storage" factory-method="load">
<service id="private_key" class="Bitpay\PrivateKey">
<argument>%bitpay.private_key%</argument>
</service>
</services>

View File

@ -78,6 +78,7 @@ class Invoice implements InvoiceInterface
protected $url;
/**
* @deprecated Deprecated with introduction of BCH
* @var float
*/
protected $btcPrice;
@ -108,11 +109,18 @@ class Invoice implements InvoiceInterface
protected $exceptionStatus;
/**
* @deprecated Deprecated with introduction of BCH
* @var
*/
protected $btcPaid;
/**
* @var
*/
protected $amountPaid;
/**
* @deprecated Deprecated with introduction of BCH
* @var
*/
protected $rate;
@ -127,6 +135,31 @@ class Invoice implements InvoiceInterface
*/
protected $refundAddresses;
/**
* @var string
*/
protected $transactionCurrency;
/**
* @var array
*/
protected $exchangeRates;
/**
* @var array
*/
protected $paymentSubtotals;
/**
* @var array
*/
protected $paymentTotals;
/**
* @var array
*/
protected $paymentCurrencies;
/**
* @inheritdoc
*/
@ -135,6 +168,14 @@ class Invoice implements InvoiceInterface
return $this->getItem()->getPrice();
}
/**
* @inheritdoc
*/
public function getTaxIncluded()
{
return $this->getItem()->getTaxIncluded();
}
/**
* @param float $price
*
@ -149,6 +190,20 @@ class Invoice implements InvoiceInterface
return $this;
}
/**
* @param float $taxIncluded
*
* @return InvoiceInterface
*/
public function setTaxIncluded($taxIncluded)
{
if (!empty($taxIncluded)) {
$this->getItem()->setTaxIncluded($taxIncluded);
}
return $this;
}
/**
* @inheritdoc
*/
@ -434,6 +489,7 @@ class Invoice implements InvoiceInterface
}
/**
* @deprecated Deprecated with introduction of BCH
* @inheritdoc
*/
public function getBtcPrice()
@ -442,6 +498,7 @@ class Invoice implements InvoiceInterface
}
/**
* @deprecated Deprecated with introduction of BCH
* @param float $btcPrice
*
* @return InvoiceInterface
@ -470,10 +527,13 @@ class Invoice implements InvoiceInterface
*/
public function setInvoiceTime($invoiceTime)
{
if (!empty($invoiceTime)) {
if (is_a($invoiceTime, 'DateTime')) {
$this->invoiceTime = $invoiceTime;
} else if (is_numeric($invoiceTime)) {
$invoiceDateTime = new \DateTime('', new \DateTimeZone("UTC"));
$invoiceDateTime->setTimestamp($invoiceTime);
$this->invoiceTime = $invoiceDateTime;
}
return $this;
}
@ -492,10 +552,13 @@ class Invoice implements InvoiceInterface
*/
public function setExpirationTime($expirationTime)
{
if (!empty($expirationTime)) {
if (is_a($expirationTime, 'DateTime')) {
$this->expirationTime = $expirationTime;
} else if (is_numeric($expirationTime)) {
$expirationDateTime = new \DateTime('', new \DateTimeZone("UTC"));
$expirationDateTime->setTimestamp($expirationTime);
$this->expirationTime = $expirationDateTime;
}
return $this;
}
@ -514,10 +577,13 @@ class Invoice implements InvoiceInterface
*/
public function setCurrentTime($currentTime)
{
if (!empty($currentTime)) {
if (is_a($currentTime, 'DateTime')) {
$this->currentTime = $currentTime;
} else if (is_numeric($currentTime)) {
$currentDateTime = new \DateTime('', new \DateTimeZone("UTC"));
$currentDateTime->setTimestamp($currentTime);
$this->currentTime = $currentDateTime;
}
return $this;
}
@ -536,10 +602,7 @@ class Invoice implements InvoiceInterface
*/
public function setOrderId($orderId)
{
if (!empty($orderId) && ctype_print($orderId)) {
$this->orderId = trim($orderId);
}
$this->orderId = $orderId;
return $this;
}
@ -666,6 +729,7 @@ class Invoice implements InvoiceInterface
}
/**
* @deprecated Deprecated with introduction of BCH
* @param void
* @return
*/
@ -675,6 +739,7 @@ class Invoice implements InvoiceInterface
}
/**
* @deprecated Deprecated with introduction of BCH
* @param
* @return Invoice
*/
@ -688,6 +753,29 @@ class Invoice implements InvoiceInterface
}
/**
* @param void
* @return
*/
public function getAmountPaid()
{
return $this->amountPaid;
}
/**
* @param
* @return Invoice
*/
public function setAmountPaid($amountPaid)
{
if (isset($amountPaid)) {
$this->amountPaid = $amountPaid;
}
return $this;
}
/**
* @deprecated Deprecated with introduction of BCH
* @param void
* @return Invoice
*/
@ -697,6 +785,7 @@ class Invoice implements InvoiceInterface
}
/**
* @deprecated Deprecated with introduction of BCH
* @param
* @return
*/
@ -709,6 +798,29 @@ class Invoice implements InvoiceInterface
return $this;
}
/**
* @param void
* @return Invoice
*/
public function getExchangeRates()
{
return $this->exchangeRates;
}
/**
* @param
* @return
*/
public function setExchangeRates($exchangeRates)
{
if (!empty($exchangeRates)) {
$this->exchangeRates = $exchangeRates;
}
return $this;
}
/**
* @return TokenInterface
*/
@ -746,4 +858,86 @@ class Invoice implements InvoiceInterface
return $this;
}
/**
* @inheritdoc
*/
public function getTransactionCurrency()
{
return $this->transactionCurrency;
}
/**
* @param string $transactionCurrency
*
* @return InvoiceInterface
*/
public function setTransactionCurrency($transactionCurrency)
{
if (!empty($transactionCurrency) && ctype_print($transactionCurrency)) {
$this->transactionCurrency = trim($transactionCurrency);
}
return $this;
}
/**
* @param void
* @return Invoice
*/
public function getPaymentSubtotals()
{
return $this->paymentSubtotals;
}
/**
* @param
* @return
*/
public function setPaymentSubtotals($paymentSubtotals)
{
if (!empty($paymentSubtotals)) {
$this->paymentSubtotals = $paymentSubtotals;
}
return $this;
}
/**
* @param void
* @return Invoice
*/
public function getPaymentTotals()
{
return $this->paymentTotals;
}
/**
* @param
* @return
*/
public function setPaymentTotals($paymentTotals)
{
if (!empty($paymentTotals)) {
$this->paymentTotals = $paymentTotals;
}
return $this;
}
/**
* @inheritdoc
*/
public function getPaymentCurrencies() {
return $this->paymentCurrencies;
}
/**
* @inheritdoc
*/
public function setPaymentCurrencies($paymentCurrencies) {
$this->paymentCurrencies = $paymentCurrencies;
return $this;
}
}

View File

@ -84,6 +84,8 @@ interface InvoiceInterface
*/
public function getPrice();
public function getTaxIncluded();
/**
* This is the currency code set for the price setting.  The pricing currencies
* currently supported are USD, EUR, BTC, and all of the codes listed on this page:
@ -377,4 +379,22 @@ interface InvoiceInterface
* @return array|object
*/
public function getRefundAddresses();
/**
* Get the enforced transaction currencies.
*
* @return array|null
*/
public function getPaymentCurrencies();
/**
* Set specific invoice currencies and to enforce them on payment step.
*
* @param array $paymentCurrencies
* The currencies need to match what is supported by BTCPay Server.
* E.g. BTC, BTC_ONCHAIN, BTC_OFFCHAIN, LTC, XMR_MONEROLIKE etc.
*
* @return InvoiceInterface
*/
public function setPaymentCurrencies($paymentCurrencies);
}

View File

@ -29,6 +29,11 @@ class Item implements ItemInterface
*/
protected $price;
/**
* @var float
*/
protected $taxIncluded;
/**
* @var integer
*/
@ -96,6 +101,16 @@ class Item implements ItemInterface
return $this->price;
}
/**
* @inheritdoc
*
* @return float
*/
public function getTaxIncluded()
{
return $this->taxIncluded;
}
/**
* @param mixed $price A float, integer, or en_US formatted numeric string
*
@ -112,6 +127,17 @@ class Item implements ItemInterface
return $this;
}
public function setTaxIncluded($taxIncluded)
{
if (is_string($taxIncluded)) {
$this->checkPriceFormat($taxIncluded);
}
$this->taxIncluded = (float)$taxIncluded;
return $this;
}
/**
* @inheritdoc
*/
@ -157,12 +183,8 @@ class Item implements ItemInterface
* values with more than 6 decimals.
*
* @param string $price The price value to check
* @throws \Exception
*/
protected function checkPriceFormat($price)
{
if (preg_match('/^[0-9]+?[\.,][0-9]{1,6}?$/', $price) !== 1) {
throw new \Bitpay\Client\ArgumentException("Price must be formatted as a float");
}
}
}

View File

@ -34,6 +34,11 @@ interface ItemInterface
*/
public function getPrice();
/**
* @return string
*/
public function getTaxIncluded();
/**
* @return string
*/

View File

@ -1,47 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay\Network;
/**
*
* @package Bitcore
*/
class Customnet implements NetworkInterface
{
protected $host_url;
protected $host_port;
public $isPortRequiredInUrl;
public function __construct($url, $port, $isPortRequiredInUrl = false)
{
$this->host_url = $url;
$this->host_port = $port;
$this->isPortRequiredInUrl = $isPortRequiredInUrl;
}
public function getName()
{
return 'Custom Network';
}
public function getAddressVersion()
{
return 0x00;
}
public function getApiHost()
{
return $this->host_url;
}
public function getApiPort()
{
return $this->host_port;
}
}

View File

@ -1,34 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay\Network;
/**
*
* @package Bitcore
*/
class Livenet implements NetworkInterface
{
public function getName()
{
return 'livenet';
}
public function getAddressVersion()
{
return 0x00;
}
public function getApiHost()
{
return 'bitpay.com';
}
public function getApiPort()
{
return 443;
}
}

View File

@ -1,27 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay\Network;
/**
*
* @package Bitcore
*/
abstract class NetworkAware implements NetworkAwareInterface
{
/**
* @var NetworkInterface
*/
protected $network;
/**
* @inheritdoc
*/
public function setNetwork(NetworkInterface $network = null)
{
$this->network = $network;
}
}

View File

@ -1,21 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay\Network;
/**
*
* @package Bitcore
*/
interface NetworkAwareInterface
{
/**
* Set the network the object will work with
*
* @param NetworkInterface $network
*/
public function setNetwork(NetworkInterface $network = null);
}

View File

@ -1,43 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay\Network;
/**
*
* @package Bitcore
*/
interface NetworkInterface
{
/**
* Name of network, currently on livenet and testnet
*
* @return string
*/
public function getName();
/**
* @return string
*/
public function getAddressVersion();
/**
* The host that is used to interact with this network
*
* @see https://github.com/bitpay/insight
* @see https://github.com/bitpay/insight-api
*
* @return string
*/
public function getApiHost();
/**
* The port of the host
*
* @return integer
*/
public function getApiPort();
}

View File

@ -1,34 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay\Network;
/**
*
* @package Bitcore
*/
class Testnet implements NetworkInterface
{
public function getName()
{
return 'testnet';
}
public function getAddressVersion()
{
return 0x6f;
}
public function getApiHost()
{
return 'test.bitpay.com';
}
public function getApiPort()
{
return 443;
}
}

View File

@ -433,13 +433,6 @@ class Util
$requirements['PHP'] = true;
}
// Mcrypt Extension
if (!extension_loaded('mcrypt')) {
$requirements['Mcrypt'] = 'The Mcrypt PHP extension could not be found.';
} else {
$requirements['Mcrypt'] = true;
}
// OpenSSL Extension
if (!extension_loaded('openssl')) {
$requirements['OpenSSL'] = 'The OpenSSL PHP extension could not be found.';

View File

@ -15,9 +15,7 @@ class BitpayTest extends \PHPUnit_Framework_TestCase
{
$bitpay = new \Bitpay\Bitpay(
array(
'bitpay' => array(
'network' => 'testnet',
)
'bitpay' => array()
)
);
}
@ -31,11 +29,11 @@ class BitpayTest extends \PHPUnit_Framework_TestCase
public function testGet()
{
$bitpay = new \Bitpay\Bitpay();
$this->assertInstanceOf('Bitpay\Network\Livenet', $bitpay->get('network'));
$this->assertInstanceOf('Bitpay\Client\Adapter\CurlAdapter', $bitpay->get('adapter'));
}
/**
* @expectedException Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
*/
public function testGetInvalidService()
{
@ -49,7 +47,6 @@ class BitpayTest extends \PHPUnit_Framework_TestCase
$bitpay = new \Bitpay\Bitpay(
array(
'bitpay' => array(
'network' => 'testnet',
'private_key' => vfsStream::url('tmp/key.pri'),
'public_key' => vfsStream::url('tmp/key.pub'),
)

View File

@ -29,24 +29,25 @@ class CurlAdapterTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(array(), $adapter->getCurlOptions());
}
/**
* @expectedException \Bitpay\Client\ConnectionException
*/
public function testSendRequestWithException()
{
$this->setExpectedException('Bitpay\Client\ConnectionException');
$curl_options = array(
CURLOPT_URL => "www.example.com",
CURLOPT_URL => 'btcpay.example.com',
CURLOPT_SSL_VERIFYPEER => 1,
CURLOPT_SSL_VERIFYHOST => 2,
);
$adapter = new CurlAdapter($curl_options);
$response = $adapter->sendRequest($this->request);
$adapter->sendRequest($this->request);
}
public function testSendRequestWithoutException()
{
$curl_options = array(
CURLOPT_URL => "www.bitpay.com",
CURLOPT_URL => 'www.bitpay.com',
CURLOPT_SSL_VERIFYPEER => 1,
CURLOPT_SSL_VERIFYHOST => 2,
);
@ -56,4 +57,4 @@ class CurlAdapterTest extends \PHPUnit_Framework_TestCase
$this->assertNotNull($response);
}
}
}

View File

@ -22,7 +22,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
public function setUp()
{
$this->client = new Client();
$this->client->setNetwork(new \Bitpay\Network\Testnet());
$this->client->setUri('https://btcpay.server/');
$this->client->setToken($this->getMockToken());
$this->client->setPublicKey($this->getMockPublicKey());
$this->client->setPrivateKey($this->getMockPrivateKey());
@ -48,11 +48,13 @@ class ClientTest extends \PHPUnit_Framework_TestCase
}
/**
* @expectedException \Exception
* @expectedException \Bitpay\Client\BitpayException
* @expectedExceptionMessage You should provider the url of your BTCPAY server
*/
public function testCheckPriceAndCurrencyWithException() {
$client = new ChildOfClient();
$res = $client->checkPriceAndCurrency(.991, 'ABC');
public function testBtcPayServerUrlNotProvided()
{
$client = new Client();
$client->getTokens();
}
/**
@ -166,7 +168,6 @@ class ClientTest extends \PHPUnit_Framework_TestCase
public function testCreateInvoice()
{
$buyer = $this->getMockBuyer();
$buyer->method('getAddress')->will($this->returnValue(array()));
@ -182,7 +183,6 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$item->setPrice('19.95');
$invoice->setItem($item);
$response = $this->getMockResponse();
$response->method('getBody')->willReturn(file_get_contents(__DIR__ . '/../../DataFixtures/invoice.json'));
@ -195,12 +195,12 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('abcdefghijkmnopqrstuvw', $invoice->getId());
$this->assertEquals('https://test.bitpay.com/invoice?id=abcdefghijkmnopqrstuvw', $invoice->getUrl());
$this->assertEquals('new', $invoice->getStatus());
$this->assertEquals('0.0632', $invoice->getBtcPrice());
//$this->assertEquals('0.0632', $invoice->getBtcPrice());
$this->assertEquals(19.95, $invoice->getPrice());
$this->assertEquals(1412594514486, $invoice->getInvoiceTime());
$this->assertEquals(1412595414486, $invoice->getExpirationTime());
$this->assertEquals(1412594514518, $invoice->getCurrentTime());
$this->assertEquals('0.0000', $invoice->getBtcPaid());
$this->assertInstanceOf('DateTime', $invoice->getInvoiceTime());
$this->assertInstanceOf('DateTime', $invoice->getExpirationTime());
$this->assertInstanceOf('DateTime', $invoice->getCurrentTime());
//$this->assertEquals('0.0000', $invoice->getBtcPaid());
$this->assertEquals(315.7, $invoice->getRate());
$this->assertEquals(false, $invoice->getExceptionStatus());
$this->assertEquals('abcdefghijklmno', $invoice->getToken()->getToken());
@ -223,12 +223,12 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$invoice->method('setId')->will($this->returnSelf());
$invoice->method('setUrl')->will($this->returnSelf());
$invoice->method('setStatus')->will($this->returnSelf());
$invoice->method('setBtcPrice')->will($this->returnSelf());
//$invoice->method('setBtcPrice')->will($this->returnSelf());
$invoice->method('setPrice')->will($this->returnSelf());
$invoice->method('setInvoiceTime')->will($this->returnSelf());
$invoice->method('setExpirationTime')->will($this->returnSelf());
$invoice->method('setCurrentTime')->will($this->returnSelf());
$invoice->method('setBtcPaid')->will($this->returnSelf());
//$invoice->method('setBtcPaid')->will($this->returnSelf());
$invoice->method('setRate')->will($this->returnSelf());
$invoice->method('setExceptionStatus')->will($this->returnSelf());
$invoice->method('getCurrency')->willReturn($this->getMockCurrency());
@ -243,71 +243,6 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$this->client->createInvoice($invoice);
}
/**
* @expectedException Exception
*/
public function testCreateInvoiceWithTooMuchPrecisionForAnythingButBitcoin()
{
$item = $this->getMockItem();
$currency = $this->getMockCurrency();
$currency->method('getCode')->will($this->returnValue("USD"));
$item->method('getPrice')->will($this->returnValue(9.999));
$buyer = $this->getMockBuyer();
$buyer->method('getAddress')->will($this->returnValue(array()));
$invoice = $this->getMockInvoice();
$invoice->method('getItem')->willReturn($item);
$invoice->method('getBuyer')->willReturn($buyer);
$invoice->method('setId')->will($this->returnSelf());
$invoice->method('setUrl')->will($this->returnSelf());
$invoice->method('setStatus')->will($this->returnSelf());
$invoice->method('setBtcPrice')->will($this->returnSelf());
$invoice->method('setPrice')->will($this->returnSelf());
$invoice->method('setInvoiceTime')->will($this->returnSelf());
$invoice->method('setExpirationTime')->will($this->returnSelf());
$invoice->method('setCurrentTime')->will($this->returnSelf());
$invoice->method('setBtcPaid')->will($this->returnSelf());
$invoice->method('setRate')->will($this->returnSelf());
$invoice->method('setExceptionStatus')->will($this->returnSelf());
$invoice->method('getCurrency')->willReturn($currency);
$this->client->createInvoice($invoice);
}
/**
* @expectedException Exception
*/
public function testCreateInvoiceWithTooMuchPrecisionEvenForBitcoin()
{
$item = $this->getMockItem();
$currency = $this->getMockCurrency();
$currency->method('getCode')->will($this->returnValue("BTC"));
$item->method('getPrice')->will($this->returnValue(.9999999));
$buyer = $this->getMockBuyer();
$buyer->method('getAddress')->will($this->returnValue(array()));
$invoice = $this->getMockInvoice();
$invoice->method('getItem')->willReturn($item);
$invoice->method('getBuyer')->willReturn($buyer);
$invoice->method('setId')->will($this->returnSelf());
$invoice->method('setUrl')->will($this->returnSelf());
$invoice->method('setStatus')->will($this->returnSelf());
$invoice->method('setBtcPrice')->will($this->returnSelf());
$invoice->method('setPrice')->will($this->returnSelf());
$invoice->method('setInvoiceTime')->will($this->returnSelf());
$invoice->method('setExpirationTime')->will($this->returnSelf());
$invoice->method('setCurrentTime')->will($this->returnSelf());
$invoice->method('setBtcPaid')->will($this->returnSelf());
$invoice->method('setRate')->will($this->returnSelf());
$invoice->method('setExceptionStatus')->will($this->returnSelf());
$invoice->method('getCurrency')->willReturn($currency);
$this->client->createInvoice($invoice);
}
/**
* @depends testCreateInvoice
*/
@ -338,12 +273,12 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$invoice->method('setId')->will($this->returnSelf());
$invoice->method('setUrl')->will($this->returnSelf());
$invoice->method('setStatus')->will($this->returnSelf());
$invoice->method('setBtcPrice')->will($this->returnSelf());
//$invoice->method('setBtcPrice')->will($this->returnSelf());
$invoice->method('setPrice')->will($this->returnSelf());
$invoice->method('setInvoiceTime')->will($this->returnSelf());
$invoice->method('setExpirationTime')->will($this->returnSelf());
$invoice->method('setCurrentTime')->will($this->returnSelf());
$invoice->method('setBtcPaid')->will($this->returnSelf());
//$invoice->method('setBtcPaid')->will($this->returnSelf());
$invoice->method('setRate')->will($this->returnSelf());
$invoice->method('setExceptionStatus')->will($this->returnSelf());
$invoice->method('getCurrency')->willReturn($this->getMockCurrency());
@ -616,7 +551,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
$invoice = $this->getMockBuilder('Bitpay\InvoiceInterface')
->setMethods(
array(
'getPrice', 'getCurrency', 'getItem', 'getBuyer', 'getTransactionSpeed',
'getPrice', 'getTaxIncluded', 'getCurrency', 'getItem', 'getBuyer', 'getTransactionSpeed',
'getNotificationEmail', 'getNotificationUrl', 'getRedirectUrl', 'getPosData', 'getStatus',
'isFullNotifications', 'getId', 'getUrl', 'getBtcPrice', 'getInvoiceTime',
'getExpirationTime', 'getCurrentTime', 'getOrderId', 'getItemDesc', 'getItemCode',
@ -624,7 +559,8 @@ class ClientTest extends \PHPUnit_Framework_TestCase
'getBuyerState', 'getBuyerZip', 'getBuyerCountry', 'getBuyerEmail', 'getBuyerPhone',
'getExceptionStatus', 'getBtcPaid', 'getRate', 'getToken', 'getRefundAddresses',
'setId', 'setUrl', 'setStatus', 'setBtcPrice', 'setPrice', 'setInvoiceTime', 'setExpirationTime',
'setCurrentTime', 'setBtcPaid', 'setRate', 'setToken', 'setExceptionStatus', 'isExtendedNotifications'
'setCurrentTime', 'setBtcPaid', 'setRate', 'setToken', 'setExceptionStatus', 'isExtendedNotifications',
'setPosData',
)
)
->getMock();
@ -702,6 +638,7 @@ class ClientTest extends \PHPUnit_Framework_TestCase
'getCode',
'getDescription',
'getPrice',
'getTaxIncluded',
'getQuantity',
'isPhysical',
)

View File

@ -8,6 +8,9 @@ namespace Bitpay\Client;
class RequestTest extends \PHPUnit_Framework_TestCase
{
/** @var Request */
private $request;
public function setUp()
{
$this->request = new Request();
@ -77,35 +80,10 @@ class RequestTest extends \PHPUnit_Framework_TestCase
$this->assertFalse($this->request->isMethod('unknown method'));
}
public function testGetPort()
public function testSetUri()
{
$this->assertSame(443, $this->request->getPort());
}
public function testSetPort()
{
$this->request->setPort(444);
$this->assertSame(444, $this->request->getPort());
}
public function testGetSchema()
{
$this->assertSame('https', $this->request->getSchema());
}
public function testGetHost()
{
$this->assertNull($this->request->getHost());
}
/**
* @depends testGetHost
*/
public function testSetHost()
{
$this->request->setHost('test.bitpay.com');
$this->assertSame('test.bitpay.com', $this->request->getHost());
$this->request->setUri('https://btcpay.server/');
$this->assertSame('https://btcpay.server/', $this->request->getUri());
}
public function testGetPath()
@ -122,26 +100,6 @@ class RequestTest extends \PHPUnit_Framework_TestCase
$this->assertSame('api/invoice', $this->request->getPath());
}
/**
* @depends testSetHost
* @depends testGetPath
*/
public function testGetUri()
{
$this->request->setHost('test.bitpay.com');
$this->assertSame('https://test.bitpay.com/', $this->request->getUri());
}
/**
* @depends testSetHost
* @depends testGetPath
*/
public function testGetUriWithPort()
{
$this->request->setHost('test.bitpay.com');
$this->assertSame('https://test.bitpay.com:443/', $this->request->getUriWithPort());
}
public function testGetHeaders()
{
$this->assertInternalType('array', $this->request->getHeaders());
@ -182,15 +140,15 @@ class RequestTest extends \PHPUnit_Framework_TestCase
/**
* @depends testGetMethod
* @depends testGetUri
* @depends testSetUri
* @depends testGetHeaders
* @depends testGetBody
*/
public function testToStringWithoutBody()
{
$this->request->setHost('test.bitpay.com');
$this->request->setUri('https://btcpay.server:443');
$raw = array(
'POST https://test.bitpay.com:443/ HTTP/1.1',
'POST https://btcpay.server:443/ HTTP/1.1',
'Content-Type: application/json',
);
$raw = implode("\r\n", $raw);
@ -199,16 +157,16 @@ class RequestTest extends \PHPUnit_Framework_TestCase
/**
* @depends testGetMethod
* @depends testGetUri
* @depends testSetUri
* @depends testGetHeaders
* @depends testGetBody
*/
public function testToStringWithBody()
{
$this->request->setHost('test.bitpay.com');
$this->request->setUri('https://btcpay.server:443');
$this->request->setBody('{"json":true}');
$raw = array(
'POST https://test.bitpay.com:443/ HTTP/1.1',
'POST https://btcpay.server:443/ HTTP/1.1',
'Content-Type: application/json',
'Content-Length: 13',
'',

View File

@ -21,15 +21,14 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase
$this->assertArrayHasKey('public_key', $processedConfig);
$this->assertArrayHasKey('private_key', $processedConfig);
$this->assertArrayHasKey('sin_key', $processedConfig);
$this->assertArrayHasKey('network', $processedConfig);
$this->assertArrayHasKey('adapter', $processedConfig);
$this->assertArrayHasKey('key_storage', $processedConfig);
$this->assertArrayHasKey('key_storage_password', $processedConfig);
$this->assertCount(7, $processedConfig);
$this->assertCount(6, $processedConfig);
}
/**
* @expectedException Exception
* @expectedException \Exception
*/
public function testClassNotFoundKeyStorageConfig()
{
@ -45,7 +44,7 @@ class ConfigurationTest extends \PHPUnit_Framework_TestCase
}
/**
* @expectedException Exception
* @expectedException \Exception
*/
public function testClassDoesNotImplementInterfaceKeyStorageConfig()
{

View File

@ -1,70 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay\Crypto;
/**
* @package Bitauth
*/
class McryptExtensionTest extends \PHPUnit_Framework_TestCase
{
public function testHasSupport()
{
$mcrypt = new McryptExtension();
$this->assertSame(extension_loaded('mcrypt'), $mcrypt->hasSupport());
}
public function testEncrypt()
{
$mcrypt = new McryptExtension();
$key = 'testEncrypt';
$data = array(
'lsdkjflaslkfslj' => 'kz2DG4D3vkA6bkDbhrvD+Q==',
'a340932084093280' => 'gNaNgXFc7ecle8SaAJAJOw==',
'*&($*@*%&*$*#*&@(*#*(' => 'cVGF2lnyH6OHLYWHa+8XxHbFzVNK5IYL',
'___asdfa234($*(#__' => 'I8OFg5parn9b0Qk8mJnQH0+SgQWwYER5'
);
foreach($data as $unencrypted => $encrypted )
{
$encryptedtext = $mcrypt->encrypt($unencrypted, $key, '00000000');
$this->assertEquals($encrypted, $encryptedtext);
}
}
public function testDecrypt()
{
$mcrypt = new McryptExtension();
$key = 'testEncrypt';
$data = array(
'lsdkjflaslkfslj' => 'kz2DG4D3vkA6bkDbhrvD+Q==',
'a340932084093280' => 'gNaNgXFc7ecle8SaAJAJOw==',
'*&($*@*%&*$*#*&@(*#*(' => 'cVGF2lnyH6OHLYWHa+8XxHbFzVNK5IYL',
'___asdfa234($*(#__' => 'I8OFg5parn9b0Qk8mJnQH0+SgQWwYER5'
);
foreach($data as $unencrypted => $encrypted )
{
$plaintext = $mcrypt->decrypt($encrypted, $key, '00000000');
$this->assertEquals($unencrypted, $plaintext);
}
}
private function generateRandomString($length = 10)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
}

View File

@ -244,7 +244,7 @@ class InvoiceTest extends \PHPUnit_Framework_TestCase
public function testSetInvoiceTime()
{
$this->assertNotNull($this->invoice);
$date = new \DateTime();
$date = new \DateTime('now', new \DateTimeZone("UTC"));
$this->invoice->setInvoiceTime($date);
$this->assertSame($date, $this->invoice->getInvoiceTime());
}
@ -262,7 +262,7 @@ class InvoiceTest extends \PHPUnit_Framework_TestCase
{
$this->assertNotNull($this->invoice);
$date = new \DateTime();
$date = new \DateTime('now',new \DateTimeZone("UTC"));
$this->assertNotNull($date);
@ -283,7 +283,7 @@ class InvoiceTest extends \PHPUnit_Framework_TestCase
{
$this->assertNotNull($this->invoice);
$date = new \DateTime();
$date = new \DateTime('now',new \DateTimeZone("UTC"));
$this->assertNotNull($date);

View File

@ -83,9 +83,6 @@ class ItemTest extends \PHPUnit_Framework_TestCase
// throw an error
}
/**
* @expectedException \Bitpay\Client\ArgumentException
*/
public function testBadStringPrice()
{
// Accepts standard integer string
@ -141,21 +138,6 @@ class ItemTest extends \PHPUnit_Framework_TestCase
setlocale(LC_NUMERIC, 'en_US');
}
/**
* @expectedException \Bitpay\Client\ArgumentException
*/
public function testSetPriceExceptionNoNumber()
{
$this->item->setPrice(".");
}
/**
* @expectedException \Bitpay\Client\ArgumentException
*/
public function testSetPriceExceptionDoubleDecimal()
{
$this->item->setPrice("6..5");
}
public function testGetQuantity()
{

View File

@ -1,30 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay\Network;
class LivenetTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->network = new Livenet();
}
public function testGetName()
{
$this->assertSame('livenet', $this->network->getName());
}
public function testGetAddressVersion()
{
$this->assertSame(0x00, $this->network->getAddressVersion());
}
public function testGetApiHost()
{
$this->assertSame('bitpay.com', $this->network->getApiHost());
}
}

View File

@ -1,23 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay\Network;
class NetworkAwareTest extends \PHPUnit_Framework_TestCase
{
public function testSetNetwork()
{
$networkAware = $this->getMockForAbstractClass('Bitpay\Network\NetworkAware');
$networkAware->setNetwork(new \Bitpay\Network\Testnet());
$r = new \ReflectionObject($networkAware);
$network = $r->getProperty('network');
$network->setAccessible(true);
$network = $network->getValue($networkAware);
$this->assertInstanceOf('Bitpay\Network\NetworkInterface', $network);
}
}

View File

@ -1,30 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* see https://github.com/bitpay/php-bitpay-client/blob/master/LICENSE
*/
namespace Bitpay\Network;
class TestnetTest extends \PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->network = new Testnet();
}
public function testGetName()
{
$this->assertSame('testnet', $this->network->getName());
}
public function testGetAddressVersion()
{
$this->assertSame(0x6f, $this->network->getAddressVersion());
}
public function testGetApiHost()
{
$this->assertSame('test.bitpay.com', $this->network->getApiHost());
}
}

View File

@ -273,13 +273,6 @@ class UtilTest extends \PHPUnit_Framework_TestCase
$this->assertTrue(is_string($requirements['PHP']));
}
// Mcrypt Extension
if (extension_loaded('mcrypt')) {
$this->assertTrue($requirements['Mcrypt']);
} else {
$this->assertTrue(is_string($requirements['Mcrypt']));
}
// OpenSSL Extension
if (extension_loaded('openssl')) {
$this->assertTrue($requirements['OpenSSL']);

View File

@ -14,6 +14,7 @@
"btcPrice":"0.0632",
"btcDue":"0.0632",
"price":19.95,
"taxIncluded": 0.0,
"currency":"USD",
"exRates":
{

View File

@ -1 +1 @@
{"facade":"public/invoice","data":{"url":"https://test.bitpay.com/invoice?id=5NxFkXcJbCSivtQRJa4kHP","posData":"{\"posData\":{\"orderId\":\"100000009\"},\"hash\":\"GA.VW7o8puqPA\"}","status":"expired","btcPrice":"0.0032","btcDue":"0.0032","price":1.99,"currency":"USD","exRates":{"USD":619.39},"orderId":"100000009","invoiceTime":1405974404088,"expirationTime":1405975304088,"currentTime":1412886370907,"id":"5NxFkXcJbCSivtQRJa4kHP","btcPaid":"0.0000","rate":619.39,"exceptionStatus":false,"token":"9CKEkTYE4VA4skhMPBxUsPQyUqXE36qpmitmYbtKssPnY3p8rYqhTTcEzUeowKwvzL"}}
{"facade":"public/invoice","data":{"url":"https://test.bitpay.com/invoice?id=5NxFkXcJbCSivtQRJa4kHP","posData":"{\"posData\":{\"orderId\":\"100000009\"},\"hash\":\"GA.VW7o8puqPA\"}","status":"expired","btcPrice":"0.0032","btcDue":"0.0032","price":1.99,"taxIncluded":0.0,"currency":"USD","exRates":{"USD":619.39},"orderId":"100000009","invoiceTime":1405974404088,"expirationTime":1405975304088,"currentTime":1412886370907,"id":"5NxFkXcJbCSivtQRJa4kHP","btcPaid":"0.0000","rate":619.39,"exceptionStatus":false,"token":"9CKEkTYE4VA4skhMPBxUsPQyUqXE36qpmitmYbtKssPnY3p8rYqhTTcEzUeowKwvzL"}}