Merge pull request #91 from ionux/master

Added extra error handling and fixed debugging
This commit is contained in:
Rich Morgan 2015-01-12 15:19:58 -05:00
commit 31e24362ae
28 changed files with 796 additions and 401 deletions

View File

@ -1,3 +1,10 @@
2.1.2
Added extra error handling and fixed debugging
Re-added new order email notifications
Updated README documentation for accuracy
Re-wrote delete.sh shell script to autodetect Magento directory and
be more helpful when cleaning an old BitPay plugin from the server
2.1.1 2.1.1
Bug fix sanitizing labels for token pairing Bug fix sanitizing labels for token pairing
Replaced GMP only requirement with GMP or BC Math requirement Replaced GMP only requirement with GMP or BC Math requirement

173
README.md
View File

@ -5,130 +5,86 @@ bitpay/magento-plugin
[![Build Status](https://travis-ci.org/bitpay/magento-plugin.svg?branch=master)](https://travis-ci.org/bitpay/magento-plugin) [![Build Status](https://travis-ci.org/bitpay/magento-plugin.svg?branch=master)](https://travis-ci.org/bitpay/magento-plugin)
# Brief Description
BitPay has the most powerful bitcoin infrastructure on the planet and is trusted by over 40,000 merchants. # Description
# Detail Description Bitcoin is a powerful new peer-to-peer platform for the next generation of financial technology. The decentralized nature of the Bitcoin network allows for a highly resilient value transfer infrastructure, and this allows merchants to gain greater profits.
Bitcoin is a powerful new peer-to-peer platform for the next generation of This is because there are little to no fees for transferring Bitcoins from one person to another. Unlike other payment methods, Bitcoin payments cannot be reversed, so once you are paid you can ship! No waiting days for a payment to clear.
financial technology. The decentralized nature of the Bitcoin network allows
for a highly resilient value transfer infrastructure, and this allows merchants
to gain greater profits.
This is because there are little to no fees for transferring Bitcoins from one
person to another. Unlike other payment methods, Bitcoin payments cannot be
reversed, so once you are paid you can ship! No waiting days for a payment to
clear.
# Requirements # Requirements
* [Magento](http://magento.com/resources/system-requirements) >= 1.9.0.1 (Older version will work, but we do not test against those) * [Magento CE](http://magento.com/resources/system-requirements) 1.9.0.1 or higher. Older versions might work, however this plugin has been validated to work against the 1.9.0.1 Community Edition release.
* [GMP](http://us2.php.net/gmp) You may have to install this as most servers do not come with it. * [GMP](http://us2.php.net/gmp) or [BC Math](http://us2.php.net/manual/en/book.bc.php) PHP extensions. GMP is preferred for performance reasons but you may have to install this as most servers do not come with it installed by default. BC Math is commonly installed however and the plugin will fall back to this method if GMP is not found.
* [mcrypt](http://us2.php.net/mcrypt) Magento requires this so you're fine * [OpenSSL](http://us2.php.net/openssl) Must be compiled with PHP and is used for certain cryptographic operations.
* [OpenSSL](http://us2.php.net/openssl) Must be compiled with PHP * [PHP](http://us2.php.net/downloads.php) 5.4 or higher. This plugin will not work on PHP 5.3 and below.
* PHP >= 5.4
# Upgrade From Version 1.x to 2.x
Merchants who have previous been using the BitPay Magento plugin will need to remove # Upgrade From Plugin Version 1.x to 2.x
previous plugin. This can be done by using the [scripts/delete](https://github.com/bitpay/magento-plugin/blob/master/scripts/delete)
script before installing the new plugin. ***Very Important:*** You must complete remove any previous versions of the Bitpay Magento plugin before installing this new updated version. The plugin has been completely re-written to work with BitPay's new cryptographically secure RESTful API and will conflict with any previous plugin versions which use the old API. To help you remove the old plugin files from your system, we have created a convenient shell script for Unix/Linux/Mac OS systems which will scan your webserver for these older files and delete them. You may also remove these files by hand of course and the complete list of the files can be found in the source of the script for your convenience. You can download this delete script here: [scripts/delete.sh](https://github.com/bitpay/magento-plugin/blob/master/scripts/delete.sh).
To use this script, simply download to your server and execute the script from a shell. You may have to mark the script executable before first use.
```sh
chmod +x delete.sh
./delete.sh
```
# Installation # Installation
## Magento Connect Manager ## Magento Connect Manager
Goto [http://www.magentocommerce.com/magento-connect/bitpay-payment-method.html](http://www.magentocommerce.com/magento-connect/bitpay-payment-method.html) Goto [http://www.magentocommerce.com/magento-connect/bitpay-payment-method.html](http://www.magentocommerce.com/magento-connect/bitpay-payment-method.html) and click the *Install Now* link which will give you the *Extension Key* needed for the next step.
and click the *Install Now* link which will give you the *Extension Key* needed
for the next step.
Once you have the key, log into you Magento Store's Admin Panel and navigate to Once you have the key, log into you Magento Store's Admin Panel and navigate to **System > Magento Connect > Magento Connect Manager**.
**System > Magento Connect > Magento Connect Manager**.
***NOTE*** It may ask you to log in again using the same credentials that you use ***NOTE:*** It may ask you to log in again using the same credentials that you use to log into the Admin Panel.
to log into the Admin Panel.
All you need to do is paste the extension key and click on the *Install* button. All you need to do is paste the extension key and click on the *Install* button.
***WARNING*** It is good practice to backup your database before installing ***WARNING:*** It is good practice to backup your database before installing extensions. Please make sure you Create Backups.
extensions. Please make sure you Create Backups.
## Download ## Download
Visit the [Releases](https://github.com/bitpay/magento-plugin/releases) page of Visit the [Releases](https://github.com/bitpay/magento-plugin/releases) page of this repository and download the latest version. Once this is done, you can just unzip the contents and use any method you want to put them on your server. The contents will mirror the Magento directory structure.
this repository and download the latest version. Once this is done, you can just
unzip the contents and use any method you want to put them on your server. The
contents will mirror the Magento directory structure.
***NOTE*** These files can also up uploaded using the *Magento Connect Manager* ***NOTE:*** These files can also up uploaded using the *Magento Connect Manager* that comes with your Magento Store
that comes with your Magento Store
***WARNING:*** It is good practice to backup your database before installing extensions. Please make sure you Create Backups.
***WARNING*** It is good practice to backup your database before installing
extensions. Please make sure you Create Backups.
## modman ## modman
Using [modman](https://github.com/colinmollenhour/modman) you can Using [modman](https://github.com/colinmollenhour/modman) you can install the BitPay Magento Plugin. Once you have modman installed, run `modman init` if you have not already done so. Next just run `modman clone https://github.com/bitpay/magento-plugin.git` in the root of the Magento installation. In this case it is `/var/www/magento`.
install the BitPay Magento Plugin. Once
you have modman installed, run `modman init` if you have not already done so. Next
just run `modman clone https://github.com/bitpay/magento-plugin.git` in the root
of the Magento installation. In this case it is `/var/www/magento`.
## Development
For developers wanting to contribute to this project, it is assumed you have a
stable Magento environment to work with, and are familiar with developing for
Magento. You will need to clone this repository or fork and clone the repository
you created.
Once you have cloned the repository, you will need to run [composer install](https://getcomposer.org/doc/00-intro.md#using-composer).
Using and setting up composer is outside the scope, however you will find the
documentation on their site comprehensive.
Once you are done, you can then run the ``scripts/package`` script to create a
distribution files which you can find in ``build/dist``. This is the file that
you can upload to your server to unzip or do with what you will.
If you encounter any issues or implement any updates or changes, please open an
[issue](https://github.com/bitpay/magento-plugin/issues) or submit a Pull Request.
***NOTE*** The ``scripts/package`` file contains some configuration settings that
will need to change for different releases. If you are using this script to build
files that are for distribution, these will need to be updated.
# Configuration # Configuration
Configuration can be done using the Administrator section of your Megento store. Configuration can be done using the Administrator section of your Megento store. Once Logged in, you will find the configuration settings under **System > Configuration > Sales > Payment Methods**.
Once Logged in, you will find the configuration settings under **System > Configuration > Sales > Payment Methods**.
![BitPay Magento Settings](https://raw.githubusercontent.com/bitpay/magento-plugin/master/docs/MagentoSettings.png "BitPay Megento Settings") ![BitPay Magento Settings](https://raw.githubusercontent.com/bitpay/magento-plugin/master/docs/MagentoSettings.png "BitPay Megento Settings")
Here your will need to create a [pairing code](https://bitpay.com/api-tokens) using Here your will need to create a [pairing code](https://bitpay.com/api-tokens) using your BitPay merchant account. Once you have a Pairing Code, put the code in the Pairing Code field. This will take care of the rest for you.
your BitPay merchant account. Once you have a Pairing Code, put the code in the
Pairing Code field. This will take care of the rest for you.
***NOTE*** Pairing Codes are only valid for a short period of time. If it expires ***NOTE:*** Pairing Codes are only valid for a short period of time. If it expires before you get to use it, you can always create a new one an use the new one.
before you get to use it, you can always create a new one an use the new one.
***NOTE*** You will only need to do this once since each time you do this, the ***NOTE:*** You will only need to do this once since each time you do this, the extension will generate public and private keys that are used to identify you when using the API.
extension will generate public and private keys that are used to identify you
when using the API.
You are also able to configure how BitPay's IPN (Instant Payment Notifications) You are also able to configure how BitPay's IPN (Instant Payment Notifications) changes the order in your Magento store.
changes the order in your Magento store.
![BitPay Invoice Settings](https://raw.githubusercontent.com/bitpay/magento-plugin/master/docs/MagentoInvoiceSettings.png "BitPay Invoice Settings") ![BitPay Invoice Settings](https://raw.githubusercontent.com/bitpay/magento-plugin/master/docs/MagentoInvoiceSettings.png "BitPay Invoice Settings")
# Usage # Usage
Once enabled, your customers will be given the option to pay with Bitcoins. Once Once enabled, your customers will be given the option to pay with Bitcoins. Once they checkout they are redirected to a full screen BitPay invoice to pay for the order.
they checkout they are redirected to a full screen BitPay invoice to pay for
the order. As a merchant, the orders in your Magento store can be treated as any other order. You may need to adjust the Invoice Settings depending on your order fulfillment.
As a merchant, the orders in your Magento store can be treated as any other
order. You may need to adjust the Invoice Settings depending on your order
fulfillment.
# Support # Support
@ -143,30 +99,19 @@ fulfillment.
* [Homepage](http://magento.com) * [Homepage](http://magento.com)
* [Documentation](http://docs.magentocommerce.com) * [Documentation](http://docs.magentocommerce.com)
* [Support Forums](https://www.magentocommerce.com/support/ce/) * [Community Edition Support Forums](https://www.magentocommerce.com/support/ce/)
# Troubleshooting # Troubleshooting
1. Ensure a valid SSL certificate is installed on your server. Also ensure your 1. Ensure a valid SSL certificate is installed on your server. Also ensure your root CA cert is updated. If your CA cert is not current, you will see curl SSL verification errors.
root CA cert is updated. If your CA cert is not current, you will see curl 2. Verify that your web server is not blocking POSTs from servers it may not recognize. Double check this on your firewall as well, if one is being used.
SSL verification errors. 3. Check the `payment_bitpay.log` file for any errors during BitPay payment attempts. If you contact BitPay support, they will ask to see the log file to help diagnose the problem. The log file will be found inside your Magento's `var/log/` directory. ***NOTE:*** You will need to enable the debugging setting for the extension to output information into the log file.
2. Verify that your web server is not blocking POSTs from servers it may not 4. Check the version of this plugin against the official plugin repository to ensure you are using the latest version. Your issue might have been addressed in a newer version! See the [Releases](https://github.com/bitpay/magento-plugin/releases) page or the Magento Connect store for the latest version.
recognize. Double check this on your firewall as well, if one is being used. 5. If all else fails, send an email describing your issue **in detail** to support@bitpay.com
3. Check the `payment_bitpay.log` file for any errors during BitPay payment attempts.
If you contact BitPay support, they will ask to see the log file to help
diagnose the problem. The log file will be found inside your Magento's
`var/log/` directory. ***NOTE*** You will need to enable the debugging
setting for the extension to output information into the log file.
4. Check the version of this plugin against the official plugin repository to
ensure you are using the latest version. Your issue might have been
addressed in a newer version! See the [Releases](https://github.com/bitpay/magento-plugin/releases)
page for the latest.
5. If all else fails, send an email describing your issue **in detail** to
support@bitpay.com
***TIP***: When contacting support it will help us is you provide: ***TIP:*** When contacting support it will help us is you provide:
* Magento Version (Found at the bottom page in the Administration section) * Magento CE Version (Found at the bottom page in the Administration section)
* Other extensions you have installed * Other extensions you have installed
* Some extensions do not play nice * Some extensions do not play nice
* Configuration settings for the extension (Most merchants take screen grabs) * Configuration settings for the extension (Most merchants take screen grabs)
@ -175,9 +120,17 @@ fulfillment.
* enabled debugging for this extension and send us `var/log/payment_bitpay.log` * enabled debugging for this extension and send us `var/log/payment_bitpay.log`
* Screen grabs of error message if applicable. * Screen grabs of error message if applicable.
# Contribute # Contribute
To contribute to this project, please fork and submit a pull request. For developers wanting to contribute to this project, it is assumed you have a stable Magento environment to work with, and are familiar with developing for Magento. You will need to clone this repository or fork and clone the repository you created.
Once you have cloned the repository, you will need to run [composer install](https://getcomposer.org/doc/00-intro.md#using-composer). Using and setting up composer is outside the scope, however you will find the documentation on their site comprehensive. You can then run the ``scripts/package`` script to create a distribution files which you can find in ``build/dist``. This is the file that you can upload to your server to unzip or do with what you will.
If you encounter any issues or implement any updates or changes, please open an [issue](https://github.com/bitpay/magento-plugin/issues) or submit a Pull Request.
***NOTE:*** The ``scripts/package`` file contains some configuration settings that will need to change for different releases. If you are using this script to build files that are for distribution, these will need to be updated.
# License # License
@ -185,20 +138,8 @@ The MIT License (MIT)
Copyright (c) 2011-2014 BitPay, Inc. Copyright (c) 2011-2014 BitPay, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -15,9 +15,14 @@ class Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Extension extends Mag
*/ */
protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element) protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
{ {
if (false === isset($element) || true === empty($element)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Extension::_getElementHtml(): Missing or invalid $element parameter passed to function.');
throw new \Exception('In Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Extension::_getElementHtml(): Missing or invalid $element parameter passed to function.');
}
$phpExtension = $element->getFieldConfig()->php_extension; $phpExtension = $element->getFieldConfig()->php_extension;
if (in_array($phpExtension, get_loaded_extensions())) { if (true === in_array($phpExtension, get_loaded_extensions())) {
return 'Installed'; return 'Installed';
} }

View File

@ -23,6 +23,11 @@ class Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Header extends Mage_A
*/ */
public function render(Varien_Data_Form_Element_Abstract $element) public function render(Varien_Data_Form_Element_Abstract $element)
{ {
if (false === isset($element) || true === empty($element)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Header::render(): Missing or invalid $element parameter passed to function.');
throw new \Exception('In Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Header::render(): Missing or invalid $element parameter passed to function.');
}
return $this->toHtml(); return $this->toHtml();
} }
} }

View File

@ -8,7 +8,10 @@ class Bitpay_Core_Block_Form_Bitpay extends Mage_Payment_Block_Form
{ {
protected function _construct() protected function _construct()
{ {
$payment_template = 'bitpay/form/bitpay.phtml';
parent::_construct(); parent::_construct();
$this->setTemplate('bitpay/form/bitpay.phtml');
$this->setTemplate($payment_template);
} }
} }

View File

@ -2,6 +2,8 @@
/** /**
* @license Copyright 2011-2014 BitPay Inc., MIT License * @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE * @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*
* TODO: Finish this iFrame implemenation... :/
*/ */
class Bitpay_Core_Block_Iframe extends Mage_Checkout_Block_Onepage_Payment class Bitpay_Core_Block_Iframe extends Mage_Checkout_Block_Onepage_Payment
@ -21,48 +23,67 @@ class Bitpay_Core_Block_Iframe extends Mage_Checkout_Block_Onepage_Payment
*/ */
public function getIframeUrl() public function getIframeUrl()
{ {
if (Mage::getModel('bitpay/ipn')->getQuotePaid($this->getQuote()->getId())) { if (\Mage::getModel('bitpay/ipn')->getQuotePaid($this->getQuote()->getId())) {
return 'paid'; // quote's already paid, so don't show the iframe return 'paid'; // quote's already paid, so don't show the iframe
} }
/*** @var Bitpay_Core_Model_PaymentMethod ***/ /*** @var Bitpay_Core_Model_PaymentMethod ***/
$method = $this->getQuote()->getPayment()->getMethodInstance(); $method = $this->getQuote()->getPayment()->getMethodInstance();
if (false === isset($method) || true === empty($method)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_Block_Iframe::getIframeUrl(): Could not obtain an instance of the payment method.');
throw new \Exception('In Bitpay_Core_Block_Iframe::getIframeUrl(): Could not obtain an instance of the payment method.');
}
$options = array_merge( $options = array_merge(
array( array(
'currency' => $this->getQuote()->getQuoteCurrencyCode(), 'currency' => $this->getQuote()->getQuoteCurrencyCode(),
'fullNotifications' => 'true', 'fullNotifications' => 'true',
'notificationURL' => Mage::getUrl('bitpay/ipn'), 'notificationURL' => \Mage::getUrl('bitpay/ipn'),
'redirectURL' => Mage::getUrl('checkout/onepage/success'), 'redirectURL' => \Mage::getUrl('checkout/onepage/success'),
'transactionSpeed' => Mage::getStoreConfig('payment/bitpay/speed'), 'transactionSpeed' => \Mage::getStoreConfig('payment/bitpay/speed'),
), ),
$method->extractAddress($this->getQuote()->getShippingAddress()) $method->extractAddress($this->getQuote()->getShippingAddress())
); );
Mage::helper('bitpay')->debugData($options);
if (false === isset($options) || true === empty($options)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_Block_Iframe::getIframeUrl(): Could not merge the options array.');
throw new \Exception('In Bitpay_Core_Block_Iframe::getIframeUrl(): Could not merge the options array.');
} else {
\Mage::helper('bitpay')->debugData($options);
}
// Mage doesn't round the total until saving and it can have more precision // Mage doesn't round the total until saving and it can have more precision
// at this point which would be bad for later comparing records w/ bitpay. // at this point which would be bad for later comparing records w/ bitpay.
// So round here to match what the price will be saved as: // So round here to match what the price will be saved as:
$price = round($this->getQuote()->getGrandTotal(), 4); $price = round($this->getQuote()->getGrandTotal(), 4);
if (false === isset($price) || true === empty($price)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_Block_Iframe::getIframeUrl(): Could not get the new rounded price.');
throw new \Exception('In Bitpay_Core_Block_Iframe::getIframeUrl(): Could not get the new rounded price.');
}
//serialize info about the quote to detect changes //serialize info about the quote to detect changes
$hash = $method->getQuoteHash($this->getQuote()->getId()); $hash = $method->getQuoteHash($this->getQuote()->getId());
Mage::helper('bitpay')->registerAutoloader(); if (false === isset($hash) || true === empty($hash)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_Block_Iframe::getIframeUrl(): Could not get the quote hash.');
throw new \Exception('In Bitpay_Core_Block_Iframe::getIframeUrl(): Could not merge the quote hash.');
}
\Mage::helper('bitpay')->registerAutoloader();
//$invoice = bpCreateInvoice($quoteId, $price, array('quoteId' => $quoteId, 'quoteHash' => $hash), $options); //$invoice = bpCreateInvoice($quoteId, $price, array('quoteId' => $quoteId, 'quoteHash' => $hash), $options);
$invoice = array('url' => 'https://test.bitpay.com/invoice?id=5NxFkXcJbCSivtQRJa4kHP'); $invoice = array('url' => 'https://test.bitpay.com/invoice?id=5NxFkXcJbCSivtQRJa4kHP');
if (array_key_exists('error', $invoice)) { if (array_key_exists('error', $invoice)) {
Mage::helper('bitpay')->debugData( \Mage::helper('bitpay')->debugData(array('Error creating bitpay invoice', $invoice['error'],));
array( \Mage::throwException("Error creating BitPay invoice. Please try again or use another payment option.");
'Error creating bitpay invoice',
$invoice['error'],
)
);
Mage::throwException("Error creating BitPay invoice. Please try again or use another payment option.");
return false; return false;
} }
return $invoice['url'].'&view=iframe'; //return $invoice['url'].'&view=iframe';
return false;
} }
} }

View File

@ -15,11 +15,22 @@ class Bitpay_Core_Block_Info extends Mage_Payment_Block_Info
public function getBitpayInvoiceUrl() public function getBitpayInvoiceUrl()
{ {
$order = $this->getInfo()->getOrder(); $order = $this->getInfo()->getOrder();
if (false === isset($order) || true === empty($order)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_Block_Info::getBitpayInvoiceUrl(): could not obtain the order.');
throw new \Exception('In Bitpay_Core_Block_Info::getBitpayInvoiceUrl(): could not obtain the order.');
}
$incrementId = $order->getIncrementId(); $incrementId = $order->getIncrementId();
$bitpayInvoice = Mage::getModel('bitpay/invoice')->load($incrementId, 'increment_id'); if (false === isset($incrementId) || true === empty($incrementId)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_Block_Info::getBitpayInvoiceUrl(): could not obtain the incrementId.');
throw new \Exception('In Bitpay_Core_Block_Info::getBitpayInvoiceUrl(): could not obtain the incrementId.');
}
if ($bitpayInvoice) { $bitpayInvoice = \Mage::getModel('bitpay/invoice')->load($incrementId, 'increment_id');
if (true === isset($bitpayInvoice) && false === empty($bitpayInvoice)) {
return $bitpayInvoice->getUrl(); return $bitpayInvoice->getUrl();
} }
} }

View File

@ -21,7 +21,9 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function debugData($debugData) public function debugData($debugData)
{ {
Mage::getModel('bitpay/method_bitcoin')->debugData($debugData); if (true === isset($debugData) && false === empty($debugData)) {
\Mage::getModel('bitpay/method_bitcoin')->debugData($debugData);
}
} }
/** /**
@ -29,7 +31,7 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function isDebug() public function isDebug()
{ {
return (boolean) Mage::getStoreConfig('payment/bitpay/debug'); return (boolean) \Mage::getStoreConfig('payment/bitpay/debug');
} }
/** /**
@ -39,7 +41,7 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function hasTransactionSpeed() public function hasTransactionSpeed()
{ {
$speed = Mage::getStoreConfig('payment/bitpay/speed'); $speed = \Mage::getStoreConfig('payment/bitpay/speed');
return !empty($speed); return !empty($speed);
} }
@ -51,7 +53,7 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function getNotificationUrl() public function getNotificationUrl()
{ {
return Mage::getUrl(Mage::getStoreConfig('payment/bitpay/notification_url')); return \Mage::getUrl(\Mage::getStoreConfig('payment/bitpay/notification_url'));
} }
/** /**
@ -61,7 +63,7 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function getRedirectUrl() public function getRedirectUrl()
{ {
return Mage::getUrl(Mage::getStoreConfig('payment/bitpay/redirect_url')); return \Mage::getUrl(\Mage::getStoreConfig('payment/bitpay/redirect_url'));
} }
/** /**
@ -70,11 +72,19 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function registerAutoloader() public function registerAutoloader()
{ {
if (null === $this->_autoloaderRegistered) { if (true === empty($this->_autoloaderRegistered)) {
require_once Mage::getBaseDir('lib').'/Bitpay/Autoloader.php'; $autoloader_filename = \Mage::getBaseDir('lib').'/Bitpay/Autoloader.php';
if (true === is_file($autoloader_filename) && true === is_readable($autoloader_filename)) {
require_once $autoloader_filename;
\Bitpay\Autoloader::register(); \Bitpay\Autoloader::register();
$this->_autoloaderRegistered = true; $this->_autoloaderRegistered = true;
$this->debugData('BitPay Autoloader has been registered'); $this->debugData('[INFO] In Bitpay_Core_Helper_Data::registerAutoloader(): autoloader file was found and has been registered.');
} else {
$this->_autoloaderRegistered = false;
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::registerAutoloader(): autoloader file was not found or is not readable. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::registerAutoloader(): autoloader file was not found or is not readable. Cannot continue!');
}
} }
} }
@ -84,21 +94,36 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function generateAndSaveKeys() public function generateAndSaveKeys()
{ {
$this->debugData('Generating Keys'); $this->debugData('[INFO] In Bitpay_Core_Helper_Data::generateAndSaveKeys(): attempting to generate new keypair and save to database.');
if (true === empty($this->_autoloaderRegistered)) {
$this->registerAutoloader(); $this->registerAutoloader();
}
$this->_privateKey = new Bitpay\PrivateKey('payment/bitpay/private_key'); $this->_privateKey = new Bitpay\PrivateKey('payment/bitpay/private_key');
if (false === isset($this->_privateKey) || true === empty($this->_privateKey)) {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::generateAndSaveKeys(): could not create new Bitpay private key object. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::generateAndSaveKeys(): could not create new Bitpay private key object. Cannot continue!');
} else {
$this->_privateKey->generate(); $this->_privateKey->generate();
}
$this->_publicKey = new Bitpay\PublicKey('payment/bitpay/public_key'); $this->_publicKey = new Bitpay\PublicKey('payment/bitpay/public_key');
if (false === isset($this->_publicKey) || true === empty($this->_publicKey)) {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::generateAndSaveKeys(): could not create new Bitpay public key object. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::generateAndSaveKeys(): could not create new Bitpay public key object. Cannot continue!');
} else {
$this->_publicKey $this->_publicKey
->setPrivateKey($this->_privateKey) ->setPrivateKey($this->_privateKey)
->generate(); ->generate();
}
$this->getKeyManager()->persist($this->_publicKey); $this->getKeyManager()->persist($this->_publicKey);
$this->getKeyManager()->persist($this->_privateKey); $this->getKeyManager()->persist($this->_privateKey);
$this->debugData('Keys persisted to database'); $this->debugData('[INFO] In Bitpay_Core_Helper_Data::generateAndSaveKeys(): key manager called to persist keypair to database.');
} }
/** /**
@ -106,36 +131,62 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function sendPairingRequest($pairingCode) public function sendPairingRequest($pairingCode)
{ {
$this->debugData( if (false === isset($pairingCode) || true === empty($pairingCode)) {
sprintf('Sending Paring Request with pairing code "%s"', $pairingCode) $this->debugData('[ERROR] In Bitpay_Core_Helper_Data::sendPairingRequest(): missing or invalid pairingCode parameter.');
); throw new \Exception('In Bitpay_Core_Helper_Data::sendPairingRequest(): missing or invalid pairingCode parameter.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::sendPairingRequest(): function called with the pairingCode parameter: ' . $pairingCode);
}
if (true === empty($this->_autoloaderRegistered)) {
$this->registerAutoloader();
}
// Generate/Regenerate keys // Generate/Regenerate keys
$this->generateAndSaveKeys(); $this->generateAndSaveKeys();
$sin = $this->getSinKey(); $sin = $this->getSinKey();
$this->debugData( if (false === isset($sin) || true === empty($sin)) {
sprintf('Sending Pairing Request for SIN "%s"', (string) $sin) $this->debugData('[ERROR] In Bitpay_Core_Helper_Data::sendPairingRequest(): could not retrieve the SIN parameter. Cannot continue!');
); throw new \Exception('In Bitpay_Core_Helper_Data::sendPairingRequest(): could not retrieve the SIN parameter. Cannot continue!');
} else {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::sendPairingRequest(): attempting to pair with the SIN parameter: ' . $sin);
}
// Sanitize label // Sanitize label
$label = preg_replace('/[^a-zA-Z0-9 \-\_\.]/', '', Mage::app()->getStore()->getName()); $label = preg_replace('/[^a-zA-Z0-9 ]/', '', \Mage::app()->getStore()->getName());
$label = substr('Magento - '.$label, 0, 59); $label = substr('Magento ' . $label, 0, 59);
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::sendPairingRequest(): using the label "' . $label . '".');
$token = $this->getBitpayClient()->createToken( $token = $this->getBitpayClient()->createToken(
array( array(
'id' => (string) $sin, 'id' => (string) $sin,
'pairingCode' => $pairingCode, 'pairingCode' => (string) $pairingCode,
'label' => $label, 'label' => (string) $label,
) )
); );
$this->debugData('Token Obtained'); if (false === isset($token) || true === empty($token)) {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::sendPairingRequest(): could not obtain the token from the pairing process. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::sendPairingRequest(): could not obtain the token from the pairing process. Cannot continue!');
} else {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::sendPairingRequest(): token successfully obtained.');
}
$config = new \Mage_Core_Model_Config(); $config = new \Mage_Core_Model_Config();
$config->saveConfig('payment/bitpay/token', $token->getToken());
$this->debugData('Token Persisted persisted to database'); if (false === isset($config) || true === empty($config)) {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::sendPairingRequest(): could not create new Mage_Core_Model_Config object. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::sendPairingRequest(): could not create new Mage_Core_Model_Config object. Cannot continue!');
}
if($config->saveConfig('payment/bitpay/token', $token->getToken())) {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::sendPairingRequest(): token saved to database.');
} else {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::sendPairingRequest(): token could not be saved to database.');
throw new \Exception('In Bitpay_Core_Helper_Data::sendPairingRequest(): token could not be saved to database.');
}
} }
/** /**
@ -143,53 +194,97 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function getSinKey() public function getSinKey()
{ {
if (null !== $this->_sin) { if (false === empty($this->_sin)) {
return $this->_sin; return $this->_sin;
} }
$this->debugData('Getting SIN Key'); $this->debugData('[INFO] In Bitpay_Core_Helper_Data::getSinKey(): attempting to get the SIN parameter.');
if (true === empty($this->_autoloaderRegistered)) {
$this->registerAutoloader(); $this->registerAutoloader();
}
$this->_sin = new Bitpay\SinKey(); $this->_sin = new Bitpay\SinKey();
if (false === isset($this->_sin) || true === empty($this->_sin)) {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::getSinKey(): could not create new BitPay SinKey object. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::getSinKey(): could not create new BitPay SinKey object. Cannot continue!');
}
$this->_sin $this->_sin
->setPublicKey($this->getPublicKey()) ->setPublicKey($this->getPublicKey())
->generate(); ->generate();
if (false === isset($this->_sin) || true === empty($this->_sin)) {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::getSinKey(): could not generate a new SIN from the public key. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::getSinKey(): could not generate a new SIN from the public key. Cannot continue!');
}
return $this->_sin; return $this->_sin;
} }
public function getPublicKey() public function getPublicKey()
{ {
if (null !== $this->_publicKey) { if (true === isset($this->_publicKey) && false === empty($this->_publicKey)) {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPublicKey(): found an existing public key, returning that.');
return $this->_publicKey; return $this->_publicKey;
} }
$this->debugData('Getting Public Key'); if (true === empty($this->_autoloaderRegistered)) {
$this->registerAutoloader();
}
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPublicKey(): did not find an existing public key, attempting to load one from the key manager.');
$this->_publicKey = $this->getKeyManager()->load('payment/bitpay/public_key'); $this->_publicKey = $this->getKeyManager()->load('payment/bitpay/public_key');
if (!$this->_publicKey) { if (true === empty($this->_publicKey)) {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPublicKey(): could not load a public key from the key manager, generating a new one.');
$this->generateAndSaveKeys(); $this->generateAndSaveKeys();
} else {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPublicKey(): successfully loaded public key from the key manager, returning that.');
return $this->_publicKey;
} }
if (false === empty($this->_publicKey)) {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPublicKey(): successfully generated a new public key.');
return $this->_publicKey; return $this->_publicKey;
} else {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::getPublicKey(): could not load or generate a new public key. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::getPublicKey(): could not load or generate a new public key. Cannot continue!');
}
} }
public function getPrivateKey() public function getPrivateKey()
{ {
if (null !== $this->_privateKey) { if (false === empty($this->_privateKey)) {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPrivateKey(): found an existing private key, returning that.');
return $this->_privateKey; return $this->_privateKey;
} }
$this->debugData('Getting Private Key'); if (true === empty($this->_autoloaderRegistered)) {
$this->registerAutoloader();
}
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPrivateKey(): did not find an existing private key, attempting to load one from the key manager.');
$this->_privateKey = $this->getKeyManager()->load('payment/bitpay/private_key'); $this->_privateKey = $this->getKeyManager()->load('payment/bitpay/private_key');
if (!$this->_publicKey) { if (true === empty($this->_privateKey)) {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPrivateKey(): could not load a private key from the key manager, generating a new one.');
$this->generateAndSaveKeys(); $this->generateAndSaveKeys();
} else {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPrivateKey(): successfully loaded private key from the key manager, returning that.');
return $this->_privateKey;
} }
if (false === empty($this->_privateKey)) {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPrivateKey(): successfully generated a new private key.');
return $this->_privateKey; return $this->_privateKey;
} else {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::getPrivateKey(): could not load or generate a new private key. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::getPrivateKey(): could not load or generate a new private key. Cannot continue!');
}
} }
/** /**
@ -197,10 +292,19 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function getKeyManager() public function getKeyManager()
{ {
if (null == $this->_keyManager) { if (true === empty($this->_keyManager)) {
if (true === empty($this->_autoloaderRegistered)) {
$this->registerAutoloader(); $this->registerAutoloader();
$this->debugData('Creating instance of KeyManager'); }
$this->_keyManager = new Bitpay\KeyManager(new Bitpay\Storage\MagentoStorage()); $this->_keyManager = new Bitpay\KeyManager(new Bitpay\Storage\MagentoStorage());
if (false === isset($this->_keyManager) || true === empty($this->_keyManager)) {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::getKeyManager(): could not create new BitPay KeyManager object. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::getKeyManager(): could not create new BitPay KeyManager object. Cannot continue!');
} else {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getKeyManager(): successfully created new BitPay KeyManager object.');
}
} }
return $this->_keyManager; return $this->_keyManager;
@ -214,9 +318,19 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function getBitpay() public function getBitpay()
{ {
if (null === $this->_bitpay) { if (true === empty($this->_bitpay)) {
if (true === empty($this->_autoloaderRegistered)) {
$this->registerAutoloader(); $this->registerAutoloader();
}
$this->_bitpay = new Bitpay\Bitpay(array('bitpay' => $this->getBitpayConfig())); $this->_bitpay = new Bitpay\Bitpay(array('bitpay' => $this->getBitpayConfig()));
if (false === isset($this->_bitpay) || true === empty($this->_bitpay)) {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::getBitpay(): could not create new BitPay object. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::getBitpay(): could not create new BitPay object. Cannot continue!');
} else {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getBitpay(): successfully created new BitPay object.');
}
} }
return $this->_bitpay; return $this->_bitpay;
@ -232,7 +346,7 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
return array( return array(
'public_key' => 'payment/bitpay/public_key', 'public_key' => 'payment/bitpay/public_key',
'private_key' => 'payment/bitpay/private_key', 'private_key' => 'payment/bitpay/private_key',
'network' => Mage::getStoreConfig('payment/bitpay/network'), 'network' => \Mage::getStoreConfig('payment/bitpay/network'),
'key_storage' => '\\Bitpay\\Storage\\MagentoStorage', 'key_storage' => '\\Bitpay\\Storage\\MagentoStorage',
); );
} }
@ -242,13 +356,23 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/ */
public function getBitpayClient() public function getBitpayClient()
{ {
if (null !== $this->_client) { if (false === empty($this->_client)) {
return $this->_client; return $this->_client;
} }
if (true === empty($this->_autoloaderRegistered)) {
$this->registerAutoloader(); $this->registerAutoloader();
}
$this->_client = new Bitpay\Client\Client(); $this->_client = new Bitpay\Client\Client();
if (false === isset($this->_client) || true === empty($this->_client)) {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::getBitpayClient(): could not create new BitPay Client object. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::getBitpayClient(): could not create new BitPay Client object. Cannot continue!');
} else {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getBitpayClient(): successfully created new BitPay Client object.');
}
$this->_client->setPublicKey($this->getPublicKey()); $this->_client->setPublicKey($this->getPublicKey());
$this->_client->setPrivateKey($this->getPrivateKey()); $this->_client->setPrivateKey($this->getPrivateKey());
$this->_client->setNetwork($this->getBitpay()->get('network')); $this->_client->setNetwork($this->getBitpay()->get('network'));
@ -260,9 +384,20 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
public function getToken() public function getToken()
{ {
if (true === empty($this->_autoloaderRegistered)) {
$this->registerAutoloader(); $this->registerAutoloader();
}
$token = new Bitpay\Token(); $token = new Bitpay\Token();
$token->setToken(Mage::getStoreConfig('payment/bitpay/token'));
if (false === isset($token) || true === empty($token)) {
$this->debugData('[ERROR] In Bitpay_Core_Helper_Data::getToken(): could not create new BitPay Token object. Cannot continue!');
throw new \Exception('In Bitpay_Core_Helper_Data::getToken(): could not create new BitPay Token object. Cannot continue!');
} else {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getToken(): successfully created new BitPay Token object.');
}
$token->setToken(\Mage::getStoreConfig('payment/bitpay/token'));
return $token; return $token;
} }

View File

@ -23,25 +23,21 @@ class Bitpay_Core_Model_Config_PairingCode extends Mage_Core_Model_Config_Data
*/ */
$pairingCode = trim($this->getValue()); $pairingCode = trim($this->getValue());
if (empty($pairingCode)) { if (true === empty($pairingCode)) {
return; return;
} }
Mage::helper('bitpay')->debugData('Attempting Pair Code'); \Mage::helper('bitpay')->debugData('[INFO] In Bitpay_Core_Model_Config_PairingCode::save(): attempting to pair with BitPay with pairing code ' . $pairingCode);
try { try {
Mage::helper('bitpay')->sendPairingRequest($pairingCode); \Mage::helper('bitpay')->sendPairingRequest($pairingCode);
} catch (Exception $e) { } catch (\Exception $e) {
Mage::helper('bitpay')->debugData( \Mage::helper('bitpay')->debugData(sprintf('[ERROR] Exception thrown while calling the sendPairingRequest() function. The specific error message is: "%s"', $e->getMessage()));
sprintf('Error Pairing Code "%s"', $e->getMessage()) \Mage::getSingleton('core/session')->addError('There was an error while trying to pair with BitPay using the pairing code '.$pairingCode.'. Please try again or enable debug mode and send the "payment_bitpay.log" file to support@bitpay.com for more help.');
);
Mage::getSingleton('core/session')->addError(
'There was an error while trying to pair the pairing code. Please try again or enabled debug mode and send the "payment_bitpay.log" file to support.'
);
return; return;
} }
Mage::getSingleton('core/session')->addSuccess('Pairing Code was successful.'); \Mage::getSingleton('core/session')->addSuccess('Pairing with BitPay was successful.');
} }
} }

View File

@ -24,18 +24,20 @@ class Bitpay_Core_Model_Invoice extends Mage_Core_Model_Abstract
*/ */
public function prepareWithBitpayInvoice($invoice) public function prepareWithBitpayInvoice($invoice)
{ {
if (false === isset($invoice) || true === empty($invoice)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_Model_Invoice::prepareWithBitpayInvoice(): Missing or empty $invoice parameter.');
throw new \Exception('In Bitpay_Core_Model_Invoice::prepareWithBitpayInvoice(): Missing or empty $invoice parameter.');
}
$this->addData( $this->addData(
array( array(
'id' => $invoice->getId(), 'id' => $invoice->getId(),
//'updated_at' => 'NOW()',
'url' => $invoice->getUrl(), 'url' => $invoice->getUrl(),
'pos_data' => $invoice->getPosData(), 'pos_data' => $invoice->getPosData(),
'status' => $invoice->getStatus(), 'status' => $invoice->getStatus(),
'btc_price' => $invoice->getBtcPrice(), 'btc_price' => $invoice->getBtcPrice(),
//'btc_due' => $invoice->getBtcDue(),
'price' => $invoice->getPrice(), 'price' => $invoice->getPrice(),
'currency' => $invoice->getCurrency()->getCode(), 'currency' => $invoice->getCurrency()->getCode(),
//'ex_rates' => $invoice->getExRates(),
'order_id' => $invoice->getOrderId(), 'order_id' => $invoice->getOrderId(),
'invoice_time' => $invoice->getInvoiceTime(), 'invoice_time' => $invoice->getInvoiceTime(),
'expiration_time' => $invoice->getExpirationTime(), 'expiration_time' => $invoice->getExpirationTime(),
@ -43,7 +45,6 @@ class Bitpay_Core_Model_Invoice extends Mage_Core_Model_Abstract
'btc_paid' => $invoice->getBtcPaid(), 'btc_paid' => $invoice->getBtcPaid(),
'rate' => $invoice->getRate(), 'rate' => $invoice->getRate(),
'exception_status' => $invoice->getExceptionStatus(), 'exception_status' => $invoice->getExceptionStatus(),
//'token' => $invoice->getToken(),
) )
); );
@ -58,6 +59,11 @@ class Bitpay_Core_Model_Invoice extends Mage_Core_Model_Abstract
*/ */
public function prepateWithOrder($order) public function prepateWithOrder($order)
{ {
if (false === isset($order) || true === empty($order)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_Model_Invoice::prepateWithOrder(): Missing or empty $order parameter.');
throw new \Exception('In Bitpay_Core_Model_Invoice::prepateWithOrder(): Missing or empty $order parameter.');
}
$this->addData( $this->addData(
array( array(
'quote_id' => $order->getQuoteId(), 'quote_id' => $order->getQuoteId(),

View File

@ -12,6 +12,7 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
protected $_code = 'bitpay'; protected $_code = 'bitpay';
protected $_formBlockType = 'bitpay/form_bitpay'; protected $_formBlockType = 'bitpay/form_bitpay';
protected $_infoBlockType = 'bitpay/info'; protected $_infoBlockType = 'bitpay/info';
protected $_isGateway = true; protected $_isGateway = true;
protected $_canAuthorize = true; protected $_canAuthorize = true;
protected $_canCapture = false; protected $_canCapture = false;
@ -19,12 +20,14 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
protected $_isInitializeNeeded = false; protected $_isInitializeNeeded = false;
protected $_canFetchTransactionInfo = false; protected $_canFetchTransactionInfo = false;
protected $_canManagerRecurringProfiles = false; protected $_canManagerRecurringProfiles = false;
//protected $_canUseCheckout = true; protected $_canUseCheckout = true;
//protected $_canUseForMultishipping = true; protected $_canUseForMultishipping = true;
//protected $_canCapturePartial = false; protected $_canCapturePartial = false;
//protected $_canRefund = false; protected $_canRefund = false;
//protected $_canVoid = false; protected $_canVoid = false;
protected $_debugReplacePrivateDataKeys = array(); protected $_debugReplacePrivateDataKeys = array();
protected static $_redirectUrl; protected static $_redirectUrl;
/** /**
@ -34,40 +37,46 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/ */
public function authorize(Varien_Object $payment, $amount) public function authorize(Varien_Object $payment, $amount)
{ {
$this->debugData('authorizing new order'); if (false === isset($payment) || false === isset($amount) || true === empty($payment) || true === empty($amount)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::authorize(): missing payment or amount parameters.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::authorize(): missing payment or amount parameters.');
}
$this->debugData('[INFO] Bitpay_Core_Model_Method_Bitcoin::authorize(): authorizing new order.');
// Create BitPay Invoice // Create BitPay Invoice
$invoice = $this->initializeInvoice(); $invoice = $this->initializeInvoice();
if (false === isset($invoice) || true === empty($invoice)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::authorize(): could not initialize invoice.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::authorize(): could not initialize invoice.');
}
$invoice = $this->prepareInvoice($invoice, $payment, $amount); $invoice = $this->prepareInvoice($invoice, $payment, $amount);
try { try {
$bitpayInvoice = Mage::helper('bitpay')->getBitpayClient()->createInvoice($invoice); $bitpayInvoice = \Mage::helper('bitpay')->getBitpayClient()->createInvoice($invoice);
} catch (Exception $e) { } catch (\Exception $e) {
$this->debugData($e->getMessage()); $this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::authorize(): ' . $e->getMessage());
$this->debugData( \Mage::throwException('In Bitpay_Core_Model_Method_Bitcoin::authorize(): Could not authorize transaction.');
array(
Mage::helper('bitpay')->getBitpayClient()->getRequest()->getBody(),
Mage::helper('bitpay')->getBitpayClient()->getResponse()->getBody(),
)
);
Mage::throwException('Could not authorize transaction.');
} }
self::$_redirectUrl = $bitpayInvoice->getUrl(); self::$_redirectUrl = $bitpayInvoice->getUrl();
$this->debugData( $this->debugData(
array( array(
'BitPay Invoice created', '[INFO] BitPay Invoice created',
sprintf('Invoice URL: "%s"', $bitpayInvoice->getUrl()), sprintf('Invoice URL: "%s"', $bitpayInvoice->getUrl()),
) )
); );
// Save BitPay Invoice in database for reference // Save BitPay Invoice in database for reference
$mirrorInvoice = Mage::getModel('bitpay/invoice') $mirrorInvoice = \Mage::getModel('bitpay/invoice')
->prepareWithBitpayInvoice($bitpayInvoice) ->prepareWithBitpayInvoice($bitpayInvoice)
->prepateWithOrder($payment->getOrder()) ->prepateWithOrder($payment->getOrder())
->save(); ->save();
$this->debugData($bitpayInvoice->getId()); $this->debugData('[INFO] Leaving Bitpay_Core_Model_Method_Bitcoin::authorize(): invoice id ' . $bitpayInvoice->getId());
return $this; return $this;
} }
@ -81,18 +90,20 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/ */
public function canUseCheckout() public function canUseCheckout()
{ {
$token = Mage::getStoreConfig('payment/bitpay/token'); $token = \Mage::getStoreConfig('payment/bitpay/token');
if (empty($token)) { if (false === isset($token) || true === empty($token)) {
/** /**
* Merchant must goto their account and create a pairing code to * Merchant must goto their account and create a pairing code to
* enter in. * enter in.
*/ */
$this->debugData('Magento store does not have a BitPay token.'); $this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::canUseCheckout(): There was an error retrieving the token store param from the database or this Magento store does not have a BitPay token.');
return false; return false;
} }
$this->debugData('[INFO] Leaving Bitpay_Core_Model_Method_Bitcoin::canUseCheckout(): token obtained from storage successfully.');
return true; return true;
} }
@ -104,11 +115,33 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/ */
public function fetchInvoice($id) public function fetchInvoice($id)
{ {
Mage::helper('bitpay')->registerAutoloader(); if (false === isset($id) || true === empty($id)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::fetchInvoice(): missing or invalid id parameter.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::fetchInvoice(): missing or invalid id parameter.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::fetchInvoice(): function called with id ' . $id);
}
\Mage::helper('bitpay')->registerAutoloader();
$client = \Mage::helper('bitpay')->getBitpayClient();
if (false === isset($client) || true === empty($client)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::fetchInvoice(): could not obtain BitPay client.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::fetchInvoice(): could not obtain BitPay client.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::fetchInvoice(): obtained BitPay client successfully.');
}
$client = Mage::helper('bitpay')->getBitpayClient();
$invoice = $client->getInvoice($id); $invoice = $client->getInvoice($id);
if (false === isset($invoice) || true === empty($invoice)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::fetchInvoice(): could not retrieve invoice from BitPay.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::fetchInvoice(): could not retrieve invoice from BitPay.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::fetchInvoice(): successfully retrieved invoice id ' . $id . ' from BitPay.');
}
return $invoice; return $invoice;
} }
@ -121,9 +154,12 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/ */
public function extractAddress($address) public function extractAddress($address)
{ {
$this->debugData( if (false === isset($address) || true === empty($address)) {
sprintf('Extracting addess') $this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::extractAddress(): missing or invalid address parameter.');
); throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::extractAddress(): missing or invalid address parameter.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::extractAddress(): called with good address parameter, extracting now.');
}
$options = array(); $options = array();
$options['buyerName'] = $address->getName(); $options['buyerName'] = $address->getName();
@ -145,8 +181,11 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
// trim to fit API specs // trim to fit API specs
foreach (array('buyerName', 'buyerAddress1', 'buyerAddress2', 'buyerAddress3', 'buyerAddress4', 'buyerCity', 'buyerState', 'buyerZip', 'buyerCountry', 'buyerEmail', 'buyerPhone') as $f) { foreach (array('buyerName', 'buyerAddress1', 'buyerAddress2', 'buyerAddress3', 'buyerAddress4', 'buyerCity', 'buyerState', 'buyerZip', 'buyerCountry', 'buyerEmail', 'buyerPhone') as $f) {
if (true === isset($options[$f]) && strlen($options[$f]) > 100) {
$this->debugData('[WARNING] In Bitpay_Core_Model_Method_Bitcoin::extractAddress(): the ' . $f . ' parameter was greater than 100 characters, trimming.');
$options[$f] = substr($options[$f], 0, 100); $options[$f] = substr($options[$f], 0, 100);
} }
}
return $options; return $options;
} }
@ -158,9 +197,7 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/ */
public function getOrderPlaceRedirectUrl() public function getOrderPlaceRedirectUrl()
{ {
$this->debugData( $this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::getOrderPlaceRedirectUrl(): $_redirectUrl is ' . self::$_redirectUrl);
'Customer wants to place the order. Create invoice and redirect user to invoice'
);
return self::$_redirectUrl; return self::$_redirectUrl;
} }
@ -173,13 +210,21 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/ */
private function initializeInvoice() private function initializeInvoice()
{ {
Mage::helper('bitpay')->registerAutoloader(); \Mage::helper('bitpay')->registerAutoloader();
$invoice = new Bitpay\Invoice(); $invoice = new Bitpay\Invoice();
if (false === isset($invoice) || true === empty($invoice)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::initializeInvoice(): could not construct new BitPay invoice object.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::initializeInvoice(): could not construct new BitPay invoice object.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::initializeInvoice(): constructed new BitPay invoice object successfully.');
}
$invoice->setFullNotifications(true); $invoice->setFullNotifications(true);
$invoice->setTransactionSpeed(Mage::getStoreConfig('payment/bitpay/speed')); $invoice->setTransactionSpeed(\Mage::getStoreConfig('payment/bitpay/speed'));
$invoice->setNotificationUrl(Mage::getUrl(Mage::getStoreConfig('payment/bitpay/notification_url'))); $invoice->setNotificationUrl(\Mage::getUrl(\Mage::getStoreConfig('payment/bitpay/notification_url')));
$invoice->setRedirectUrl(Mage::getUrl(Mage::getStoreConfig('payment/bitpay/redirect_url'))); $invoice->setRedirectUrl(\Mage::getUrl(\Mage::getStoreConfig('payment/bitpay/redirect_url')));
return $invoice; return $invoice;
} }
@ -195,14 +240,15 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/ */
private function prepareInvoice($invoice, $payment, $amount) private function prepareInvoice($invoice, $payment, $amount)
{ {
if (false === isset($invoice) || true === empty($invoice) || false === isset($payment) || true === empty($payment) || false === isset($amount) || true === empty($amount)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::prepareInvoice(): missing or invalid invoice, payment or amount parameter.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::prepareInvoice(): missing or invalid invoice, payment or amount parameter.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::prepareInvoice(): entered function with good invoice, payment and amount parameters.');
}
$invoice->setOrderId($payment->getOrder()->getIncrementId()); $invoice->setOrderId($payment->getOrder()->getIncrementId());
$invoice->setPosData( $invoice->setPosData(json_encode(array('id' => $payment->getOrder()->getIncrementId())));
json_encode(
array(
'id' => $payment->getOrder()->getIncrementId(),
)
)
);
$invoice = $this->addCurrencyInfo($invoice, $payment->getOrder()); $invoice = $this->addCurrencyInfo($invoice, $payment->getOrder());
$invoice = $this->addPriceInfo($invoice, $amount); $invoice = $this->addPriceInfo($invoice, $amount);
@ -220,7 +266,20 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/ */
private function addBuyerInfo($invoice, $order) private function addBuyerInfo($invoice, $order)
{ {
if (false === isset($invoice) || true === empty($invoice) || false === isset($order) || true === empty($order)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::addBuyerInfo(): missing or invalid invoice or order parameter.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::addBuyerInfo(): missing or invalid invoice or order parameter.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::addBuyerInfo(): function called with good invoice and order parameters.');
}
$buyer = new Bitpay\Buyer(); $buyer = new Bitpay\Buyer();
if (false === isset($buyer) || true === empty($buyer)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::addBuyerInfo(): could not construct new BitPay buyer object.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::addBuyerInfo(): could not construct new BitPay buyer object.');
}
$buyer->setFirstName($order->getCustomerFirstname()); $buyer->setFirstName($order->getCustomerFirstname());
$buyer->setLastName($order->getCustomerLastname()); $buyer->setLastName($order->getCustomerLastname());
$invoice->setBuyer($buyer); $invoice->setBuyer($buyer);
@ -237,7 +296,20 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/ */
private function addCurrencyInfo($invoice, $order) private function addCurrencyInfo($invoice, $order)
{ {
if (false === isset($invoice) || true === empty($invoice) || false === isset($order) || true === empty($order)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::addCurrencyInfo(): missing or invalid invoice or order parameter.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::addCurrencyInfo(): missing or invalid invoice or order parameter.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::addCurrencyInfo(): function called with good invoice and order parameters.');
}
$currency = new Bitpay\Currency(); $currency = new Bitpay\Currency();
if (false === isset($currency) || true === empty($currency)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::addCurrencyInfo(): could not construct new BitPay currency object.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::addCurrencyInfo(): could not construct new BitPay currency object.');
}
$currency->setCode($order->getBaseCurrencyCode()); $currency->setCode($order->getBaseCurrencyCode());
$invoice->setCurrency($currency); $invoice->setCurrency($currency);
@ -253,7 +325,20 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/ */
private function addPriceInfo($invoice, $amount) private function addPriceInfo($invoice, $amount)
{ {
if (false === isset($invoice) || true === empty($invoice) || false === isset($amount) || true === empty($amount)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::addPriceInfo(): missing or invalid invoice or amount parameter.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::addPriceInfo(): missing or invalid invoice or amount parameter.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::addPriceInfo(): function called with good invoice and amount parameters.');
}
$item = new \Bitpay\Item(); $item = new \Bitpay\Item();
if (false === isset($item) || true === empty($item)) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::addPriceInfo(): could not construct new BitPay item object.');
throw new \Exception('In Bitpay_Core_Model_Method_Bitcoin::addPriceInfo(): could not construct new BitPay item object.');
}
$item->setPrice($amount); $item->setPrice($amount);
$invoice->setItem($item); $invoice->setItem($item);

View File

@ -18,8 +18,8 @@ class Bitpay_Core_Model_Network
public function toOptionArray() public function toOptionArray()
{ {
return array( return array(
array('value' => self::NETWORK_LIVENET, 'label' => Mage::helper('bitpay')->__('Livenet')), array('value' => self::NETWORK_LIVENET, 'label' => \Mage::helper('bitpay')->__(ucwords(self::NETWORK_LIVENET))),
array('value' => self::NETWORK_TESTNET, 'label' => Mage::helper('bitpay')->__('Testnet')), array('value' => self::NETWORK_TESTNET, 'label' => \Mage::helper('bitpay')->__(ucwords(self::NETWORK_TESTNET))),
); );
} }
} }

View File

@ -6,61 +6,61 @@
class Bitpay_Core_Model_Observer class Bitpay_Core_Model_Observer
{ {
/** /*
* TODO: Why is this here?
*/ */
public function checkForRequest($observer) public function checkForRequest($observer)
{ {
} }
/** /*
* Queries BitPay to update the order states in magento to make sure that * Queries BitPay to update the order states in magento to make sure that
* open orders are closed/canceled if the BitPay invoice expires or becomes * open orders are closed/canceled if the BitPay invoice expires or becomes
* invalid. * invalid.
*/ */
public function updateOrderStates() public function updateOrderStates()
{ {
Mage::helper('bitpay')->debugData( $apiKey = \Mage::getStoreConfig('payment/bitpay/api_key');
'cronjob: started'
);
$apiKey = Mage::getStoreConfig('payment/bitpay/api_key'); if (false === isset($apiKey) || empty($apiKey)) {
\Mage::helper('bitpay')->debugData('[INFO] Bitpay_Core_Model_Observer::updateOrderStates() could not start job to update the order states because the API key was not set.');
if (empty($apiKey)) { return;
Mage::helper('bitpay')->debugData( } else {
'cronjob: Api Key not set.' \Mage::helper('bitpay')->debugData('[INFO] Bitpay_Core_Model_Observer::updateOrderStates() started job to query BitPay to update the existing order states.');
);
return; // Api Key needs to be set
} }
/** /*
* Get all of the orders that are open and have not received an IPN for * Get all of the orders that are open and have not received an IPN for
* complete, expired, or invalid. * complete, expired, or invalid.
*
* If anyone knows of a better way to do this, please let me know
*/ */
$orders = Mage::getModel('bitpay/ipn')->getOpenOrders(); $orders = \Mage::getModel('bitpay/ipn')->getOpenOrders();
/** if (false === isset($orders) || empty($orders)) {
\Mage::helper('bitpay')->debugData('[INFO] Bitpay_Core_Model_Observer::updateOrderStates() could not retrieve the open orders.');
return;
} else {
\Mage::helper('bitpay')->debugData('[INFO] Bitpay_Core_Model_Observer::updateOrderStates() successfully retrieved existing open orders.');
}
/*
* Get all orders that have been paid using bitpay and * Get all orders that have been paid using bitpay and
* are not complete/closed/etc * are not complete/closed/etc
*/ */
foreach ($orders as $order) { foreach ($orders as $order) {
/** /*
* Query BitPay with the invoice ID to get the status. We must take * Query BitPay with the invoice ID to get the status. We must take
* care not to anger the API limiting gods and disable our access * care not to anger the API limiting gods and disable our access
* to the API. * to the API.
*/ */
$status = null; $status = null;
// TODO:
// Does the order need to be updated? // Does the order need to be updated?
// Yes? Update Order Status // Yes? Update Order Status
// No? continue // No? continue
} }
Mage::helper('bitpay')->debugData( \Mage::helper('bitpay')->debugData('[INFO] Bitpay_Core_Model_Observer::updateOrderStates() order status update job finished.');
'cronjob: end'
);
} }
/** /**
@ -69,6 +69,7 @@ class Bitpay_Core_Model_Observer
*/ */
public function cleanExpired() public function cleanExpired()
{ {
Mage::helper('bitpay')->cleanExpired(); \Mage::helper('bitpay')->debugData('[INFO] Bitpay_Core_Model_Observer::cleanExpired() called.');
\Mage::helper('bitpay')->cleanExpired();
} }
} }

View File

@ -19,12 +19,12 @@ class Bitpay_Core_Model_Status
public function toOptionArray() public function toOptionArray()
{ {
return array( return array(
array('value' => self::STATUS_NEW, 'label' => Mage::helper('bitpay')->__('New')), array('value' => self::STATUS_NEW, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_NEW))),
array('value' => self::STATUS_PAID, 'label' => Mage::helper('bitpay')->__('Paid')), array('value' => self::STATUS_PAID, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_PAID))),
array('value' => self::STATUS_CONFIRMED, 'label' => Mage::helper('bitpay')->__('Confirmed')), array('value' => self::STATUS_CONFIRMED, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_CONFIRMED))),
array('value' => self::STATUS_COMPLETE, 'label' => Mage::helper('bitpay')->__('Complete')), array('value' => self::STATUS_COMPLETE, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_COMPLETE))),
array('value' => self::STATUS_EXPIRED, 'label' => Mage::helper('bitpay')->__('Expired')), array('value' => self::STATUS_EXPIRED, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_EXPIRED))),
array('value' => self::STATUS_INVALID, 'label' => Mage::helper('bitpay')->__('Invalid')), array('value' => self::STATUS_INVALID, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_INVALID))),
); );
} }
} }

View File

@ -16,9 +16,9 @@ class Bitpay_Core_Model_TransactionSpeed
public function toOptionArray() public function toOptionArray()
{ {
return array( return array(
array('value' => self::SPEED_LOW, 'label' => Mage::helper('bitpay')->__('Low')), array('value' => self::SPEED_LOW, 'label' => \Mage::helper('bitpay')->__(ucwords(self::SPEED_LOW))),
array('value' => self::SPEED_MEDIUM, 'label' => Mage::helper('bitpay')->__('Medium')), array('value' => self::SPEED_MEDIUM, 'label' => \Mage::helper('bitpay')->__(ucwords(self::SPEED_MEDIUM))),
array('value' => self::SPEED_HIGH, 'label' => Mage::helper('bitpay')->__('High')), array('value' => self::SPEED_HIGH, 'label' => \Mage::helper('bitpay')->__(ucwords(self::SPEED_HIGH))),
); );
} }
} }

View File

@ -14,19 +14,21 @@ class Bitpay_Core_IndexController extends Mage_Core_Controller_Front_Action
*/ */
public function indexAction() public function indexAction()
{ {
$params = $this->getRequest()->getParams();
$paid = false; $paid = false;
if (isset($params['paid'])) { $params = $this->getRequest()->getParams();
Mage::helper('bitpay')->registerAutoloader();
Mage::helper('bitpay')->debugData( if (true === isset($params['paid'])) {
$params \Mage::helper('bitpay')->registerAutoloader();
); \Mage::helper('bitpay')->debugData($params);
} else {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_IndexController::indexAction(), Could not get parameters from HTTP request.');
} }
$this->loadLayout(); $this->loadLayout();
$this->getResponse()->setHeader('Content-type', 'application/json'); $this->getResponse()->setHeader('Content-type', 'application/json');
$this->getResponse()->setBody(
json_encode(array('paid' => $paid)) // ?
); $this->getResponse()->setBody(json_encode(array('paid' => $paid)));
} }
} }

View File

@ -4,8 +4,6 @@
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE * @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/ */
/** /**
* @route /bitpay/ipn * @route /bitpay/ipn
*/ */
@ -19,33 +17,41 @@ class Bitpay_Core_IpnController extends Mage_Core_Controller_Front_Action
*/ */
public function indexAction() public function indexAction()
{ {
if (!ini_get('allow_url_fopen')) { if (false === ini_get('allow_url_fopen')) {
ini_set('allow_url_fopen', true); ini_set('allow_url_fopen', true);
} }
$raw_post_data = file_get_contents('php://input'); $raw_post_data = file_get_contents('php://input');
if ($raw_post_data === false) { if (false === $raw_post_data) {
throw new Exception('Could not read from the php://input stream or invalid Bitpay IPN received.'); \Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), Could not read from the php://input stream or invalid Bitpay IPN received.');
throw new \Exception('Could not read from the php://input stream or invalid Bitpay IPN received.');
} }
Mage::helper('bitpay')->registerAutoloader(); \Mage::helper('bitpay')->registerAutoloader();
Mage::helper('bitpay')->debugData(
array( \Mage::helper('bitpay')->debugData(array(sprintf('[INFO] In Bitpay_Core_IpnController::indexAction(), Incoming IPN message from BitPay: '),$raw_post_data,));
sprintf('Incoming IPN from bitpay'),
getallheaders(),
$raw_post_data,
)
);
// Magento doesn't seem to have a way to get the Request body // Magento doesn't seem to have a way to get the Request body
$ipn = json_decode($raw_post_data); $ipn = json_decode($raw_post_data);
if (true === empty($ipn)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), Could not decode the JSON payload from BitPay.');
throw new \Exception('Could not decode the JSON payload from BitPay.');
}
if (true === empty($ipn->id) || false === isset($ipn->posData)) {
\Mage::helper('bitpay')->debugData(sprintf('[ERROR] In Bitpay_Core_IpnController::indexAction(), Did not receive order ID in IPN: ', $ipn));
throw new \Exception('Invalid Bitpay payment notification message received - did not receive order ID.');
}
$ipn->posData = is_string($ipn->posData) ? json_decode($ipn->posData) : $ipn->posData; $ipn->posData = is_string($ipn->posData) ? json_decode($ipn->posData) : $ipn->posData;
$ipn->buyerFields = isset($ipn->buyerFields) ? $ipn->buyerFields : new stdClass(); $ipn->buyerFields = isset($ipn->buyerFields) ? $ipn->buyerFields : new stdClass();
Mage::helper('bitpay')->debugData($ipn);
\Mage::helper('bitpay')->debugData($ipn);
// Log IPN // Log IPN
$mageIpn = Mage::getModel('bitpay/ipn')->addData( $mageIpn = \Mage::getModel('bitpay/ipn')->addData(
array( array(
'invoice_id' => isset($ipn->id) ? $ipn->id : '', 'invoice_id' => isset($ipn->id) ? $ipn->id : '',
'url' => isset($ipn->url) ? $ipn->url : '', 'url' => isset($ipn->url) ? $ipn->url : '',
@ -63,18 +69,11 @@ class Bitpay_Core_IpnController extends Mage_Core_Controller_Front_Action
) )
)->save(); )->save();
if (empty($ipn->id) || !isset($ipn->posData->id)) { $order = \Mage::getModel('sales/order')->loadByIncrementId($ipn->posData->id);
Mage::helper('bitpay')->debugData(
sprintf('Did not receive order id in IPN. See IPN "%s" in database.', $mageIpn->getId())
);
throw new Exception('Invalid Bitpay IPN received.');
}
$order = Mage::getModel('sales/order')->loadByIncrementId($ipn->posData->id); if (false === isset($order) || true === empty($order->getId())) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), Invalid Bitpay IPN received.');
if (!$order->getId()) { \Mage::throwException('Invalid Bitpay IPN received.');
Mage::helper('bitpay')->debugData('Invalid Bitpay IPN received.');
Mage::throwException('Invalid Bitpay IPN received.');
} }
/** /**
@ -82,32 +81,58 @@ class Bitpay_Core_IpnController extends Mage_Core_Controller_Front_Action
* match up and no one is using an automated tool to post IPN's to merchants * match up and no one is using an automated tool to post IPN's to merchants
* store. * store.
*/ */
$invoice = Mage::getModel('bitpay/method_bitcoin')->fetchInvoice($ipn->id); $invoice = \Mage::getModel('bitpay/method_bitcoin')->fetchInvoice($ipn->id);
if (false === isset($invoice) || true === empty($invoice)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), Could not retrieve the invoice details for the ipn ID of ' . $ipn->id);
\Mage::throwException('Could not retrieve the invoice details for the ipn ID of ' . $ipn->id);
}
// Does the status match? // Does the status match?
if ($invoice && $invoice->getStatus() != $ipn->status) { if ($invoice->getStatus() != $ipn->status) {
Mage::getModel('bitpay/method_bitcoin')->debugData('IPN status and status from BitPay are different'); \Mage::getModel('bitpay/method_bitcoin')->debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), IPN status and status from BitPay are different. Rejecting this IPN!');
Mage::throwException('There was an error processing the ipn'); \Mage::throwException('There was an error processing the IPN - statuses are different. Rejecting this IPN!');
} }
// Does the price match? // Does the price match?
if ($invoice && $invoice->getPrice() != $ipn->price) { if ($invoice->getPrice() != $ipn->price) {
Mage::getModel('bitpay/method_bitcoin')>debugData('Price difference'); \Mage::getModel('bitpay/method_bitcoin')>debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), IPN price and invoice price are different. Rejecting this IPN!');
Mage::throwException('There was an error processing the ipn'); \Mage::throwException('There was an error processing the IPN - invoice price does not match the IPN price. Rejecting this IPN!');
} }
// Update the order to notifiy that it has been paid // Update the order to notifiy that it has been paid
if (in_array($invoice->getStatus(), array('paid', 'confirmed', 'complete'))) { if (true === in_array($invoice->getStatus(), array('paid', 'confirmed', 'complete'))) {
$payment = Mage::getModel('sales/order_payment')->setOrder($order); $payment = \Mage::getModel('sales/order_payment')->setOrder($order);
if (true === isset($payment) && false === empty($payment)) {
$payment->registerCaptureNotification($invoice->getPrice()); $payment->registerCaptureNotification($invoice->getPrice());
$order->addPayment($payment)->save(); $order->addPayment($payment);
// If the customer has not already been notified by email
// send the notification now that there's a new order.
if (!$order->getEmailSent()) {
\Mage::helper('bitpay')->debugData('[INFO] In Bitpay_Core_IpnController::indexAction(), Order email not sent so I am calling $order->sendNewOrderEmail() now...');
$order->sendNewOrderEmail();
}
$order->save();
} else {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), Could not create a payment object in the Bitpay IPN controller.');
\Mage::throwException('Could not create a payment object in the Bitpay IPN controller.');
}
} }
// use state as defined by Merchant // use state as defined by Merchant
$state = Mage::getStoreConfig(sprintf('payment/bitpay/invoice_%s', $invoice->getStatus())); $state = \Mage::getStoreConfig(sprintf('payment/bitpay/invoice_%s', $invoice->getStatus()));
if (false === isset($state) || true === empty($state)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), Could not retrieve the defined state parameter to update this order to in the Bitpay IPN controller.');
\Mage::throwException('Could not retrieve the defined state parameter to update this order to in the Bitpay IPN controller.');
}
$order->addStatusToHistory( $order->addStatusToHistory(
$state, $state,
sprintf('Incoming IPN status "%s" updated order state to "%s"', $invoice->getStatus(), $state) sprintf('[INFO] In Bitpay_Core_IpnController::indexAction(), Incoming IPN status "%s" updated order state to "%s"', $invoice->getStatus(), $state)
)->save(); )->save();
} }
} }

View File

@ -28,9 +28,8 @@
<pairing_code translate="label"> <pairing_code translate="label">
<label>Pairing Code</label> <label>Pairing Code</label>
<comment> <comment>
<![CDATA[Create a pairing code for your account at <a href="https://bitpay.com/api-tokens">https://bitpay.com/api-tokens</a> and put <![CDATA[You must first create a pairing code for your BitPay Merchant account at <a href="https://bitpay.com/api-tokens" target="_blank">https://bitpay.com/api-tokens</a> and copy/paste
the code that was generated in this field. Once you have paired your Mangento store you can begin accepted Bitcoins as payment that code here. Once you have successfully paired this Magento store with your BitPay Merchant account, you can begin accepting Bitcoins as payment.]]>
on your store.]]>
</comment> </comment>
<frontend_type>text</frontend_type> <frontend_type>text</frontend_type>
<backend_model>bitpay/config_pairingCode</backend_model> <backend_model>bitpay/config_pairingCode</backend_model>
@ -51,8 +50,7 @@
<title translate="label"> <title translate="label">
<label>Title</label> <label>Title</label>
<comment> <comment>
What your customers will see during their checkout <![CDATA[This is the payment method name your customers will see during checkout.]]>
experience.
</comment> </comment>
<frontend_type>text</frontend_type> <frontend_type>text</frontend_type>
<sort_order>20</sort_order> <sort_order>20</sort_order>
@ -63,7 +61,7 @@
<network translate="label"> <network translate="label">
<label>Network</label> <label>Network</label>
<comment> <comment>
<![CDATA[You can sign up for a test account at <a href="https://test.bitpay.com">test.bitpay.com</a>.]]> <![CDATA[You can sign up for a test account at <a href="https://test.bitpay.com" target="_blank">test.bitpay.com</a>.]]>
</comment> </comment>
<frontend_type>select</frontend_type> <frontend_type>select</frontend_type>
<source_model>bitpay/network</source_model> <source_model>bitpay/network</source_model>
@ -74,7 +72,9 @@
</network> </network>
<debug translate="label"> <debug translate="label">
<label>Debug</label> <label>Debug</label>
<comment>By enabling this, it will output more verbose information in log files.</comment> <comment>
<![CDATA[By enabling this, it will output more verbose information in log files.]]>
</comment>
<frontend_type>select</frontend_type> <frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model> <source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>40</sort_order> <sort_order>40</sort_order>
@ -106,7 +106,9 @@
<show_in_default>1</show_in_default> <show_in_default>1</show_in_default>
<show_in_website>1</show_in_website> <show_in_website>1</show_in_website>
<show_in_store>1</show_in_store> <show_in_store>1</show_in_store>
<comment><![CDATA[Determines when a BitPay payment confirmation is sent.<br /><strong>High:</strong> an invoice is confirmed immediately when payment received.<br /><strong>Medium:</strong> an invoice is confirmed after 1 block confirmation by the network (~10 mins).<br /><strong>Low:</strong> an invoice is confirmed after 6 block confirmations by the network (~1 hour).<br />The default and safest setting is "Low". A "High" setting is quicker to generate a payment confirmation but is riskier since the transaction could have not been officially confirmed by the Bitcoin network itself.]]></comment> <comment>
<![CDATA[Determines when a BitPay payment confirmation is sent.<br /><strong>High:</strong> an invoice is confirmed immediately when payment received.<br /><strong>Medium:</strong> an invoice is confirmed after 1 block confirmation by the Bitcoin network (~10 mins).<br /><strong>Low:</strong> an invoice is confirmed after 6 block confirmations by the Bitcoin network (~1 hour).<br />The default and safest setting is "Low". A "High" setting is quicker to generate a payment confirmation but is riskier since the transaction could have not been officially confirmed by the Bitcoin network itself.]]>
</comment>
</speed> </speed>
<mage_settings_heading> <mage_settings_heading>
<label>Magento Specific Settings</label> <label>Magento Specific Settings</label>
@ -170,8 +172,7 @@
<invoice_paid translate="label"> <invoice_paid translate="label">
<label>Paid</label> <label>Paid</label>
<comment> <comment>
An invoice is considered "paid" when the bitcoin <![CDATA[An invoice is considered "paid" when the Bitcoin network sees a transaction.]]>
network sees a transaction.
</comment> </comment>
<frontend_type>select</frontend_type> <frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_order_status</source_model> <source_model>adminhtml/system_config_source_order_status</source_model>
@ -183,8 +184,7 @@
<invoice_confirmed translate="label"> <invoice_confirmed translate="label">
<label>Confirmed</label> <label>Confirmed</label>
<comment> <comment>
A confirmed invoice means that the Bitcoin network <![CDATA[A confirmed invoice means that the Bitcoin network has approved the transaction.]]>
has approved the transaction.
</comment> </comment>
<frontend_type>select</frontend_type> <frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_order_status</source_model> <source_model>adminhtml/system_config_source_order_status</source_model>
@ -196,8 +196,7 @@
<invoice_complete translate="label"> <invoice_complete translate="label">
<label>Complete</label> <label>Complete</label>
<comment> <comment>
Complete invoices mean that you have gotten credit <![CDATA[A completed BitPay invoice indicates the payment for the invoice has been fully confirmed by the Bitcoin network and the funds have been deposited into your BitPay Merchant account.]]>
for the payment in your BitPay merchant account.
</comment> </comment>
<frontend_type>select</frontend_type> <frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_order_status</source_model> <source_model>adminhtml/system_config_source_order_status</source_model>
@ -210,7 +209,7 @@
<label>Requirements</label> <label>Requirements</label>
<frontend_model>adminhtml/system_config_form_field_heading</frontend_model> <frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
<comment> <comment>
<![CDATA[If you do not meet the requirements, this extension will fail to work.]]> <![CDATA[This extension will not function if you do not meet the system requirements.]]>
</comment> </comment>
<sort_order>500</sort_order> <sort_order>500</sort_order>
<show_in_default>1</show_in_default> <show_in_default>1</show_in_default>

View File

@ -3,16 +3,15 @@
* @license Copyright 2011-2014 BitPay Inc., MIT License * @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE * @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/ */
?>
<?php
/** /**
* @see Bitpay_Core_Block_Info * @see Bitpay_Core_Block_Info
*/ */
?>
<h3>Ordered with BitPay</h3>
<?php if ($url = $this->getBitpayInvoiceUrl()): ?> echo '<h3>Ordered with BitPay</h3>';
<p>
<a href="<?php echo $url; ?>" target="_new">View Invoice</a> if ($url = $this->getBitpayInvoiceUrl()) {
</p> echo '<p><a href="' . $url . '" target="_blank">View Invoice</a></p>';
<?php endif; ?> }
?>

View File

@ -3,15 +3,16 @@
* @license Copyright 2011-2014 BitPay Inc., MIT License * @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE * @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/ */
?>
<?php
/** /**
* @see Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Header * @see Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Header
*/ */
echo '<div style="background-color:#002855;padding:5px;color:#ffffff">' .
'<img src="https://raw.githubusercontent.com/bitpay/bitpay-brand/master/bitpay-logo-primary.png" alt="BitPay" witdth="113" height="44" />' .
'<a style="color:#ffffff;font-family:\'Ubuntu\',sans-serif;text-decoration:none;margin:15px" href="https://support.bitpay.com/?ref=magento" target="_blank">Support</a>' .
'<a style="color:#ffffff;font-family:\'Ubuntu\',sans-serif;text-decoration:none;margin:15px" href="https://bitpay.com/start?ref=magento" target="_blank">Sign Up</a>' .
'<a style="color:#ffffff;font-family:\'Ubuntu\',sans-serif;text-decoration:none;margin:15px" href="https://bitpay.com/merchant-login?ref=magento" target="_blank">Login</a>' .
'</div>';
?> ?>
<div style="background-color:#002855;padding:5px;color:#ffffff">
<img src="https://raw.githubusercontent.com/bitpay/bitpay-brand/master/bitpay-logo-primary.png" alt="BitPay" witdth="113" height="44" />
<a style="color:#ffffff;font-family:'Ubuntu',sans-serif;text-decoration:none;margin:15px" href="https://support.bitpay.com/?ref=magento" target="_new">Support</a>
<a style="color:#ffffff;font-family:'Ubuntu',sans-serif;text-decoration:none;margin:15px" href="https://bitpay.com/start?ref=magento" target="_new">Sign Up</a>
<a style="color:#ffffff;font-family:'Ubuntu',sans-serif;text-decoration:none;margin:15px" href="https://bitpay.com/merchant-login?ref=magento" target="_new">Login</a>
</div>

View File

@ -3,17 +3,14 @@
* @license Copyright 2011-2014 BitPay Inc., MIT License * @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE * @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/ */
?>
<?php
/** /**
* @see Bitpay_Core_Block_Form_Bitpay * @see Bitpay_Core_Block_Form_Bitpay
*/ */
$_code = $this->getMethodCode();
echo '<ul class="form-list" id="payment_form_' . $_code . '" style="display:none;">' .
'<li>You will be transfered to <a href="https://bitpay.com" target="_blank">BitPay</a> to complete your purchase when using this payment method.</li>' .
'</ul>';
?> ?>
<?php $_code = $this->getMethodCode() ?>
<ul class="form-list" id="payment_form_<?php echo $_code ?>" style="display:none;">
<li>
When paying with this payment method, once you click on the `Place Order` button
you will be transfered to <a href="https://bitpay.com" target="_new">BitPay</a>
to complete your purchase.
</li>
</ul>

View File

@ -32,7 +32,7 @@ if ($request->getScheme() == 'https') {
//<![CDATA[ //<![CDATA[
new PeriodicalExecuter(function() { new PeriodicalExecuter(function() {
new Ajax.Request( new Ajax.Request(
"<?php echo $url; ?>?quote=<?php echo $quoteId; ?>", "<?php echo $url . '?quote=' . $quoteId; ?>",
{ {
asynchronous: true, asynchronous: true,
evalScripts: true, evalScripts: true,

View File

@ -3,7 +3,8 @@
* @license Copyright 2011-2014 BitPay Inc., MIT License * @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE * @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/ */
?>
<p><strong><?php echo $this->escapeHtml($this->getMethod()->getTitle()) ?></strong></p>
<?php echo $this->getChildHtml()?> echo '<p><strong>' . $this->escapeHtml($this->getMethod()->getTitle()) . '</strong></p>';
echo $this->getChildHtml();
?>

View File

@ -27,7 +27,13 @@ class MagentoStorage implements StorageInterface
$data = serialize($key); $data = serialize($key);
$encryptedData = \Mage::helper('core')->encrypt($data); $encryptedData = \Mage::helper('core')->encrypt($data);
$config = new \Mage_Core_Model_Config(); $config = new \Mage_Core_Model_Config();
if (true === isset($config) && false === empty($config)) {
$config->saveConfig($key->getId(), $encryptedData); $config->saveConfig($key->getId(), $encryptedData);
} else {
\Mage::helper('bitpay')->debugData('[ERROR] In file lib/Bitpay/Storage/MagentoStorage.php, class MagentoStorage::persist - Could not instantiate a \Mage_Core_Model_Config object.');
throw new \Exception('[ERROR] In file lib/Bitpay/Storage/MagentoStorage.php, class MagentoStorage::persist - Could not instantiate a \Mage_Core_Model_Config object.');
}
} }
/** /**
@ -35,7 +41,7 @@ class MagentoStorage implements StorageInterface
*/ */
public function load($id) public function load($id)
{ {
if (isset($this->_keys[$id])) { if (true === isset($id) && true === isset($this->_keys[$id])) {
return $this->_keys[$id]; return $this->_keys[$id];
} }
@ -44,16 +50,20 @@ class MagentoStorage implements StorageInterface
/** /**
* Not in database * Not in database
*/ */
if (empty($entity)) { if (false === isset($entity) || true === empty($entity)) {
\Mage::helper('bitpay')->debugData('[INFO] Call to MagentoStorage::load($id) with the id of ' . $id . ' did not return the store config parameter because it was not found in the database.');
return false; return false;
} }
$decodedEntity = unserialize(\Mage::helper('core')->decrypt($entity)); $decodedEntity = unserialize(\Mage::helper('core')->decrypt($entity));
if (empty($decodedEntity)) { if (false === isset($decodedEntity) || true === empty($decodedEntity)) {
\Mage::helper('bitpay')->debugData('[INFO] Call to MagentoStorage::load($id) with the id of ' . $id . ' could not decrypt & unserialize the entity ' . $entity . '.');
return false; return false;
} }
\Mage::helper('bitpay')->debugData('[INFO] Call to MagentoStorage::load($id) with the id of ' . $id . ' successfully decrypted & unserialized the entity ' . $entity . '.');
return $decodedEntity; return $decodedEntity;
} }
} }

View File

@ -1,10 +0,0 @@
#!/usr/bin/env sh
####
#
# Script that removes old BitPay extension
#
rm -vrf app/code/community/Bitpay/Bitcoins
rm -v app/design/frontend/base/default/layout/bitcoins.xml
rm -vrf app/etc/modules/Bitpay_Bitcoins.xml
rm -vrf lib/bitpay
rm -v shell/bitpay.php

156
scripts/delete.sh Executable file
View File

@ -0,0 +1,156 @@
#!/usr/bin/env sh
#
# (c) 2014 BitPay, Inc.
#
# Shell script that locates and removes
# any previously installed BitPay Magento
# plugin files.
#
# Written by Rich Morgan <rich@bitpay.com>
# For full transparency I've listed all the depricated files and folders
# related to the old plugin here for your information. This is the complete
# list of items you would want to backup and/or remove if you wanted to do
# this by hand yourself or if you just wanted a list for tracking purposes.
old_files[0]="/lib/bitpay/bp_config_default.php"
old_files[1]="/lib/bitpay/bp_lib.php"
old_files[2]="/lib/bitpay/bp_options.php"
old_files[3]="/lib/bitpay"
old_files[4]="/app/design/frontend/base/default/template/bitcoins/iframe.phtml"
old_files[5]="/app/design/frontend/base/default/template/bitcoins"
old_files[6]="/app/design/frontend/base/default/layout/bitcoins.xml"
old_files[7]="/app/code/community/Bitpay/Bitcoins/Model/Resource/Ipn/Collection.php"
old_files[8]="/app/code/community/Bitpay/Bitcoins/Model/Resource/Ipn"
old_files[9]="/app/code/community/Bitpay/Bitcoins/Model/Resource/Ipn.php"
old_files[10]="/app/code/community/Bitpay/Bitcoins/Model/PaymentMethod.php"
old_files[11]="/app/code/community/Bitpay/Bitcoins/Model/Ipn.php"
old_files[12]="/app/code/community/Bitpay/Bitcoins/Model/Source/Speed.php"
old_files[13]="/app/code/community/Bitpay/Bitcoins/Model/Source"
old_files[14]="/app/code/community/Bitpay/Bitcoins/Model/Resource"
old_files[15]="/app/code/community/Bitpay/Bitcoins/Model"
old_files[16]="/app/code/community/Bitpay/Bitcoins/sql/Bitcoins_setup/upgrade-0.1.0-1.0.0.php"
old_files[17]="/app/code/community/Bitpay/Bitcoins/sql/Bitcoins_setup/upgrade-1.0.0-1.1.0.php"
old_files[18]="/app/code/community/Bitpay/Bitcoins/sql/Bitcoins_setup"
old_files[19]="/app/code/community/Bitpay/Bitcoins/sql"
old_files[20]="/app/code/community/Bitpay/Bitcoins/Block/Iframe.php"
old_files[21]="/app/code/community/Bitpay/Bitcoins/Block"
old_files[22]="/app/code/community/Bitpay/Bitcoins/controllers/IndexController.php"
old_files[23]="/app/code/community/Bitpay/Bitcoins/controllers"
old_files[24]="/app/code/community/Bitpay/Bitcoins/etc/config.xml"
old_files[25]="/app/code/community/Bitpay/Bitcoins/etc/system.xml"
old_files[26]="/app/code/community/Bitpay/Bitcoins/etc"
old_files[27]="/app/code/community/Bitpay/Bitcoins"
old_files[28]="/app/code/community/Bitpay"
old_files[29]="/app/etc/modules/Bitpay_Bitcoins.xml"
old_files[30]="composer.json"
old_files[31]="magento-plugin-master.zip"
old_files[32]="modman"
old_files[33]="README.md"
CLEAN="true"
RMOPTS="-vrfd"
echo "Looking for your Magento installation. Please stand by - this may take a few minutes while I search..."
# In case we have multiple Magento installs on this one
# server, we will just take the first one and ask...
i=`find /var /usr /opt -name Mage.php -type f | head -n 1 2>/dev/null`
if [ -e $i ]
then
DIR=`dirname $i`
cd $DIR && cd ../
mage_dir=`pwd`
echo "It looks like Magento is installed in the $mage_dir directory."
echo "Is this correct? (y/n) > "
else
# In case we can't find the Magento folder, we are just
# providing a default value here. This happens to be the
# default for an Ubuntu-based machine, for example.
DIR="/var/www/html/magento"
cd $DIR
mage_dir=`pwd`
echo "You don't have Magento installed or this script doesn't have permissions to view the directory it's contained in."
echo "Should I default to $mage_dir ? (y/n) > "
fi
read answer
if [ $answer = "y" ]
then
echo "Attempting to delete the old plugin files now. Please stand by..."
for filename in "${old_files[@]}"
do
fullname=$mage_dir$filename
if [ -e $fullname ]
then
echo " Found $fullname - removing!"
rm $RMOPTS $fullname
else
echo " $filename does not exist - skipping!"
fi
done
echo "File removal process complete. Checking to make sure your Magento environment was completely cleaned of old BitPay files..."
echo ""
for filename in "${old_files[@]}"
do
fullname=$mage_dir$filename
if [ -e $fullname ]
then
echo " The old plugin file $fullname is still present!"
CLEAN="false"
else
echo " $filename is not present - good!"
fi
done
if [ $CLEAN = "false" ]
then
echo "Old BitPay plugin files are still present in your Magento directory. This is likely due to this script not having permissions to delete them. You can fix this by running this script as superuser or you can remove the files by hand."
else
echo "Good! I didn't find any remaining old BitPay plugin files in your Magento directory! You can now safely install the new BitPay plugin."
fi
echo "Process complete."
echo ""
else
echo "Okay, please enter the path you would like me to use or QUIT if you wish to abort the process."
echo "Full path or QUIT ? > "
read answer
if [ $answer = "QUIT" ]
then
echo "Quitting!"
else
echo "Attempting to delete the old plugin files at the directory you provided. Please stand by..."
for filename in "${old_files[@]}"
do
fullname=$answer$filename
if [ -e $fullname ]
then
echo " Found $fullname - removing!"
rm $RMOPTS $fullname
else
echo " $filename does not exist - skipping!"
fi
done
echo "File removal process complete. Checking to make sure your Magento environment was completely cleaned of old BitPay files..."
echo ""
for filename in "${old_files[@]}"
do
fullname=$mage_dir$filename
if [ -e $fullname ]
then
echo " The old plugin file $fullname is still present!"
CLEAN="false"
else
echo " $filename is not present - good!"
fi
done
if [ $CLEAN = "false" ]
then
echo "Old BitPay plugin files are still present in your Magento directory. This is likely due to this script not having permissions to delete them. You can fix this by running this script as superuser or you can remove the files by hand."
else
echo "Good! I didn't find any remaining old BitPay plugin files in your Magento directory! You can now safely install the new BitPay plugin."
fi
echo "Process complete."
echo ""
fi
fi

View File

@ -6,7 +6,6 @@
if ($mage = realpath(__DIR__.'/../build/magento/app/Mage.php')) { if ($mage = realpath(__DIR__.'/../build/magento/app/Mage.php')) {
require_once $mage; require_once $mage;
//Mage::setIsDeveloperMode(true);
Mage::app(); Mage::app();
} else { } else {
exit('Could not find Mage.php'); exit('Could not find Mage.php');