Compare commits

..

84 Commits

Author SHA1 Message Date
piotrgild
52c4981207 Created btcpay namespace (#2) 2018-10-29 18:14:02 +01:00
Andrew Camilleri
7b83d511a4
Merge pull request #1 from Kukks/master 2018-09-05 10:13:48 +02:00
Andrew Camilleri
a575cf3996 Merge remote-tracking branch 'bitpay/master' 2018-09-05 10:11:45 +02:00
Pieter Poorthuis
9594ac684e
Merge pull request #155 from Magebinary/master
Fixes #154 - fix modman with miss files
2018-08-28 08:54:41 +02:00
Alex
036b237ad9 Fixes #154 - fix modman with miss files 2018-08-28 14:03:12 +12:00
Andrew Camilleri
04101c5eb3 change network to a free text instead of options 2018-08-07 15:24:58 +02:00
Andrew Camilleri
9bc1335d71
Update bitpay.phtml 2018-08-07 14:27:04 +02:00
Andrew Camilleri
2d6d8401f0
Update header.phtml 2018-08-07 14:25:28 +02:00
Andrew Camilleri
133d7d2e87
Update default.phtml 2018-08-07 14:24:13 +02:00
Pieter Poorthuis
ff760487fd Version bump to 2.1.20 2018-06-14 15:32:42 +02:00
Pieter Poorthuis
c5d6563742 Update for v2.1.20 2018-06-14 15:31:40 +02:00
Pieter Poorthuis
8c6c7c02fe Added logging to IpnController 2018-06-14 15:27:30 +02:00
Pieter Poorthuis
9feef77c9b
Send order confirmation when paid IPN comes in
Only send order confirmation when paid IPN comes in. Make sure to send the order confirmation only once.
2018-06-14 14:19:53 +02:00
Pieter Poorthuis
2d830b0438
Merge pull request #153 from damianbz321/master
fix invoices
2018-06-14 13:54:45 +02:00
Damian Bzdon
a973c6943a fix invoices 2018-06-12 15:12:22 +02:00
Pieter Poorthuis
9b96fd5581
Stop adding buyer address info to BitPay invoice 2018-06-07 15:54:13 +02:00
Pieter Poorthuis
f8dab1e940
Merge pull request #152 from damianbz321/master
issue 148
2018-06-07 11:42:53 +02:00
Pieter Poorthuis
05eeff288b
Merge branch 'master' into master 2018-06-07 11:05:41 +02:00
Damian Bzdon
9d684867c1 fix issues 148, 150 2018-06-07 10:50:19 +02:00
Damian Bzdon
de0d707ee4 issue 150 2018-06-04 15:32:23 +02:00
Damian Bzdon
cb886b8f09 issue 148 2018-05-28 14:37:52 +02:00
Pieter Poorthuis
5b368ef3d4
Merge pull request #151 from damianbz321/master
issue 150 stop populating buyer fields (except buyerEmail)
2018-05-25 10:39:25 +02:00
Damian Bzdon
6a37190156 issue 150 stop populating buyer fields (except buyerEmail) 2018-05-25 10:29:54 +02:00
Pieter Poorthuis
964d06fcf8
Merge pull request #149 from damianbz321/master
issue 145 - disable OFAC sanctioned countries
2018-05-24 14:41:14 +02:00
Damian Bzdon
4114c21999 issue 145 - disable OFAC sanctioned countries 2018-05-24 12:51:37 +02:00
Pieter Poorthuis
eaa90f96a6
Merge pull request #147 from damianbz321/master
issues 142,143,144
2018-05-23 14:27:09 +02:00
Damian Bzdon
281e70b975 issue 144 2018-05-18 12:24:22 +02:00
Damian Bzdon
c6c08c5cd7 issue 143 2018-05-18 12:24:14 +02:00
Damian Bzdon
8b4680d91f issue 142 2018-05-18 12:24:03 +02:00
Pieter Poorthuis
8caed778fd
Merge pull request #146 from damianbz321/master
fix issue 141
2018-05-14 11:55:26 +02:00
Damian Bzdon
d8f4a04c1e fix issue 141 2018-05-10 12:01:49 +02:00
Pieter Poorthuis
c54c521c07
Update Magento connect procedure 2018-04-25 10:22:14 +02:00
Pieter Poorthuis
f16cc16bf6
Updated link to Magento Marketplace 2018-04-10 12:49:55 +02:00
Pieter Poorthuis
c6e69e05e4 Update for v2.1.19 2018-04-09 16:42:34 +02:00
Pieter Poorthuis
f43c3bac6c Simplified plugin configuration, improved error messages 2018-03-19 14:55:39 +01:00
Pieter Poorthuis
b2d2fe9213 Updated package info for Magento marketplace compatibility 2018-03-16 14:49:44 +01:00
Pieter Poorthuis
daf46c7a5f Update for v2.1.18 2018-03-16 12:39:19 +01:00
Pieter Poorthuis
a0a16815cd
Merge pull request #138 from damianbz321/master
iframre redirect
2018-03-15 14:45:57 +01:00
Damian Bzdon
d2351ea220 iframre redirect 2018-03-15 14:17:44 +01:00
Pieter Poorthuis
adbcabbf18
Merge pull request #137 from damianbz321/master
issue 126 - Magento marketplace compatibility
2018-03-14 10:20:37 +01:00
Damian Bzdon
f3f82944b8 issue 126 - Magento marketplace compatibility 2018-03-14 09:58:20 +01:00
Pieter Poorthuis
6f8a6b647b
Merge pull request #136 from damianbz321/master
fix issue 117,123,124
2018-03-13 12:40:44 +01:00
Damian Bzdon
849890d660 configuration page 2018-03-13 11:34:30 +01:00
Damian Bzdon
76b82f8c7f expired invoice - wrong redirect 2018-03-13 11:32:10 +01:00
Damian Bzdon
23db274908 failure page configurations 2018-03-13 11:31:29 +01:00
Damian Bzdon
c97216582a failure page configurations 2018-03-13 11:31:22 +01:00
Pieter Poorthuis
be4f5f7189
Merge pull request #134 from damianbz321/master
issue 122 - There is no apikeys configuration on system.xml based on observer code
2018-03-12 14:29:33 +01:00
Damian Bzdon
ed00d715d8 add api key 2018-03-12 14:24:08 +01:00
Damian Bzdon
18c6f7b300 checkForRequest - this function is not used anywhere 2018-03-12 14:23:52 +01:00
Pieter Poorthuis
600a647f5d
Merge pull request #133 from rafaldr91/master
Non-debug logging fix
2018-03-08 13:54:08 +01:00
Rafał Drożdżal
673bc5ad5f Non-debug logging fix 2018-03-08 10:46:25 +01:00
Pieter Poorthuis
4dfb59aaf8
Merge pull request #132 from rafaldr91/master
Display "Invoice price must be at least" error
2018-03-07 13:28:24 +01:00
Rafał Drożdżal
33928948eb display "Invoice price must be at least" error 2018-03-07 12:16:14 +01:00
Pieter Poorthuis
f8486a1fe9
Merge pull request #131 from rafaldr91/master
Added missing methods in the Magento version below 1.9
2018-02-26 12:04:30 +01:00
Rafał Drożdżal
51ee0cda2c Added missing methods in the Magento version below 1.9: _isSameCurrency, getStatusStatuses, addStatusfilter. 2018-02-26 11:47:26 +01:00
Pieter Poorthuis
9a33a88b5b
Merge pull request #130 from rafaldr91/master
IPN creates second invoice in database issue fix
2018-02-22 14:48:37 +01:00
Rafał Drożdżal
2f9b734a46 IPN creates after payment a second invoice in database instead of update invoice 2018-02-22 13:58:24 +01:00
Pieter Poorthuis
a99f45b6fe Merge pull request #108 from innoppl-developers/master
Order status issue
2017-01-24 16:30:32 +01:00
Gopinath
592fd53cc3 Order status issue 2017-01-24 17:37:58 +05:30
Pieter Poorthuis
8193bdf366 Update CHANGELOG 2016-12-15 15:11:24 +01:00
P.H. Poorthuis
5d936704f8 Updated GUIDE & README 2016-12-15 15:00:06 +01:00
Pieter Poorthuis
d281a3463f Delete release.txt 2016-12-15 11:40:17 +01:00
Pieter Poorthuis
33d11c9612 Merge pull request #107 from pieterpoorthuis/master
Switched from user currency to magento shop currency to prevent fraud…
2016-12-12 17:23:11 +01:00
P.H. Poorthuis
957c84e171 Switched from user currency to magento shop currency to prevent fraud messages 2016-12-12 14:09:20 +01:00
Chris Kleeschulte
4dfa531842 Added check for orderId. 2016-09-07 17:55:12 -04:00
Chris Kleeschulte
c80ecb8a46 Merge pull request #106 from kleetus/bug/invoiceCreationTime
Unified order creation to the same place as redirected check out.
2016-09-07 10:40:11 -04:00
Chris Kleeschulte
d6f71f8cc9 Removed unneeded comment. 2016-09-07 10:34:03 -04:00
Chris Kleeschulte
9c1ed7fdbe Unified order creation to the same place as redirected check out.
- Redirected check out and iframe checkout share the same order creation logic.
- The order will be created during saveOrder call to backend. 
- The difference between the two will be injection of client-side javascript during payment type selection. 
	- if BitPay/Bitcoin, client-side JS will be inserted into page to swap the out the next step after order save is complete
	- in all cases, Magento will create the invoice and pass the client a redirect_url
	- the iframe invoice will receive the redirect url and build an iframe with the src being the bitpay url. 
	- the redirected check out will not have any new client side JS, so the next step will be to redirect from Magento.
2016-09-06 18:07:17 -04:00
Chris Kleeschulte
04800164e6 Added changelog entries. 2016-07-18 14:31:21 -04:00
Chris Kleeschulte
ccdbd88a6d Merge pull request #105 from kleetus/master
Iframe invoice will create order
2016-07-09 20:49:48 -04:00
Chris Kleeschulte
ca747284ba Helper scripts
- Added an ipn helper script to post ipns
2016-07-09 20:16:46 -04:00
Chris Kleeschulte
d0a5152770 Iframe invoice will create order
- For merchants using an iframe BitPay invoice (set "Redirect Checkout"
  to "No")
  - Before this change:
    - When a user confirms the payment method, the BitPay invoice will
      be displayed and the Magento order will not yet be created.
    - The Magento order is only created if the user pays the invoice,
      leaves the checkout browser window open, and BitPay is able to see
the user's transaction and send the IPN successfully to the Magento
server.
    - The problem is when the customer sends a bitcoin transaction, but
      their transaction isn't relayed because the fee is too low or the
network is under high load.
    - Under this condition, the customer has paid, yet they have no
      order with the merchant. The merchant has a hard time serving
their customer under these conditions.
  After this change:
    - When the user confirms their payment method, the BitPay invoice
      will NOT be displayed until the user clicks "Place Order".
    - This will guarantee that an order is created BEFORE the customer
      is able to pay the BitPay invoice.
    - This will allow the merchant to self-serve their customer by being
      able to find their customer in their dashboard and issue a refund
or apply the transaction.
2016-07-09 17:52:46 -04:00
Chris Kleeschulte
98403f4353 Merge pull request #104 from kleetus/master
Repaired redirected checkout BitPay invoice amount calculation
2016-05-30 14:44:12 -04:00
Chris Kleeschulte
69565a2a49 Bumped package script hard-coded version. 2016-05-27 16:15:38 -04:00
Chris Kleeschulte
e7811a71c5 Repaired redirected checkout BitPay invoice amount calculation
- If shopping cart user's currency is not the same as the Magento configured base currency and the type of BitPay invoice is a redirected checkout (non iFrame), then the $amount (invoice amount) passed to Bitcoin.php authorize() will be in the base currency and not the user's currency. A BitPay invoice is then created based on the user's currency and the amount, which is wrong.

- The Bitcoin.php authorize function now recomputes the amount in the event that the amount is not correct.


- Updated the README and GUIDE to show latest Magento version checked.
2016-05-27 16:02:48 -04:00
Chris Kleeschulte
2738aa44a0 Merge pull request #102 from spofa/master
add getLogFile function
2016-03-16 17:33:24 -04:00
spofa
75184d74c2 add getLogeFile function
add getLogeFile function
2016-03-08 22:42:16 +08:00
Chris Kleeschulte
52d42c474d Merge pull request #101 from jameswalpole/patch-1
Update Support Link
2016-02-19 15:44:38 -05:00
James Walpole
e991500dc1 Update Support Link 2016-02-19 09:25:41 -05:00
Chris Kleeschulte
fcd44e0a08 Update GUIDE.md 2015-11-18 14:56:33 -05:00
Chris Kleeschulte
4c4ff8810e Update README.md 2015-11-18 14:55:56 -05:00
Chris Kleeschulte
3f9b79622c Update README.md 2015-11-06 10:15:08 -05:00
Paul Daigle
5f494f3763 bump package version 2015-08-28 15:19:51 -04:00
J. Paul Daigle
4817c3f728 Merge pull request #99 from bitpay/bug/orderCurrencyCode
Fixes #98: Pulls currency code from  instead of
2015-08-28 14:06:41 -05:00
59 changed files with 1533 additions and 1037 deletions

View File

@ -1,4 +1,32 @@
Unreleased
2.1.19 (2018-04-09)
Simplified BitPay Magento configuration screen
Updated PHP library to v2.2.20 (supporting BitPay's API after May 1st 2018)
Support for Magento Marketplace: https://marketplace.magento.com/bitpay-bitpay-core.html
2.1.18 (2018-03-16)
Fixed dependencies in composer.json (#127)
Fixed landing page after failure or expired payment (#124, #123, #117, #120)
Fixed missing apikeys configuration in system.xml (#122)
Fixed IPN creating 2nd invoice instead of updating invoice (#121)
Fixed non-debug logging (#115)
Fixed checkout page text (#112)
2.1.17
Added missing methods in the Magento version below 1.9: _isSameCurrency, getStatusStatuses, addStatusfilter.
2.1.16
Fixed creating after payment a second invoice in database instead of update invoice issue
2.1.14
Use Magento shop base currency to create a BitPay invoice (instead of the shopper's selected currency)
2.1.13
Redirected check out and iframe checkout share the same order creation logic.
The order will be created during saveOrder call to backend.
2.1.12
iFrame order will create order
2.1.11
Repaired redirected checkout invoice amount calculation
2.1.10
Fixed currency issue
2.1.9
Fixed code incompatible with PHP 5.4

View File

@ -6,29 +6,19 @@ You must have a BitPay merchant account to use this plugin. It's free to [sign-
## Server Requirements
* Last Cart Version Tested: 1.9.3.8
* [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) 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.
* [OpenSSL](http://us2.php.net/openssl) Must be compiled with PHP and is used for certain cryptographic operations.
* [PHP](http://us2.php.net/downloads.php) 5.4 or higher. This plugin will not work on PHP 5.3 and below.
## When Upgrading From Plugin Version 1.x to 2.x:
**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
**From the Magento Connect Manager:**
**From the Magento Market Place**
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.
* Goto [https://marketplace.magento.com/bitpay-bitpay-core.html](https://marketplace.magento.com/bitpay-bitpay-core.html) and click the *Add to Cart* link.
* Select your shopping cart, click *Checkout* and then *Place order*
* Click *Install* and copy the access key of the latest version of the BitPay bitcoin acceptance plugin
Once you have the key, log into you Magento Store's Admin Panel and navigate to **System > Magento Connect > Magento Connect Manager**.
@ -43,16 +33,8 @@ All you need to do is paste the extension key and click on the *Install* button.
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.
**NOTE:** These files can also up uploaded using the *Magento Connect Manager* that comes with your Magento Store
**WARNING:** It is good practice to backup your database before installing extensions. Please make sure you Create Backups.
**Using Modman:**
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`.
## Configuration
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**.
@ -75,3 +57,14 @@ You are also able to configure how BitPay's IPN (Instant Payment Notifications)
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.
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.
## When Upgrading From Plugin Version 1.x to 2.x:
**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
```

View File

@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2011-2014 BitPay, Inc.
Copyright (c) 2011-2018 BitPay, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@ -1,3 +1,8 @@
# NOTICE
This is a Community-supported project.
If you are interested in becoming a maintainer of this project, please contact us at integrations@bitpay.com. Developers at BitPay will attempt to work along the new maintainers to ensure the project remains viable for the foreseeable future.
# Description
Bitcoin payment plugin for Magento using the bitpay.com service.
@ -13,9 +18,10 @@ To get up and running with our plugin quickly, see the GUIDE here: https://githu
**BitPay Support:**
* Last Cart Version Tested: 1.9.3.8
* [GitHub Issues](https://github.com/bitpay/magento-plugin/issues)
* Open an issue if you are having issues with this plugin.
* [Support](https://support.bitpay.com)
* [Support](https://help.bitpay.com)
* BitPay merchant support documentation
**Magento Support:**
@ -59,7 +65,7 @@ If you encounter any issues or implement any updates or changes, please open an
The MIT License (MIT)
Copyright (c) 2011-2015 BitPay, Inc.
Copyright (c) 2011-2018 BitPay, Inc.
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:

View File

@ -1,70 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT 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
{
/**
*/
protected function _construct()
{
parent::_construct();
$this->setTemplate('bitpay/iframe.phtml');
}
/**
* create an invoice and return the url so that iframe.phtml can display it
*
* @return string
*/
public function getIframeUrl()
{
if (!($quote = Mage::getSingleton('checkout/session')->getQuote())
or !($payment = $quote->getPayment())
or !($paymentMethod = $payment->getMethod())
or ($paymentMethod !== 'bitpay')
or (Mage::getStoreConfig('payment/bitpay/fullscreen')))
{
return 'notbitpay';
}
\Mage::helper('bitpay')->registerAutoloader();
// fullscreen disabled?
if (Mage::getStoreConfig('payment/bitpay/fullscreen'))
{
return 'disabled';
}
if (\Mage::getModel('bitpay/ipn')->getQuotePaid($this->getQuote()->getId())) {
return 'paid'; // quote's already paid, so don't show the iframe
}
/*** @var Bitpay_Core_Model_PaymentMethod ***/
$method = $this->getQuote()->getPayment()->getMethodInstance();
$amount = $this->getQuote()->getGrandTotal();
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.');
}
$bitcoinMethod = \Mage::getModel('bitpay/method_bitcoin');
try {
$bitcoinMethod->authorize($payment, $amount, true);
} catch (\Exception $e) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_Block_Iframe::getIframeUrl(): failed with the message: ' . $e->getMessage());
\Mage::throwException("Error creating BitPay invoice. Please try again or use another payment option.");
return false;
}
return $bitcoinMethod->getOrderPlaceRedirectUrl();
}
}

View File

@ -1,37 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
class Bitpay_Core_Block_Info extends Mage_Payment_Block_Info
{
public function _construct()
{
parent::_construct();
$this->setTemplate('bitpay/info/default.phtml');
}
public function getBitpayInvoiceUrl()
{
$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();
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.');
}
$bitpayInvoice = \Mage::getModel('bitpay/invoice')->load($incrementId, 'increment_id');
if (true === isset($bitpayInvoice) && false === empty($bitpayInvoice)) {
return $bitpayInvoice->getUrl();
}
}
}

View File

@ -1,25 +0,0 @@
<?php
/**
* @license Copyright 2011-2015 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
/**
* Used to display bitcoin networks
*/
class Bitpay_Core_Model_Network
{
const NETWORK_LIVENET = 'livenet';
const NETWORK_TESTNET = 'testnet';
/**
* @return array
*/
public function toOptionArray()
{
return array(
array('value' => self::NETWORK_LIVENET, 'label' => \Mage::helper('bitpay')->__(ucwords(self::NETWORK_LIVENET))),
array('value' => self::NETWORK_TESTNET, 'label' => \Mage::helper('bitpay')->__(ucwords(self::NETWORK_TESTNET))),
);
}
}

View File

@ -1,75 +0,0 @@
<?php
/**
* @license Copyright 2011-2015 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
class Bitpay_Core_Model_Observer
{
/*
* TODO: Why is this here?
*/
public function checkForRequest($observer)
{
}
/*
* 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
* invalid.
*/
public function updateOrderStates()
{
$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.');
return;
} else {
\Mage::helper('bitpay')->debugData('[INFO] Bitpay_Core_Model_Observer::updateOrderStates() started job to query BitPay to update the existing order states.');
}
/*
* Get all of the orders that are open and have not received an IPN for
* complete, expired, or invalid.
*/
$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
* are not complete/closed/etc
*/
foreach ($orders as $order) {
/*
* 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
* to the API.
*/
$status = null;
// TODO:
// Does the order need to be updated?
// Yes? Update Order Status
// No? continue
}
\Mage::helper('bitpay')->debugData('[INFO] Bitpay_Core_Model_Observer::updateOrderStates() order status update job finished.');
}
/**
* Method that is called via the magento cron to update orders if the
* invoice has expired
*/
public function cleanExpired()
{
\Mage::helper('bitpay')->debugData('[INFO] Bitpay_Core_Model_Observer::cleanExpired() called.');
\Mage::helper('bitpay')->cleanExpired();
}
}

View File

@ -1,29 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
/**
* @route bitpay/index/
*/
class Bitpay_Core_IndexController extends Mage_Core_Controller_Front_Action
{
/**
* @route bitpay/index/index?quote=n
*/
public function indexAction()
{
$params = $this->getRequest()->getParams();
$quoteId = $params['quote'];
\Mage::helper('bitpay')->registerAutoloader();
\Mage::helper('bitpay')->debugData($params);
$paid = Mage::getModel('bitpay/ipn')->GetQuotePaid($quoteId);
$this->loadLayout();
$this->getResponse()->setHeader('Content-type', 'application/json');
$this->getResponse()->setBody(json_encode(array('paid' => $paid)));
}
}

View File

@ -1,131 +0,0 @@
<?xml version="1.0"?>
<!--
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
-->
<config>
<modules>
<Bitpay_Core>
<version>2.1.9</version>
</Bitpay_Core>
</modules>
<frontend>
<routers>
<bitpay>
<use>standard</use>
<args>
<module>Bitpay_Core</module>
<frontName>bitpay</frontName>
</args>
</bitpay>
</routers>
<layout>
<updates>
<bitpay>
<file>bitpay.xml</file>
</bitpay>
</updates>
</layout>
<translate>
<modules>
<bitpay>
<files>
<default>Bitpay_Core.csv</default>
</files>
</bitpay>
</modules>
</translate>
</frontend>
<admin>
<routers>
<adminhtml>
<args>
<modules>
<bitpay before="Mage_Adminhtml">Bitpay_Core_Adminhtml</bitpay>
</modules>
</args>
</adminhtml>
</routers>
</admin>
<global>
<blocks>
<bitpay>
<class>Bitpay_Core_Block</class>
</bitpay>
</blocks>
<helpers>
<bitpay>
<class>Bitpay_Core_Helper</class>
</bitpay>
</helpers>
<models>
<bitpay>
<class>Bitpay_Core_Model</class>
<resourceModel>bitpay_mysql4</resourceModel>
</bitpay>
<bitpay_mysql4>
<class>Bitpay_Core_Model_Mysql4</class>
<entities>
<invoice>
<table>bitpay_invoices</table>
</invoice>
<ipn>
<table>bitpay_ipns</table>
</ipn>
</entities>
</bitpay_mysql4>
</models>
<resources>
<bitpay_write>
<connection>
<use>core_write</use>
</connection>
</bitpay_write>
<bitpay_read>
<connection>
<use>core_read</use>
</connection>
</bitpay_read>
<bitpay_setup>
<setup>
<module>Bitpay_Core</module>
<class>Bitpay_Core_Model_Resource_Mysql4_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</bitpay_setup>
</resources>
</global>
<default>
<payment>
<bitpay>
<model>bitpay/method_bitcoin</model>
<order_status>new</order_status>
<payment_action>authorize</payment_action>
<active>0</active>
<title>Bitcoin</title>
<network>testnet</network>
<debug>0</debug>
<notification_url>bitpay/ipn</notification_url>
<redirect_url>checkout/onepage/success</redirect_url>
<speed>medium</speed>
<fullscreen>0</fullscreen>
<invoice_new>new</invoice_new>
<invoice_paid>processing</invoice_paid>
<invoice_confirmed>processing</invoice_confirmed>
<invoice_complete>complete</invoice_complete>
<invoice_expired>canceled</invoice_expired>
<invoice_invalid>canceled</invoice_invalid>
</bitpay>
</payment>
</default>
</config>

View File

@ -7,7 +7,7 @@
/**
* This is used to display php extensions and if they are installed or not
*/
class Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Extension extends Mage_Adminhtml_Block_System_Config_Form_Field
class Btcpay_Core_Block_Adminhtml_System_Config_Form_Field_Extension extends Mage_Adminhtml_Block_System_Config_Form_Field
{
/**
* @param Varien_Data_Form_Element_Abstract $element
@ -16,8 +16,8 @@ class Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Extension extends Mag
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.');
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_Block_Adminhtml_System_Config_Form_Field_Extension::_getElementHtml(): Missing or invalid $element parameter passed to function.');
throw new \Exception('In Btcpay_Core_Block_Adminhtml_System_Config_Form_Field_Extension::_getElementHtml(): Missing or invalid $element parameter passed to function.');
}
$phpExtension = $element->getFieldConfig()->php_extension;

View File

@ -7,7 +7,7 @@
/**
* Used to display header on the admin configuration page
*/
class Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Header extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface
class Btcpay_Core_Block_Adminhtml_System_Config_Form_Field_Header extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface
{
/**
* This is the location of the template used to display the output
@ -15,7 +15,7 @@ class Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Header extends Mage_A
*
* @var string
*/
protected $_template = 'bitpay/system/config/field/header.phtml';
protected $_template = 'btcpay/system/config/field/header.phtml';
/**
* @param Varien_Data_Form_Element_Abstract $element
@ -24,8 +24,8 @@ class Bitpay_Core_Block_Adminhtml_System_Config_Form_Field_Header extends Mage_A
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.');
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_Block_Adminhtml_System_Config_Form_Field_Header::render(): Missing or invalid $element parameter passed to function.');
throw new \Exception('In Btcpay_Core_Block_Adminhtml_System_Config_Form_Field_Header::render(): Missing or invalid $element parameter passed to function.');
}
return $this->toHtml();

View File

@ -4,11 +4,11 @@
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
class Bitpay_Core_Block_Form_Bitpay extends Mage_Payment_Block_Form
class Btcpay_Core_Block_Form_Btcpay extends Mage_Payment_Block_Form
{
protected function _construct()
{
$payment_template = 'bitpay/form/bitpay.phtml';
$payment_template = 'btcpay/form/btcpay.phtml';
parent::_construct();

View File

@ -0,0 +1,42 @@
<?php
/**
* @license Copyright 2011-2014 Bitpay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*
*/
class Btcpay_Core_Block_Iframe extends Mage_Checkout_Block_Onepage_Payment
{
/**
*/
protected function _construct()
{
parent::_construct();
$this->setTemplate('btcpay/iframe.phtml');
}
/**
* create an invoice and return the url so that iframe.phtml can display it
*
* @return string
*/
public function getIframeUrl()
{
if (!($quote = Mage::getSingleton('checkout/session')->getQuote())
or !($payment = $quote->getPayment())
or !($paymentMethod = $payment->getMethod())
or ($paymentMethod !== 'btcpay') )
{
return 'notbtcpay';
}
\Mage::helper('btcpay')->registerAutoloader();
if (\Mage::getModel('btcpay/ipn')->getQuotePaid($this->getQuote()->getId())) {
return 'paid'; // quote's already paid, so don't show the iframe
}
return 'redirect';
}
}

View File

@ -0,0 +1,40 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
class Btcpay_Core_Block_Info extends Mage_Payment_Block_Info
{
public function _construct()
{
parent::_construct();
$this->setTemplate('btcpay/info/default.phtml');
}
public function getBtcpayInvoiceUrl()
{
$order = $this->getInfo()->getOrder();
if (false === isset($order) || true === empty($order)) {
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_Block_Info::getBtcpayInvoiceUrl(): could not obtain the order.');
throw new \Exception('In Btcpay_Core_Block_Info::getBtcpayInvoiceUrl(): could not obtain the order.');
}
$incrementId = $order->getIncrementId();
if (false === isset($incrementId) || true === empty($incrementId)) {
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_Block_Info::getBtcpayInvoiceUrl(): could not obtain the incrementId.');
throw new \Exception('In Btcpay_Core_Block_Info::getBtcpayInvoiceUrl(): could not obtain the incrementId.');
}
$btcpayInvoice = \Mage::getModel('btcpay/invoice')->load($incrementId, 'increment_id');
if (true === isset($btcpayInvoice) && false === empty($btcpayInvoice)) {
return $btcpayInvoice->getUrl();
}
else {
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_Block_Info::getBtcpayInvoiceUrl(): invoice is null or empty.');
}
}
}

View File

@ -6,10 +6,10 @@
/**
*/
class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
class Btcpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
{
protected $_autoloaderRegistered;
protected $_bitpay;
protected $_btcpay;
protected $_sin;
protected $_publicKey;
protected $_privateKey;
@ -21,8 +21,15 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/
public function debugData($debugData)
{
//log information about the environment
$phpVersion = explode('-', phpversion())[0];
$extendedDebugData = '[PHP version = ' . $phpVersion .', '.
'Magento version = ' . \Mage::getVersion() .', '.
'Btcpay plugin version = ' . $this->getExtensionVersion() .']'. PHP_EOL;
if (true === isset($debugData) && false === empty($debugData)) {
\Mage::getModel('bitpay/method_bitcoin')->debugData($debugData);
\Mage::getModel('btcpay/method_bitcoin')->debugData($extendedDebugData);
\Mage::getModel('btcpay/method_bitcoin')->debugData($debugData);
}
}
@ -31,7 +38,7 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/
public function isDebug()
{
return (boolean) \Mage::getStoreConfig('payment/bitpay/debug');
return (boolean) \Mage::getStoreConfig('payment/btcpay/debug');
}
/**
@ -41,7 +48,7 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/
public function hasTransactionSpeed()
{
$speed = \Mage::getStoreConfig('payment/bitpay/speed');
$speed = \Mage::getStoreConfig('payment/btcpay/speed');
return !empty($speed);
}
@ -53,7 +60,7 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/
public function getNotificationUrl()
{
return \Mage::getUrl(\Mage::getStoreConfig('payment/bitpay/notification_url'));
return \Mage::getUrl(\Mage::getStoreConfig('payment/btcpay/notification_url'));
}
/**
@ -63,12 +70,12 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
*/
public function getRedirectUrl()
{
return \Mage::getUrl(\Mage::getStoreConfig('payment/bitpay/redirect_url'));
return \Mage::getUrl(\Mage::getStoreConfig('payment/btcpay/redirect_url'));
}
/**
* Registers the BitPay autoloader to run before Magento's. This MUST be
* called before using any bitpay classes.
* Registers the Bitpay autoloader to run before Magento's. This MUST be
* called before using any Bitpay classes.
*/
public function registerAutoloader()
{
@ -79,41 +86,41 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
require_once $autoloader_filename;
\Bitpay\Autoloader::register();
$this->_autoloaderRegistered = true;
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::registerAutoloader(): autoloader file was found and has been registered.');
$this->debugData('[INFO] In Btcpay_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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::registerAutoloader(): autoloader file was not found or is not readable. Cannot continue!');
throw new \Exception('In Btcpay_Core_Helper_Data::registerAutoloader(): autoloader file was not found or is not readable. Cannot continue!');
}
}
}
/**
* This function will generate keys that will need to be paired with BitPay
* using
* This function will generate keys that will need to be paired with Btcpay
*
*/
public function generateAndSaveKeys()
{
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::generateAndSaveKeys(): attempting to generate new keypair and save to database.');
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::generateAndSaveKeys(): attempting to generate new keypair and save to database.');
if (true === empty($this->_autoloaderRegistered)) {
$this->registerAutoloader();
}
$this->_privateKey = new Bitpay\PrivateKey('payment/bitpay/private_key');
$this->_privateKey = new Bitpay\PrivateKey('payment/btcpay/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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::generateAndSaveKeys(): could not create new Btcpay private key object. Cannot continue!');
throw new \Exception('In Btcpay_Core_Helper_Data::generateAndSaveKeys(): could not create new Btcpay private key object. Cannot continue!');
} else {
$this->_privateKey->generate();
}
$this->_publicKey = new Bitpay\PublicKey('payment/bitpay/public_key');
$this->_publicKey = new Bitpay\PublicKey('payment/btcpay/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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::generateAndSaveKeys(): could not create new Btcpay public key object. Cannot continue!');
throw new \Exception('In Btcpay_Core_Helper_Data::generateAndSaveKeys(): could not create new Btcpay public key object. Cannot continue!');
} else {
$this->_publicKey
->setPrivateKey($this->_privateKey)
@ -123,19 +130,19 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
$this->getKeyManager()->persist($this->_publicKey);
$this->getKeyManager()->persist($this->_privateKey);
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::generateAndSaveKeys(): key manager called to persist keypair to database.');
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::generateAndSaveKeys(): key manager called to persist keypair to database.');
}
/**
* Send a pairing request to BitPay to receive a Token
* Send a pairing request to Btcpay to receive a Token
*/
public function sendPairingRequest($pairingCode)
{
if (false === isset($pairingCode) || true === empty($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.');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::sendPairingRequest(): missing or invalid pairingCode parameter.');
throw new \Exception('In Btcpay_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);
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::sendPairingRequest(): function called with the pairingCode parameter: ' . $pairingCode);
}
if (true === empty($this->_autoloaderRegistered)) {
@ -147,17 +154,17 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
$sin = $this->getSinKey();
if (false === isset($sin) || true === empty($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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::sendPairingRequest(): could not retrieve the SIN parameter. Cannot continue!');
throw new \Exception('In Btcpay_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);
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::sendPairingRequest(): attempting to pair with the SIN parameter: ' . $sin);
}
// Sanitize label
$label = preg_replace('/[^a-zA-Z0-9 ]/', '', \Mage::app()->getStore()->getName());
$label = substr('Magento ' . $label, 0, 59);
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::sendPairingRequest(): using the label "' . $label . '".');
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::sendPairingRequest(): using the label "' . $label . '".');
$token = $this->getBitpayClient()->createToken(
array(
@ -166,26 +173,30 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
'label' => (string) $label,
)
);
$networkURL = \Mage::getStoreConfig('payment/btcpay/network');
$network = new Bitpay\Network\Customnet($networkURL, 443, false);
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::sendPairingRequest(): using the network "' . $network->getApiHost() . '".');
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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::sendPairingRequest(): could not obtain the token from the pairing process. Cannot continue!');
throw new \Exception('In Btcpay_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.');
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::sendPairingRequest(): token successfully obtained.');
}
$config = new \Mage_Core_Model_Config();
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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::sendPairingRequest(): could not create new Mage_Core_Model_Config object. Cannot continue!');
throw new \Exception('In Btcpay_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.');
if($config->saveConfig('payment/btcpay/token', $token->getToken())) {
$this->debugData('[INFO] In Btcpay_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.');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::sendPairingRequest(): token could not be saved to database.');
throw new \Exception('In Btcpay_Core_Helper_Data::sendPairingRequest(): token could not be saved to database.');
}
}
@ -198,7 +209,7 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
return $this->_sin;
}
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getSinKey(): attempting to get the SIN parameter.');
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::getSinKey(): attempting to get the SIN parameter.');
if (true === empty($this->_autoloaderRegistered)) {
$this->registerAutoloader();
@ -207,8 +218,8 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
$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->debugData('[ERROR] In Btcpay_Core_Helper_Data::getSinKey(): could not create new Bitpay SinKey object. Cannot continue!');
throw new \Exception('In Btcpay_Core_Helper_Data::getSinKey(): could not create new Bitpay SinKey object. Cannot continue!');
}
$this->_sin
@ -216,8 +227,8 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
->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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::getSinKey(): could not generate a new SIN from the public key. Cannot continue!');
throw new \Exception('In Btcpay_Core_Helper_Data::getSinKey(): could not generate a new SIN from the public key. Cannot continue!');
}
return $this->_sin;
@ -226,7 +237,7 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
public function getPublicKey()
{
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.');
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::getPublicKey(): found an existing public key, returning that.');
return $this->_publicKey;
}
@ -234,31 +245,31 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
$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->debugData('[INFO] In Btcpay_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/btcpay/public_key');
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->debugData('[INFO] In Btcpay_Core_Helper_Data::getPublicKey(): could not load a public key from the key manager, generating a new one.');
$this->generateAndSaveKeys();
} else {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPublicKey(): successfully loaded public key from the key manager, returning that.');
$this->debugData('[INFO] In Btcpay_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.');
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::getPublicKey(): successfully generated a new public key.');
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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::getPublicKey(): could not load or generate a new public key. Cannot continue!');
throw new \Exception('In Btcpay_Core_Helper_Data::getPublicKey(): could not load or generate a new public key. Cannot continue!');
}
}
public function getPrivateKey()
{
if (false === empty($this->_privateKey)) {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPrivateKey(): found an existing private key, returning that.');
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::getPrivateKey(): found an existing private key, returning that.');
return $this->_privateKey;
}
@ -266,24 +277,24 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
$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->debugData('[INFO] In Btcpay_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/btcpay/private_key');
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->debugData('[INFO] In Btcpay_Core_Helper_Data::getPrivateKey(): could not load a private key from the key manager, generating a new one.');
$this->generateAndSaveKeys();
} else {
$this->debugData('[INFO] In Bitpay_Core_Helper_Data::getPrivateKey(): successfully loaded private key from the key manager, returning that.');
$this->debugData('[INFO] In Btcpay_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.');
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::getPrivateKey(): successfully generated a new private key.');
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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::getPrivateKey(): could not load or generate a new private key. Cannot continue!');
throw new \Exception('In Btcpay_Core_Helper_Data::getPrivateKey(): could not load or generate a new private key. Cannot continue!');
}
}
@ -297,13 +308,13 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
$this->registerAutoloader();
}
$this->_keyManager = new Bitpay\KeyManager(new Bitpay\Storage\MagentoStorage());
$this->_keyManager = new Bitpay\KeyManager(new Bitpay\Storage\BtcpayMagentoStorage());
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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::getKeyManager(): could not create new Bitpay KeyManager object. Cannot continue!');
throw new \Exception('In Btcpay_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.');
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::getKeyManager(): successfully created new Bitpay KeyManager object.');
}
}
@ -326,17 +337,18 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
$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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::getBitpayClient(): could not create new Bitpay Client object. Cannot continue!');
throw new \Exception('In Btcpay_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->debugData('[INFO] In Btcpay_Core_Helper_Data::getBitpayClient(): successfully created new Bitpay Client object.');
}
if(\Mage::getStoreConfig('payment/bitpay/network') === 'livenet') {
$network = new Bitpay\Network\Livenet();
} else {
$network = new Bitpay\Network\Testnet();
}
$networkURL = \Mage::getStoreConfig('payment/btcpay/network');
$network = new Bitpay\Network\Customnet($networkURL, 443);
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::getBitpayClient: using the network ' . $network->getApiHost() . '.');
$adapter = new Bitpay\Client\Adapter\CurlAdapter();
$this->_client->setPublicKey($this->getPublicKey());
@ -344,6 +356,7 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
$this->_client->setNetwork($network);
$this->_client->setAdapter($adapter);
$this->_client->setToken($this->getToken());
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::getBitpayClient(): Token has been set.');
return $this->_client;
}
@ -357,14 +370,27 @@ class Bitpay_Core_Helper_Data extends Mage_Core_Helper_Abstract
$token = new 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!');
$this->debugData('[ERROR] In Btcpay_Core_Helper_Data::getToken(): could not create new Bitpay Token object. Cannot continue!');
throw new \Exception('In Btcpay_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.');
$this->debugData('[INFO] In Btcpay_Core_Helper_Data::getToken(): successfully created new Bitpay Token object.');
}
$token->setToken(\Mage::getStoreConfig('payment/bitpay/token'));
$token->setToken(\Mage::getStoreConfig('payment/btcpay/token'));
return $token;
}
/**
* @return string
*/
public function getLogFile()
{
return "payment_btcpay.log";
}
public function getExtensionVersion()
{
return (string) \Mage::getConfig()->getNode()->modules->Btcpay_Core->version;
}
}

View File

@ -6,9 +6,9 @@
/**
* This class will take the pairing code the merchant entered and pair it with
* BitPay's API.
* BTCPay's API.
*/
class Bitpay_Core_Model_Config_PairingCode extends Mage_Core_Model_Config_Data
class Btcpay_Core_Model_Config_PairingCode extends Mage_Core_Model_Config_Data
{
/**
* @inheritdoc
@ -27,17 +27,17 @@ class Bitpay_Core_Model_Config_PairingCode extends Mage_Core_Model_Config_Data
return;
}
\Mage::helper('bitpay')->debugData('[INFO] In Bitpay_Core_Model_Config_PairingCode::save(): attempting to pair with BitPay with pairing code ' . $pairingCode);
\Mage::helper('btcpay')->debugData('[INFO] In Btcpay_Core_Model_Config_PairingCode::save(): attempting to pair with BTCPay with pairing code ' . $pairingCode);
try {
\Mage::helper('bitpay')->sendPairingRequest($pairingCode);
\Mage::helper('btcpay')->sendPairingRequest($pairingCode);
} catch (\Exception $e) {
\Mage::helper('bitpay')->debugData(sprintf('[ERROR] Exception thrown while calling the sendPairingRequest() function. The specific error message is: "%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::helper('btcpay')->debugData(sprintf('[ERROR] Exception thrown while calling the sendPairingRequest() function. The specific error message is: "%s"', $e->getMessage()));
\Mage::getSingleton('core/session')->addError('There was an error while trying to pair with BTCPay using the pairing code '.$pairingCode.'. Please make sure you select the correct Network (Livenet vs Testnet) and try again with a new 7 character pairing code or enable debug mode and send the "payment_btcpay.log" file to support@btcpay.com for more help.');
return;
}
\Mage::getSingleton('core/session')->addSuccess('Pairing with BitPay was successful.');
\Mage::getSingleton('core/session')->addSuccess('Pairing with BTCPay was successful.');
}
}

View File

@ -6,13 +6,13 @@
/**
*/
class Bitpay_Core_Model_Invoice extends Mage_Core_Model_Abstract
class Btcpay_Core_Model_Invoice extends Mage_Core_Model_Abstract
{
/**
*/
protected function _construct()
{
$this->_init('bitpay/invoice');
$this->_init('btcpay/invoice');
}
/**
@ -20,31 +20,29 @@ class Bitpay_Core_Model_Invoice extends Mage_Core_Model_Abstract
* BitPay's API
*
* @param Bitpay\Invoice $invoice
* @return Bitpay_Core_Model_Invoice
* @return Btcpay_Core_Model_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.');
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_Model_Invoice::prepareWithBitpayInvoice(): Missing or empty $invoice parameter.');
throw new \Exception('In Btcpay_Core_Model_Invoice::prepareWithBitpayInvoice(): Missing or empty $invoice parameter.');
}
$this->addData(
array(
'id' => $invoice->getId(),
'url' => $invoice->getUrl(),
'pos_data' => $invoice->getPosData(),
'status' => $invoice->getStatus(),
'btc_price' => $invoice->getBtcPrice(),
'price' => $invoice->getPrice(),
'currency' => $invoice->getCurrency()->getCode(),
'order_id' => $invoice->getOrderId(),
'invoice_time' => intval($invoice->getInvoiceTime() / 1000),
'expiration_time' => intval($invoice->getExpirationTime() / 1000),
'current_time' => intval($invoice->getCurrentTime() / 1000),
'btc_paid' => $invoice->getBtcPaid(),
'rate' => $invoice->getRate(),
'invoice_time' => intval(date_format($invoice->getInvoiceTime(), 'U') / 1000),
'expiration_time' => intval(date_format($invoice->getExpirationTime(), 'U') / 1000),
'current_time' => intval(date_format($invoice->getCurrentTime(), 'U') / 1000),
'exception_status' => $invoice->getExceptionStatus(),
'transactionCurrency' => $invoice->getTransactionCurrency()
)
);
@ -55,13 +53,13 @@ class Bitpay_Core_Model_Invoice extends Mage_Core_Model_Abstract
* Adds information to based on the order object inside magento
*
* @param Mage_Sales_Model_Order $order
* @return Bitpay_Core_Model_Invoice
* @return Btcpay_Core_Model_Invoice
*/
public function prepareWithOrder($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.');
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_Model_Invoice::prepateWithOrder(): Missing or empty $order parameter.');
throw new \Exception('In Btcpay_Core_Model_Invoice::prepateWithOrder(): Missing or empty $order parameter.');
}
$this->addData(

View File

@ -6,14 +6,14 @@
/**
*/
class Bitpay_Core_Model_Ipn extends Mage_Core_Model_Abstract
class Btcpay_Core_Model_Ipn extends Mage_Core_Model_Abstract
{
/**
*/
protected function _construct()
{
parent::_construct();
$this->_init('bitpay/ipn');
$this->_init('btcpay/ipn');
}
/**
@ -29,11 +29,18 @@ class Bitpay_Core_Model_Ipn extends Mage_Core_Model_Abstract
return false;
}
$quote = Mage::getModel('sales/quote')->load($quoteId, 'entity_id');
$order = \Mage::getModel('sales/order')->load($quoteId, 'quote_id');
if (!$quote)
{
Mage::log('quote not found', Zend_Log::WARN, 'bitpay.log');
if (false === isset($order) || true === empty($order)) {
\Mage::helper('btcpay')->debugData('[DEBUG] Btcpay_Core_Model_Ipn::GetStatusReceived(), order not found for quoteId' . $quoteId);
return false;
}
$orderId = $order->getIncrementId();
if (false === isset($orderId) || true === empty($orderId)) {
\Mage::helper('btcpay')->debugData('[DEBUG] Btcpay_Core_Model_Ipn::GetStatusReceived(), orderId not found for quoteId' . $quoteId);
return false;
}
@ -41,7 +48,7 @@ class Bitpay_Core_Model_Ipn extends Mage_Core_Model_Abstract
foreach ($collection as $i)
{
if ($quoteId == json_decode($i->pos_data, true)['quoteId']) {
if ($orderId == json_decode($i->pos_data, true)['orderId']) {
if (in_array($i->status, $statuses)) {
return true;
}

View File

@ -1,17 +1,17 @@
<?php
/**
* @license Copyright 2011-2015 BitPay Inc., MIT License
* @license Copyright 2011-2015 Bitpay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
/**
* Bitcoin payment method support by BitPay
* Bitcoin payment method support by BTCPay
*/
class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstract
class Btcpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstract
{
protected $_code = 'bitpay';
protected $_formBlockType = 'bitpay/form_bitpay';
protected $_infoBlockType = 'bitpay/info';
protected $_code = 'btcpay';
protected $_formBlockType = 'btcpay/form_btcpay';
protected $_infoBlockType = 'btcpay/info';
protected $_isGateway = true;
protected $_canAuthorize = true;
@ -33,69 +33,70 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
/**
* @param Mage_Sales_Model_Order_Payment $payment
* @param float $amount
* @return Bitpay_Core_Model_PaymentMethod
* @return Btcpay_Core_Model_PaymentMethod
*/
public function authorize(Varien_Object $payment, $amount, $iframe = false)
{
// Check if coming from iframe or submit button
if ((!Mage::getStoreConfig('payment/bitpay/fullscreen') && $iframe === false)
|| (Mage::getStoreConfig('payment/bitpay/fullscreen') && $iframe === true)) {
$quoteId = $payment->getOrder()->getQuoteId();
$ipn = Mage::getModel('bitpay/ipn');
if (!$ipn->GetQuotePaid($quoteId))
{
// This is the error that is displayed to the customer during checkout.
Mage::throwException("Order not paid for. Please pay first and then Place your Order.");
Mage::log('Order not paid for. Please pay first and then Place Your Order.', Zend_Log::CRIT, Mage::helper('bitpay')->getLogFile());
}
return $this;
}
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('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::authorize(): missing payment or amount parameters.');
throw new \Exception('In Btcpay_Core_Model_Method_Bitcoin::authorize(): missing payment or amount parameters.');
}
$this->debugData('[INFO] Bitpay_Core_Model_Method_Bitcoin::authorize(): authorizing new order.');
// use the price in the currency of the store (not in the user selected currency)
$amount = $payment->getOrder()->getQuote()->getBaseGrandTotal();
// Create BitPay Invoice
$this->debugData('[INFO] Btcpay_Core_Model_Method_Bitcoin::authorize(): authorizing new order.');
// Create Bitpay Invoice
$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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::authorize(): could not initialize invoice.');
throw new \Exception('In Btcpay_Core_Model_Method_Bitcoin::authorize(): could not initialize invoice.');
}
//add order id to the redirect url to match order in the checkout/onepage/success if btcpay invoice expired
$order_id = $payment->getOrder()->getId();
$redirect_url = \Mage::getUrl(\Mage::getStoreConfig('payment/btcpay/redirect_url') . '/order_id/'.$order_id);
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::authorize(): order id = '.$order_id);
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::authorize(): redirect url = '.$redirect_url);
$invoice->setRedirectUrl($redirect_url);
$invoice = $this->prepareInvoice($invoice, $payment, $amount);
try {
$bitpayInvoice = \Mage::helper('bitpay')->getBitpayClient()->createInvoice($invoice);
$bitpayInvoice = \Mage::helper('btcpay')->getBitpayClient()->createInvoice($invoice);
} catch (\Exception $e) {
$this->debugData('[ERROR] In Bitpay_Core_Model_Method_Bitcoin::authorize(): ' . $e->getMessage());
\Mage::throwException('In Bitpay_Core_Model_Method_Bitcoin::authorize(): Could not authorize transaction.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::authorize(): ' . $e->getMessage());
//display min invoice value error
if(strpos($e->getMessage(), 'Invoice price must be') !== FALSE)
{
\Mage::throwException($e->getMessage());
}
\Mage::throwException('In Btcpay_Core_Model_Method_Bitcoin::authorize(): Could not authorize transaction.');
}
self::$_redirectUrl = (Mage::getStoreConfig('payment/bitpay/fullscreen')) ? $bitpayInvoice->getUrl(): $bitpayInvoice->getUrl().'&view=iframe';
self::$_redirectUrl = $bitpayInvoice->getUrl();
$this->debugData(
array(
'[INFO] BitPay Invoice created',
'[INFO] BTCPay / Bitpay Invoice created',
sprintf('Invoice URL: "%s"', $bitpayInvoice->getUrl()),
)
);
$quote = Mage::getSingleton('checkout/session')->getQuote();
$quote = \Mage::getSingleton('checkout/session')->getQuote();
$order = \Mage::getModel('sales/order')->load($quote->getId(), 'quote_id');
// Save BitPay Invoice in database for reference
$mirrorInvoice = \Mage::getModel('bitpay/invoice')
$this->debugData('[INFO] Saving invoice for reference. increment_id = ' . $order->getIncrementId(). ' and quote_id = '.$quote->getId()) ;
// Save Bitpay Invoice in database for reference
$mirrorInvoice = \Mage::getModel('btcpay/invoice')
->prepareWithBitpayInvoice($bitpayInvoice)
->prepareWithOrder(array('increment_id' => $order->getIncrementId(), 'quote_id'=> $quote->getId()))
->save();
$this->debugData('[INFO] Leaving Bitpay_Core_Model_Method_Bitcoin::authorize(): invoice id ' . $bitpayInvoice->getId());
$this->debugData('[INFO] Leaving Btcpay_Core_Model_Method_Bitcoin::authorize(): invoice id ' . $bitpayInvoice->getId());
return $this;
}
@ -109,25 +110,25 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/
public function canUseCheckout()
{
$token = \Mage::getStoreConfig('payment/bitpay/token');
$token = \Mage::getStoreConfig('payment/btcpay/token');
if (false === isset($token) || true === empty($token)) {
/**
* Merchant must goto their account and create a pairing code to
* enter in.
*/
$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.');
$this->debugData('[ERROR] In Btcpay_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 BTCPay token.');
return false;
}
$this->debugData('[INFO] Leaving Bitpay_Core_Model_Method_Bitcoin::canUseCheckout(): token obtained from storage successfully.');
$this->debugData('[INFO] Leaving Btcpay_Core_Model_Method_Bitcoin::canUseCheckout(): token obtained from storage successfully.');
return true;
}
/**
* Fetchs an invoice from BitPay
* Fetchs an invoice from BTCPay
*
* @param string $id
* @return Bitpay\Invoice
@ -135,30 +136,30 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
public function fetchInvoice($id)
{
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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::fetchInvoice(): missing or invalid id parameter.');
throw new \Exception('In Btcpay_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);
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::fetchInvoice(): function called with id ' . $id);
}
\Mage::helper('bitpay')->registerAutoloader();
\Mage::helper('btcpay')->registerAutoloader();
$client = \Mage::helper('bitpay')->getBitpayClient();
$client = \Mage::helper('btcpay')->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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::fetchInvoice(): could not obtain BTCPay client.');
throw new \Exception('In Btcpay_Core_Model_Method_Bitcoin::fetchInvoice(): could not obtain BTCPay client.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::fetchInvoice(): obtained BitPay client successfully.');
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::fetchInvoice(): obtained BTCPay client successfully.');
}
$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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::fetchInvoice(): could not retrieve invoice from BTCPay.');
throw new \Exception('In Btcpay_Core_Model_Method_Bitcoin::fetchInvoice(): could not retrieve invoice from BTCPay.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::fetchInvoice(): successfully retrieved invoice id ' . $id . ' from BitPay.');
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::fetchInvoice(): successfully retrieved invoice id ' . $id . ' from BTCPay.');
}
return $invoice;
@ -174,34 +175,19 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
public function extractAddress($address)
{
if (false === isset($address) || true === empty($address)) {
$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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::extractAddress(): missing or invalid address parameter.');
throw new \Exception('In Btcpay_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.');
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::extractAddress(): called with good address parameter, extracting now.');
}
$options = array();
$options['buyerName'] = $address->getName();
if ($address->getCompany()) {
$options['buyerName'] = $options['buyerName'].' c/o '.$address->getCompany();
}
$options['buyerAddress1'] = $address->getStreet1();
$options['buyerAddress2'] = $address->getStreet2();
$options['buyerAddress3'] = $address->getStreet3();
$options['buyerAddress4'] = $address->getStreet4();
$options['buyerCity'] = $address->getCity();
$options['buyerState'] = $address->getRegionCode();
$options['buyerZip'] = $address->getPostcode();
$options['buyerCountry'] = $address->getCountry();
$options['buyerEmail'] = $address->getEmail();
$options['buyerPhone'] = $address->getTelephone();
// trim to fit API specs
foreach (array('buyerName', 'buyerAddress1', 'buyerAddress2', 'buyerAddress3', 'buyerAddress4', 'buyerCity', 'buyerState', 'buyerZip', 'buyerCountry', 'buyerEmail', 'buyerPhone') as $f) {
foreach (array('buyerEmail') 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.');
$this->debugData('[WARNING] In Btcpay_Core_Model_Method_Bitcoin::extractAddress(): the ' . $f . ' parameter was greater than 100 characters, trimming.');
$options[$f] = substr($options[$f], 0, 100);
}
}
@ -216,7 +202,7 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/
public function getOrderPlaceRedirectUrl()
{
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::getOrderPlaceRedirectUrl(): $_redirectUrl is ' . self::$_redirectUrl);
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::getOrderPlaceRedirectUrl(): $_redirectUrl is ' . self::$_redirectUrl);
return self::$_redirectUrl;
@ -230,27 +216,27 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
*/
private function initializeInvoice()
{
\Mage::helper('bitpay')->registerAutoloader();
\Mage::helper('btcpay')->registerAutoloader();
$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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::initializeInvoice(): could not construct new BTCPay invoice object.');
throw new \Exception('In Btcpay_Core_Model_Method_Bitcoin::initializeInvoice(): could not construct new BTCPay invoice object.');
} else {
$this->debugData('[INFO] In Bitpay_Core_Model_Method_Bitcoin::initializeInvoice(): constructed new BitPay invoice object successfully.');
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::initializeInvoice(): constructed new Bitpay invoice object successfully.');
}
$invoice->setFullNotifications(true);
$invoice->setTransactionSpeed(\Mage::getStoreConfig('payment/bitpay/speed'));
$invoice->setNotificationUrl(\Mage::getUrl(\Mage::getStoreConfig('payment/bitpay/notification_url')));
$invoice->setRedirectUrl(\Mage::getUrl(\Mage::getStoreConfig('payment/bitpay/redirect_url')));
$invoice->setTransactionSpeed('medium');
$invoice->setNotificationUrl(\Mage::getUrl(\Mage::getStoreConfig('payment/btcpay/notification_url')));
$invoice->setRedirectUrl(\Mage::getUrl(\Mage::getStoreConfig('payment/btcpay/redirect_url')));
return $invoice;
}
/**
* Prepares the invoice object to be sent to BitPay's API. This method sets
* Prepares the invoice object to be sent to BTCPay's API. This method sets
* all the other info that we have to rely on other objects for.
*
* @param Bitpay\Invoice $invoice
@ -261,24 +247,18 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::prepareInvoice(): missing or invalid invoice, payment or amount parameter.');
throw new \Exception('In Btcpay_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.');
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::prepareInvoice(): entered function with good invoice, payment and amount parameters.');
}
$quote = Mage::getSingleton('checkout/session')->getQuote();
$order = \Mage::getModel('sales/order')->load($quote->getId(), 'quote_id');
if (Mage::getStoreConfig('payment/bitpay/fullscreen')) {
$invoice->setOrderId($order->getIncrementId());
$invoice->setPosData(json_encode(array('orderId' => $order->getIncrementId())));
} else {
$invoice->setOrderId($quote->getId());
$invoice->setPosData(json_encode(array('quoteId' => $quote->getId())));
$convertQuote = Mage::getSingleton('sales/convert_quote');
$order = $convertQuote->toOrder($quote);
}
$invoice->setOrderId($order->getIncrementId());
$invoice->setExtendedNotifications(true);
$invoice->setPosData(json_encode(array('orderId' => $order->getIncrementId())));
$invoice = $this->addCurrencyInfo($invoice, $order);
$invoice = $this->addPriceInfo($invoice, $amount);
@ -297,76 +277,24 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::addBuyerInfo(): missing or invalid invoice or order parameter.');
throw new \Exception('In Btcpay_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.');
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::addBuyerInfo(): function called with good invoice and order parameters.');
}
$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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::addBuyerInfo(): could not construct new Bitpay buyer object.');
throw new \Exception('In Btcpay_Core_Model_Method_Bitcoin::addBuyerInfo(): could not construct new Bitpay buyer object.');
}
$buyer->setFirstName($order->getCustomerFirstname());
$buyer->setLastName($order->getCustomerLastname());
if (Mage::getStoreConfig('payment/bitpay/fullscreen')) {
$address = $order->getBillingAddress();
} else {
$quote = Mage::getSingleton('checkout/session')->getQuote();
$address = $quote->getBillingAddress();
}
$street = $address->getStreet1();
if (null !== $street && '' !== $street) {
$buyer->setAddress(
array(
$street,
$address->getStreet2(),
$address->getStreet3(),
$address->getStreet4()
)
);
}
$region = $address->getRegion();
$regioncode = $address->getRegionCode();
if (null !== $regioncode && '' !== $regioncode) {
$buyer->setState($regioncode);
} else if (null !== $region && '' !== $region) {
$buyer->setState($region);
}
$country = $address->getCountry();
if (null !== $country && '' !== $country) {
$buyer->setCountry($country);
}
$city = $address->getCity();
if (null !== $city && '' !== $city) {
$buyer->setCity($city);
}
$postcode = $address->getPostcode();
if (null !== $postcode && '' !== $postcode) {
$buyer->setZip($postcode);
}
$address = $order->getBillingAddress();
$email = $address->getEmail();
if (null !== $email && '' !== $email) {
$buyer->setEmail($email);
}
$telephone = $address->getTelephone();
if (null !== $telephone && '' !== $telephone) {
$buyer->setPhone($telephone);
}
$invoice->setBuyer($buyer);
return $invoice;
@ -382,20 +310,22 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::addCurrencyInfo(): missing or invalid invoice or order parameter.');
throw new \Exception('In Btcpay_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.');
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::addCurrencyInfo(): function called with good invoice and order parameters.');
}
$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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::addCurrencyInfo(): could not construct new BTCPay currency object.');
throw new \Exception('In Btcpay_Core_Model_Method_Bitcoin::addCurrencyInfo(): could not construct new BTCPay currency object.');
}
$currency->setCode($order->getOrderCurrencyCode());
//$currency->setCode($order->getOrderCurrencyCode());
//use the store currency code (not the customer selected currency)
$currency->setCode(\Mage::app()->getStore()->getBaseCurrencyCode());
$invoice->setCurrency($currency);
return $invoice;
@ -411,17 +341,17 @@ class Bitpay_Core_Model_Method_Bitcoin extends Mage_Payment_Model_Method_Abstrac
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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::addPriceInfo(): missing or invalid invoice or amount parameter.');
throw new \Exception('In Btcpay_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.');
$this->debugData('[INFO] In Btcpay_Core_Model_Method_Bitcoin::addPriceInfo(): function called with good invoice and amount parameters.');
}
$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.');
$this->debugData('[ERROR] In Btcpay_Core_Model_Method_Bitcoin::addPriceInfo(): could not construct new BTCPay item object.');
throw new \Exception('In Btcpay_Core_Model_Method_Bitcoin::addPriceInfo(): could not construct new BTCPay item object.');
}
$item->setPrice($amount);

View File

@ -6,7 +6,7 @@
/**
*/
class Bitpay_Core_Model_Mysql4_Invoice extends Mage_Core_Model_Mysql4_Abstract
class Btcpay_Core_Model_Mysql4_Invoice extends Mage_Core_Model_Mysql4_Abstract
{
protected $_isPkAutoIncrement = false;
@ -14,6 +14,6 @@ class Bitpay_Core_Model_Mysql4_Invoice extends Mage_Core_Model_Mysql4_Abstract
*/
protected function _construct()
{
$this->_init('bitpay/invoice', 'id');
$this->_init('btcpay/invoice', 'id');
}
}

View File

@ -6,7 +6,7 @@
/**
*/
class Bitpay_Core_Model_Mysql4_Invoice_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
class Btcpay_Core_Model_Mysql4_Invoice_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
protected $_isPkAutoIncrement = false;
@ -14,6 +14,6 @@ class Bitpay_Core_Model_Mysql4_Invoice_Collection extends Mage_Core_Model_Mysql4
*/
protected function _construct()
{
$this->_init('bitpay/invoice');
$this->_init('btcpay/invoice');
}
}

View File

@ -6,12 +6,12 @@
/**
*/
class Bitpay_Core_Model_Mysql4_Ipn extends Mage_Core_Model_Mysql4_Abstract
class Btcpay_Core_Model_Mysql4_Ipn extends Mage_Core_Model_Mysql4_Abstract
{
/**
*/
protected function _construct()
{
$this->_init('bitpay/ipn', 'id');
$this->_init('btcpay/ipn', 'id');
}
}

View File

@ -4,13 +4,13 @@
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
class Bitpay_Core_Model_Mysql4_Ipn_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
class Btcpay_Core_Model_Mysql4_Ipn_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
/**
*/
protected function _construct()
{
parent::_construct();
$this->_init('bitpay/ipn');
$this->_init('btcpay/ipn');
}
}

View File

@ -0,0 +1,124 @@
<?php
/**
* @license Copyright 2011-2015 BTCPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
class Btcpay_Core_Model_Observer {
public function implementOrderStatus($e) {
$order = $e -> getOrder();
$paymentCode = $order -> getPayment() -> getMethodInstance() -> getCode();
if ($paymentCode == 'btcpay') {
$order -> setState(Mage_Sales_Model_Order::STATE_NEW, true);
$order -> save();
}
// Mage::log('$order = $event->getOrder();' . $order -> getState());
}
/*
* Queries BTCPay to update the order states in magento to make sure that
* open orders are closed/canceled if the BTCPay invoice expires or becomes
* invalid.
*/
public function updateOrderStates() {
$apiKey = \Mage::getStoreConfig('payment/btcpay/api_key');
if (false === isset($apiKey) || empty($apiKey)) {
\Mage::helper('btcpay') -> debugData('[INFO] Btcpay_Core_Model_Observer::updateOrderStates() could not start job to update the order states because the API key was not set.');
return;
} else {
\Mage::helper('btcpay') -> debugData('[INFO] Btcpay_Core_Model_Observer::updateOrderStates() started job to query BTCPay to update the existing order states.');
}
/*
* Get all of the orders that are open and have not received an IPN for
* complete, expired, or invalid.
*/
$orders = \Mage::getModel('btcpay/ipn') -> getOpenOrders();
if (false === isset($orders) || empty($orders)) {
\Mage::helper('btcpay') -> debugData('[INFO] Btcpay_Core_Model_Observer::updateOrderStates() could not retrieve the open orders.');
return;
} else {
\Mage::helper('btcpay') -> debugData('[INFO] Btcpay_Core_Model_Observer::updateOrderStates() successfully retrieved existing open orders.');
}
/*
* Get all orders that have been paid using btcpay and
* are not complete/closed/etc
*/
foreach ($orders as $order) {
/*
* Query BTCPay with the invoice ID to get the status. We must take
* care not to anger the API limiting gods and disable our access
* to the API.
*/
$status = null;
// TODO:
// Does the order need to be updated?
// Yes? Update Order Status
// No? continue
}
\Mage::helper('btcpay') -> debugData('[INFO] Btcpay_Core_Model_Observer::updateOrderStates() order status update job finished.');
}
/**
* Method that is called via the magento cron to update orders if the
* invoice has expired
*/
public function cleanExpired() {
\Mage::helper('btcpay') -> debugData('[INFO] Btcpay_Core_Model_Observer::cleanExpired() called.');
\Mage::helper('btcpay') -> cleanExpired();
}
/**
* Event Hook: checkout_onepage_controller_success_action
* @param $observer Varien_Event_Observer
*/
public function redirectToCartIfExpired(Varien_Event_Observer $observer)
{
if ($observer->getEvent()->getName() == 'checkout_onepage_controller_success_action')
{
$lastOrderId = null;
foreach(\Mage::app()->getRequest()->getParams() as $key=>$value)
{
if($key == 'order_id')
$lastOrderId = $value;
}
if($lastOrderId != null)
{
//get order
$order = \Mage::getModel('sales/order')->load($lastOrderId);
if (false === isset($order) || true === empty($order)) {
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_Model_Observer::redirectToCartIfExpired(), Invalid Order ID received.');
return;
}
//check if order is pending
if($order->getStatus() != 'pending')
{
return;
}
//check if invoice for order exist in btcpay_invoices table
$btcpayInvoice = \Mage::getModel('btcpay/invoice')->load($order->getIncrementId(), 'increment_id');
$btcpayInvoiceData = $btcpayInvoice->getData();
//if is empty or not is array abort
if(!is_array($btcpayInvoiceData) || is_array($btcpayInvoiceData) && empty($btcpayInvoiceData))
return;
//check if btcpay invoice id expired
$invoiceExpirationTime = $btcpayInvoiceData['expiration_time'];
if($invoiceExpirationTime < strtotime('now'))
{
$failure_url = \Mage::getUrl(\Mage::getStoreConfig('payment/btcpay/failure_url'));
\Mage::app()->getResponse()->setRedirect($failure_url)->sendResponse();
}
}
}
}
}

View File

@ -0,0 +1,273 @@
<?php
class Btcpay_Core_Model_Order_Payment extends Mage_Sales_Model_Order_Payment {
protected function _authorize($isOnline, $amount)
{
// check for authorization amount to be equal to grand total
$this->setShouldCloseParentTransaction(false);
$isSameCurrency = $this->_isSameCurrency();
if (!$isSameCurrency || !$this->_isCaptureFinal($amount)) {
$this->setIsFraudDetected(true);
}
// update totals
$amount = $this->_formatAmount($amount, true);
$this->setBaseAmountAuthorized($amount);
// do authorization
$order = $this->getOrder();
$payment = $order -> getPayment();
$paymentMethodCode = $payment -> getMethodInstance() -> getCode();
if ($paymentMethodCode != 'btcpay'){
$state = Mage_Sales_Model_Order::STATE_PROCESSING;
}
else {
$state = Mage_Sales_Model_Order::STATE_NEW;
}
$status = true;
if ($isOnline) {
// invoke authorization on gateway
$this->getMethodInstance()->setStore($order->getStoreId())->authorize($this, $amount);
}
// similar logic of "payment review" order as in capturing
if ($this->getIsTransactionPending()) {
$message = Mage::helper('sales')->__('Authorizing amount of %s is pending approval on gateway.', $this->_formatPrice($amount));
$state = Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW;
if ($this->getIsFraudDetected()) {
$status = Mage_Sales_Model_Order::STATUS_FRAUD;
}
} else {
if ($this->getIsFraudDetected()) {
$state = Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW;
$message = Mage::helper('sales')->__('Order is suspended as its authorizing amount %s is suspected to be fraudulent.', $this->_formatPrice($amount, $this->getCurrencyCode()));
$status = Mage_Sales_Model_Order::STATUS_FRAUD;
} else {
$message = Mage::helper('sales')->__('Authorized amounta of %s.', $this->_formatPrice($amount));
}
}
// update transactions, order state and add comments
$transaction = $this->_addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_AUTH);
if ($order->isNominal()) {
$message = $this->_prependMessage(Mage::helper('sales')->__('Nominal order registered.'));
} else {
$message = $this->_prependMessage($message);
$message = $this->_appendTransactionToMessage($transaction, $message);
}
$order->setState($state, $status, $message);
return $this;
}
public function registerCaptureNotification($amount, $skipFraudDetection = false)
{
$this->_generateTransactionId(Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE,
$this->getAuthorizationTransaction()
);
$order = $this->getOrder();
$amount = (float)$amount;
$invoice = $this->_getInvoiceForTransactionId($this->getTransactionId());
// register new capture
if (!$invoice) {
$isSameCurrency = $this->_isSameCurrency();
if ($isSameCurrency && $this->_isCaptureFinal($amount)) {
$invoice = $order->prepareInvoice()->register();
$order->addRelatedObject($invoice);
$this->setCreatedInvoice($invoice);
} else {
if (!$skipFraudDetection || !$isSameCurrency) {
$this->setIsFraudDetected(true);
}
$this->_updateTotals(array('base_amount_paid_online' => $amount));
}
}
$status = true;
if ($this->getIsTransactionPending()) {
$message = Mage::helper('sales')->__('Capturing amount of %s is pending approval on gateway.', $this->_formatPrice($amount));
$state = Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW;
if ($this->getIsFraudDetected()) {
$message = Mage::helper('sales')->__('Order is suspended as its capture amount %s is suspected to be fraudulent.', $this->_formatPrice($amount, $this->getCurrencyCode()));
$status = Mage_Sales_Model_Order::STATUS_FRAUD;
}
} else {
$message = Mage::helper('sales')->__('Registered notification about captured amount of %s.', $this->_formatPrice($amount));
$payment = $order -> getPayment();
$paymentMethodCode = $payment -> getMethodInstance() -> getCode();
if ($paymentMethodCode != 'btcpay'){
$state = Mage_Sales_Model_Order::STATE_PROCESSING;
}
else {
$state = Mage_Sales_Model_Order::STATE_NEW;
}
if ($this->getIsFraudDetected()) {
$state = Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW;
$message = Mage::helper('sales')->__('Order is suspended as its capture amount %s is suspected to be fraudulent.', $this->_formatPrice($amount, $this->getCurrencyCode()));
$status = Mage_Sales_Model_Order::STATUS_FRAUD;
}
// register capture for an existing invoice
if ($invoice && Mage_Sales_Model_Order_Invoice::STATE_OPEN == $invoice->getState()) {
$invoice->pay();
$this->_updateTotals(array('base_amount_paid_online' => $amount));
$order->addRelatedObject($invoice);
}
}
$transaction = $this->_addTransaction(Mage_Sales_Model_Order_Payment_Transaction::TYPE_CAPTURE, $invoice, true);
$message = $this->_prependMessage($message);
$message = $this->_appendTransactionToMessage($transaction, $message);
$order->setState($state, $status, $message);
return $this;
}
public function place()
{
Mage::dispatchEvent('sales_order_payment_place_start', array('payment' => $this));
$order = $this->getOrder();
$this->setAmountOrdered($order->getTotalDue());
$this->setBaseAmountOrdered($order->getBaseTotalDue());
$this->setShippingAmount($order->getShippingAmount());
$this->setBaseShippingAmount($order->getBaseShippingAmount());
$methodInstance = $this->getMethodInstance();
$methodInstance->setStore($order->getStoreId());
$orderState = Mage_Sales_Model_Order::STATE_NEW;
$stateObject = new Varien_Object();
/**
* Do order payment validation on payment method level
*/
$methodInstance->validate();
$action = $methodInstance->getConfigPaymentAction();
if ($action) {
if ($methodInstance->isInitializeNeeded()) {
/**
* For method initialization we have to use original config value for payment action
*/
$methodInstance->initialize($methodInstance->getConfigData('payment_action'), $stateObject);
} else {
$payment = $order -> getPayment();
$paymentMethodCode = $payment -> getMethodInstance() -> getCode();
if ($paymentMethodCode != 'btcpay'){
$orderState = Mage_Sales_Model_Order::STATE_PROCESSING;
}
else {
$orderState = Mage_Sales_Model_Order::STATE_NEW;
}
switch ($action) {
case Mage_Payment_Model_Method_Abstract::ACTION_ORDER:
$this->_order($order->getBaseTotalDue());
break;
case Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE:
$this->_authorize(true, $order->getBaseTotalDue()); // base amount will be set inside
$this->setAmountAuthorized($order->getTotalDue());
break;
case Mage_Payment_Model_Method_Abstract::ACTION_AUTHORIZE_CAPTURE:
$this->setAmountAuthorized($order->getTotalDue());
$this->setBaseAmountAuthorized($order->getBaseTotalDue());
$this->capture(null);
break;
default:
break;
}
}
}
$this->_createBillingAgreement();
$orderIsNotified = null;
if ($stateObject->getState() && $stateObject->getStatus()) {
$orderState = $stateObject->getState();
$orderStatus = $stateObject->getStatus();
$orderIsNotified = $stateObject->getIsNotified();
} else {
$orderStatus = $methodInstance->getConfigData('order_status');
if (!$orderStatus) {
$orderStatus = $order->getConfig()->getStateDefaultStatus($orderState);
} else {
// check if $orderStatus has assigned a state
if(method_exists($order->getConfig(), 'getStatusStates'))
{
$states = $order->getConfig()->getStatusStates($orderStatus);
}
else
{
$states = $this->getStatusStates($orderStatus);
}
if (count($states) == 0) {
$orderStatus = $order->getConfig()->getStateDefaultStatus($orderState);
}
}
}
$isCustomerNotified = (null !== $orderIsNotified) ? $orderIsNotified : $order->getCustomerNoteNotify();
$message = $order->getCustomerNote();
// add message if order was put into review during authorization or capture
if ($order->getState() == Mage_Sales_Model_Order::STATE_PAYMENT_REVIEW) {
if ($message) {
$order->addStatusToHistory($order->getStatus(), $message, $isCustomerNotified);
}
} elseif ($order->getState() && ($orderStatus !== $order->getStatus() || $message)) {
// add message to history if order state already declared
$order->setState($orderState, $orderStatus, $message, $isCustomerNotified);
} elseif (($order->getState() != $orderState) || ($order->getStatus() != $orderStatus) || $message) {
// set order state
$order->setState($orderState, $orderStatus, $message, $isCustomerNotified);
}
Mage::dispatchEvent('sales_order_payment_place_end', array('payment' => $this));
return $this;
}
/**
* Check whether payment currency corresponds to order currency
*
* @return bool
*/
public function _isSameCurrency()
{
return !$this->getCurrencyCode() || $this->getCurrencyCode() == $this->getOrder()->getBaseCurrencyCode();
}
/**
* Retrieve state available for status
* Get all assigned states for specified status
*
* @param string $status
* @return array
*/
private function getStatusStates($status)
{
$states = array();
$collectionObj = Mage::getResourceModel('sales/order_status_collection');
$collection = $this->addStatusFilter($collectionObj, $status);
foreach ($collection as $state) {
$states[] = $state;
}
return $states;
}
/**
* add status code filter to collection
*
* @param object Mage_Sales_Model_Resource_Order_Status_Collection
* @param string $status
* @return Mage_Sales_Model_Resource_Order_Status_Collection
*/
private function addStatusFilter($collectionObj, $status)
{
$collectionObj->joinStates();
$collectionObj->getSelect()->where('state_table.status=?', $status);
return $collectionObj;
}
}

View File

@ -24,7 +24,7 @@
* THE SOFTWARE.
*/
class Bitpay_Core_Model_Resource_Ipn_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
class Btcpay_Core_Model_Resource_Ipn_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract
{
/**
@ -32,7 +32,7 @@ class Bitpay_Core_Model_Resource_Ipn_Collection extends Mage_Core_Model_Mysql4_C
protected function _construct()
{
parent::_construct();
$this->_init('bitpay/ipn');
$this->_init('btcpay/ipn');
}
public function delete()

View File

@ -6,6 +6,6 @@
/**
*/
class Bitpay_Core_Model_Resource_Mysql4_Setup extends Mage_Core_Model_Resource_Setup
class Btcpay_Core_Model_Resource_Mysql4_Setup extends Mage_Core_Model_Resource_Setup
{
}

View File

@ -0,0 +1,27 @@
<?php
/**
* @license Copyright 2011-2015 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
class Btcpay_Core_Model_SpecificCountry
{
/**
* @return array
*/
public function toOptionArray()
{
$country = \Mage::getModel('adminhtml/system_config_source_country')->toOptionArray();
$allowCountry = array();
foreach($country as $v)
{
if($v['value'] != '' && $v['value'] != 'SY' && $v['value'] != 'IR' && $v['value'] != 'KP' && $v['value'] != 'SD' && $v['value'] != 'CU')
{
$allowCountry[] = $v;
}
}
return $allowCountry;
}
}

View File

@ -4,7 +4,7 @@
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
class Bitpay_Core_Model_Status
class Btcpay_Core_Model_Status
{
const STATUS_NEW = 'new';
const STATUS_PAID = 'paid';
@ -19,12 +19,12 @@ class Bitpay_Core_Model_Status
public function toOptionArray()
{
return array(
array('value' => self::STATUS_NEW, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_NEW))),
array('value' => self::STATUS_PAID, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_PAID))),
array('value' => self::STATUS_CONFIRMED, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_CONFIRMED))),
array('value' => self::STATUS_COMPLETE, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_COMPLETE))),
array('value' => self::STATUS_EXPIRED, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_EXPIRED))),
array('value' => self::STATUS_INVALID, 'label' => \Mage::helper('bitpay')->__(ucwords(self::STATUS_INVALID))),
array('value' => self::STATUS_NEW, 'label' => \Mage::helper('btcpay')->__(ucwords(self::STATUS_NEW))),
array('value' => self::STATUS_PAID, 'label' => \Mage::helper('btcpay')->__(ucwords(self::STATUS_PAID))),
array('value' => self::STATUS_CONFIRMED, 'label' => \Mage::helper('btcpay')->__(ucwords(self::STATUS_CONFIRMED))),
array('value' => self::STATUS_COMPLETE, 'label' => \Mage::helper('btcpay')->__(ucwords(self::STATUS_COMPLETE))),
array('value' => self::STATUS_EXPIRED, 'label' => \Mage::helper('btcpay')->__(ucwords(self::STATUS_EXPIRED))),
array('value' => self::STATUS_INVALID, 'label' => \Mage::helper('btcpay')->__(ucwords(self::STATUS_INVALID))),
);
}
}

View File

@ -4,7 +4,7 @@
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
class Bitpay_Core_Model_TransactionSpeed
class Btcpay_Core_Model_TransactionSpeed
{
const SPEED_LOW = 'low';
const SPEED_MEDIUM = 'medium';
@ -16,9 +16,9 @@ class Bitpay_Core_Model_TransactionSpeed
public function toOptionArray()
{
return array(
array('value' => self::SPEED_LOW, 'label' => \Mage::helper('bitpay')->__(ucwords(self::SPEED_LOW))),
array('value' => self::SPEED_MEDIUM, 'label' => \Mage::helper('bitpay')->__(ucwords(self::SPEED_MEDIUM))),
array('value' => self::SPEED_HIGH, 'label' => \Mage::helper('bitpay')->__(ucwords(self::SPEED_HIGH))),
array('value' => self::SPEED_LOW, 'label' => \Mage::helper('btcpay')->__(ucwords(self::SPEED_LOW))),
array('value' => self::SPEED_MEDIUM, 'label' => \Mage::helper('btcpay')->__(ucwords(self::SPEED_MEDIUM))),
array('value' => self::SPEED_HIGH, 'label' => \Mage::helper('btcpay')->__(ucwords(self::SPEED_HIGH))),
);
}
}

View File

@ -0,0 +1,34 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
/**
* @route btcpay/index/
*/
class Btcpay_Core_IndexController extends Mage_Core_Controller_Front_Action
{
/**
* @route bitpay/index/index?quote=n
*/
public function indexAction()
{
\Mage::helper('btcpay')->registerAutoloader();
\Mage::helper('btcpay')->debugData($params);
$params = $this->getRequest()->getParams();
$quoteId = $params['quote'];
if (!is_numeric($quoteId))
{
return $this->getResponse()->setHttpResponseCode(400);
}
$paid = \Mage::getModel('btcpay/ipn')->GetQuotePaid($quoteId);
$this->loadLayout();
$this->getResponse()->setHeader('Content-type', 'application/json');
return $this->getResponse()->setBody(json_encode(array('paid' => $paid)));
}
}

View File

@ -5,15 +5,15 @@
*/
/**
* @route /bitpay/ipn
* @route /btcpay/ipn
*/
class Bitpay_Core_IpnController extends Mage_Core_Controller_Front_Action
class Btcpay_Core_IpnController extends Mage_Core_Controller_Front_Action
{
/**
* bitpay's IPN lands here
* btcpay's IPN lands here
*
* @route /bitpay/ipn
* @route /bitpay/ipn/index
* @route /btcpay/ipn
* @route /btcpay/ipn/index
*/
public function indexAction()
{
@ -24,48 +24,51 @@ class Bitpay_Core_IpnController extends Mage_Core_Controller_Front_Action
$raw_post_data = file_get_contents('php://input');
if (false === $raw_post_data) {
\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('btcpay')->debugData('[ERROR] In Btcpay_Core_IpnController::indexAction(), Could not read from the php://input stream or invalid Btcpay IPN received.');
throw new \Exception('Could not read from the php://input stream or invalid Btcpay IPN received.');
}
\Mage::helper('bitpay')->registerAutoloader();
\Mage::helper('btcpay')->registerAutoloader();
\Mage::helper('bitpay')->debugData(array(sprintf('[INFO] In Bitpay_Core_IpnController::indexAction(), Incoming IPN message from BitPay: '),$raw_post_data,));
\Mage::helper('btcpay')->debugData(array(sprintf('[INFO] In Btcpay_Core_IpnController::indexAction(), Incoming IPN message from BTCPay: '),$raw_post_data,));
// Magento doesn't seem to have a way to get the Request body
$ipn = json_decode($raw_post_data);
if(isset($ipn->data))
{
$ipn = $ipn->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.');
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_IpnController::indexAction(), Could not decode the JSON payload from BTCPay.');
throw new \Exception('Could not decode the JSON payload from BTCPay.');
}
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.');
\Mage::helper('btcpay')->debugData(sprintf('[ERROR] In Btcpay_Core_IpnController::indexAction(), Did not receive order ID in IPN: ', $ipn));
throw new \Exception('Invalid Btcpay payment notification message received - did not receive order ID.');
}
$ipn->posData = is_string($ipn->posData) ? json_decode($ipn->posData) : $ipn->posData;
$ipn->buyerFields = isset($ipn->buyerFields) ? $ipn->buyerFields : new stdClass();
\Mage::helper('bitpay')->debugData($ipn);
\Mage::helper('btcpay')->debugData($ipn);
// Log IPN
$mageIpn = \Mage::getModel('bitpay/ipn')->addData(
$mageIpn = \Mage::getModel('btcpay/ipn')->addData(
array(
'invoice_id' => isset($ipn->id) ? $ipn->id : '',
'url' => isset($ipn->url) ? $ipn->url : '',
'pos_data' => json_encode($ipn->posData),
'status' => isset($ipn->status) ? $ipn->status : '',
'btc_price' => isset($ipn->btcPrice) ? $ipn->btcPrice : '',
'price' => isset($ipn->price) ? $ipn->price : '',
'currency' => isset($ipn->currency) ? $ipn->currency : '',
'invoice_time' => isset($ipn->invoiceTime) ? intval($ipn->invoiceTime / 1000) : '',
'expiration_time' => isset($ipn->expirationTime) ? intval($ipn->expirationTime / 1000) : '',
'current_time' => isset($ipn->currentTime) ? intval($ipn->currentTime / 1000) : '',
'btc_paid' => isset($ipn->btcPaid) ? $ipn->btcPaid : '',
'rate' => isset($ipn->rate) ? $ipn->rate : '',
'exception_status' => isset($ipn->exceptionStatus) ? $ipn->exceptionStatus : '',
'transactionCurrency' => isset($ipn->transactionCurrency) ? $ipn->transactionCurrency : ''
)
)->save();
@ -78,14 +81,14 @@ class Bitpay_Core_IpnController extends Mage_Core_Controller_Front_Action
}
if (false === isset($order) || true === empty($order)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), Invalid Bitpay IPN received.');
\Mage::throwException('Invalid Bitpay IPN received.');
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_IpnController::indexAction(), Invalid Btcpay IPN received.');
\Mage::throwException('Invalid Btcpay IPN received.');
}
$orderId = $order->getId();
if (false === isset($orderId) || true === empty($orderId)) {
\Mage::helper('bitpay')->debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), Invalid Bitpay IPN received.');
\Mage::throwException('Invalid Bitpay IPN received.');
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_IpnController::indexAction(), Invalid Btcpay IPN received.');
\Mage::throwException('Invalid Btcpay IPN received.');
}
/**
@ -93,57 +96,31 @@ 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
* store.
*/
$invoice = \Mage::getModel('bitpay/method_bitcoin')->fetchInvoice($ipn->id);
$invoice = \Mage::getModel('btcpay/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::helper('btcpay')->debugData('[ERROR] In Btcpay_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?
if ($invoice->getStatus() != $ipn->status) {
\Mage::getModel('bitpay/method_bitcoin')->debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), IPN status and status from BitPay are different. Rejecting this IPN!');
/* if ($invoice->getStatus() != $ipn->status) {
\Mage::getModel('btcpay/method_bitcoin')->debugData('[ERROR] In Btcpay_Core_IpnController::indexAction(), IPN status and status from BitPay are different. Rejecting this IPN!');
\Mage::throwException('There was an error processing the IPN - statuses are different. Rejecting this IPN!');
}
}*/
// Does the price match?
if ($invoice->getPrice() != $ipn->price) {
\Mage::getModel('bitpay/method_bitcoin')>debugData('[ERROR] In Bitpay_Core_IpnController::indexAction(), IPN price and invoice price are different. Rejecting this IPN!');
\Mage::getModel('btcpay/method_bitcoin')>debugData('[ERROR] In Btcpay_Core_IpnController::indexAction(), IPN price and invoice price are different. Rejecting this 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
$transactionSpeed = \Mage::getStoreConfig('payment/bitpay/speed');
if ($invoice->getStatus() === 'paid'
|| ($invoice->getStatus() === 'confirmed' && $transactionSpeed === 'high')) {
$payment = \Mage::getModel('sales/order_payment')->setOrder($order);
if (true === isset($payment) && false === empty($payment)) {
$payment->registerCaptureNotification($invoice->getPrice());
$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
$state = \Mage::getStoreConfig(sprintf('payment/bitpay/invoice_%s', $invoice->getStatus()));
$state = \Mage::getStoreConfig(sprintf('payment/btcpay/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 in the Bitpay IPN controller.');
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_IpnController::indexAction(), Could not retrieve the defined state parameter to update this order to in the Btcpay IPN controller.');
\Mage::throwException('Could not retrieve the defined state parameter to update this order in the Btcpay IPN controller.');
}
// Check if status should be updated
@ -160,11 +137,52 @@ class Bitpay_Core_IpnController extends Mage_Core_Controller_Front_Action
default:
$order->addStatusToHistory(
$state,
sprintf('[INFO] In Bitpay_Core_IpnController::indexAction(), Incoming IPN status "%s" updated order state to "%s"', $invoice->getStatus(), $state)
sprintf('[INFO] In Btcpay_Core_IpnController::indexAction(), Incoming IPN status "%s" updated order state to "%s"', $invoice->getStatus(), $state)
)->save();
break;
}
if($ipn->status == 'expired')
{
$order->cancel();
$order->setState(Mage_Sales_Model_Order::STATE_CANCELED, true, 'Cancel Transaction.');
$order->setStatus("canceled");
$order->save();
}
if ($ipn->status === 'paid') {
\Mage::helper('btcpay')->debugData('[INFO] Receiving paid IPN, creating invoice for order.');
// Create a Magento invoice for the order when the 'paid' notification comes in
if ($payments = $order->getPaymentsCollection())
{
$payment = count($payments->getItems())>0 ? end($payments->getItems()) : \Mage::getModel('sales/order_payment')->setOrder($order);
}
if (true === isset($payment) && false === empty($payment)) {
$payment->registerCaptureNotification($invoice->getPrice());
$order->setPayment($payment);
$order_confirmation = \Mage::getStoreConfig('payment/btcpay/order_confirmation');
if($order_confirmation == '1') {
if (!$order->getEmailSent()) {
\Mage::helper('btcpay')->debugData('[INFO] In Btcpay_Core_IpnController::indexAction(), Order email not sent so I am calling $order->sendNewOrderEmail() now...');
$order->sendNewOrderEmail();
}
else
{
\Mage::helper('btcpay')->debugData('[INFO] Plugin configured to send order confirmation, but order confirmation already sent.');
}
}
else {
\Mage::helper('btcpay')->debugData('[INFO] Plugin configured to not send order confirmation.');
}
$order->save();
}
else {
\Mage::helper('btcpay')->debugData('[ERROR] In Btcpay_Core_IpnController::indexAction(), Could not create a payment object in the Btcpay IPN controller.');
\Mage::throwException('Could not create a payment object in the Btcpay IPN controller.');
}
}
}
}

View File

@ -10,16 +10,16 @@
<resources>
<admin>
<children>
<bitpay translate="title" module="bitpay">
<title>BitPay</title>
</bitpay>
<btcpay translate="title" module="btcpay">
<title>BtcPayServer</title>
</btcpay>
<system>
<children>
<config>
<children>
<bitpay translate="title" module="bitpay">
<title>BitPay Settings</title>
</bitpay>
<btcpay translate="title" module="btcpay">
<title>BtcPayServer Settings</title>
</btcpay>
</children>
</config>
</children>
@ -30,18 +30,18 @@
</acl>
<layout>
<updates>
<bitpay>
<file>bitpay.xml</file>
</bitpay>
<btcpay>
<file>btcpay.xml</file>
</btcpay>
</updates>
</layout>
<translate>
<modules>
<bitpay>
<btcpay>
<files>
<default>Bitpay_Core.csv</default>
<default>Btcpay_Core.csv</default>
</files>
</bitpay>
</btcpay>
</modules>
</translate>
</config>

View File

@ -0,0 +1,153 @@
<?xml version="1.0"?>
<!--
/**
* @license Copyright 2011-2018 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
-->
<config>
<modules>
<Btcpay_Core>
<version>2.1.20</version>
</Btcpay_Core>
</modules>
<frontend>
<routers>
<btcpay>
<use>standard</use>
<args>
<module>Btcpay_Core</module>
<frontName>btcpay</frontName>
</args>
</btcpay>
</routers>
<layout>
<updates>
<btcpay>
<file>btcpay.xml</file>
</btcpay>
</updates>
</layout>
<translate>
<modules>
<btcpay>
<files>
<default>Btcpay_Core.csv</default>
</files>
</btcpay>
</modules>
</translate>
</frontend>
<admin>
<routers>
<adminhtml>
<args>
<modules>
<btcpay before="Mage_Adminhtml">Btcpay_Core_Adminhtml</btcpay>
</modules>
</args>
</adminhtml>
</routers>
</admin>
<global>
<blocks>
<btcpay>
<class>Btcpay_Core_Block</class>
</btcpay>
</blocks>
<helpers>
<btcpay>
<class>Btcpay_Core_Helper</class>
</btcpay>
</helpers>
<models>
<btcpay>
<class>Btcpay_Core_Model</class>
<resourceModel>btcpay_mysql4</resourceModel>
</btcpay>
<btcpay_mysql4>
<class>Btcpay_Core_Model_Mysql4</class>
<entities>
<invoice>
<table>btcpay_invoices</table>
</invoice>
<ipn>
<table>btcpay_ipns</table>
</ipn>
</entities>
</btcpay_mysql4>
<sales>
<rewrite>
<order_payment>Btcpay_Core_Model_Order_Payment</order_payment>
</rewrite>
</sales>
</models>
<events>
<sales_order_place_before>
<observers>
<auto_invoice_order>
<type>singleton</type>
<class>Btcpay_Core_Model_Observer</class>
<method>implementOrderStatus</method>
</auto_invoice_order>
</observers>
</sales_order_place_before>
<checkout_onepage_controller_success_action>
<observers>
<btcpay_checkout_onepage_success_observer>
<type>singleton</type>
<class>Btcpay_Core_Model_Observer</class>
<method>redirectToCartIfExpired</method>
</btcpay_checkout_onepage_success_observer>
</observers>
</checkout_onepage_controller_success_action>
</events>
<resources>
<btcpay_write>
<connection>
<use>core_write</use>
</connection>
</btcpay_write>
<btcpay_read>
<connection>
<use>core_read</use>
</connection>
</btcpay_read>
<btcpay_setup>
<setup>
<module>Btcpay_Core</module>
<class>Btcpay_Core_Model_Resource_Mysql4_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</btcpay_setup>
</resources>
</global>
<default>
<payment>
<btcpay>
<model>btcpay/method_bitcoin</model>
<order_status>new</order_status>
<payment_action>authorize</payment_action>
<active>0</active>
<title>Bitcoin</title>
<api_key>test</api_key>
<network>https://btcpayjungle.com</network>
<order_confirmation>1</order_confirmation>
<debug>0</debug>
<notification_url>btcpay/ipn</notification_url>
<redirect_url>checkout/onepage/success</redirect_url>
<failure_url>checkout/cart</failure_url>
<speed>medium</speed>
<invoice_new>new</invoice_new>
<invoice_paid>pending</invoice_paid>
<invoice_confirmed>processing</invoice_confirmed>
<invoice_complete>processing</invoice_complete>
<invoice_expired>canceled</invoice_expired>
<invoice_invalid>pending</invoice_invalid>
</btcpay>
</payment>
</default>
</config>

View File

@ -1,7 +1,7 @@
<?xml version="1.0"?>
<!--
/**
* @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
*/
-->
@ -9,17 +9,17 @@
<sections>
<payment>
<groups>
<bitpay translate="label" module="bitpay">
<label>Bitpay</label>
<btcpay translate="label" module="btcpay">
<label>Btcpay</label>
<sort_order>670</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
<fields>
<header>
<label>BitPay</label>
<label>BTCPay</label>
<frontend_class>complex</frontend_class>
<frontend_model>bitpay/adminhtml_system_config_form_field_header</frontend_model>
<frontend_model>btcpay/adminhtml_system_config_form_field_header</frontend_model>
<sort_order>0</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
@ -28,11 +28,10 @@
<pairing_code translate="label">
<label>Pairing Code</label>
<comment>
<![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
that code here. Once you have successfully paired this Magento store with your BitPay Merchant account, you can begin accepting Bitcoins as payment.]]>
<![CDATA[You must first create a pairing code for your BTCPay Merchant account.]]>
</comment>
<frontend_type>text</frontend_type>
<backend_model>bitpay/config_pairingCode</backend_model>
<backend_model>btcpay/config_pairingCode</backend_model>
<sort_order>1</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
@ -59,12 +58,11 @@
<show_in_store>1</show_in_store>
</title>
<network translate="label">
<label>Network</label>
<label>BtcPayServer Url</label>
<comment>
<![CDATA[You can sign up for a test account at <a href="https://test.bitpay.com" target="_blank">test.bitpay.com</a>.]]>
<![CDATA[A BtcPayServer host url]]>
</comment>
<frontend_type>select</frontend_type>
<source_model>bitpay/network</source_model>
<frontend_type>text</frontend_type>
<sort_order>30</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
@ -98,28 +96,85 @@
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</redirect_url>
<fullscreen translate="label">
<label>Redirect Checkout</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>2</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</fullscreen>
<speed translate="label">
<label>Transaction Speed</label>
<frontend_type>select</frontend_type>
<source_model>bitpay/transactionSpeed</source_model>
<failure_url translate="label">
<label>Failure URL</label>
<frontend_type>text</frontend_type>
<sort_order>60</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</failure_url>
<invoice>
<label>Invoice Settings</label>
<frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
<sort_order>70</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</invoice>
<invoice_paid translate="label">
<label>Paid</label>
<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.]]>
<![CDATA[An invoice is considered "paid" when the Bitcoin network sees a transaction.]]>
</comment>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_order_status</source_model>
<sort_order>71</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</invoice_paid>
<invoice_confirmed translate="label">
<label>Confirmed</label>
<comment>
<![CDATA[A confirmed invoice means that the Bitcoin network has approved the transaction.]]>
</comment>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_order_status</source_model>
<sort_order>72</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</invoice_confirmed>
<invoice_complete translate="label">
<label>Complete</label>
<comment>
<![CDATA[A completed BTCPay invoice indicates the payment for the invoice has been fully confirmed by the Bitcoin network and the funds have been deposited into your BTCPay Merchant account.]]>
</comment>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_order_status</source_model>
<sort_order>73</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</invoice_complete>
<speed translate="label">
<label>Transaction Speed</label>
<frontend_type>select</frontend_type>
<source_model>btcpay/transactionSpeed</source_model>
<sort_order>74</sort_order>
<show_in_default>0</show_in_default>
<show_in_website>0</show_in_website>
<show_in_store>0</show_in_store>
<comment>
<![CDATA[Determines when a BTCPay 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>
<mage_settings_heading>
<order_confirmation translate="label">
<label>Send Magento order confirmation email</label>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<sort_order>70</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
</order_confirmation>
<mage_settings_heading>
<label>Magento Specific Settings</label>
<frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
<sort_order>75</sort_order>
@ -140,7 +195,7 @@
<label>Payment from Specific Countries</label>
<frontend_type>multiselect</frontend_type>
<sort_order>77</sort_order>
<source_model>adminhtml/system_config_source_country</source_model>
<source_model>btcpay/specificCountry</source_model>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>0</show_in_store>
@ -170,50 +225,7 @@
<show_in_store>0</show_in_store>
<frontend_class>validate-number</frontend_class>
</sort_order>
<invoice>
<label>Invoice Settings</label>
<frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
<sort_order>100</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</invoice>
<invoice_paid translate="label">
<label>Paid</label>
<comment>
<![CDATA[An invoice is considered "paid" when the Bitcoin network sees a transaction.]]>
</comment>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_order_status</source_model>
<sort_order>120</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</invoice_paid>
<invoice_confirmed translate="label">
<label>Confirmed</label>
<comment>
<![CDATA[A confirmed invoice means that the Bitcoin network has approved the transaction.]]>
</comment>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_order_status</source_model>
<sort_order>130</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</invoice_confirmed>
<invoice_complete translate="label">
<label>Complete</label>
<comment>
<![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.]]>
</comment>
<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_order_status</source_model>
<sort_order>140</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</invoice_complete>
<requirements>
<label>Requirements</label>
<frontend_model>adminhtml/system_config_form_field_heading</frontend_model>
@ -228,14 +240,14 @@
<has_openssl>
<label>OpenSSL</label>
<php_extension>openssl</php_extension>
<frontend_model>bitpay/adminhtml_system_config_form_field_extension</frontend_model>
<frontend_model>btcpay/adminhtml_system_config_form_field_extension</frontend_model>
<sort_order>510</sort_order>
<show_in_default>1</show_in_default>
<show_in_website>1</show_in_website>
<show_in_store>1</show_in_store>
</has_openssl>
</fields>
</bitpay>
</btcpay>
</groups>
</payment>
</sections>

View File

@ -8,9 +8,9 @@ $this->startSetup();
/**
* IPN Log Table, used to keep track of incoming IPNs
*/
$this->run(sprintf('DROP TABLE IF EXISTS `%s`;', $this->getTable('bitpay/ipn')));
$this->run(sprintf('DROP TABLE IF EXISTS `%s`;', $this->getTable('btcpay/ipn')));
$ipnTable = new Varien_Db_Ddl_Table();
$ipnTable->setName($this->getTable('bitpay/ipn'));
$ipnTable->setName($this->getTable('btcpay/ipn'));
$ipnTable->addColumn('id', Varien_Db_Ddl_Table::TYPE_INTEGER, 11, array('auto_increment' => true, 'nullable' => false, 'primary' => true,));
$ipnTable->addColumn('invoice_id', Varien_Db_Ddl_Table::TYPE_TEXT, 200);
$ipnTable->addColumn('url', Varien_Db_Ddl_Table::TYPE_TEXT, 400);
@ -34,9 +34,9 @@ $this->getConnection()->createTable($ipnTable);
* Table used to keep track of invoices that have been created. The
* IPNs that are received are used to update this table.
*/
$this->run(sprintf('DROP TABLE IF EXISTS `%s`;', $this->getTable('bitpay/invoice')));
$this->run(sprintf('DROP TABLE IF EXISTS `%s`;', $this->getTable('btcpay/invoice')));
$invoiceTable = new Varien_Db_Ddl_Table();
$invoiceTable->setName($this->getTable('bitpay/invoice'));
$invoiceTable->setName($this->getTable('btcpay/invoice'));
$invoiceTable->addColumn('id', Varien_Db_Ddl_Table::TYPE_TEXT, 64, array('nullable' => false, 'primary' => true));
$invoiceTable->addColumn('quote_id', Varien_Db_Ddl_Table::TYPE_INTEGER, 11);
$invoiceTable->addColumn('increment_id', Varien_Db_Ddl_Table::TYPE_INTEGER, 11);

View File

@ -11,6 +11,6 @@ $this->startSetup();
* Fixes `curent_time` typo
*/
$ipnTable = new Varien_Db_Ddl_Table();
$this->getConnection()->changeColumn($this->getTable('bitpay/ipn'), 'curent_time', 'current_time', array('type' => Varien_Db_Ddl_Table::TYPE_INTEGER));
$this->getConnection()->changeColumn($this->getTable('btcpay/ipn'), 'curent_time', 'current_time', array('type' => Varien_Db_Ddl_Table::TYPE_INTEGER));
$this->endSetup();

View File

@ -8,9 +8,9 @@
* @see Bitpay_Core_Block_Info
*/
echo '<h3>Ordered with BitPay</h3>';
echo '<h3>Ordered with BTCPay Server</h3>';
if ($url = $this->getBitpayInvoiceUrl()) {
if ($url = $this->getBtcpayInvoiceUrl()) {
echo '<p><a href="' . $url . '" target="_blank">View Invoice</a></p>';
}

View File

@ -9,7 +9,7 @@
*/
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" />' .
'<img src="https://github.com/btcpayserver/btcpayserver/raw/master/BTCPayServer/wwwroot/img/btc_pay_BG_twitter.png" alt="BTCPayServer" 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>' .

View File

@ -8,7 +8,7 @@
<layout>
<checkout_onepage_review>
<reference name="checkout.onepage.review.info.items.after">
<block name="iframe" type="bitpay/iframe"/>
<block name="iframe" type="btcpay/iframe"/>
</reference>
</checkout_onepage_review>
</layout>

View File

@ -1,17 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
/**
* @see Bitpay_Core_Block_Form_Bitpay
*/
$_code = $this->getMethodCode();
if (Mage::getStoreConfig('payment/bitpay/fullscreen')) {
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>';
}
?>

View File

@ -1,49 +0,0 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
$url = $this->getIframeUrl();
switch($url) {
case 'notbitpay':
break; // customer is using another payment method
case 'paid':
echo 'Order payment received. Place Order to complete.';
break;
case 'disabled':
echo 'Please click Place Order to continue to bitpay.com.';
break;
case false:
echo 'Error creating invoice. Please try again or try another payment solution.';
break;
default:
echo '<iframe src="'.$url.'" style="width:500px; height:150px; overflow:hidden; border:none; margin:auto; display:block;" scrolling="no" allowtransparency="true" frameborder="0"> </iframe>';
break;
}
$quoteId = $this->getQuote()->getId();
$request = Mage::app()->getRequest();
$url = Mage::getUrl('bitpay/index/index/');
if ($request->getScheme() == 'https') {
$url = str_replace('http://', 'https://', $url);
}
?>
<script type="text/javascript">
//<![CDATA[
new PeriodicalExecuter(function() {
new Ajax.Request(
"<?php echo $url . '?quote=' . $quoteId; ?>",
{
asynchronous: true,
evalScripts: true,
onComplete: function(request, json) {
var data = request.responseText.evalJSON();
if (data.paid) {
review.save();
}
}
}
);
}, 5);
//]]>
</script>

View File

@ -0,0 +1,17 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
/**
* @see Btcpay_Core_Block_Form_Btcpay
*/
$_code = $this->getMethodCode();
echo '<ul class="form-list" id="payment_form_' . $_code . '" style="display:none;">' .
'<li>You will be transfered to the payment provider to complete your purchase when using this payment method.</li>' .
'</ul>';
?>

View File

@ -0,0 +1,94 @@
<?php
/**
* @license Copyright 2011-2016 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
$url = $this->getIframeUrl();
switch($url) {
case 'notbtcpay':
echo 'Order selected using a different payment method than BTC Pay';
break; // customer is using another payment method
case 'paid':
echo 'Order payment received. Place Order to complete.';
break;
case 'redirect':
echo 'Please click Place Order to continue to pay via BTC Pay.';
break;
case false:
echo 'Error creating invoice. Please try again or try another payment solution.';
break;
default:
// display the BTC pay invoice in an iframe. Currently only 'redirect' is supported, so the below will not be executed
echo '<div class="btcpay_invoice_div" style="display:none; width:100%;"></div>';
break;
}
$quoteId = $this->getQuote()->getId();
$request = Mage::app()->getRequest();
$url = Mage::getUrl('btcpay/index/index/');
if ($request->getScheme() == 'https') {
$url = str_replace('http://', 'https://', $url);
}
?>
<script type="text/javascript">
//<![CDATA[
if ($$('div.btcpay_invoice_div').length > 0) {
var bpListener = {
nextStep: function(transport) {
if (transport && transport.responseText) {
try{
response = eval('(' + transport.responseText + ')');
}
catch (e) {
response = {};
}
if (response.success) {
$$('button.btn-checkout')[0].setStyle({display:'none'});
var invoice_div = $$('div.btcpay_invoice_div')[0];
invoice_div.setStyle({display:'block'});
invoice_div.innerHTML = '<iframe class="btcpay_invoice_iframe" src="' + response.redirect + '" style="width:500px; height:150px; overflow:hidden; border:none; display:block; margin:auto; scrolling="no" allowtransparency="true" frameborder="0"></iframe>';
var ipnPoller = new PeriodicalExecuter(function() {
new Ajax.Request("<?php echo $url . '?quote=' . $quoteId; ?>",
{
asynchronous: true,
evalScripts: true,
onComplete: function(request) {
var data = request.responseText.evalJSON();
if (data.paid) {
ipnPoller.stop();
response.redirect = null;
}
}
});
}, 5);
} else {
var msg = response.error_messages;
if (typeof(msg)=='object') {
msg = msg.join("\n");
}
if (msg) {
alert(msg);
}
}
if (response.update_section) {
$('checkout-'+response.update_section.name+'-load').update(response.update_section.html);
}
if (response.goto_section) {
checkout.gotoSection(response.goto_section, true);
}
}
}
};
var reviewCheck = new PeriodicalExecuter(function() {
if (review) {
reviewCheck.stop();
var originalSaveHandler = review.onSave;
review.onSave = bpListener.nextStep.bindAsEventListener(review);
}
}, 1);
}
//]]>
</script>

View File

@ -1,7 +1,8 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
* @see
*/
?>
{

View File

@ -7,12 +7,12 @@
-->
<config>
<modules>
<Bitpay_Core>
<Btcpay_Core>
<active>true</active>
<codePool>community</codePool>
<depends>
<Mage_Payment />
</depends>
</Bitpay_Core>
</Btcpay_Core>
</modules>
</config>

View File

@ -11,5 +11,4 @@
"Low","Low"
"Medium","Medium"
"High","High"
"Livenet","Livenet"
"Testnet","Testnet"
1 Enabled Enabled
11 Low Low
12 Medium Medium
13 High High
14
Testnet Testnet

View File

@ -5,7 +5,7 @@
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
-->
<project name="bitpay/magento-plugin" default="build">
<project name="btcpay/magento-plugin" default="build">
<!--
Default properties
-->
@ -243,15 +243,15 @@
environment. This should closely follow the `modman` file.
-->
<target name="plugin:symlink" hidden="true">
<mkdir dir="${project.basedir}/build/magento/app/code/community/Bitpay" />
<mkdir dir="${project.basedir}/build/magento/app/code/community/btcpay" />
<mkdir dir="${project.basedir}/build/magento/app/design/frontend/base/default/layout" />
<mkdir dir="${project.basedir}/build/magento/app/design/frontend/base/default/template" />
<mkdir dir="${project.basedir}/build/magento/app/etc/modules" />
<mkdir dir="${project.basedir}/build/magento/lib" />
<mkdir dir="${project.basedir}/build/magento/shell" />
<symlink
target="${project.basedir}/app/code/community/Bitpay/Bitcoins"
link="${project.basedir}/build/magento/app/code/community/Bitpay/Bitcoins"
target="${project.basedir}/app/code/community/btcpay/Bitcoins"
link="${project.basedir}/build/magento/app/code/community/btcpay/Bitcoins"
overwrite="true" />
<symlink
target="${project.basedir}/app/design/frontend/base/default/layout/bitcoins.xml"
@ -262,16 +262,16 @@
link="${project.basedir}/build/magento/app/design/frontend/base/default/template/bitcoins"
overwrite="true" />
<symlink
target="${project.basedir}/app/etc/modules/Bitpay_Bitcoins.xml"
link="${project.basedir}/build/magento/app/etc/modules/Bitpay_Bitcoins.xml"
target="${project.basedir}/app/etc/modules/btcpay_Bitcoins.xml"
link="${project.basedir}/build/magento/app/etc/modules/btcpay_Bitcoins.xml"
overwrite="true" />
<symlink
target="${project.basedir}/lib/bitpay"
link="${project.basedir}/build/magento/lib/bitpay"
target="${project.basedir}/lib/btcpay"
link="${project.basedir}/build/magento/lib/btcpay"
overwrite="true" />
<symlink
target="${project.basedir}/shell/bitpay.php"
link="${project.basedir}/build/magento/shell/bitpay.php"
target="${project.basedir}/shell/btcpay.php"
link="${project.basedir}/build/magento/shell/btcpay.php"
overwrite="true" />
</target>
</project>

View File

@ -1,19 +1,18 @@
{
"name": "bitpay/magento-plugin",
"description": "Bitcoin payment module using the bitpay.com service",
"keywords": ["magento","bitcoin"],
"name": "btcpay/magento-plugin",
"description": "Bitcoin payment module using the btcpay.com service",
"keywords": ["magento","bitcoin", "bitcoin cash"],
"minimum-stability": "stable",
"type": "magento-plugin",
"homepage": "https://github.com/bitpay/magento-plugin",
"homepage": "https://github.com/btcpayserver/magento-plugin",
"license": "MIT",
"support": {
"email": "support@bitpay.com",
"issues": "https://github.com/bitpay/magento-plugin/issues",
"source": "https://github.com/bitpay/magento-plugin"
"email": "support@btcpay.com",
"issues": "https://github.com/btcpayserver/magento-plugin/issues",
"source": "https://github.com/btcpayserver/magento-plugin"
},
"require": {
"composer/installers": "~1.0",
"bitpay/php-client": "dev-master#9027ce67e4b28516ff1ebd1046bdd15c37a7a59f"
"bitpay/php-client": "~2.2"
},
"require-dev": {
"symfony/finder": "~2.3",

View File

@ -0,0 +1,69 @@
<?php
/**
* @license Copyright 2011-2014 BitPay Inc., MIT License
* @see https://github.com/bitpay/magento-plugin/blob/master/LICENSE
*/
namespace Bitpay\Storage;
/**
* This is part of the magento plugin. This is responsible for saving and loading
* keys for magento.
*/
class BtcpayMagentoStorage implements StorageInterface
{
/**
* @var array
*/
protected $_keys;
/**
* @inheritdoc
*/
public function persist(\Bitpay\KeyInterface $key)
{
$this->_keys[$key->getId()] = $key;
$data = serialize($key);
$encryptedData = \Mage::helper('core')->encrypt($data);
$config = new \Mage_Core_Model_Config();
if (true === isset($config) && false === empty($config)) {
$config->saveConfig($key->getId(), $encryptedData);
} else {
\Mage::helper('btcpay')->debugData('[ERROR] In file lib/Bitpay/Storage/BtcpayMagentoStorage.php, class BtcpayMagentoStorage::persist - Could not instantiate a \Mage_Core_Model_Config object.');
throw new \Exception('[ERROR] In file lib/Bitpay/Storage/BtcpayMagentoStorage.php, class BtcpayMagentoStorage::persist - Could not instantiate a \Mage_Core_Model_Config object.');
}
}
/**
* @inheritdoc
*/
public function load($id)
{
if (true === isset($id) && true === isset($this->_keys[$id])) {
return $this->_keys[$id];
}
$entity = \Mage::getStoreConfig($id);
/**
* Not in database
*/
if (false === isset($entity) || true === empty($entity)) {
\Mage::helper('btcpay')->debugData('[INFO] Call to BtcpayMagentoStorage::load($id) with the id of ' . $id . ' did not return the store config parameter because it was not found in the database.');
throw new \Exception('[INFO] Call to BtcpayMagentoStorage::load($id) with the id of ' . $id . ' did not return the store config parameter because it was not found in the database.');
}
$decodedEntity = unserialize(\Mage::helper('core')->decrypt($entity));
if (false === isset($decodedEntity) || true === empty($decodedEntity)) {
\Mage::helper('btcpay')->debugData('[INFO] Call to BtcpayMagentoStorage::load($id) with the id of ' . $id . ' could not decrypt & unserialize the entity ' . $entity . '.');
throw new \Exception('[INFO] Call to BtcpayMagentoStorage::load($id) with the id of ' . $id . ' could not decrypt & unserialize the entity ' . $entity . '.');
}
\Mage::helper('btcpay')->debugData('[INFO] Call to BtcpayMagentoStorage::load($id) with the id of ' . $id . ' successfully decrypted & unserialized the entity ' . $entity . '.');
return $decodedEntity;
}
}

View File

@ -31,7 +31,7 @@ class MagentoStorage implements StorageInterface
if (true === isset($config) && false === empty($config)) {
$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.');
\Mage::helper('btcpay')->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.');
}
}
@ -51,18 +51,18 @@ class MagentoStorage implements StorageInterface
* Not in database
*/
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.');
\Mage::helper('btcpay')->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.');
throw new \Exception('[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.');
}
$decodedEntity = unserialize(\Mage::helper('core')->decrypt($entity));
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 . '.');
\Mage::helper('btcpay')->debugData('[INFO] Call to MagentoStorage::load($id) with the id of ' . $id . ' could not decrypt & unserialize the entity ' . $entity . '.');
throw new \Exception('[INFO] Call to MagentoStorage::load($id) with the id of ' . $id . ' could not decrypt & unserialize the entity ' . $entity . '.');
}
\Mage::helper('bitpay')->debugData('[INFO] Call to MagentoStorage::load($id) with the id of ' . $id . ' successfully decrypted & unserialized the entity ' . $entity . '.');
\Mage::helper('btcpay')->debugData('[INFO] Call to MagentoStorage::load($id) with the id of ' . $id . ' successfully decrypted & unserialized the entity ' . $entity . '.');
return $decodedEntity;
}

23
modman
View File

@ -20,8 +20,21 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
app/code/community/Bitpay/Core app/code/community/Bitpay/Core
app/design/frontend/base/default/layout/bitpay.xml app/design/frontend/base/default/layout/bitpay.xml
app/design/frontend/base/default/template/bitpay app/design/frontend/base/default/template/bitpay
app/etc/modules/Bitpay_Core.xml app/etc/modules/Bitpay_Core.xml
lib/Bitpay lib/Bitpay
# Modman file generated by 'generate-modman'
# app/code
app/code/community/BTCpay/Core app/code/community/BTCpay/Core
# app/etc
app/etc/modules/BTCpay_Core.xml app/etc/modules/BTCpay_Core.xml
# app/locale
app/locale/en_US/BTCpay_Core.csv app/locale/en_US/BTCpay_Core.csv
# app/design
app/design/adminhtml/default/default/template/btcpay/info/default.phtml app/design/adminhtml/default/default/template/btcpay/info/default.phtml
app/design/adminhtml/default/default/template/btcpay/system/config/field/header.phtml app/design/adminhtml/default/default/template/btcpay/system/config/field/header.phtml
app/design/adminhtml/default/default/layout/btcpay.xml app/design/adminhtml/default/default/layout/btcpay.xml
app/design/frontend/base/default/template/btcpay/iframe.phtml app/design/frontend/base/default/template/btcpay/iframe.phtml
app/design/frontend/base/default/template/btcpay/info/default.phtml app/design/frontend/base/default/template/btcpay/info/default.phtml
app/design/frontend/base/default/template/btcpay/json.phtml app/design/frontend/base/default/template/btcpay/json.phtml
app/design/frontend/base/default/template/btcpay/form/btcpay.phtml app/design/frontend/base/default/template/btcpay/form/btcpay.phtml
app/design/frontend/base/default/layout/btcpay.xml app/design/frontend/base/default/layout/btcpay.xml
# lib
lib/BTCpay/Storage/MagentoStorage.php lib/BTCpay/Storage/MagentoStorage.php

View File

@ -1,4 +0,0 @@
[ ] Update version in composer.json file
[ ] Update version in `scripts/package` and run script
[ ] Update CHANGELOG file
[ ] Update to Mangento Connect and GitHub

11
scripts/config.json Normal file
View File

@ -0,0 +1,11 @@
{
"mysql": {
"host": "localhost",
"user": "magento",
"password": "magento",
"database": "magento"
},
"host": "http://127.0.0.1/magento/index.php/bitpay/ipn",
"status": "confirmed"
}

View File

@ -11,11 +11,11 @@ date_default_timezone_set('America/New_York'); // Main Office is in Eastern Time
/**
* Various Configuration Settings
*/
$version = '2.1.9';
$version = '2.1.20';
$vendorDir = __DIR__ . '/../vendor';
$distDir = __DIR__ . '/../build/dist';
$tmpDistDir = $distDir . '/tmp'; // Files will be placed here temporarly so we can zip/tar them.
$distFile = $distDir . '/Bitpay_Core-'.$version; // Without extension
$distFile = $distDir . '/Btcpay_Core-'.$version; // Without extension
require_once $vendorDir . '/autoload.php';
@ -51,99 +51,23 @@ foreach ($finder as $file) {
}
$filesystem->mirror('app/', sprintf('%s/app/', $tmpDistDir));
$filesystem->mirror('lib/', sprintf('%s/lib/', $tmpDistDir));
$filesystem->copy('LICENSE', sprintf('%s/app/code/community/Bitpay/Core/LICENSE', $tmpDistDir));
$filesystem->copy('README.md', sprintf('%s/app/code/community/Bitpay/Core/README.md', $tmpDistDir));
$filesystem->copy('LICENSE', sprintf('%s/app/code/community/BTCpay/Core/LICENSE', $tmpDistDir));
$filesystem->copy('README.md', sprintf('%s/app/code/community/BTCpay/Core/README.md', $tmpDistDir));
// All required files are in the temp. distribution directory
/**
* Need to create the package.xml file required by Magento
*/
$xml = simplexml_load_string('<package/>');
$xml->addChild('name', 'Bitpay_Core');
$xml->addChild('version', $version);
$xml->addChild('stability', 'stable');
$xml->addChild('license', 'MIT')
->addAttribute('uri', 'https://github.com/bitpay/magento-plugin/blob/master/LICENSE');
$xml->addChild('channel', 'community');
$xml->addChild('extends');
$xml->addChild('summary');
$xml->addChild('description');
$xml->addChild('notes');
$authorsNode = $xml->addChild('authors');
$authors = array(
array(
'Integrations Team', // Name
'BitPayInc', // Magento Connect Username
'support@bitpay.com', // Email
),
);
foreach ($authors as $author) {
$authorNode = $authorsNode->addChild('author');
$authorNode->addChild('name', $author[0]);
$authorNode->addChild('user', $author[1]);
$authorNode->addChild('email', $author[2]);
}
$xml->addChild('date', date('Y-m-d'));
$xml->addChild('time', date('G:i:s'));
$xml->addChild('compatible');
$xml->addChild('dependencies');
$requiredNode = $xml->addChild('required', 'php');
$requiredNode->addAttribute('php_min', '5.4.0');
$requiredNode->addAttribute('php_max', '6.0.0');
$extensionsNode = $xml->addChild('extensions');
foreach (array('openssl', 'mcrypt') as $ext) {
$extNode = $extensionsNode->addChild('name', $ext);
$extNode->addChild('min');
$extNode->addChild('max');
}
$targetNode = $xml->addChild('contents')->addChild('target');
$targetNode->addAttribute('name', 'mage');
$finder = new \Symfony\Component\Finder\Finder();
$finder
->files()
->in($tmpDistDir);
foreach ($finder as $file) {
$node = $targetNode;
$directories = explode('/', $file->getRelativePathname());
$filename = array_pop($directories);
for ($i = 1; $i <= count($directories); $i++) {
$dir = $directories[$i - 1];
$nodes = $node->xpath('dir[@name="' . $dir . '"]');
if (count($nodes)) {
$node = array_pop($nodes);
} else {
$node = $node->addChild('dir');
$node->addAttribute('name', $dir);
}
}
$fileNode = $node->addChild('file');
$fileNode->addAttribute('name', $file->getBaseName());
$fileNode->addAttribute('hash', md5_file($file->getRealPath()));
}
$xml->asXml($tmpDistDir . '/package.xml');
// package.xml created, just need to tar/zip everything
// Just need to tar/zip everything
$filesystem->remove($distFile.'.zip');
$filesystem->remove($distFile.'.tgz');
$process = new \Symfony\Component\Process\Process(
sprintf('cd %s; tar -czf %s *', $tmpDistDir, $distFile.'.tgz')
);
$process->run();
$process = new \Symfony\Component\Process\Process(
sprintf('cd %s; zip -r %s *', $tmpDistDir, $distFile.'.zip')
);
$process->run();
// Cleanup

View File

@ -0,0 +1,95 @@
var mysql = require('mysql');
var format = require('string-template');
var query = 'select * from bitpay_invoices where quote_id=(select MAX(quote_id) from bitpay_invoices)';
var spawn = require('child_process').spawn;
var config = require('./config.json');
var data = {};
var connection = mysql.createConnection(config.mysql);
function postIpn() {
connection.connect();
connection.query(query, processRows);
}
function send(curl_args) {
var curl = spawn('curl', curl_args);
var stderr;
curl.stdout.on('data', function(data) {
console.log(data.toString());
});
curl.stderr.on('data', function(data) {
stderr = data;
});
curl.on('close', function(code) {
if (code === 0) {
console.log('curl exited successfully');
} else {
console.log('curl exited with an error: ' + stderr);
}
});
}
function processRows(err, rows, fields) {
if (err) {
throw err;
}
var curl_args = [
'-X', 'POST', '-H',
'Content-Type: application/json',
'-H', "Content-Length: {length}",
'-H', 'Connection: close',
'-H', 'Accept: application/json',
'-d', '',
config.host ];
var convertedKeys = convertNames(fields);
var timeRegExp = new RegExp(/.*Time$/);
for (var i=0; i<convertedKeys.length; i++) {
var rowValue = rows[0][fields[i].name];
if (convertedKeys[i] === 'status') {
data[convertedKeys[i]] = config.status;
} else if (convertedKeys[i].match(timeRegExp)) {
data[convertedKeys[i]] = rowValue * 1000;
}
else {
data[convertedKeys[i]] = rowValue;
}
}
data.buyerFields = {};
data.url = 'https://test.bitpay.com:443/invoice?id=' + rows[0].id;
data.posData = '{\"orderId\":\"' + rows[0].order_id.toString() + '\"}';
data.btcPaid = data.btcPrice;
data.btcDue = '0.000000';
var jsonPayload = JSON.stringify(data);
curl_args[5] = format(curl_args[5], {length: jsonPayload.length});
curl_args[11] = jsonPayload;
connection.end();
send(curl_args);
}
function convertNames(names) {
var ret = [];
if (!names || typeof names !== 'object' || names.length === 0) {
return ret;
}
for (var j = 0; j < names.length; j++) {
var name = names[j].name;
var converted = name[0];
var i = 1;
while (i < (name.length - 1)) {
if (name[i] === '_') {
converted += name[i+1].toUpperCase();
i = i+2;
} else {
converted += name[i];
i++;
}
}
converted += name[name.length-1];
ret.push(converted);
}
return ret;
}
postIpn();