From 319c81467e5e5bebc3d5d688e3b0e8e3098878b1 Mon Sep 17 00:00:00 2001 From: Vincent Pietri Date: Mon, 14 May 2018 15:52:08 +0200 Subject: [PATCH 01/20] mbouchot [TBD-MB] commit after Magento marketplace technical review --- .../Payline/ManagecontractsController.php | 5 ++ .../ManageproductcategoriesController.php | 11 +++- .../Payline/controllers/IndexController.php | 59 +++++++++++-------- .../controllers/UnloggedwalletController.php | 8 ++- .../Monext/Payline/etc/adminhtml.xml | 10 +++- .../community/Monext/Payline/etc/config.xml | 2 +- .../Monext/Payline/lib/paylineSDK.php | 2 +- package.xml | 2 +- 8 files changed, 63 insertions(+), 36 deletions(-) diff --git a/app/code/community/Monext/Payline/controllers/Adminhtml/Payline/ManagecontractsController.php b/app/code/community/Monext/Payline/controllers/Adminhtml/Payline/ManagecontractsController.php index 5778a23..b9e7629 100644 --- a/app/code/community/Monext/Payline/controllers/Adminhtml/Payline/ManagecontractsController.php +++ b/app/code/community/Monext/Payline/controllers/Adminhtml/Payline/ManagecontractsController.php @@ -6,6 +6,11 @@ class Monext_Payline_Adminhtml_Payline_ManagecontractsController extends Mage_Adminhtml_Controller_Action { + protected function _isAllowed() + { + return Mage::getSingleton('admin/session')->isAllowed('payline/contract'); + } + public function indexAction() { $this->_title($this->__('Manage Payline Contracts')); diff --git a/app/code/community/Monext/Payline/controllers/Adminhtml/Payline/ManageproductcategoriesController.php b/app/code/community/Monext/Payline/controllers/Adminhtml/Payline/ManageproductcategoriesController.php index b0ae616..c3e7833 100644 --- a/app/code/community/Monext/Payline/controllers/Adminhtml/Payline/ManageproductcategoriesController.php +++ b/app/code/community/Monext/Payline/controllers/Adminhtml/Payline/ManageproductcategoriesController.php @@ -5,6 +5,11 @@ */ class Monext_Payline_Adminhtml_Payline_ManageproductcategoriesController extends Mage_Adminhtml_Controller_Action { + protected function _isAllowed() + { + return Mage::getSingleton('admin/session')->isAllowed('catalog/payline'); + } + public function indexAction() { $this->_title($this->__('Manage Payline Product Categories')); @@ -27,9 +32,9 @@ public function unassignAction() $data = array('payline_category_id' => -1, 'payline_category_label' => ''); $model->addData($data); try { - $model->setId($rowId)->save(); + $model->setId($rowId)->save(); } catch (Exception $e){ - echo $e->getMessage(); + Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } $this->_redirect('*/*/'); } @@ -73,7 +78,7 @@ public function assignPostAction() try { $model->setId($rowId)->save(); } catch (Exception $e){ - echo $e->getMessage(); + Mage::getSingleton('adminhtml/session')->addError($e->getMessage()); } $this->_redirect('*/*/index'); return; diff --git a/app/code/community/Monext/Payline/controllers/IndexController.php b/app/code/community/Monext/Payline/controllers/IndexController.php index f2effb7..0412a4e 100644 --- a/app/code/community/Monext/Payline/controllers/IndexController.php +++ b/app/code/community/Monext/Payline/controllers/IndexController.php @@ -212,7 +212,7 @@ public function cptAction(){ $token->save(); header("location:" . $result['redirectURL']); - exit(); + return; } else { // Payline error Mage::helper('payline/payment')->updateStock($this->order); $msg = Mage::helper('payline')->__('Error during payment'); @@ -446,7 +446,9 @@ public function walletAction(){ $paylineSDK->setPrivate($privateData); } - if(!isset($_POST['PaRes']) && in_array(Mage::getStoreConfig('payment/PaylineWALLET/wallet_payment_security'), array(Monext_Payline_Helper_Data::WALLET_3DS,Monext_Payline_Helper_Data::WALLET_BOTH))){ + $postData = $this->getRequest()->getPost(); + + if(!isset($postData['PaRes']) && in_array(Mage::getStoreConfig('payment/PaylineWALLET/wallet_payment_security'), array(Monext_Payline_Helper_Data::WALLET_3DS,Monext_Payline_Helper_Data::WALLET_BOTH))){ // customer has to be redirected on ACC for 3DS password filling $verifyEnrollmentRequest = array(); $verifyEnrollmentRequest['version'] = $array['version']; @@ -471,13 +473,14 @@ public function walletAction(){ return; } if($verifyEnrollmentResponse['result']['code'] == '03000'){ - echo "
"; - echo " "; - echo " "; - echo " "; - echo "
"; - echo ""; - return; + $output = "
"; + $output .= " "; + $output .= " "; + $output .= " "; + $output .= "
"; + $output .= ""; + $this->getResponse()->setBody($output); + return; }else{ Mage::helper('payline/payment')->updateStock($this->order); $msgLog='PAYLINE ERROR during verifyEnrollment: '.$verifyEnrollmentResponse['result']['code']. ' ' . $verifyEnrollmentResponse['result']['shortMessage'] . ' ('.$verifyEnrollmentResponse['result']['longMessage'].')'; @@ -491,9 +494,9 @@ public function walletAction(){ } } - if(isset($_POST['PaRes'])){ // back from ACS - $array['3DSecure']['md'] = $_POST['MD']; - $array['3DSecure']['pares'] = $_POST['PaRes']; + if(isset($postData['PaRes'])){ // back from ACS + $array['3DSecure']['md'] = $postData['MD']; + $array['3DSecure']['pares'] = $postData['PaRes']; } try{ @@ -637,7 +640,7 @@ public function nxAction(){ $this->order->setState(Mage_Sales_Model_Order::STATE_NEW, $initStatus, '', false); $this->order->save(); header("location:" . $result['redirectURL']); - exit(); + return; } else { Mage::helper('payline/payment')->updateStock($this->order); if (isset($result) && is_array($result)) { @@ -767,15 +770,16 @@ public function cptReturnAction(){ $tokenModel = Mage::getModel('payline/token')->getCollection()->addFieldToFilter('token',$paylineToken); $tokenData = $tokenModel->getFirstItem()->getData(); + $queryData = $this->getRequest()->getQuery(); // Order is loaded from id associated to the token if(sizeof($tokenData) == 0){ - Mage::helper('payline/logger')->log('[cptReturnAction] - token '.$_GET['token'].' is unknown'); + Mage::helper('payline/logger')->log('[cptReturnAction] - token '.$queryData['token'].' is unknown'); return; } $this->order = Mage::getModel('sales/order')->loadByIncrementId($tokenData['order_id']); - if(!in_array($tokenData['status'],array(0,3)) && !isset($_GET['force_upd'])){ // order update is already done => exit this function - if(isset($_GET['notificationType'])) return; // call from notify URL => no page to display + if(!in_array($tokenData['status'],array(0,3)) && !isset($queryData['force_upd'])){ // order update is already done => exit this function + if(isset($queryData['notificationType'])) return; // call from notify URL => no page to display $acceptedCodes = array( '00000', // Credit card -> Transaction approved @@ -886,7 +890,7 @@ public function cptReturnAction(){ return; } $this->order->save(); - if(isset($_GET['notificationType'])) return; // call from notify URL => no page to display + if(isset($queryData['notificationType'])) return; // call from notify URL => no page to display $this->_redirectUrl($redirectUrl); } @@ -902,7 +906,8 @@ public function nxReturnAction(){ * Save NX payment result, called by the bank when the transaction is done */ public function nxNotifAction(){ - $res = Mage::helper('payline')->initPayline('NX')->getWebPaymentDetails(array('token' => $_GET['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); + $queryData = $this->getRequest()->getQuery(); + $res = Mage::helper('payline')->initPayline('NX')->getWebPaymentDetails(array('token' => $queryData['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); if (isset($res['privateDataList']['privateData']['value'])) { $orderRef = $res['privateDataList']['privateData']['value']; } else { @@ -986,18 +991,19 @@ public function nxNotifAction(){ */ public function nxTermNotifAction() { + $queryData = $this->getRequest()->getQuery(); $statusScheduleAlert = Mage::getStoreConfig('payment/PaylineNX/status_when_payline_schedule_alert'); $statusCCExpired = Mage::getStoreConfig('payment/PaylineNX/status_when_credit_card_schedule_is_expired'); if (! empty($statusScheduleAlert) || ! empty($statusCCExpired)) { - if ($this->isNxTermParamsOk($_GET)) { + if ($this->isNxTermParamsOk($queryData)) { /* * BILL = value required for terms notifications * WEBTRS = value for cash web payment */ - if ($_GET['notificationType'] == 'BILL') { // + if ($queryData['notificationType'] == 'BILL') { // $transactionParams = array(); - $transactionParams['transactionId'] = $_GET['transactionId']; - $transactionParams['orderRef'] = $_GET['orderRef']; + $transactionParams['transactionId'] = $queryData['transactionId']; + $transactionParams['orderRef'] = $queryData['orderRef']; $transactionParams['version'] = Monext_Payline_Helper_Data::VERSION; $transactionParams['startDate'] = ''; $transactionParams['endDate'] = ''; @@ -1018,12 +1024,12 @@ public function nxTermNotifAction() break; case '02501': // payment card will expire if (! empty($statusScheduleAlert)) { - $this->order = $this->setOrderStatus($statusScheduleAlert, $_GET['orderRef']); + $this->order = $this->setOrderStatus($statusScheduleAlert, $queryData['orderRef']); break; } default: // if default => error (cc expired or other errors) if (! empty($statusCCExpired)) { - $this->order = $this->setOrderStatus($statusCCExpired, $_GET['orderRef']); + $this->order = $this->setOrderStatus($statusCCExpired, $queryData['orderRef']); } else { $mustSave = false; } @@ -1092,7 +1098,8 @@ private function setOrderStatus($status, $orderRef) * Cancel a NX payment request /order */ public function nxCancelAction(){ - $res = Mage::helper('payline')->initPayline('NX')->getWebPaymentDetails(array('token' => $_GET['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); + $queryData = $this->getRequest()->getQuery(); + $res = Mage::helper('payline')->initPayline('NX')->getWebPaymentDetails(array('token' => $queryData['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); if (isset($res['privateDataList']['privateData']['value'])) { $orderRef = $res['privateDataList']['privateData']['value']; } else { @@ -1189,7 +1196,7 @@ public function waitingOrderUpdateAction(){ $tokenCollection = Mage::getModel('payline/token')->getCollection()->addFieldToFilter('status',3); // 3 stands 'pending payment result' status foreach($tokenCollection as $token) { $this->getRequest()->setParam('token', $token->getToken()); - $_GET['notificationType'] = 'WAITUPD'; // force notificationType param to prevent cptReturnAction to display customer result page + $this->getRequest()->setQuery('notificationType', 'WAITUPD'); // force notificationType param to prevent cptReturnAction to display customer result page $this->cptReturnAction(); } } diff --git a/app/code/community/Monext/Payline/controllers/UnloggedwalletController.php b/app/code/community/Monext/Payline/controllers/UnloggedwalletController.php index 64c5f8f..46b32a8 100644 --- a/app/code/community/Monext/Payline/controllers/UnloggedwalletController.php +++ b/app/code/community/Monext/Payline/controllers/UnloggedwalletController.php @@ -11,7 +11,8 @@ class Monext_Payline_UnloggedwalletController extends Mage_Core_Controller_Front * New subscription notification */ public function subscribeNotifyAction(){ - $res = Mage::helper('payline')->initPayline('WALLET')->getWebWallet(array('token' => $_GET['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); + $queryData = $this->getRequest()->getQuery(); + $res = Mage::helper('payline')->initPayline('WALLET')->getWebWallet(array('token' => $queryData['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); $redirectUrl="payline/wallet/manage"; if (!isset($res['result']) || $res['result']['code']!='02500'){ if(isset($res['result'])){ @@ -68,8 +69,9 @@ public function subscribeCancelAction(){ * New subscription notification */ public function updateNotifyAction(){ - $customerData = Mage::getSingleton('customer/session')->getCustomer()->getData(); - Mage::helper('payline')->initPayline('WALLET')->getWebWallet(array('token' => $_GET['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); // appel sans traitement pour désactiver la notification + $queryData = $this->getRequest()->getQuery(); + $customerData = Mage::getSingleton('customer/session')->getCustomer()->getData(); + Mage::helper('payline')->initPayline('WALLET')->getWebWallet(array('token' => $queryData['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); // appel sans traitement pour d�sactiver la notification $res = Mage::helper('payline')->initPayline('WALLET')->getCards(array('contractNumber' => $customerData['wallet_contract_number'], 'walletId' => $customerData['wallet_id'])); $redirectUrl="payline/wallet/manage"; if ($res['result']['code']!='02500'){ diff --git a/app/code/community/Monext/Payline/etc/adminhtml.xml b/app/code/community/Monext/Payline/etc/adminhtml.xml index 6cb3197..4357fc3 100644 --- a/app/code/community/Monext/Payline/etc/adminhtml.xml +++ b/app/code/community/Monext/Payline/etc/adminhtml.xml @@ -42,12 +42,20 @@ - + Manage Payline Product Categories 10 + + + + Manage Payline Contracts + 10 + + + diff --git a/app/code/community/Monext/Payline/etc/config.xml b/app/code/community/Monext/Payline/etc/config.xml index 169d55a..0b32112 100644 --- a/app/code/community/Monext/Payline/etc/config.xml +++ b/app/code/community/Monext/Payline/etc/config.xml @@ -2,7 +2,7 @@ - 1.8.5.6 + 1.8.5.7 diff --git a/app/code/community/Monext/Payline/lib/paylineSDK.php b/app/code/community/Monext/Payline/lib/paylineSDK.php index 11ac797..48dd59a 100644 --- a/app/code/community/Monext/Payline/lib/paylineSDK.php +++ b/app/code/community/Monext/Payline/lib/paylineSDK.php @@ -411,7 +411,7 @@ public function write($message) { class paylineSDK{ // kit version - const KIT_VERSION = 'module Magento 1.8.5.6'; + const KIT_VERSION = 'module Magento 1.8.5.7'; // trace log var $logger; diff --git a/package.xml b/package.xml index d4fcacd..137253c 100644 --- a/package.xml +++ b/package.xml @@ -1,7 +1,7 @@ Payline - 1.8.5.6 + 1.8.5.7 stable GNU General Public License (GPL) community From a0135ecdee10b33aa542272bb097765820d4848a Mon Sep 17 00:00:00 2001 From: Vincent Pietri Date: Mon, 14 May 2018 16:09:20 +0200 Subject: [PATCH 02/20] Move adminhtml design files --- .../default/layout/payline.xml | 0 .../default/template/payline/Cpt.phtml | 0 .../default/template/payline/Direct.phtml | 0 .../default/template/payline/Payline.phtml | 0 .../payline/assignProductCategories.phtml | 0 .../default/template/payline/contracts.phtml | 0 .../template/payline/customer/tab/view.phtml | 0 .../payline/payment/info/monext.phtml | 0 .../template/payline/productcategories.phtml | 0 .../default/template/payline/switcher.phtml | 0 .../system/config/fieldset/welcome.phtml | 92 +++++++++---------- .../system/config/form/field/array.phtml | 0 .../template/payline/wallet/form.phtml | 0 13 files changed, 46 insertions(+), 46 deletions(-) rename app/design/adminhtml/{base => default}/default/layout/payline.xml (100%) rename app/design/adminhtml/{base => default}/default/template/payline/Cpt.phtml (100%) rename app/design/adminhtml/{base => default}/default/template/payline/Direct.phtml (100%) rename app/design/adminhtml/{base => default}/default/template/payline/Payline.phtml (100%) rename app/design/adminhtml/{base => default}/default/template/payline/assignProductCategories.phtml (100%) rename app/design/adminhtml/{base => default}/default/template/payline/contracts.phtml (100%) rename app/design/adminhtml/{base => default}/default/template/payline/customer/tab/view.phtml (100%) rename app/design/adminhtml/{base => default}/default/template/payline/payment/info/monext.phtml (100%) rename app/design/adminhtml/{base => default}/default/template/payline/productcategories.phtml (100%) rename app/design/adminhtml/{base => default}/default/template/payline/switcher.phtml (100%) rename app/design/adminhtml/{base => default}/default/template/payline/system/config/fieldset/welcome.phtml (90%) rename app/design/adminhtml/{base => default}/default/template/payline/system/config/form/field/array.phtml (100%) rename app/design/adminhtml/{base => default}/default/template/payline/wallet/form.phtml (100%) diff --git a/app/design/adminhtml/base/default/layout/payline.xml b/app/design/adminhtml/default/default/layout/payline.xml similarity index 100% rename from app/design/adminhtml/base/default/layout/payline.xml rename to app/design/adminhtml/default/default/layout/payline.xml diff --git a/app/design/adminhtml/base/default/template/payline/Cpt.phtml b/app/design/adminhtml/default/default/template/payline/Cpt.phtml similarity index 100% rename from app/design/adminhtml/base/default/template/payline/Cpt.phtml rename to app/design/adminhtml/default/default/template/payline/Cpt.phtml diff --git a/app/design/adminhtml/base/default/template/payline/Direct.phtml b/app/design/adminhtml/default/default/template/payline/Direct.phtml similarity index 100% rename from app/design/adminhtml/base/default/template/payline/Direct.phtml rename to app/design/adminhtml/default/default/template/payline/Direct.phtml diff --git a/app/design/adminhtml/base/default/template/payline/Payline.phtml b/app/design/adminhtml/default/default/template/payline/Payline.phtml similarity index 100% rename from app/design/adminhtml/base/default/template/payline/Payline.phtml rename to app/design/adminhtml/default/default/template/payline/Payline.phtml diff --git a/app/design/adminhtml/base/default/template/payline/assignProductCategories.phtml b/app/design/adminhtml/default/default/template/payline/assignProductCategories.phtml similarity index 100% rename from app/design/adminhtml/base/default/template/payline/assignProductCategories.phtml rename to app/design/adminhtml/default/default/template/payline/assignProductCategories.phtml diff --git a/app/design/adminhtml/base/default/template/payline/contracts.phtml b/app/design/adminhtml/default/default/template/payline/contracts.phtml similarity index 100% rename from app/design/adminhtml/base/default/template/payline/contracts.phtml rename to app/design/adminhtml/default/default/template/payline/contracts.phtml diff --git a/app/design/adminhtml/base/default/template/payline/customer/tab/view.phtml b/app/design/adminhtml/default/default/template/payline/customer/tab/view.phtml similarity index 100% rename from app/design/adminhtml/base/default/template/payline/customer/tab/view.phtml rename to app/design/adminhtml/default/default/template/payline/customer/tab/view.phtml diff --git a/app/design/adminhtml/base/default/template/payline/payment/info/monext.phtml b/app/design/adminhtml/default/default/template/payline/payment/info/monext.phtml similarity index 100% rename from app/design/adminhtml/base/default/template/payline/payment/info/monext.phtml rename to app/design/adminhtml/default/default/template/payline/payment/info/monext.phtml diff --git a/app/design/adminhtml/base/default/template/payline/productcategories.phtml b/app/design/adminhtml/default/default/template/payline/productcategories.phtml similarity index 100% rename from app/design/adminhtml/base/default/template/payline/productcategories.phtml rename to app/design/adminhtml/default/default/template/payline/productcategories.phtml diff --git a/app/design/adminhtml/base/default/template/payline/switcher.phtml b/app/design/adminhtml/default/default/template/payline/switcher.phtml similarity index 100% rename from app/design/adminhtml/base/default/template/payline/switcher.phtml rename to app/design/adminhtml/default/default/template/payline/switcher.phtml diff --git a/app/design/adminhtml/base/default/template/payline/system/config/fieldset/welcome.phtml b/app/design/adminhtml/default/default/template/payline/system/config/fieldset/welcome.phtml similarity index 90% rename from app/design/adminhtml/base/default/template/payline/system/config/fieldset/welcome.phtml rename to app/design/adminhtml/default/default/template/payline/system/config/fieldset/welcome.phtml index eb495f2..3e0d6c4 100644 --- a/app/design/adminhtml/base/default/template/payline/system/config/fieldset/welcome.phtml +++ b/app/design/adminhtml/default/default/template/payline/system/config/fieldset/welcome.phtml @@ -1,46 +1,46 @@ - -
- - - -
- -
- __('Welcome in the Payline configuration payment center for Magento'); ?> -
-
-
- __('Need help? contact us')?> -
support@payline.com -
-
-
- -
- getVersion()): ?> - __('Module version: %s', $this->getVersion()); ?> - - - getRelease()): ?> - __('(release: %s)', $this->getRelease()); ?> - -
- - - -
- isProduction()): ?> - __('Access your Monext Administrative Center in order to manage your Payline account, check follow transactions or check technical issues.'); ?> - - __('In order to configure and try the module you need to create a test account'); ?> -
- __('Access your Monext Administrative Center in order to manage your Payline account, check follow transactions or check technical issues.'); ?> - - -
-
-
+ +
+ + + +
+ +
+ __('Welcome in the Payline configuration payment center for Magento'); ?> +
+
+
+ __('Need help? contact us')?> +
support@payline.com +
+
+
+ +
+ getVersion()): ?> + __('Module version: %s', $this->getVersion()); ?> + + + getRelease()): ?> + __('(release: %s)', $this->getRelease()); ?> + +
+ + + +
+ isProduction()): ?> + __('Access your Monext Administrative Center in order to manage your Payline account, check follow transactions or check technical issues.'); ?> + + __('In order to configure and try the module you need to create a test account'); ?> +
+ __('Access your Monext Administrative Center in order to manage your Payline account, check follow transactions or check technical issues.'); ?> + + +
+
+
diff --git a/app/design/adminhtml/base/default/template/payline/system/config/form/field/array.phtml b/app/design/adminhtml/default/default/template/payline/system/config/form/field/array.phtml similarity index 100% rename from app/design/adminhtml/base/default/template/payline/system/config/form/field/array.phtml rename to app/design/adminhtml/default/default/template/payline/system/config/form/field/array.phtml diff --git a/app/design/adminhtml/base/default/template/payline/wallet/form.phtml b/app/design/adminhtml/default/default/template/payline/wallet/form.phtml similarity index 100% rename from app/design/adminhtml/base/default/template/payline/wallet/form.phtml rename to app/design/adminhtml/default/default/template/payline/wallet/form.phtml From 78bc5dc0e4bcdd7df251691d4dc54990455487be Mon Sep 17 00:00:00 2001 From: Vincent Pietri Date: Mon, 14 May 2018 16:14:58 +0200 Subject: [PATCH 03/20] Code refactoring Remove unused template files Use js widget callback --- .gitignore | 1 + .../Block/Checkout/Widget/Opcheckout.php | 29 +- .../Monext/Payline/Helper/Payment.php | 8 +- .../Monext/Payline/Model/Observer.php | 1056 ++--- .../Payline/controllers/IndexController.php | 80 +- .../community/Monext/Payline/etc/config.xml | 642 +-- .../Monext/Payline/lib/paylineSDK.php | 4106 ++++++++--------- .../onepage/widget-opcheckout-js-init.phtml | 193 +- .../onepage/widget-opcheckout-js.phtml | 94 - .../checkout/onepage/widget-update.phtml | 14 - modman | 12 + skin/frontend/base/default/js/payline.js | 1077 ++--- 12 files changed, 3640 insertions(+), 3672 deletions(-) create mode 100644 .gitignore delete mode 100644 app/design/frontend/base/default/template/payline/checkout/onepage/widget-opcheckout-js.phtml delete mode 100644 app/design/frontend/base/default/template/payline/checkout/onepage/widget-update.phtml create mode 100644 modman diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..485dee6 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.idea diff --git a/app/code/community/Monext/Payline/Block/Checkout/Widget/Opcheckout.php b/app/code/community/Monext/Payline/Block/Checkout/Widget/Opcheckout.php index ba28979..4415408 100644 --- a/app/code/community/Monext/Payline/Block/Checkout/Widget/Opcheckout.php +++ b/app/code/community/Monext/Payline/Block/Checkout/Widget/Opcheckout.php @@ -4,23 +4,6 @@ class Monext_Payline_Block_Checkout_Widget_Opcheckout extends Mage_Checkout_Bloc { protected $_custom_methods; - public function __construct() - { - parent::__construct(); - $this->setTemplate('payline/checkout/onepage/widget-opcheckout-js.phtml'); - } - - /** - * - * @param Mage_Sales_Block_Order_History $block - * @param Varien_Object $transport - */ - public function addHtmlAsChild($block, $transport) - { - $transport->setHtml($transport->getHtml() . $this->_toHtml()); - } - - /** * Retrieve available payment methods @@ -39,8 +22,9 @@ public function getAllMethods() } - - + /** + * @return string + */ public function getJsonAllMethods() { if (is_null($this->_custom_methods)) { @@ -55,7 +39,6 @@ public function getJsonAllMethods() $html = preg_replace('/display:none;/', '', $this->getPaymentMethodFormHtml($_method)); $html = str_replace(array("\r\n","\r","\n"),"",$this->jsQuoteEscape($html)); - //$html = $this->getPaymentMethodFormHtml($_method); $customMethods[] = array('code'=>$_code, 'title'=>$this->escapeHtml($this->getMethodTitle($_method)), 'label'=>$this->getMethodLabelAfterHtml($_method), @@ -69,6 +52,9 @@ public function getJsonAllMethods() return Mage::helper('core')->jsonEncode($this->_custom_methods); } + /** + * @return string + */ public function getJsonCurrentMethods() { $currentMethods = array(); @@ -87,6 +73,9 @@ public function getJsonCurrentMethods() return Mage::helper('core')->jsonEncode($currentMethods); } + /** + * @return mixed + */ public function getSaveUrl() { return Mage::getUrl('payline/index/cptWidgetCustom'); diff --git a/app/code/community/Monext/Payline/Helper/Payment.php b/app/code/community/Monext/Payline/Helper/Payment.php index c8ad1e7..c01c049 100644 --- a/app/code/community/Monext/Payline/Helper/Payment.php +++ b/app/code/community/Monext/Payline/Helper/Payment.php @@ -65,7 +65,7 @@ protected function _init($salesObject) if ($buyerFirstName == null || $buyerFirstName == '') { $buyerFirstName = substr($billingAddress->getFirstname(), 0, 50); } - + $buyerPrefix = $customer->getPrefix(); if($buyerPrefix == 'Mme'){ $array['buyer']['title'] = '1'; @@ -75,7 +75,7 @@ protected function _init($salesObject) $array['buyer']['title'] = '4'; } else { $array['buyer']['title'] = '4'; - } + } $array['buyer']['lastName'] = Mage::helper('payline')->encodeString($buyerLastName); $array['buyer']['firstName'] = Mage::helper('payline')->encodeString($buyerFirstName); $email = $customer->getEmail(); @@ -155,10 +155,10 @@ protected function _init($salesObject) $array['billingAddress']['state'] = Mage::helper('payline')->encodeString($billingAddress->getRegion()); $billingPhone = str_replace($forbidenPhoneCars, '', $billingAddress->getTelephone()); if (preg_match($regexpPhone, $billingPhone)) { - $array['billingAddress']['phone'] = $billingPhone; + $array['billingAddress']['phone'] = $billingPhone; } if($billingPhone){ - $array['buyer']['mobilePhone'] = $billingPhone; + $array['buyer']['mobilePhone'] = $billingPhone; }else{ $array['buyer']['mobilePhone'] = $shippingPhone; } diff --git a/app/code/community/Monext/Payline/Model/Observer.php b/app/code/community/Monext/Payline/Model/Observer.php index de2f6bc..72e8b06 100644 --- a/app/code/community/Monext/Payline/Model/Observer.php +++ b/app/code/community/Monext/Payline/Model/Observer.php @@ -1,523 +1,533 @@ -getOrder()->getPayment()->getMethodInstance()->getCode(); - if (!Mage::helper('payline')->isPayline($code)) { - return; - } - - // infinite loop protection - if (is_null(Mage::registry('payline_create_invoice'))) { - $order = $observer->getEvent()->getOrder(); - if ($this->_canCreateInvoice($order)) { - $this->_createInvoice($order); - } - // capture or not, that is the question - $paymentMethod = $order->getPayment()->getMethod(); - $paymentActionConf = Mage::getStoreConfig('payment/' . $paymentMethod . '/payline_payment_action'); - // if payment action user conf == authorization => need to capture - if ($paymentActionConf == "100") { - $fireCaptureOption = Mage::getStoreConfig('payment/' . $paymentMethod . '/capture_payment_when_i_said'); - // if status match w/ user conf && !PaylineNX - if ($order->getStatus() == $fireCaptureOption && $paymentMethod != 'PaylineNX') { - $invoice = $this->_getInvoiceFromOrder($order); - if ($invoice) { - $invoice->setState(Mage_Sales_Model_Order_Invoice::STATE_OPEN); - } - if ($invoice && $invoice->parentCanCapture()) { // invoice present && ok => capture - Mage::register('payline_create_invoice', true); - $invoice->capture(); - Mage::unregister('payline_create_invoice'); - } - } // end if status matches - } // end if( $paymentActionConf == 100 ) - } - } - -// end createInvoiceWhenStatusChange() - - /** - * Return the invoice's order data or false if not exist or NX payment - */ - protected function _getInvoiceFromOrder($order) - { - $invoice = $order->getInvoiceCollection(); - $invoice = sizeof($invoice) == 1 ? $invoice->getFirstItem() : false; - return $invoice; - } - - protected function _getMode($order) - { - if ($this->_mode === null) { - $paymentMethod = $order->getPayment()->getMethod(); - $mode = explode('Payline', $paymentMethod); - if (isset($mode[1])) { - $mode = $mode[1]; - $this->_mode = $mode; - } - } - return $this->_mode; - } - - protected function _canCreateInvoice($order) - { - $result = false; - if ($order->canInvoice()) { - $paymentMethod = $order->getPayment()->getMethod(); - if (strstr($paymentMethod, 'Payline') !== false) { - $mode = $this->_getMode($order); - if (!empty($mode)) { - $statusToCreateInvoice = Mage::getStoreConfig('payment/' . $paymentMethod . '/automate_invoice_creation'); - if ($order->getStatus() == $statusToCreateInvoice && !empty($statusToCreateInvoice)) { - if ($order->getData('status') !== $order->getOrigData('status')) { - $result = true; - } - } - } - } - } - return $result; - } - - protected function _createInvoice($order) - { - $transId = $order->getPayment()->getCcTransId(); - if (!empty($transId)) { - $array = array( - 'transactionId' => $transId, - 'orderRef' => $order->getRealOrderId(), - 'startDate' => '', - 'endDate' => '', - 'transactionHistory' => '', - 'version' => Monext_Payline_Helper_Data::VERSION, - 'archiveSearch' => '' - ); - try { - $mode = $this->_getMode($order); - $res = Mage::helper('payline')->initPayline($mode)->getTransactionDetails($array); - if (isset($res['payment']['action'])) { - $order->setCreateInvoice(true); - $action = $res['payment']['action']; - if ($mode == 'NX') { - $action = Monext_Payline_Model_Cpt::ACTION_AUTH_CAPTURE; - } - Mage::helper('payline')->createInvoice($action, $order); - } - } catch (Exception $e) { - Mage::logException($e); - Mage::helper('payline/logger')->log( - '[createInvoiceWhenStatusChange] ' - . '[' . $order->getIncrementId() . '] ' - . '[' . $transId . '] ' - . $e->getMessage() - ); - } - } - } - - public function saveQuoteNxFees(Varien_Event_Observer $observer) - { - // Only if the payment method is one of Payline - $code = $observer->getQuote()->getPayment()->getMethod(); - if (!Mage::helper('payline')->isPayline($code)) { - return; - } - - $applyCosts = (int) Mage::getStoreConfig('payment/PaylineNX/cost_type'); - if (!$applyCosts) { - return; - } - - $quote = $observer->getEvent()->getQuote(); - - if (!$quote->getPaylineFee()) { - $payment = $quote->getPayment(); - if ($payment) { - $paymentMethod = $payment->getMethod(); - $fee = Mage::getModel('payline/fees')->getCollection() - ->addFieldtoFilter('quote_id', $quote->getId())->getFirstItem(); - $quote->setPaylineFee($fee); - if ($paymentMethod == 'PaylineNX') { - $amount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); - $baseamount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); - - if ($applyCosts == Monext_Payline_Model_Datasource_Costs::COST_PERCENT) { - $amount = round(($quote->getSubtotal() * $amount) / 100, 2); - $baseamount = round(($quote->getBaseSubtotal() * $baseamount) / 100, 2); - } - - //save fees - if ($fee->getId()) { - $fee->setAmount($amount)->setBaseAmount($baseamount)->save(); - } else { - Mage::getModel('payline/fees')->setQuoteId($quote->getId()) - ->setAmount($amount) - ->setBaseAmount($baseamount) - ->save(); - } - } elseif ($fee->getId()) { - $fee->delete(); - } - } - } - } - - public function saveOrderNxFees(Varien_Event_Observer $observer) - { - // Only if the payment method is one of Payline - $code = $observer->getOrder()->getPayment()->getMethodInstance()->getCode(); - if (!Mage::helper('payline')->isPayline($code)) { - return; - } - - $applyCosts = (int) Mage::getStoreConfig('payment/PaylineNX/cost_type'); - if (!$applyCosts) { - return; - } - - $order = $observer->getEvent()->getOrder(); - if (!$order->getPaylineFee()) { - $quoteId = $order->getQuoteId(); - $payment = $order->getPayment(); - if ($quoteId && $payment) { - $paymentMethod = $payment->getMethod(); - $fee = Mage::getModel('payline/fees')->getCollection() - ->addFieldtoFilter('quote_id', $quoteId)->getFirstItem(); - $order->setPaylineFee($fee); - if ($paymentMethod == 'PaylineNX') { - $amount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); - $baseamount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); - - if ($applyCosts == Monext_Payline_Model_Datasource_Costs::COST_PERCENT) { - $amount = round(($order->getSubtotal() * $amount) / 100, 2); - $baseamount = round(($order->getBaseSubtotal() * $baseamount) / 100, 2); - } - - //save fees - if ($fee->getId()) { - $fee->setOrderId($order->getId())->setAmount($amount)->setBaseAmount($baseamount)->save(); - } - } elseif ($fee->getId()) { - $fee->delete(); - } - } - } - } - - public function saveInvoiceNxFees(Varien_Event_Observer $observer) - { - // Only if the payment method is one of Payline - $code = $observer->getInvoice()->getOrder()->getPayment()->getMethodInstance()->getCode(); - if (!Mage::helper('payline')->isPayline($code)) { - return; - } - - $applyCosts = (int) Mage::getStoreConfig('payment/PaylineNX/cost_type'); - if (!$applyCosts) { - return; - } - - $invoice = $observer->getEvent()->getInvoice(); - $order = $invoice->getOrder(); - $payment = $order->getPayment(); - if ($payment) { - $paymentMethod = $payment->getMethod(); - if ($paymentMethod == 'PaylineNX') { - $fee = Mage::getModel('payline/fees')->getCollection() - ->addFieldtoFilter('order_id', $order->getId())->getFirstItem(); - - $amount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); - $baseamount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); - - if ($applyCosts == Monext_Payline_Model_Datasource_Costs::COST_PERCENT) { - $amount = round(($order->getSubtotal() * $amount) / 100, 2); - $baseamount = round(($order->getBaseSubtotal() * $baseamount) / 100, 2); - } - - //save fees - if ($fee->getId() && !$fee->getInvoiceId()) { - $fee->setInvoiceId($invoice->getId())->save(); - } - } - } - } - - public function afterSaveShippingAction(Varien_Event_Observer $observer) - { - $controller = $observer->getControllerAction(); - - $paymentMethodsBlock = $controller->getLayout()->createBlock('checkout/onepage_payment_methods'); - $methods = $paymentMethodsBlock->getMethods(); - - // check if more than one methods available - if (count($methods) != 1) { - return; - } - - $method = current($methods); - - // check if only payline methods (direct method should not be skipped) - if (!in_array($method->getCode(), array('PaylineCPT', 'PaylineNX', 'PaylineWALLET'))) { - return; - } - - $data = array('method' => $method->getCode()); - - if ($method->getCode() == 'PaylineCPT') { - // retrive sub methods (card types) - $cptBlock = $controller->getLayout()->createBlock('payline/cpt'); - $ccTypes = $cptBlock->getPaymentMethods(); - if (count($ccTypes) != 1) { - return; - } - $ccType = current($ccTypes); - $data['cc_type'] = $ccType['number']; - } - - // seems that payment step can be skipped, so save the unique payment method now - $result = Mage::getSingleton('checkout/type_onepage')->savePayment($data); - if (!empty($result['error'])) { - return; - } - - $layout = Mage::getModel('core/layout'); - $layout->getUpdate()->load('checkout_onepage_review'); - $layout->generateXml()->generateBlocks(); - $layout->getBlock('root')->getChild('button')->setTemplate('checkout/onepage/review/button.phtml'); - $reviewHtml = $layout->getBlock('root')->toHtml(); - - $result['goto_section'] = 'review'; - $result['update_section'] = array( - 'name' => 'review', - 'html' => $reviewHtml - ); - - $json = Mage::helper('core')->jsonEncode($result); - $response = Mage::helper('core')->jsonDecode($controller->getResponse()->getBody()); - - $response['update_section']['html'].= ''; - - - $controller->getResponse()->setBody(Mage::helper('core')->jsonEncode($response)); - } - - /** - * Clean payline - * @see customer_logout - */ - public function cleanPayline(Varien_Event_Observer $observer) - { - // Clean the wallet - Mage::getSingleton('payline/wallet')->clean(); - } - - - /** - * - * @param Varien_Event_Observer $observer - */ - public function checkForConfigChanged(Varien_Event_Observer $observer) - { - $disablePayments = Mage::registry('payline_config_disable_payments'); - if ($disablePayments) { - $config=Mage::getModel('core/config'); - $store=null; - $paymentConfig = Mage::getStoreConfig('payment', $store); - foreach ($paymentConfig as $code => $methodConfig) { - if (Mage::getStoreConfigFlag('payment/'.$code.'/active', $store) and stripos($code,'payline')!==false ) { - $config->saveConfig('payment/'.$code.'/active', 0); - } - } - } - - - $change = Mage::registry('payline_config_change'); - if ($change) { - $url = Mage::helper("adminhtml")->getUrl('adminhtml/payline_managecontracts/importFromConfig'); - - Mage::app()->getFrontController()->getResponse()->setRedirect($url); - Mage::app()->getResponse()->sendResponse(); - exit; - } - } - - /** - * - * @param Varien_Event_Observer $observer - * @return void - */ - public function configNestedPayment(Varien_Event_Observer $observer) - { - $paymentGroups = $observer->getEvent()->getConfig()->getNode('sections/payline/groups'); - - $payments = $paymentGroups->xpath('payline_payments_availables/*'); - foreach ($payments as $payment) { - if ((int)$payment->include) { - - $fields = $paymentGroups->xpath((string)$payment->group . '/fields'); - if (isset($fields[0])) { - $fields[0]->appendChild($payment, true); - } - } - } - } - - - /** - * - * @param Varien_Event_Observer $observer - * @return Monext_Payline_Model_Observer - */ - public function updateHandleToUnsetPaymentStep(Varien_Event_Observer $observer) - { - $action = $observer->getEvent()->getAction(); - if ($action->getFullActionName() == "checkout_onepage_index" && Mage::helper('payline')->disableOnepagePaymentStep()) { - $update = $observer->getEvent()->getLayout()->getUpdate(); - $update->addHandle('payline_remove_onepage_payment_step_handler'); - } - return $this; - } - - - /** - * - * @param Varien_Event_Observer $observer - * @return Monext_Payline_Model_Observer - */ - public function updateSectionTitle(Varien_Event_Observer $observer) - { - $action = $observer->getEvent()->getAction(); - if ($action->getFullActionName() == "checkout_onepage_index" && Mage::helper('payline')->disableOnepagePaymentStep()) { - Mage::getSingleton('checkout/session')->setStepData('payment', array( - 'label' => Mage::helper('checkout')->__('Payment Information'), - 'is_show' => true - )); - Mage::getSingleton('checkout/session')->setStepData('review', array( - 'label' => Mage::helper('checkout')->__('Payment Information'), - 'is_show' => true - ));; - } - return $this; - } - - - /** - * - * @param Varien_Event_Observer $observer - * @return Monext_Payline_Model_Observer - */ - public function postdispatchOnepageSaveShippingMethod(Varien_Event_Observer $observer) - { - if (!Mage::helper('payline')->disableOnepagePaymentStep()) { - return $this; - } - - /* @var $controller Mage_Checkout_OnepageController */ - $controller = $observer->getEvent()->getControllerAction(); - $response = Mage::app()->getFrontController()->getResponse()->getBody(true); - - if (!isset($response['default'])) { - return; - } - - $response = Mage::helper('core')->jsonDecode($response['default']); - - if ($response['goto_section'] == 'payment') { - - $contractNumber = Mage::helper('payline')->getDefaultContractNumberForWidget(); - if(empty($contractNumber)) { - throw new Exception('Cannot find valid contract number'); - } - $onePage = Mage::getSingleton('checkout/type_onepage'); - $onePage->getQuote()->getPayment()->importData(array('method'=>'PaylineCPT', 'cc_type'=>$contractNumber)); - - - $layout = $controller->getLayout(); - $update = $layout->getUpdate(); - // Needed with cache activated - $update->setCacheId(uniqid("payline_onepage_review_payline")); - - $controller->loadLayout(array('checkout_onepage_review','payline_onepage_review_handler'), true, true); - $response['goto_section'] = 'review'; - $response['update_section'] = array( - 'name' => 'review', - 'html' => $controller->getLayout()->getBlock('root')->toHtml() - ); - - $controller->getResponse()->setBody(Mage::helper('core')->jsonEncode($response)); - } - - return $this; - } - - - /** - * - * @param Varien_Event_Observer $observer - */ - public function alterBlockHtmlAfter(Varien_Event_Observer $observer) - { - if (!Mage::helper('payline')->disableOnepagePaymentStep()) { - return $this; - } - - $block = $observer->getEvent()->getBlock(); - $transport = $observer->getEvent()->getTransport(); - - if($block instanceof Mage_Checkout_Block_Onepage_Shipping_Method) { - $block->getLayout() - ->createBlock('payline/checkout_widget_opcheckout', 'payline_checkout_widget_opcheckout_init') - ->setTemplate('payline/checkout/onepage/widget-opcheckout-js-init.phtml') - ->addHtmlAsChild($block, $transport); - } - - } - - - /** - * - * @param Varien_Event_Observer $observer - */ - public function predispatchCheckoutOnepage(Varien_Event_Observer $observer) - { - if (!Mage::helper('payline')->disableOnepagePaymentStep()) { - return $this; - } - - $needRedirect = false; - - /* @var $controller Mage_Checkout_OnepageController */ - $controller = $observer->getEvent()->getControllerAction(); - $paylinetoken = $controller->getRequest()->getParam('paylinetoken'); - - $referer = Mage::helper('core/http')->getHttpReferer(); - if ($paylinetoken) { - $token = Mage::getModel('payline/token')->load($paylinetoken, 'token'); - if($token->getId()) { - $needRedirect = true; - } - } - - if ($needRedirect) { - $params = $controller->getRequest()->getParams(); - $params['_secure'] = true; - - $controller->getResponse()->setRedirect( - Mage::getUrl('payline/index/cptReturnWidget', $params) - ); - $controller->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true); - } - } -} +getOrder()->getPayment()->getMethodInstance()->getCode(); + if (!Mage::helper('payline')->isPayline($code)) { + return; + } + + // infinite loop protection + if (is_null(Mage::registry('payline_create_invoice'))) { + $order = $observer->getEvent()->getOrder(); + if ($this->_canCreateInvoice($order)) { + $this->_createInvoice($order); + } + // capture or not, that is the question + $paymentMethod = $order->getPayment()->getMethod(); + $paymentActionConf = Mage::getStoreConfig('payment/' . $paymentMethod . '/payline_payment_action'); + // if payment action user conf == authorization => need to capture + if ($paymentActionConf == "100") { + $fireCaptureOption = Mage::getStoreConfig('payment/' . $paymentMethod . '/capture_payment_when_i_said'); + // if status match w/ user conf && !PaylineNX + if ($order->getStatus() == $fireCaptureOption && $paymentMethod != 'PaylineNX') { + $invoice = $this->_getInvoiceFromOrder($order); + if ($invoice) { + $invoice->setState(Mage_Sales_Model_Order_Invoice::STATE_OPEN); + } + if ($invoice && $invoice->parentCanCapture()) { // invoice present && ok => capture + Mage::register('payline_create_invoice', true); + $invoice->capture(); + Mage::unregister('payline_create_invoice'); + } + } // end if status matches + } // end if( $paymentActionConf == 100 ) + } + } + +// end createInvoiceWhenStatusChange() + + /** + * Return the invoice's order data or false if not exist or NX payment + */ + protected function _getInvoiceFromOrder($order) + { + $invoice = $order->getInvoiceCollection(); + $invoice = sizeof($invoice) == 1 ? $invoice->getFirstItem() : false; + return $invoice; + } + + protected function _getMode($order) + { + if ($this->_mode === null) { + $paymentMethod = $order->getPayment()->getMethod(); + $mode = explode('Payline', $paymentMethod); + if (isset($mode[1])) { + $mode = $mode[1]; + $this->_mode = $mode; + } + } + return $this->_mode; + } + + protected function _canCreateInvoice($order) + { + $result = false; + if ($order->canInvoice()) { + $paymentMethod = $order->getPayment()->getMethod(); + if (strstr($paymentMethod, 'Payline') !== false) { + $mode = $this->_getMode($order); + if (!empty($mode)) { + $statusToCreateInvoice = Mage::getStoreConfig('payment/' . $paymentMethod . '/automate_invoice_creation'); + if ($order->getStatus() == $statusToCreateInvoice && !empty($statusToCreateInvoice)) { + if ($order->getData('status') !== $order->getOrigData('status')) { + $result = true; + } + } + } + } + } + return $result; + } + + protected function _createInvoice($order) + { + $transId = $order->getPayment()->getCcTransId(); + if (!empty($transId)) { + $array = array( + 'transactionId' => $transId, + 'orderRef' => $order->getRealOrderId(), + 'startDate' => '', + 'endDate' => '', + 'transactionHistory' => '', + 'version' => Monext_Payline_Helper_Data::VERSION, + 'archiveSearch' => '' + ); + try { + $mode = $this->_getMode($order); + $res = Mage::helper('payline')->initPayline($mode)->getTransactionDetails($array); + if (isset($res['payment']['action'])) { + $order->setCreateInvoice(true); + $action = $res['payment']['action']; + if ($mode == 'NX') { + $action = Monext_Payline_Model_Cpt::ACTION_AUTH_CAPTURE; + } + Mage::helper('payline')->createInvoice($action, $order); + } + } catch (Exception $e) { + Mage::logException($e); + Mage::helper('payline/logger')->log( + '[createInvoiceWhenStatusChange] ' + . '[' . $order->getIncrementId() . '] ' + . '[' . $transId . '] ' + . $e->getMessage() + ); + } + } + } + + public function saveQuoteNxFees(Varien_Event_Observer $observer) + { + // Only if the payment method is one of Payline + $code = $observer->getQuote()->getPayment()->getMethod(); + if (!Mage::helper('payline')->isPayline($code)) { + return; + } + + $applyCosts = (int) Mage::getStoreConfig('payment/PaylineNX/cost_type'); + if (!$applyCosts) { + return; + } + + $quote = $observer->getEvent()->getQuote(); + + if (!$quote->getPaylineFee()) { + $payment = $quote->getPayment(); + if ($payment) { + $paymentMethod = $payment->getMethod(); + $fee = Mage::getModel('payline/fees')->getCollection() + ->addFieldtoFilter('quote_id', $quote->getId())->getFirstItem(); + $quote->setPaylineFee($fee); + if ($paymentMethod == 'PaylineNX') { + $amount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); + $baseamount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); + + if ($applyCosts == Monext_Payline_Model_Datasource_Costs::COST_PERCENT) { + $amount = round(($quote->getSubtotal() * $amount) / 100, 2); + $baseamount = round(($quote->getBaseSubtotal() * $baseamount) / 100, 2); + } + + //save fees + if ($fee->getId()) { + $fee->setAmount($amount)->setBaseAmount($baseamount)->save(); + } else { + Mage::getModel('payline/fees')->setQuoteId($quote->getId()) + ->setAmount($amount) + ->setBaseAmount($baseamount) + ->save(); + } + } elseif ($fee->getId()) { + $fee->delete(); + } + } + } + } + + public function saveOrderNxFees(Varien_Event_Observer $observer) + { + // Only if the payment method is one of Payline + $code = $observer->getOrder()->getPayment()->getMethodInstance()->getCode(); + if (!Mage::helper('payline')->isPayline($code)) { + return; + } + + $applyCosts = (int) Mage::getStoreConfig('payment/PaylineNX/cost_type'); + if (!$applyCosts) { + return; + } + + $order = $observer->getEvent()->getOrder(); + if (!$order->getPaylineFee()) { + $quoteId = $order->getQuoteId(); + $payment = $order->getPayment(); + if ($quoteId && $payment) { + $paymentMethod = $payment->getMethod(); + $fee = Mage::getModel('payline/fees')->getCollection() + ->addFieldtoFilter('quote_id', $quoteId)->getFirstItem(); + $order->setPaylineFee($fee); + if ($paymentMethod == 'PaylineNX') { + $amount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); + $baseamount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); + + if ($applyCosts == Monext_Payline_Model_Datasource_Costs::COST_PERCENT) { + $amount = round(($order->getSubtotal() * $amount) / 100, 2); + $baseamount = round(($order->getBaseSubtotal() * $baseamount) / 100, 2); + } + + //save fees + if ($fee->getId()) { + $fee->setOrderId($order->getId())->setAmount($amount)->setBaseAmount($baseamount)->save(); + } + } elseif ($fee->getId()) { + $fee->delete(); + } + } + } + } + + public function saveInvoiceNxFees(Varien_Event_Observer $observer) + { + // Only if the payment method is one of Payline + $code = $observer->getInvoice()->getOrder()->getPayment()->getMethodInstance()->getCode(); + if (!Mage::helper('payline')->isPayline($code)) { + return; + } + + $applyCosts = (int) Mage::getStoreConfig('payment/PaylineNX/cost_type'); + if (!$applyCosts) { + return; + } + + $invoice = $observer->getEvent()->getInvoice(); + $order = $invoice->getOrder(); + $payment = $order->getPayment(); + if ($payment) { + $paymentMethod = $payment->getMethod(); + if ($paymentMethod == 'PaylineNX') { + $fee = Mage::getModel('payline/fees')->getCollection() + ->addFieldtoFilter('order_id', $order->getId())->getFirstItem(); + + $amount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); + $baseamount = (float) Mage::getStoreConfig('payment/PaylineNX/cost_amount'); + + if ($applyCosts == Monext_Payline_Model_Datasource_Costs::COST_PERCENT) { + $amount = round(($order->getSubtotal() * $amount) / 100, 2); + $baseamount = round(($order->getBaseSubtotal() * $baseamount) / 100, 2); + } + + //save fees + if ($fee->getId() && !$fee->getInvoiceId()) { + $fee->setInvoiceId($invoice->getId())->save(); + } + } + } + } + + public function afterSaveShippingAction(Varien_Event_Observer $observer) + { + $controller = $observer->getControllerAction(); + + $paymentMethodsBlock = $controller->getLayout()->createBlock('checkout/onepage_payment_methods'); + $methods = $paymentMethodsBlock->getMethods(); + + // check if more than one methods available + if (count($methods) != 1) { + return; + } + + $method = current($methods); + + // check if only payline methods (direct method should not be skipped) + if (!in_array($method->getCode(), array('PaylineCPT', 'PaylineNX', 'PaylineWALLET'))) { + return; + } + + $data = array('method' => $method->getCode()); + + if ($method->getCode() == 'PaylineCPT') { + // retrive sub methods (card types) + $cptBlock = $controller->getLayout()->createBlock('payline/cpt'); + $ccTypes = $cptBlock->getPaymentMethods(); + if (count($ccTypes) != 1) { + return; + } + $ccType = current($ccTypes); + $data['cc_type'] = $ccType['number']; + } + + // seems that payment step can be skipped, so save the unique payment method now + $result = Mage::getSingleton('checkout/type_onepage')->savePayment($data); + if (!empty($result['error'])) { + return; + } + + $layout = Mage::getModel('core/layout'); + $layout->getUpdate()->load('checkout_onepage_review'); + $layout->generateXml()->generateBlocks(); + $layout->getBlock('root')->getChild('button')->setTemplate('checkout/onepage/review/button.phtml'); + $reviewHtml = $layout->getBlock('root')->toHtml(); + + $result['goto_section'] = 'review'; + $result['update_section'] = array( + 'name' => 'review', + 'html' => $reviewHtml + ); + + $json = Mage::helper('core')->jsonEncode($result); + $response = Mage::helper('core')->jsonDecode($controller->getResponse()->getBody()); + + $response['update_section']['html'].= ''; + + + $controller->getResponse()->setBody(Mage::helper('core')->jsonEncode($response)); + } + + /** + * Clean payline + * @see customer_logout + */ + public function cleanPayline(Varien_Event_Observer $observer) + { + // Clean the wallet + Mage::getSingleton('payline/wallet')->clean(); + } + + + /** + * + * @param Varien_Event_Observer $observer + */ + public function checkForConfigChanged(Varien_Event_Observer $observer) + { + $disablePayments = Mage::registry('payline_config_disable_payments'); + if ($disablePayments) { + $config=Mage::getModel('core/config'); + $store=null; + $paymentConfig = Mage::getStoreConfig('payment', $store); + foreach ($paymentConfig as $code => $methodConfig) { + if (Mage::getStoreConfigFlag('payment/'.$code.'/active', $store) and stripos($code,'payline')!==false ) { + $config->saveConfig('payment/'.$code.'/active', 0); + } + } + } + + + $change = Mage::registry('payline_config_change'); + if ($change) { + $url = Mage::helper("adminhtml")->getUrl('adminhtml/payline_managecontracts/importFromConfig'); + + Mage::app()->getFrontController()->getResponse()->setRedirect($url); + Mage::app()->getResponse()->sendResponse(); + exit; + } + } + + /** + * + * @param Varien_Event_Observer $observer + * @return void + */ + public function configNestedPayment(Varien_Event_Observer $observer) + { + $paymentGroups = $observer->getEvent()->getConfig()->getNode('sections/payline/groups'); + + $payments = $paymentGroups->xpath('payline_payments_availables/*'); + foreach ($payments as $payment) { + if ((int)$payment->include) { + + $fields = $paymentGroups->xpath((string)$payment->group . '/fields'); + if (isset($fields[0])) { + $fields[0]->appendChild($payment, true); + } + } + } + } + + + /** + * + * @param Varien_Event_Observer $observer + * @return Monext_Payline_Model_Observer + */ + public function updateHandleToUnsetPaymentStep(Varien_Event_Observer $observer) + { + $action = $observer->getEvent()->getAction(); + if ($action->getFullActionName() == "checkout_onepage_index" && Mage::helper('payline')->disableOnepagePaymentStep()) { + $update = $observer->getEvent()->getLayout()->getUpdate(); + $update->addHandle('payline_remove_onepage_payment_step_handler'); + } + return $this; + } + + + /** + * + * @param Varien_Event_Observer $observer + * @return Monext_Payline_Model_Observer + */ + public function updateSectionTitle(Varien_Event_Observer $observer) + { + $action = $observer->getEvent()->getAction(); + if ($action->getFullActionName() == "checkout_onepage_index" && Mage::helper('payline')->disableOnepagePaymentStep()) { + Mage::getSingleton('checkout/session')->setStepData('payment', array( + 'label' => Mage::helper('checkout')->__('Payment Information'), + 'is_show' => true + )); + Mage::getSingleton('checkout/session')->setStepData('review', array( + 'label' => Mage::helper('checkout')->__('Payment Information'), + 'is_show' => true + ));; + } + return $this; + } + + + /** + * + * @param Varien_Event_Observer $observer + * @return Monext_Payline_Model_Observer + */ + public function postdispatchOnepageSaveShippingMethod(Varien_Event_Observer $observer) + { + if (!Mage::helper('payline')->disableOnepagePaymentStep()) { + return $this; + } + + /* @var $controller Mage_Checkout_OnepageController */ + $controller = $observer->getEvent()->getControllerAction(); + $response = Mage::app()->getFrontController()->getResponse()->getBody(true); + + if (!isset($response['default'])) { + return; + } + + $response = Mage::helper('core')->jsonDecode($response['default']); + + if ($response['goto_section'] == 'payment') { + + try { + $contractNumber = Mage::helper('payline')->getDefaultContractNumberForWidget(); + if(empty($contractNumber)) { + throw new Exception('Cannot find valid contract number'); + } + $onePage = Mage::getSingleton('checkout/type_onepage'); + $onePage->getQuote()->getPayment()->importData(array('method'=>'PaylineCPT', 'cc_type'=>$contractNumber)); + + + $layout = $controller->getLayout(); + $update = $layout->getUpdate(); + // Needed with cache activated + $update->setCacheId(uniqid("payline_onepage_review_payline")); + + $controller->loadLayout(array('checkout_onepage_review','payline_onepage_review_handler'), true, true); + $response['goto_section'] = 'review'; + $response['update_section'] = array( + 'name' => 'review', + 'html' => $controller->getLayout()->getBlock('root')->toHtml() + ); + + $controller->getResponse()->setBody(Mage::helper('core')->jsonEncode($response)); + + } catch (Exception $e) { + Mage::logException($e); + } + + } + + return $this; + } + + + /** + * core_block_abstract_to_html_after + * + * @param Varien_Event_Observer $observer + */ + public function alterBlockHtmlAfter(Varien_Event_Observer $observer) + { + if (!Mage::helper('payline')->disableOnepagePaymentStep()) { + return $this; + } + + $block = $observer->getEvent()->getBlock(); + $transport = $observer->getEvent()->getTransport(); + + if($block instanceof Mage_Checkout_Block_Onepage_Shipping_Method) { + + $htmlShipment = $transport->getHtml(); + + $blockPayline = $block->getLayout() + ->createBlock('payline/checkout_widget_opcheckout', 'payline_checkout_widget_opcheckout_init') + ->setTemplate('payline/checkout/onepage/widget-opcheckout-js-init.phtml'); + + $transport->setHtml($htmlShipment . $blockPayline->toHtml()); + } + } + + + /** + * + * @param Varien_Event_Observer $observer + */ + public function predispatchCheckoutOnepage(Varien_Event_Observer $observer) + { + if (!Mage::helper('payline')->disableOnepagePaymentStep()) { + return $this; + } + + $needRedirect = false; + + /* @var $controller Mage_Checkout_OnepageController */ + $controller = $observer->getEvent()->getControllerAction(); + $paylinetoken = $controller->getRequest()->getParam('paylinetoken'); + + $referer = Mage::helper('core/http')->getHttpReferer(); + if ($paylinetoken) { + $token = Mage::getModel('payline/token')->load($paylinetoken, 'token'); + if($token->getId()) { + $needRedirect = true; + } + } + + if ($needRedirect) { + $params = $controller->getRequest()->getParams(); + $params['_secure'] = true; + + $controller->getResponse()->setRedirect( + Mage::getUrl('payline/index/cptReturnWidget', $params) + ); + $controller->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true); + } + } +} diff --git a/app/code/community/Monext/Payline/controllers/IndexController.php b/app/code/community/Monext/Payline/controllers/IndexController.php index 0412a4e..3e07595 100644 --- a/app/code/community/Monext/Payline/controllers/IndexController.php +++ b/app/code/community/Monext/Payline/controllers/IndexController.php @@ -21,6 +21,11 @@ class Monext_Payline_IndexController extends Mage_Core_Controller_Front_Action */ protected $order; + public function getCurrentOrder() + { + return $this->order; + } + protected function _getCustomerSession() { return Mage::getSingleton('customer/session'); @@ -212,7 +217,7 @@ public function cptAction(){ $token->save(); header("location:" . $result['redirectURL']); - return; + return; } else { // Payline error Mage::helper('payline/payment')->updateStock($this->order); $msg = Mage::helper('payline')->__('Error during payment'); @@ -446,9 +451,9 @@ public function walletAction(){ $paylineSDK->setPrivate($privateData); } - $postData = $this->getRequest()->getPost(); - - if(!isset($postData['PaRes']) && in_array(Mage::getStoreConfig('payment/PaylineWALLET/wallet_payment_security'), array(Monext_Payline_Helper_Data::WALLET_3DS,Monext_Payline_Helper_Data::WALLET_BOTH))){ + $postData = $this->getRequest()->getPost(); + + if(!isset($postData['PaRes']) && in_array(Mage::getStoreConfig('payment/PaylineWALLET/wallet_payment_security'), array(Monext_Payline_Helper_Data::WALLET_3DS,Monext_Payline_Helper_Data::WALLET_BOTH))){ // customer has to be redirected on ACC for 3DS password filling $verifyEnrollmentRequest = array(); $verifyEnrollmentRequest['version'] = $array['version']; @@ -473,14 +478,14 @@ public function walletAction(){ return; } if($verifyEnrollmentResponse['result']['code'] == '03000'){ - $output = "
"; - $output .= " "; - $output .= " "; - $output .= " "; - $output .= "
"; - $output .= ""; - $this->getResponse()->setBody($output); - return; + $output = "
"; + $output .= " "; + $output .= " "; + $output .= " "; + $output .= "
"; + $output .= ""; + $this->getResponse()->setBody($output); + return; }else{ Mage::helper('payline/payment')->updateStock($this->order); $msgLog='PAYLINE ERROR during verifyEnrollment: '.$verifyEnrollmentResponse['result']['code']. ' ' . $verifyEnrollmentResponse['result']['shortMessage'] . ' ('.$verifyEnrollmentResponse['result']['longMessage'].')'; @@ -494,9 +499,9 @@ public function walletAction(){ } } - if(isset($postData['PaRes'])){ // back from ACS - $array['3DSecure']['md'] = $postData['MD']; - $array['3DSecure']['pares'] = $postData['PaRes']; + if(isset($postData['PaRes'])){ // back from ACS + $array['3DSecure']['md'] = $postData['MD']; + $array['3DSecure']['pares'] = $postData['PaRes']; } try{ @@ -640,7 +645,7 @@ public function nxAction(){ $this->order->setState(Mage_Sales_Model_Order::STATE_NEW, $initStatus, '', false); $this->order->save(); header("location:" . $result['redirectURL']); - return; + return; } else { Mage::helper('payline/payment')->updateStock($this->order); if (isset($result) && is_array($result)) { @@ -664,8 +669,12 @@ public function cptWidgetCustomAction() { $result = array(); - $method = $this->getRequest()->getParam('paymentmethod'); + $data = $this->getRequest()->getParam('payment', array()); + if(empty($data) or !is_array($data)) { + $data = array(); + } + $method = $this->getRequest()->getParam('paymentmethod'); try { if(empty($method)) { throw new Exception('No payment method'); @@ -673,7 +682,7 @@ public function cptWidgetCustomAction() $onePage = Mage::getSingleton('checkout/type_onepage'); $quote = $onePage->getQuote(); if($quote and $quote->getId()) { - $data=array('method'=>$method); + $data['method'] = $method; $quote->getPayment()->importData($data); } else { // Incorrect order_id @@ -690,6 +699,7 @@ public function cptWidgetCustomAction() $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result)); } else { $this->getRequest()->setParam('form_key', Mage::getSingleton('core/session')->getFormKey()); + $this->getRequest()->setPost('payment', $data); $this->_forward('saveOrder', 'onepage', 'checkout'); } } @@ -770,16 +780,16 @@ public function cptReturnAction(){ $tokenModel = Mage::getModel('payline/token')->getCollection()->addFieldToFilter('token',$paylineToken); $tokenData = $tokenModel->getFirstItem()->getData(); - $queryData = $this->getRequest()->getQuery(); + $queryData = $this->getRequest()->getQuery(); // Order is loaded from id associated to the token if(sizeof($tokenData) == 0){ - Mage::helper('payline/logger')->log('[cptReturnAction] - token '.$queryData['token'].' is unknown'); + Mage::helper('payline/logger')->log('[cptReturnAction] - token '.$queryData['token'].' is unknown'); return; } $this->order = Mage::getModel('sales/order')->loadByIncrementId($tokenData['order_id']); - if(!in_array($tokenData['status'],array(0,3)) && !isset($queryData['force_upd'])){ // order update is already done => exit this function - if(isset($queryData['notificationType'])) return; // call from notify URL => no page to display + if(!in_array($tokenData['status'],array(0,3)) && !isset($queryData['force_upd'])){ // order update is already done => exit this function + if(isset($queryData['notificationType'])) return; // call from notify URL => no page to display $acceptedCodes = array( '00000', // Credit card -> Transaction approved @@ -890,7 +900,7 @@ public function cptReturnAction(){ return; } $this->order->save(); - if(isset($queryData['notificationType'])) return; // call from notify URL => no page to display + if(isset($queryData['notificationType'])) return; // call from notify URL => no page to display $this->_redirectUrl($redirectUrl); } @@ -906,8 +916,8 @@ public function nxReturnAction(){ * Save NX payment result, called by the bank when the transaction is done */ public function nxNotifAction(){ - $queryData = $this->getRequest()->getQuery(); - $res = Mage::helper('payline')->initPayline('NX')->getWebPaymentDetails(array('token' => $queryData['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); + $queryData = $this->getRequest()->getQuery(); + $res = Mage::helper('payline')->initPayline('NX')->getWebPaymentDetails(array('token' => $queryData['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); if (isset($res['privateDataList']['privateData']['value'])) { $orderRef = $res['privateDataList']['privateData']['value']; } else { @@ -991,19 +1001,19 @@ public function nxNotifAction(){ */ public function nxTermNotifAction() { - $queryData = $this->getRequest()->getQuery(); + $queryData = $this->getRequest()->getQuery(); $statusScheduleAlert = Mage::getStoreConfig('payment/PaylineNX/status_when_payline_schedule_alert'); $statusCCExpired = Mage::getStoreConfig('payment/PaylineNX/status_when_credit_card_schedule_is_expired'); if (! empty($statusScheduleAlert) || ! empty($statusCCExpired)) { - if ($this->isNxTermParamsOk($queryData)) { + if ($this->isNxTermParamsOk($queryData)) { /* * BILL = value required for terms notifications * WEBTRS = value for cash web payment */ - if ($queryData['notificationType'] == 'BILL') { // + if ($queryData['notificationType'] == 'BILL') { // $transactionParams = array(); - $transactionParams['transactionId'] = $queryData['transactionId']; - $transactionParams['orderRef'] = $queryData['orderRef']; + $transactionParams['transactionId'] = $queryData['transactionId']; + $transactionParams['orderRef'] = $queryData['orderRef']; $transactionParams['version'] = Monext_Payline_Helper_Data::VERSION; $transactionParams['startDate'] = ''; $transactionParams['endDate'] = ''; @@ -1024,12 +1034,12 @@ public function nxTermNotifAction() break; case '02501': // payment card will expire if (! empty($statusScheduleAlert)) { - $this->order = $this->setOrderStatus($statusScheduleAlert, $queryData['orderRef']); + $this->order = $this->setOrderStatus($statusScheduleAlert, $queryData['orderRef']); break; } default: // if default => error (cc expired or other errors) if (! empty($statusCCExpired)) { - $this->order = $this->setOrderStatus($statusCCExpired, $queryData['orderRef']); + $this->order = $this->setOrderStatus($statusCCExpired, $queryData['orderRef']); } else { $mustSave = false; } @@ -1098,8 +1108,8 @@ private function setOrderStatus($status, $orderRef) * Cancel a NX payment request /order */ public function nxCancelAction(){ - $queryData = $this->getRequest()->getQuery(); - $res = Mage::helper('payline')->initPayline('NX')->getWebPaymentDetails(array('token' => $queryData['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); + $queryData = $this->getRequest()->getQuery(); + $res = Mage::helper('payline')->initPayline('NX')->getWebPaymentDetails(array('token' => $queryData['token'], 'version' => Monext_Payline_Helper_Data::VERSION)); if (isset($res['privateDataList']['privateData']['value'])) { $orderRef = $res['privateDataList']['privateData']['value']; } else { @@ -1196,7 +1206,7 @@ public function waitingOrderUpdateAction(){ $tokenCollection = Mage::getModel('payline/token')->getCollection()->addFieldToFilter('status',3); // 3 stands 'pending payment result' status foreach($tokenCollection as $token) { $this->getRequest()->setParam('token', $token->getToken()); - $this->getRequest()->setQuery('notificationType', 'WAITUPD'); // force notificationType param to prevent cptReturnAction to display customer result page + $this->getRequest()->setQuery('notificationType', 'WAITUPD'); // force notificationType param to prevent cptReturnAction to display customer result page $this->cptReturnAction(); } } diff --git a/app/code/community/Monext/Payline/etc/config.xml b/app/code/community/Monext/Payline/etc/config.xml index 0b32112..86889aa 100644 --- a/app/code/community/Monext/Payline/etc/config.xml +++ b/app/code/community/Monext/Payline/etc/config.xml @@ -1,321 +1,321 @@ - - - - - 1.8.5.7 - - - - - - Monext_Payline_Block - - - - - Monext_Payline_Block_Adminhtml_Sales_Order_Creditmemo_Create_Items - Monext_Payline_Block_Adminhtml_Customer_Grid - - - - - - Monext_Payline_Model - payline_mysql4 - - - Monext_Payline_Model_Mysql4 - - - payline_contract
-
- - payline_contract_status
-
- - payline_nx_fees
-
- - payline_product_categories
-
- - payline_token
-
-
-
- - - Monext_Payline_Model_Order_Invoice - Monext_Payline_Model_Order_Payment - - -
- - - Monext_Payline_Helper - - - - - - Monext_Payline - Monext_Payline_Model_Resource_Eav_Mysql4_Setup - - - core_setup - - - - - core_write - - - - - core_read - - - - - - - - payline/observer - createInvoiceWhenStatusChange - - - payline/observer - saveOrderNxFees - - - - - - - payline/observer - saveQuoteNxFees - - - - - - - payline/observer - saveInvoiceNxFees - - - - - - - payline/observer - afterSaveShippingAction - - - - - - - payline/observer - cleanPayline - - - - - - - - - payline/total_nx_quote - subtotal - grand_total,tax - payline/checkout_total - - - - - - - payline/total_nx_invoice - subtotal - grand_total,tax - - - - - - - - * - - - -
- - - /payline/ - - - - standard - - Monext_Payline - payline - - - - - - - - Monext_Payline.csv - - - - - - - - payline.xml - - - - - - - - payline/observer - updateHandleToUnsetPaymentStep - - - - - - - payline/observer - updateSectionTitle - - - - - - - singleton - payline/observer - postdispatchOnepageSaveShippingMethod - - - - - - - singleton - payline/observer - alterBlockHtmlAfter - - - - - - - singleton - payline/observer - predispatchCheckoutOnepage - - - - - - - - - - - Monext_Payline_Adminhtml - - - - - - - - - - - Monext_Payline.csv - - - - - - - - payline.xml - - - - - - - - payline/observer - checkForConfigChanged - - - - - - - payline/observer - configNestedPayment - - - - - - - - - Common settings - 1 - holded - canceled - processing - pending - pending - 1 - - - payline/cpt - Payline - Cash web paiement - - 101 - 1 - - - payline/nx - Payline - Nx web payment - 1 - - - payline/direct - Payline - direct payment - - 101 - 1 - order - - - payline/wallet - Payline - wallet payment - payline_register-oneclick_customeraccount - payline_register-oneclick_catalog - 1 - 0 - One Click Checkout - - 101 - - - -
+ + + + + 1.8.5.8 + + + + + + Monext_Payline_Block + + + + + Monext_Payline_Block_Adminhtml_Sales_Order_Creditmemo_Create_Items + Monext_Payline_Block_Adminhtml_Customer_Grid + + + + + + Monext_Payline_Model + payline_mysql4 + + + Monext_Payline_Model_Mysql4 + + + payline_contract
+
+ + payline_contract_status
+
+ + payline_nx_fees
+
+ + payline_product_categories
+
+ + payline_token
+
+
+
+ + + Monext_Payline_Model_Order_Invoice + Monext_Payline_Model_Order_Payment + + +
+ + + Monext_Payline_Helper + + + + + + Monext_Payline + Monext_Payline_Model_Resource_Eav_Mysql4_Setup + + + core_setup + + + + + core_write + + + + + core_read + + + + + + + + payline/observer + createInvoiceWhenStatusChange + + + payline/observer + saveOrderNxFees + + + + + + + payline/observer + saveQuoteNxFees + + + + + + + payline/observer + saveInvoiceNxFees + + + + + + + payline/observer + afterSaveShippingAction + + + + + + + payline/observer + cleanPayline + + + + + + + + + payline/total_nx_quote + subtotal + grand_total,tax + payline/checkout_total + + + + + + + payline/total_nx_invoice + subtotal + grand_total,tax + + + + + + + + * + + + +
+ + + /payline/ + + + + standard + + Monext_Payline + payline + + + + + + + + Monext_Payline.csv + + + + + + + + payline.xml + + + + + + + + payline/observer + updateHandleToUnsetPaymentStep + + + + + + + payline/observer + updateSectionTitle + + + + + + + singleton + payline/observer + postdispatchOnepageSaveShippingMethod + + + + + + + singleton + payline/observer + alterBlockHtmlAfter + + + + + + + singleton + payline/observer + predispatchCheckoutOnepage + + + + + + + + + + + Monext_Payline_Adminhtml + + + + + + + + + + + Monext_Payline.csv + + + + + + + + payline.xml + + + + + + + + payline/observer + checkForConfigChanged + + + + + + + payline/observer + configNestedPayment + + + + + + + + + Common settings + 1 + holded + canceled + processing + pending + pending + 1 + + + payline/cpt + Payline - Cash web paiement + + 101 + 1 + + + payline/nx + Payline - Nx web payment + 1 + + + payline/direct + Payline - direct payment + + 101 + 1 + order + + + payline/wallet + Payline - wallet payment + payline_register-oneclick_customeraccount + payline_register-oneclick_catalog + 1 + 0 + One Click Checkout + + 101 + + + +
diff --git a/app/code/community/Monext/Payline/lib/paylineSDK.php b/app/code/community/Monext/Payline/lib/paylineSDK.php index 48dd59a..b3b0f50 100644 --- a/app/code/community/Monext/Payline/lib/paylineSDK.php +++ b/app/code/community/Monext/Payline/lib/paylineSDK.php @@ -1,2053 +1,2053 @@ -$v){ - if (is_object($v)) { - $array[$k] = paylineUtil::responseToArray($v); - } - else { $array[$k] = $v; - } - } - return $array; - - return $response; - } - - static function responseToArrayForGetCards($response){ - - $array = array(); - foreach($response as $k=>$v){ - - if (is_object($v) && ($k != 'cards' ) ) { - $array[$k] = paylineUtil::responseToArrayForGetCards($v); - } - else { - if($k == 'cards' && count($v) == 1 ){ - $array[$k][0] = $v; - }else{ - $array[$k] = $v; - } - } - } - return $array; - - return $response; - } -} - -// -// PL_PAYMENT OBJECT DEFINITION -// -class pl_payment{ - - // ATTRIBUTES LISTING - public $amount; - public $currency; - public $action; - public $mode; - public $method; - public $contractNumber; - public $differedActionDate; -} - -// -// PL_ORDER OBJECT DEFINITION -// -class pl_order{ - - // ATTRIBUTES LISTING - public $ref; - public $origin; - public $country; - public $taxes; - public $amount; - public $currency; - public $date; - public $quantity; - public $comment; - public $details; - public $deliveryTime; - public $deliveryMode; - public $deliveryExpectedDate; - public $deliveryExpectedDelay; - - function __construct() { - $this->date = date('d/m/Y H:i', time()); - $this->details = array(); - } -} - -// -// PL_PRIVATEDATA OBJECT DEFINITION -// -class pl_privateData{ - - // ATTRIBUTES LISTING - public $key ; - public $value; -} - -// -// PL_AUTHORIZATION OBJECT DEFINITION -// -class pl_authorization{ - - // ATTRIBUTES LISTING - public $number; - public $date; -} - -// -// PL_ADDRESS OBJECT DEFINITION -// -class pl_address{ - - // ATTRIBUTES LISTING - public $title; - public $firstName; - public $lastName; - public $name; - public $street1; - public $street2; - public $cityName; - public $zipCode; - public $country; - public $county; - public $state; - public $phoneType; - public $phone; -} - -// -// PL_OWNERADDRESS OBJECT DEFINITION -// -class pl_ownerAddress{ - - // ATTRIBUTES LISTING - public $street; - public $cityName; - public $zipCode; - public $country; - public $phone; -} - -// -// PL_BUYER OBJECT DEFINITION -// -class pl_buyer{ - - // ATTRIBUTES LISTING - public $title; - public $lastName; - public $firstName; - public $email; - public $customerId; - public $walletId; - public $walletDisplayed; - public $walletSecured; - public $walletCardInd; - public $shippingAdress; - public $billingAddress; - public $accountCreateDate; - public $accountAverageAmount; - public $accountOrderCount; - public $ip; - public $mobilePhone; - public $legalStatus; - public $legalDocument; - public $birthDate; - public $fingerprintID; - - function __construct() { - $this->accountCreateDate = date('d/m/y', time()); - } -} - -// -// PL_OWNER OBJECT DEFINITION -// -class pl_owner{ - - // ATTRIBUTES LISTING - public $lastName; - public $firstName; - public $billingAddress; - public $issueCardDate; -} - -// -// PL_ORDERDETAIL OBJECT DEFINITION -// -class pl_orderDetail{ - - // ATTRIBUTES LISTING - public $ref; - public $price; - public $quantity; - public $comment; - public $category; - public $subcategory1; - public $subcategory2; - public $brand; - public $additionalData; - public $taxRate; -} - -// -// PL_CARD OBJECT DEFINITION -// -class pl_card{ - - // ATTRIBUTES LISTING - public $number; - public $type; - public $expirationDate; - public $cvx; - public $ownerBirthdayDate; - public $password; - public $cardPresent; - public $cardholder; - public $token; - - function __construct($type) { - $this->accountCreateDate = date('d/m/y', time()); - } -} - - -// -// PL_TRANSACTION OBJECT DEFINITION -// -class pl_transaction{ - - // ATTRIBUTES LISTING - public $id; - public $isPossibleFraud; - public $isDuplicated; - public $date; -} - - -// -// PL_RESULT OBJECT DEFINITION -// -class pl_result{ - - // ATTRIBUTES LISTING - public $code; - public $shortMessage; - public $longMessage; -} - -// -// PL_CAPTURE OBJECT DEFINITION -// -class pl_capture{ - - // ATTRIBUTES LISTING - public $transactionID; - public $payment; - public $sequenceNumber; - - function __construct() { - $this->payment = new pl_payment(); - } -} - -// -// PL_REFUND OBJECT DEFINITION -// -class pl_refund extends pl_capture { - function __construct() { - parent::__construct(); - } -} - -// -// PL_WALLET OBJECT DEFINITION -// -class pl_wallet{ - - // ATTRIBUTES LISTING - public $walletId; - public $lastName; - public $firstName; - public $email; - public $shippingAddress; - public $card; - public $comment; - public $default; - public $cardStatus; - - function __construct() { - } -} - -// -// PL_RECURRING OBJECT DEFINITION -// -class pl_recurring{ - - // ATTRIBUTES LISTING - public $firstAmount; - public $amount; - public $billingCycle; - public $billingLeft; - public $billingDay; - public $startDate; - public $endDate; - public $newAmount; - public $amountModificationDate; - - function __construct() { - } -} - -// -// PL_BILLINGRECORD OBJECT DEFINITION -// -class pl_billingRecord{ - - // ATTRIBUTES LISTING - public $date; - public $amount; - public $status; - public $executionDate; - - function __construct() { - } -} - -// -// PL_AUTHENTIFICATION 3D SECURE -// -class pl_authentication3DSecure{ - - // ATTRIBUTES LISTING - public $md ; - public $pares ; - public $xid ; - public $eci ; - public $cavv ; - public $cavvAlgorithm ; - public $vadsResult ; - public $typeSecurisation; - - function __construct() { - } -} - -// -// PL_BANKACCOUNTDATA -// -class pl_bankAccountData{ - - - // ATTRIBUTES LISTING - public $countryCode ; - public $bankCode ; - public $accountNumber ; - public $key ; - - - function __construct() { - } -} - -// -// PL_CHEQUE -// -class pl_cheque{ - - // ATTRIBUTES LISTING - public $number ; - - function __construct() { - } -} - -final class paylineLog { - private $filename; - private $path; - - public function __construct($filename, $path=null) { - $this->filename = $filename; - if($path == null){ - $tmp = explode(DIRECTORY_SEPARATOR ,dirname(__FILE__)); - - // up one level from the current directory - for($i=0,$s = sizeof($tmp)-1; $i<$s; $i++){ - $this->path .= $tmp[$i].DIRECTORY_SEPARATOR; - } - $this->path .= 'logs'.DIRECTORY_SEPARATOR; - }else{ - $this->path = $path; - } - } - - public function write($message) { - $file = $this->path.$this->filename; - $handle = fopen($file, 'a+'); - fwrite($handle, date('Y-m-d G:i:s') . ' - ' . $message . "\n"); - fclose($handle); - } -} - -// -// PAYLINESDK CLASS -// -class paylineSDK{ - - // kit version - const KIT_VERSION = 'module Magento 1.8.5.7'; - - // trace log - var $logger; - var $flagLog; // 0 : pas de log / 1 : log par défaut / 2 : chemin personnalisé (pathLog) - var $pathLog; - - // environement flags - const ENV_DEV = "DEV"; - const ENV_HOMO = "HOMO"; - const ENV_PROD = "PROD"; - - // SOAP URL's - const PAYLINE_NAMESPACE = 'http://obj.ws.payline.experian.com'; - const WSDL = 'v4.44.wsdl'; - const DEV_ENDPOINT = 'https://ws.dev.payline.com/V4/services/'; - const HOMO_ENDPOINT = 'https://homologation.payline.com/V4/services/'; - const PROD_ENDPOINT = 'https://services.payline.com/V4/services/'; - - // getToken servlet URL - const DEV_GET_TOKEN_SERVLET = "https://webpayment.dev.payline.com/webpayment/getToken"; - const HOMO_GET_TOKEN_SERVLET = "https://homologation-webpayment.payline.com/webpayment/getToken"; - const PROD_GET_TOKEN_SERVLET = "https://webpayment.payline.com/webpayment/getToken"; - - // Widget JavaScript - const HOMO_WDGT_JS = "https://homologation-payment.payline.com/scripts/widget-min.js"; - const PROD_WDGT_JS = "https://payment.payline.com/scripts/widget-min.js"; - const DEV_WDGT_JS = "https://webpayment.dev.payline.com/payline-widget/scripts/widget-min.js"; - - // Widget css - const DEV_WDGT_CSS = "https://webpayment.dev.payline.com/payline-widget/styles/widget-min.css"; - const HOMO_WDGT_CSS = "https://homologation-payment.payline.com/styles/widget-min.css"; - const PROD_WDGT_CSS = "https://payment.payline.com/styles/widget-min.css"; - - - // Administration center - const DEV_CA = 'https://admin.dev.payline.aixlan.local:9363'; - const HOMO_CA = 'https://homologation-admin.payline.com'; - const PROD_CA = 'https://admin.payline.com'; - - // APIs - const DIRECT_API = 'DirectPaymentAPI'; - const EXTENDED_API = 'ExtendedAPI'; - const WEB_API = 'WebPaymentAPI'; - - // current endpoint - private $webServicesEndpoint; - - // current url to get token - private $servletTokenUrl; - - private $widgetJavascriptUrl; - private $widgetCssUrl; - - // SOAP ACTIONS CONSTANTS - const soap_result = 'result'; - const soap_authorization = 'authorization'; - const soap_card = 'card'; - const soap_order = 'order'; - const soap_orderDetail = 'orderDetail'; - const soap_payment = 'payment'; - const soap_transaction = 'transaction'; - const soap_privateData = 'privateData'; - const soap_buyer = 'buyer'; - const soap_owner = 'owner'; - const soap_address = 'address'; - const soap_ownerAddress = 'addressOwner'; - const soap_capture = 'capture'; - const soap_refund = 'refund'; - const soap_refund_auth = 'refundAuthorization'; - const soap_authentication3DSecure = 'authentication3DSecure'; - const soap_bankAccountData = 'bankAccountData'; - const soap_cheque = 'cheque'; - - const ERR_CODE = 'XXXXX'; - - // ARRAY - public $header_soap; - public $items; - public $privates; - - // OPTIONS - public $cancelURL; - public $securityMode; - public $notificationURL; - public $returnURL; - public $customPaymentTemplateURL; - public $customPaymentPageCode; - public $languageCode; - - // WALLET - public $walletIdList; - - // custom logo path - const DEFAULT_LOGO_DIR = 'customLogos'; - var $customLogoPath = ''; - - // getMerchantSettings Array - private $posData; - private $paymentMeansLogos; - - /** - * contructor of PAYLINESDK CLASS - **/ - function __construct($merchant_id, $access_key, $proxy_host, $proxy_port, $proxy_login, $proxy_password, $environment, $pathLog = null) { - if(is_null($pathLog)){ - $this->flagLog = 1; - }elseif (strlen($pathLog) == 0){ - $this->flagLog = 0; - }else{ - $this->flagLog = 2; - $this->pathLog = $pathLog; - } - - $this->writeTrace('----------------------------------------------------------'); - $this->writeTrace('paylineSDK::__construct('.$this->hideChars($merchant_id,6,1).', '.$this->hideChars($access_key,1,3).", $proxy_host, $proxy_port, $proxy_login, ".$this->hideChars($proxy_password,1,1).", $environment)"); - $this->header_soap = array(); - $this->header_soap['login'] = $merchant_id; - $this->header_soap['password'] = $access_key; - if($proxy_host != ''){ - $this->header_soap['proxy_host'] = $proxy_host; - $this->header_soap['proxy_port'] = $proxy_port; - $this->header_soap['proxy_login'] = $proxy_login; - $this->header_soap['proxy_password'] = $proxy_password; - } - - if(strcmp($environment,paylineSDK::ENV_DEV)==0){ - $this->webServicesEndpoint = paylineSDK::DEV_ENDPOINT; - $this->widgetJavascriptUrl = paylineSDK::DEV_WDGT_JS; - $this->widgetCssUrl = paylineSDK::DEV_WDGT_CSS; - }elseif(strcmp($environment,paylineSDK::ENV_PROD)==0){ - $this->webServicesEndpoint = paylineSDK::PROD_ENDPOINT; - $this->servletTokenUrl = paylineSDK::PROD_GET_TOKEN_SERVLET; - $this->widgetJavascriptUrl = paylineSDK::PROD_WDGT_JS; - $this->widgetCssUrl = paylineSDK::PROD_WDGT_CSS; - }elseif(strcmp($environment,paylineSDK::ENV_HOMO)==0){ - $this->webServicesEndpoint = paylineSDK::HOMO_ENDPOINT; - $this->servletTokenUrl = paylineSDK::HOMO_GET_TOKEN_SERVLET; - $this->widgetJavascriptUrl = paylineSDK::HOMO_WDGT_JS; - $this->widgetCssUrl = paylineSDK::HOMO_WDGT_CSS; - } - - $this->header_soap['style'] = SOAP_DOCUMENT; - $this->header_soap['use'] = SOAP_LITERAL; - $this->items = array(); - $this->privates = array(); - $this->walletIdList = array(); - - ini_set('user_agent', "PHP\r\nversion: ".paylineSDK::KIT_VERSION); - } - - /** - * function payment - * @params : $array : array. the array keys are listed in pl_payment CLASS. - * @return : SoapVar : object - * @description : build pl_payment instance from $array and make SoapVar object for payment. - **/ - protected function payment($array) { - $payment = new pl_payment(); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $payment)&&(strlen($v))){ - $payment->$k = $v; - } - } - } - return new SoapVar($payment, SOAP_ENC_OBJECT, paylineSDK::soap_payment, paylineSDK::PAYLINE_NAMESPACE); - } - - /** - * function order - * @params : $array : array. the array keys are listed in pl_order CLASS. - * @return : SoapVar : object - * @description : build pl_order instance from $array and make SoapVar object for order. - **/ - protected function order($array) { - $order = new pl_order(); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $order)&&(strlen($v))){ - $order->$k = $v; - } - } - } - $allDetails = array(); - // insert orderDetails - $order->details = $this->items; - return new SoapVar($order, SOAP_ENC_OBJECT, paylineSDK::soap_order, paylineSDK::PAYLINE_NAMESPACE); - } - - /** - * function address - * @params : $address : array. the array keys are listed in pl_address CLASS. - * @return : SoapVar : object - * @description : build pl_address instance from $array and make SoapVar object for address. - **/ - protected function address($array) { - $address = new pl_address(); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $address)&&(strlen($v)))$address->$k = $v; - } - } - return new SoapVar($address, SOAP_ENC_OBJECT, paylineSDK::soap_address, paylineSDK::PAYLINE_NAMESPACE); - } - - /** - * function ownerAddress - * @params : $address : array. the array keys are listed in pl_address CLASS. - * @return : SoapVar : object - * @description : build pl_ownerAddress instance from $array and make SoapVar object for address. - **/ - protected function ownerAddress($array) { - $address = new pl_ownerAddress(); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $address)&&(strlen($v)))$address->$k = $v; - } - } - return new SoapVar($address, SOAP_ENC_OBJECT, paylineSDK::soap_ownerAddress, paylineSDK::PAYLINE_NAMESPACE); - } - - /** - * function buyer - * @params : $array : array. the array keys are listed in pl_buyer CLASS. - * @params : $shippingAdress : array. the array keys are listed in pl_address CLASS. - * @params : $billingAddress : array. the array keys are listed in pl_address CLASS. - * @return : SoapVar : object - * @description : build pl_buyer instance from $array and $address and make SoapVar object for buyer. - **/ - protected function buyer($array,$shippingAdress,$billingAddress) { - $buyer = new pl_buyer(); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $buyer)&&(strlen($v)))$buyer->$k = $v; - } - } - $buyer->shippingAdress = $this->address($shippingAdress); - $buyer->billingAddress = $this->address($billingAddress); - return new SoapVar($buyer, SOAP_ENC_OBJECT, paylineSDK::soap_buyer, paylineSDK::PAYLINE_NAMESPACE); - } - - /** - * function owner - * @params : $array : array. the array keys are listed in pl_buyer CLASS. - * @params : $shippingAdress : array. the array keys are listed in pl_address CLASS. - * @params : $billingAddress : array. the array keys are listed in pl_address CLASS. - * @return : SoapVar : object - * @description : build pl_buyer instance from $array and $address and make SoapVar object for buyer. - **/ - protected function owner($array,$Address) { - if($array != null){ - $owner = new pl_owner(); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $owner)&&(strlen($v)))$owner->$k = $v; - } - } - $owner->billingAddress = $this->ownerAddress($Address); - return new SoapVar($owner, SOAP_ENC_OBJECT, paylineSDK::soap_owner, paylineSDK::PAYLINE_NAMESPACE); - }else{ - return null; - } - } - - /** - * function contracts - * @params : $contracts : array. array of contracts - * @return : $contracts : array. the same as params if exist, or an array with default contract defined in - * configuration - * @description : Add datas to contract array - **/ - protected function contracts($contracts) { - if($contracts && is_array($contracts)){ - return $contracts; - } - return null; - } - - /** - * function secondContracts - * @params : $secondContracts : array. array of contracts - * @return : $secondContracts : array. the same as params if exist, null otherwise - * @description : Add datas to contract array - **/ - protected function secondContracts($secondContracts) { - if($secondContracts && is_array($secondContracts)){ - return $secondContracts; - } - return null; - } - - /** - * function authentification 3Dsecure - * @params : $array : array. the array keys are listed in pl_card CLASS. - * @return : SoapVar : object - * @description : build pl_authentication3DSecure instance from $array and make SoapVar object for authentication3DSecure. - **/ - protected function authentication3DSecure($array) { - $authentication3DSecure = new pl_authentication3DSecure($array); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $authentication3DSecure)&&(strlen($v))){ - $authentication3DSecure->$k = $v; - } - } - } - return new SoapVar($authentication3DSecure, SOAP_ENC_OBJECT, paylineSDK::soap_authentication3DSecure, paylineSDK::PAYLINE_NAMESPACE); - } - - /** - * function authorization - * @params : $array : array. the array keys are listed in pl_card CLASS. - * @return : SoapVar : object - * @description : build pl_authentication3DSecure instance from $array and make SoapVar object for authentication3DSecure. - **/ - protected function authorization($array) { - $authorization = new pl_authorization($array); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $authorization)&&(strlen($v))){ - $authorization->$k = $v; - } - } - } - return new SoapVar($authorization, SOAP_ENC_OBJECT, paylineSDK::soap_authorization, paylineSDK::PAYLINE_NAMESPACE); - } - - /** - * function card - * @params : $array : array. the array keys are listed in pl_card CLASS. - * @return : SoapVar : object - * @description : build pl_card instance from $array and make SoapVar object for card. - **/ - protected function card($array) { - $card = new pl_card($array['type']); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $card)&&(strlen($v))){ - $card->$k = $v; - } - } - } - return new SoapVar($card, SOAP_ENC_OBJECT, paylineSDK::soap_card, paylineSDK::PAYLINE_NAMESPACE); - } - - - - /** - * function bankAccountData - * @params : $array : array. the array keys are listed in pl_bankAccountData CLASS. - * @return : SoapVar : object - * @description : build pl_bankAccountData instance from $array and make SoapVar object for bankAccountData. - **/ - protected function bankAccountData($array) { - $bankAccountData = new pl_bankAccountData($array); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $bankAccountData)&&(strlen($v))){ - $bankAccountData->$k = $v; - } - } - } - return new SoapVar($bankAccountData, SOAP_ENC_OBJECT, paylineSDK::soap_bankAccountData, paylineSDK::PAYLINE_NAMESPACE); - } - - /** - * function cheque - * @params : $array : array. the array keys are listed in pl_cheque CLASS. - * @return : SoapVar : object - * @description : build pl_authentication3DSecure instance from $array and make SoapVar object for cheque. - **/ - protected function cheque($array) { - $cheque = new pl_cheque($array); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $cheque)&&(strlen($v))){ - $cheque->$k = $v; - } - } - } - return new SoapVar($cheque, SOAP_ENC_OBJECT, paylineSDK::soap_cheque, paylineSDK::PAYLINE_NAMESPACE); - } - - /****************************************************/ - // WALLET // - /****************************************************/ - - /** - * function wallet - * @params : array : array. the array keys are listed in pl_wallet CLASS. - * @params : address : array. the array keys are listed in pl_address CLASS. - * @params : card : array. the array keys are listed in pl_card CLASS. - * @return : wallet: pl_wallet Object. - * @description : build a wallet object. - **/ - protected function wallet($array,$address,$card) { - $wallet = new pl_wallet(); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $wallet)&&(strlen($v)))$wallet->$k = $v; - } - } - - $wallet->shippingAddress = $this->address($address); - $wallet->card = $this->card($card); - - return $wallet; - } - - /** - * function recurring - * @params : array : array. the array keys are listed in pl_recurring CLASS. - * @return : recurring object. - * @description : build a recurring object. - **/ - protected function recurring($array) { - if($array){ - $recurring = new pl_recurring(); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $recurring)&&(strlen($v)))$recurring->$k = $v; - } - } - return $recurring; - } - else return null; - } - - /** - * function billingRecord - * @params : array : array. the array keys are listed in pl_billingRecord CLASS. - * @return : billingRecord object. - * @description : build a billingRecord object. - **/ - protected function billingRecord($array) { - if($array){ - $billingRecord = new pl_billingRecord(); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $billingRecord)&&(strlen($v)))$billingRecord->$k = $v; - } - } - return $billingRecord; - } - else return null; - } - - /** - * function setItem - * @params : $item : array. the array keys are listed in PL_ORDERDETAIL CLASS. - * @description : Make $item SoapVar object and insert in items array - **/ - public function setItem($item) { - $orderDetail = new pl_orderDetail(); - if($item && is_array($item)){ - foreach($item as $k=>$v){ - if(array_key_exists($k, $orderDetail)&&(strlen($v)))$orderDetail->$k = $v; - } - } - $this->items[] = new SoapVar($orderDetail, SOAP_ENC_OBJECT, paylineSDK::soap_orderDetail, paylineSDK::PAYLINE_NAMESPACE); - } - - /** - * function setPrivate - * @params : $private : array. the array keys are listed in PRIVATE CLASS. - * @description : Make $setPrivate SoapVar object and insert in privates array - **/ - public function setPrivate($array) { - $private = new pl_privateData(); - if($array && is_array($array)){ - foreach($array as $k=>$v){ - if(array_key_exists($k, $private)&&(strlen($v)))$private->$k = $v; - } - } - $this->privates[] = new SoapVar($private, SOAP_ENC_OBJECT, paylineSDK::soap_privateData, paylineSDK::PAYLINE_NAMESPACE); - } - - /** - * function setWalletIdList - * @params : sting : string if wallet id separated by ';'. - * @return : - * @description : make an array of wallet id . - **/ - public function setWalletIdList($walletIdList) { - if ($walletIdList) $this->walletIdList = explode(";", $walletIdList); - if(empty($walletIdList))$this->walletIdList = array(0) ; - } - - /** - * Hide characters in a string - * @param String $inString : the string to hide - * @param int $n1 : number of characters shown at the begining of the string - * @param int $n2 : number of characters shown at end begining of the string - */ - private function hideChars($inString, $n1, $n2){ - $inStringLength = strlen($inString); - if($inStringLength < ($n1+$n2)){ - return $inString; - } - $outString = substr($inString,0,$n1); - $outString .= substr("********************",0,$inStringLength-($n1+$n2)); - $outString .= substr($inString,-($n2)); - return $outString; - } - - /** - * @method writeTrace - * @desc write a trace in Payline log file - * @param $trace : the string to add in the log file - */ - public function writeTrace($trace){ - if($this->flagLog == 0){ - return; - }else{ - if(!isset($this->logger)){ - if($this->flagLog == 1){ // log dans le répertoire par défaut - $this->logger = new paylineLog(date('Y-m-d',time()).'.log'); - } - if($this->flagLog == 2){ // log dans un répertoire spécifié - $this->logger = new paylineLog(date('Y-m-d',time()).'.log',$this->pathLog); - } - } - $this->logger->write($trace); - } - } - - /** - * Custom base64 url encoding. Replace unsafe url chars - * - * @param string $input - * @return string - */ - public function base64_url_encode($input) - { - return strtr(base64_encode($input), '+/=', '-_,'); - } - - /** - * Custom base64 url decode. Replace custom url safe values with normal - * base64 characters before decoding. - * - * @param string $input - * @return string - */ - public function base64_url_decode($input) - { - return base64_decode(strtr($input, '-_,', '+/=')); - } - - // MCRYPT_RIJNDAEL_128 : AES compliant - public function getEncrypt($message, $accessKey){ - $block = mcrypt_get_block_size('rijndael_128', 'ecb'); - $pad = $block - (strlen($message) % $block); - $message .= str_repeat(chr($pad), $pad); - return $this->base64_url_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $accessKey, $message, MCRYPT_MODE_ECB)); - } - - public function getDecrypt($message, $accessKey){ - $message = $this->base64_url_decode($message); - $message = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $accessKey, $message, MCRYPT_MODE_ECB); - $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); - $pad = ord($message[($len = strlen($message)) - 1]); - $len = strlen($message); - $pad = ord($message[$len-1]); - $return = substr($message, 0, strlen($message) - $pad); - $this->writeTrace("getDecrypt($message, $accessKey) = $return"); - return $return; - } - - public function gzdecode($data,&$filename='',&$error='',$maxlength=null) - { - $this->writeTrace("gzdecode($data,$filename,$error,$maxlength)"); - $len = strlen($data); - if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) { - $error = "Not in GZIP format."; - return null; // Not GZIP format (See RFC 1952) - } - $method = ord(substr($data,2,1)); // Compression method - $flags = ord(substr($data,3,1)); // Flags - if ($flags & 31 != $flags) { - $error = "Reserved bits not allowed."; - return null; - } - // NOTE: $mtime may be negative (PHP integer limitations) - $mtime = unpack("V", substr($data,4,4)); - $mtime = $mtime[1]; - $xfl = substr($data,8,1); - $os = substr($data,8,1); - $headerlen = 10; - $extralen = 0; - $extra = ""; - if ($flags & 4) { - // 2-byte length prefixed EXTRA data in header - if ($len - $headerlen - 2 < 8) { - return false; // invalid - } - $extralen = unpack("v",substr($data,8,2)); - $extralen = $extralen[1]; - if ($len - $headerlen - 2 - $extralen < 8) { - return false; // invalid - } - $extra = substr($data,10,$extralen); - $headerlen += 2 + $extralen; - } - $filenamelen = 0; - $filename = ""; - if ($flags & 8) { - // C-style string - if ($len - $headerlen - 1 < 8) { - return false; // invalid - } - $filenamelen = strpos(substr($data,$headerlen),chr(0)); - if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) { - return false; // invalid - } - $filename = substr($data,$headerlen,$filenamelen); - $headerlen += $filenamelen + 1; - } - $commentlen = 0; - $comment = ""; - if ($flags & 16) { - // C-style string COMMENT data in header - if ($len - $headerlen - 1 < 8) { - return false; // invalid - } - $commentlen = strpos(substr($data,$headerlen),chr(0)); - if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) { - return false; // Invalid header format - } - $comment = substr($data,$headerlen,$commentlen); - $headerlen += $commentlen + 1; - } - $headercrc = ""; - if ($flags & 2) { - // 2-bytes (lowest order) of CRC32 on header present - if ($len - $headerlen - 2 < 8) { - return false; // invalid - } - $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff; - $headercrc = unpack("v", substr($data,$headerlen,2)); - $headercrc = $headercrc[1]; - if ($headercrc != $calccrc) { - $error = "Header checksum failed."; - return false; // Bad header CRC - } - $headerlen += 2; - } - // GZIP FOOTER - $datacrc = unpack("V",substr($data,-8,4)); - $datacrc = sprintf('%u',$datacrc[1] & 0xFFFFFFFF); - $isize = unpack("V",substr($data,-4)); - $isize = $isize[1]; - // decompression: - $bodylen = $len-$headerlen-8; - if ($bodylen < 1) { - // IMPLEMENTATION BUG! - return null; - } - $body = substr($data,$headerlen,$bodylen); - $data = ""; - if ($bodylen > 0) { - switch ($method) { - case 8: - // Currently the only supported compression method: - $data = gzinflate($body,$maxlength); - break; - default: - $error = "Unknown compression method."; - return false; - } - } // zero-byte body content is allowed - // Verifiy CRC32 - $crc = sprintf("%u",crc32($data)); - $crcOK = $crc == $datacrc; - $lenOK = $isize == strlen($data); - if (!$lenOK || !$crcOK) { - $error = ( $lenOK ? '' : 'Length check FAILED. ') . ( $crcOK ? '' : 'Checksum FAILED.'); - return false; - } - return $data; - } - - private function webServiceRequest($array,$WSRequest,$PaylineAPI,$Method){ - $reqTrace = "Request : $PaylineAPI.$Method"; - $resTrace = ''; - try{ - $client = new SoapClient(dirname(__FILE__).'/'.paylineSDK::WSDL, $this->header_soap); - $client->__setLocation ($this->webServicesEndpoint.$PaylineAPI); - - if(isset($array['version'])&& strlen($array['version'])) - $WSRequest['version'] = $array['version']; - else - $WSRequest['version'] = ''; - if(isset($array['media'])&& strlen($array['media'])) - $WSRequest['media'] = $array['media']; - else - $WSRequest['media'] = ''; - - switch($Method){ - case 'createMerchant': - $WSresponse = $client->createMerchant($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'createWallet': - $reqTrace .= '(contract = '.$array['contractNumber'].' - walletId = '.$array['wallet']['walletId'].' - card = '.$this->hideChars($array['card']['number'],4,4).')'; - $WSresponse = $client->createWallet($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'createWebWallet': - $reqTrace .= '(contract = '.$array['contractNumber'].' - walletId = '.$array['buyer']['walletId'].')'; - $WSresponse = $client->createWebWallet($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - if($response['result']['code'] == '00000'){ - $resTrace = ' - token = '.$response['token']; - } - break; - case 'updatePaymentRecord': - $reqTrace .= '(contract = '.$array['contractNumber'].' - paymentRecordId = '.$array['paymentRecordId'].')'; - $WSresponse = $client->updatePaymentRecord($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'getBillingRecord': - $reqTrace .= '(contract = '.$array['contractNumber'].' - paymentRecordId = '.$array['paymentRecordId'].' - billingRecordId = '.$array['billingRecordId'].')'; - $WSresponse = $client->getBillingRecord($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'updateBillingRecord': - $reqTrace .= '(contract = '.$array['contractNumber'].' - paymentRecordId = '.$array['paymentRecordId'].' - billingRecordId = '.$array['billingRecordId'].')'; - $WSresponse = $client->updateBillingRecord($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'disablePaymentRecord': - $reqTrace .= '(contract = '.$array['contractNumber'].' - paymentRecordId = '.$array['paymentRecordId'].')'; - $WSresponse = $client->disablePaymentRecord($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'disableWallet': - $reqTrace .= '(contract = '.$array['contractNumber'].' - walletIdList = '.implode(';', $this->walletIdList).')'; - $WSresponse = $client->disableWallet($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'doAuthorization': - $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - amount = '.$array['payment']['amount'].')'; - $WSresponse = $client->doAuthorization($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - $resTrace = ' - transactionID = '.$response['transaction']['id']; - break; - case 'doCapture': - $reqTrace .= '(transactionID = '.$array['transactionID'].' - amount = '.$array['payment']['amount'].')'; - $WSresponse = $client->doCapture($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - $resTrace = ' - transactionID = '.$response['transaction']['id']; - break; - case 'doCredit': - $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - order.ref = '.$array['order']['ref'].' - card = '.$this->hideChars($array['card']['number'],4,4).')'; - $WSresponse = $client->doCredit($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - $resTrace = ' - transactionID = '.$response['transaction']['id']; - break; - case 'doDebit': - $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - order.ref = '.$array['order']['ref'].' - card = '.$this->hideChars($array['card']['number'],4,4).')'; - $WSresponse = $client->doDebit($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - $resTrace = ' - transactionID = '.$response['transaction']['id']; - break; - case 'doImmediateWalletPayment': - $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - walletId = '.$array['walletId'].' - order.ref = '.$array['order']['ref'].')'; - $WSresponse = $client->doImmediateWalletPayment($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - $resTrace = ' - transactionID = '.$response['transaction']['id']; - break; - case 'doReAuthorization': - $reqTrace .= '(transactionID = '.$array['transactionID'].' - amount = '.$array['payment']['amount'].')'; - $WSresponse = $client->doReAuthorization($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - $resTrace = ' - transactionID = '.$response['transaction']['id']; - break; - case 'doRecurrentWalletPayment': - $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - walletId = '.$array['walletId'].' - order.ref = '.$array['order']['ref'].')'; - $WSresponse = $client->doRecurrentWalletPayment($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - if($response['result']['code'] == '02500'){ - $resTrace = ' - paymentRecordId = '.$response['paymentRecordId']; - } - break; - case 'doRefund': - $reqTrace .= '(transactionID = '.$array['transactionID'].' - amount = '.$array['payment']['amount'].')'; - $WSresponse = $client->doRefund($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - $resTrace = ' - transactionID = '.$response['transaction']['id']; - break; - case 'doReset': - $reqTrace .= '(transactionID = '.$array['transactionID'].')'; - $WSresponse = $client->doReset($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - $resTrace = ' - transactionID = '.$response['transaction']['id']; - break; - case 'doScheduledWalletPayment': - $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - walletId = '.$array['walletId'].' - order.ref = '.$array['order']['ref'].')'; - $WSresponse = $client->doScheduledWalletPayment($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - if($response['result']['code'] == '02500'){ - $resTrace = ' - paymentRecordId = '.$response['paymentRecordId']; - } - break; - case 'doScoringCheque': - $WSresponse = $client->doScoringCheque($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'doWebPayment': - $reqTrace .= '(order.ref = '.$array['order']['ref'].')'; - $WSresponse = $client->doWebPayment($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - if($response['result']['code'] == '00000'){ - $resTrace = ' - token = '.$response['token']; - } - break; - case 'enableWallet': - $reqTrace .= '(walletId = '.$array['walletId'].')'; - $WSresponse = $client->enableWallet($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'getAlertDetails': - $reqTrace .= '(alertId = '.$array['AlertId'].' - transactionId = '.$array['TransactionId'].')'; - $WSresponse = $client->getAlertDetails($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'getBalance': - $reqTrace .= '(contract = '.$array['contractNumber'].' - cardID = '.$this->hideChars($array['cardID'],4,4).')'; - $WSresponse = $client->getBalance($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'getCards': - $reqTrace .= '(contract - '.$array['contractNumber'].' - walletId = '.$array['walletId'].' - cardInd = '.$array['cardInd'].')'; - $WSresponse = $client->getCards($WSRequest); - $response = paylineUtil::responseToArrayForGetCards($WSresponse); - break; - case 'getEncryptionKey': - $WSresponse = $client->getEncryptionKey($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'getMerchantSettings': - $WSresponse = $client->getMerchantSettings($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'getPaymentRecord': - $reqTrace .= '(contract = '.$array['contractNumber'].' - paymentRecordId = '.$array['paymentRecordId'].')'; - $WSresponse = $client->getPaymentRecord($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'getToken': - $reqTrace .= '(contract = '.$array['contractNumber'].' - cardNumber = '.$this->hideChars($array['cardNumber'],4,4).')'; - $WSresponse = $client->getToken($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - if($response['result']['code'] == '02500'){ - $resTrace = ' - token = '.$response['token']; - } - break; - case 'getTransactionDetails': - $reqTrace = '(transactionId = '.$array['transactionId'].')'; - $WSresponse = $client->getTransactionDetails($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'getWallet': - $reqTrace .= '(contract = '.$array['contractNumber'].' - walletId = '.$array['walletId'].' - cardInd = '.$array['cardInd'].')'; - $WSresponse = $client->getWallet($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'getWebPaymentDetails': - $reqTrace .= '(token = '.$array['token'].')'; - $WSresponse = $client->getWebPaymentDetails($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - if(isset($response['transaction']['id'])){ - $resTrace = ' - transactionId = '.$response['transaction']['id']; - } - break; - case 'getWebWallet': - $reqTrace .= '(token = '.$array['token'].')'; - $WSresponse = $client->getWebWallet($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - if(isset($response['wallet']['card'])){ - $resTrace = ' - card = '.$this->hideChars($response['wallet']['card']['number'],4,4); - } - break; - case 'manageWebWallet' : - $reqTrace .= '(contract = '.$array['contractNumber'].' - walletId = '.$array['buyer']['walletId'].')'; - $WSresponse = $client->manageWebWallet($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - if($response['result']['code'] == '00000'){ - $resTrace = ' - token = '.$response['token']; - } - break; - case 'transactionsSearch': - $reqTrace .= '('; - foreach ($array as $key => $value) { - $reqTrace .= $value != '' ? "$key = $value - " : ''; - } - $reqTrace .= ')'; - $WSresponse = $client->transactionsSearch($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'unBlock': - $reqTrace .= '(transactionID = '.$array['transactionID'].')'; - $WSresponse = $client->unBlock($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'updateWallet': - $reqTrace .= '(walletId = '.$array['wallet']['walletId'].')'; - $WSresponse = $client->updateWallet($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'updateWebWallet': - $reqTrace .= '(walletId = '.$array['walletId'].')'; - $WSresponse = $client->updateWebWallet($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - if($response['result']['code'] == '00000'){ - $resTrace = ' - token = '.$response['token']; - } - break; - case 'verifyAuthentication': - $reqTrace .= '(contract = '.$array['contractNumber'].' - card = '.$this->hideChars($array['card']['number'],4,4).')'; - $WSresponse = $client->verifyAuthentication($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - case 'verifyEnrollment': - if(!empty($array['card']['number']) and !empty($array['payment']['contractNumber'])) { - $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - card = '.$this->hideChars($array['card']['number'],4,4).')'; - } - $WSresponse = $client->verifyEnrollment($WSRequest); - $response = paylineUtil::responseToArray($WSresponse); - break; - - } - $this->writeTrace($reqTrace); - $this->writeTrace('Response : code = '.$response['result']['code'].$resTrace); - return $response; - }catch ( Exception $e ) { - $this->writeTrace($reqTrace); - $this->writeTrace("Exception : ".$e->getMessage()); - $ERROR = array(); - $ERROR['result']['code'] = paylineSDK::ERR_CODE; - $ERROR['result']['longMessage'] = $e->getMessage(); - $ERROR['result']['shortMessage'] = $e->getMessage(); - return $ERROR; - } - } - - public function createWallet($array){ - if(!isset($array['walletContracts'])||!strlen($array['walletContracts'][0]))$array['walletContracts'] = ''; - if(!isset($array['buyer']))$array['buyer'] = null; - if(!isset($array['billingAddress']))$array['billingAddress'] = null; - if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; - if(!isset($array['owner']))$array['owner'] = null; - if(!isset($array['ownerAddress']))$array['ownerAddress'] = null; - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'wallet' => $this->wallet($array['wallet'],$array['address'],$array['card']), - 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), - 'owner' => $this->owner($array['owner'],$array['ownerAddress']), - 'privateDataList' => $this->privates, - 'authentication3DSecure' =>$this->authentication3DSecure($array['3DSecure']), - 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'createWallet'); - } - - public function createWebWallet($array){ - if(isset($array['customPaymentPageCode'])&& strlen($array['customPaymentPageCode'])) $this->customPaymentPageCode = $array['customPaymentPageCode']; - if(isset($array['cancelURL'])&& strlen($array['cancelURL'])) $this->cancelURL = $array['cancelURL']; - if(isset($array['notificationURL']) && strlen($array['notificationURL'])) $this->notificationURL = $array['notificationURL']; - if(isset($array['returnURL'])&& strlen($array['returnURL'])) $this->returnURL = $array['returnURL']; - if(isset($array['customPaymentTemplateURL'])&& strlen($array['customPaymentTemplateURL'])) $this->customPaymentTemplateURL = $array['customPaymentTemplateURL']; - if(isset($array['customPaymentPageCode'])&& strlen($array['customPaymentPageCode'])) $this->customPaymentPageCode = $array['customPaymentPageCode']; - if(isset($array['languageCode'])&& strlen($array['languageCode'])) $this->languageCode = $array['languageCode']; - if(isset($array['securityMode'])&& strlen($array['securityMode'])) $this->securityMode = $array['securityMode']; - if(!isset($array['contracts'])||!strlen($array['contracts'][0]))$array['contracts'] = ''; - if(!isset($array['walletContracts'])||!strlen($array['walletContracts'][0]))$array['walletContracts'] = ''; - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'selectedContractList' => $this->contracts($array['contracts']), - 'updatePersonalDetails' => $array['updatePersonalDetails'], - 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), - 'languageCode' => $this->languageCode, - 'customPaymentPageCode' => $this->customPaymentPageCode, - 'securityMode' => $this->securityMode, - 'returnURL' => $this->returnURL, - 'cancelURL' => $this->cancelURL, - 'notificationURL' => $this->notificationURL, - 'privateDataList' => $this->privates, - 'customPaymentTemplateURL' => $this->customPaymentTemplateURL, - 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::WEB_API,'createWebWallet'); - } - - public function disablePaymentRecord($array){ - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'paymentRecordId' => $array['paymentRecordId'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'disablePaymentRecord'); - } - - public function disableWallet($array){ - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'walletIdList' => $this->walletIdList, - 'cardInd' => $array['cardInd'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'disableWallet'); - } - - public function doAuthorization($array){ - if(!isset($array['buyer']))$array['buyer'] = null; - if(!isset($array['owner']))$array['owner'] = null; - if(!isset($array['billingAddress']))$array['billingAddress'] = null; - if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; - if(!isset($array['ownerAddress']))$array['ownerAddress'] = null; - if(!isset($array['3DSecure']))$array['3DSecure'] = null; - if(!isset($array['bankAccountData']))$array['bankAccountData'] = null; - $WSRequest = array ( - 'payment' => $this->payment($array['payment']), - 'card' => $this->card($array['card']), - 'order' => $this->order($array['order']), - 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), - 'owner' => $this->owner($array['owner'],$array['ownerAddress']), - 'privateDataList' => $this->privates, - 'authentication3DSecure' =>$this->authentication3DSecure($array['3DSecure']), - 'bankAccountData' => $this->bankAccountData($array['bankAccountData']) - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doAuthorization'); - } - - public function doCapture($array){ - $WSRequest = array ( - 'transactionID' =>$array['transactionID'], - 'payment' => $this->payment($array['payment']), - 'privateDataList' => $this->privates, - 'sequenceNumber'=>$array['sequenceNumber'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doCapture'); - } - - public function doCredit($array){ - if(!isset($array['buyer']))$array['buyer'] = null; - if(!isset($array['billingAddress']))$array['billingAddress'] = null; - if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; - $WSRequest = array ( - 'payment' => $this->payment($array['payment']), - 'card' => $this->card($array['card']), - 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), - 'privateDataList' => $this->privates, - 'order' => $this->order($array['order']), - 'comment' =>$array['comment'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doCredit'); - } - - public function doDebit($array){ - if(!isset($array['buyer']))$array['buyer'] = null; - if(!isset($array['billingAddress']))$array['billingAddress'] = null; - if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; - $WSRequest = array ( - 'payment' => $this->payment($array['payment']), - 'card' => $this->card($array['card']), - 'order' => $this->order($array['order']), - 'privateDataList' => $this->privates, - 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), - 'authentication3DSecure' =>$this->authentication3DSecure($array['3DSecure']), - 'authorization' =>$this->authorization($array['authorization']) - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doDebit'); - } - - public function doImmediateWalletPayment($array){ - if(!isset($array['buyer']))$array['buyer'] = null; - if(!isset($array['billingAddress']))$array['billingAddress'] = null; - if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; - if(!isset($array['3DSecure']))$array['3DSecure'] = null; - $WSRequest = array ( - 'payment' => $this->payment($array['payment']), - 'order' => $this->order($array['order']), - 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), - 'walletId' => $array['walletId'], - 'cardInd' => $array['cardInd'], - 'cvx' => $array['walletCvx'], - 'privateDataList' => $this->privates, - 'authentication3DSecure' =>$this->authentication3DSecure($array['3DSecure']) - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doImmediateWalletPayment'); - } - - public function doReAuthorization($array){ - $WSRequest = array ( - 'transactionID' => $array['transactionID'], - 'payment' => $this->payment($array['payment']), - 'order' => $this->order($array['order']), - 'privateDataList' => $this->privates - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doReAuthorization'); - } - - public function doRecurrentWalletPayment($array){ - if(!isset($array['orderRef']))$array['orderRef'] = null; - if(!isset($array['orderDate']))$array['orderDate'] = null; - if(!isset($array['scheduledDate']))$array['scheduledDate'] = null; - $WSRequest = array ( - 'payment' => $this->payment($array['payment']), - 'orderRef' => $array['orderRef'], - 'orderDate' => $array['orderDate'], - 'scheduledDate' => $array['scheduledDate'], - 'walletId' => $array['walletId'], - 'cardInd' => $array['cardInd'], - 'recurring' => $this->recurring($array['recurring']), - 'privateDataList' => $this->privates, - 'order' => $this->order($array['order']) - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doRecurrentWalletPayment'); - } - - public function doRefund($array){ - $WSRequest = array ( - 'transactionID' =>$array['transactionID'], - 'payment' =>$this->payment($array['payment']), - 'comment' =>$array['comment'], - 'privateDataList' => $this->privates, - 'sequenceNumber'=>$array['sequenceNumber'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doRefund'); - } - - public function doReset($array){ - $WSRequest = array ( - 'transactionID' => $array['transactionID'], - 'comment' => $array['comment'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doReset'); - } - - public function doScheduledWalletPayment($array){ - if(!isset($array['orderRef']))$array['orderRef'] = null; - if(!isset($array['orderDate']))$array['orderDate'] = null; - $WSRequest = array ( - 'payment' => $this->payment($array['payment']), - 'orderRef' => $array['orderRef'], - 'orderDate' => $array['orderDate'], - 'scheduledDate' => $array['scheduledDate'], - 'walletId' => $array['walletId'], - 'cardInd' => $array['cardInd'], - 'order' => $this->order($array['order']), - 'privateDataList' => $this->privates - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doScheduledWalletPayment'); - } - - public function doScoringCheque($array){ - $WSRequest = array ( - 'payment' => $this->payment($array['payment']), - 'cheque' => $this->cheque($array['cheque']), - 'order' => $this->order($array['order']), - 'privateDataList' => $this->privates - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doScoringCheque'); - } - - public function doWebPayment($array){ - if(isset($array['cancelURL'])&& strlen($array['cancelURL'])) $this->cancelURL = $array['cancelURL']; - if(isset($array['notificationURL']) && strlen($array['notificationURL'])) $this->notificationURL = $array['notificationURL']; - if(isset($array['returnURL'])&& strlen($array['returnURL'])) $this->returnURL = $array['returnURL']; - if(isset($array['customPaymentTemplateURL'])&& strlen($array['customPaymentTemplateURL'])) $this->customPaymentTemplateURL = $array['customPaymentTemplateURL']; - if(isset($array['customPaymentPageCode'])&& strlen($array['customPaymentPageCode'])) $this->customPaymentPageCode = $array['customPaymentPageCode']; - if(isset($array['languageCode'])&& strlen($array['languageCode'])) $this->languageCode = $array['languageCode']; - if(isset($array['securityMode'])&& strlen($array['securityMode'])) $this->securityMode = $array['securityMode']; - if(!isset($array['payment']))$array['payment'] = null; - if(!isset($array['contracts'])||!strlen($array['contracts'][0]))$array['contracts'] = ''; - if(!isset($array['secondContracts'])||!strlen($array['secondContracts'][0]))$array['secondContracts'] = ''; - if(!isset($array['walletContracts'])||!strlen($array['walletContracts'][0]))$array['walletContracts'] = ''; - if(!isset($array['buyer']))$array['buyer'] = null; - if(!isset($array['billingAddress']))$array['billingAddress'] = null; - if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; - if(!isset($array['recurring']))$array['recurring'] = null; - - $WSRequest = array ( - 'payment' => $this->payment($array['payment']), - 'returnURL' => $this->returnURL, - 'cancelURL' => $this->cancelURL, - 'order' => $this->order($array['order']), - 'notificationURL' => $this->notificationURL, - 'customPaymentTemplateURL' => $this->customPaymentTemplateURL, - 'selectedContractList' => $this->contracts($array['contracts']), - 'secondSelectedContractList' => $this->secondContracts($array['secondContracts']), - 'privateDataList' => $this->privates, - 'languageCode' => $this->languageCode, - 'customPaymentPageCode' => $this->customPaymentPageCode, - 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), - 'securityMode' => $this->securityMode, - 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) - ); - - - if(isset($array['payment']['mode'])){ - if(($array['payment']['mode'] == "REC") || ($array['payment']['mode'] == "NX")) { - $WSRequest['recurring'] = $this->recurring($array['recurring']); - } - } - return $this->webServiceRequest($array,$WSRequest,paylineSDK::WEB_API,'doWebPayment'); - } - - public function enableWallet($array){ - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'walletId' => $array['walletId'], - 'cardInd' => $array['cardInd'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'enableWallet'); - } - - public function getServletTokenUrl(){ - return $this->servletTokenUrl; - } - - public function getWidgetJavascriptUrl(){ - return $this->widgetJavascriptUrl; - } - - public function getWidgetCssUrl(){ - return $this->widgetCssUrl; - } - - public function getAlertDetails($array){ - $WSRequest = array( - 'AlertId' => $array['AlertId'], - 'TransactionId' => $array['TransactionId'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::EXTENDED_API,'getAlertDetails'); - } - - public function getBalance($array){ - $WSRequest = array( - 'contractNumber' => $array['contractNumber'], - 'cardID' => $array['cardID'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getBalance'); - } - - public function getCards($array){ - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'walletId' => $array['walletId'], - 'cardInd' => $array['cardInd'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getCards'); - } - - public function getEncryptionKey($array){ - $WSRequest = array(); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getEncryptionKey'); - } - - public function getMerchantSettings($array){ - $WSRequest = array(); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getMerchantSettings'); - } - - private function getPaymentMeans(){ - $this->writeTrace('getPaymentMeans'); - try{ - $client = new SoapClient(dirname(__FILE__).'/PaylineByMonext.wsdl', $this->header_soap); - $WSresponse = $client->getPaymentMeans(); - $response = paylineUtil::responseToArray($WSresponse); - $this->writeTrace($response['result']); - return $response; - }catch ( Exception $e ) { - $this->writeTrace("Exception : ".$e->getMessage()); - $ERROR = array(); - $ERROR['result']['code'] = paylineSDK::ERR_CODE; - $ERROR['result']['longMessage'] = $e->getMessage(); - $ERROR['result']['shortMessage'] = $e->getMessage(); - return $ERROR; - } - } - - private function addPOSFromObject($oPointOfSell,$pos){ - if(isset($oPointOfSell->contracts->contract)){ - $this->posData[$pos] = array(); - $this->posData[$pos]['label'] = $oPointOfSell->label; - $this->posData[$pos]['contracts'] = array(); - if(sizeof($oPointOfSell->contracts->contract) > 1){ - // more than 1 active contract in this point of sell - $ctr = 0; - foreach ($oPointOfSell->contracts->contract as $contract){ - $this->posData[$pos]['contracts'][$ctr] = array(); - $this->posData[$pos]['contracts'][$ctr]['cardType'] = $contract->cardType; - $this->posData[$pos]['contracts'][$ctr]['label'] = $contract->label; - $this->posData[$pos]['contracts'][$ctr]['contractNumber'] = $contract->contractNumber; - $this->posData[$pos]['contracts'][$ctr]['logo'] = $this->paymentMeansLogos[$this->posData[$pos]['contracts'][$ctr]['cardType']]; // default logo - if($contract->logoEnable){ - $this->posData[$pos]['contracts'][$ctr]['logo'] = $this->downloadCustomLogo($contract->normalLogo, $contract->normalLogoMime, $contract->contractNumber, $oPointOfSell->label); - } - $ctr++; - } - }else{ // only 1 active contract in this point of sell - $this->posData[$pos]['contracts'][0] = array(); - $this->posData[$pos]['contracts'][0]['cardType'] = $oPointOfSell->contracts->contract->cardType; - $this->posData[$pos]['contracts'][0]['label'] = $oPointOfSell->contracts->contract->label; - $this->posData[$pos]['contracts'][0]['contractNumber'] = $oPointOfSell->contracts->contract->contractNumber; - $this->posData[$pos]['contracts'][0]['logo'] = $this->paymentMeansLogos[$this->posData[$pos]['contracts'][0]['cardType']]; // default logo - if($oPointOfSell->contracts->contract->logoEnable){ - $this->posData[$pos]['contracts'][0]['logo'] = $this->downloadCustomLogo($oPointOfSell->contracts->contract->normalLogo, $oPointOfSell->contracts->contract->normalLogoMime, $oPointOfSell->contracts->contract->contractNumber, $oPointOfSell->label); - } - } - }else{ // no contract in this point of sell - return false; - } - - return true; - } - - private function addPOSFromArray($aPointOfSell,$pos){ - if(isset($aPointOfSell['contracts']['contract'])){ - $this->posData[$pos] = array(); - $this->posData[$pos]['label'] = $aPointOfSell['label']; - $this->posData[$pos]['contracts'] = array(); - if(isset($aPointOfSell['contracts']['contract']['label'])){ - // only 1 active contract in this point of sell - $this->posData[$pos]['contracts'][0] = array(); - $this->posData[$pos]['contracts'][0]['cardType'] = $aPointOfSell['contracts']['contract']['cardType']; - $this->posData[$pos]['contracts'][0]['label'] = $aPointOfSell['contracts']['contract']['label']; - $this->posData[$pos]['contracts'][0]['contractNumber'] = $aPointOfSell['contracts']['contract']['contractNumber']; - $this->posData[$pos]['contracts'][0]['logo'] = $this->paymentMeansLogos[$this->posData[$pos]['contracts'][0]['cardType']]; // default logo - if($aPointOfSell['contracts']['contract']['logoEnable']){ - $this->posData[$pos]['contracts'][0]['logo'] = $this->downloadCustomLogo($aPointOfSell['contracts']['contract']['normalLogo'], $aPointOfSell['contracts']['contract']['normalLogoMime'], $aPointOfSell['contracts']['contract']['contractNumber'], $aPointOfSell['label']); - } - }else{ // more than 1 active contract in this point of sell - $ctr = 0; - foreach ($aPointOfSell['contracts']['contract'] as $contract){ - $this->posData[$pos]['contracts'][$ctr] = array(); - $this->posData[$pos]['contracts'][$ctr]['cardType'] = $contract->cardType; - $this->posData[$pos]['contracts'][$ctr]['label'] = $contract->label; - $this->posData[$pos]['contracts'][$ctr]['contractNumber'] = $contract->contractNumber; - $this->posData[$pos]['contracts'][$ctr]['logo'] = $this->paymentMeansLogos[$this->posData[$pos]['contracts'][$ctr]['cardType']]; // default logo - if($contract->logoEnable){ - $this->posData[$pos]['contracts'][$ctr]['logo'] = $this->downloadCustomLogo($contract->normalLogo, $contract->normalLogoMime, $contract->contractNumber, $aPointOfSell['label']); - } - $ctr++; - } - } - }else{ // no contract in this point of sell - return false; - } - return true; - } - - private function absoluteURL($path) { - $dir = str_replace('\\', '/', dirname($path)); - return $_SERVER['HTTP_ORIGIN'].'/'.substr($dir, strlen($_SERVER['DOCUMENT_ROOT'])).'/'; - } - - private function downloadCustomLogo($base64String,$mimeType,$contractNumber,$posLabel){ - $mime = explode('/', $mimeType); - if($this->customLogoPath != null){ - if(!file_exists($this->customLogoPath)){ - mkdir($this->customLogoPath); - } - $posDir = $this->customLogoPath.$posLabel.DIRECTORY_SEPARATOR; - }else{ - $merchantDir = dirname(__DIR__).DIRECTORY_SEPARATOR.paylineSDK::DEFAULT_LOGO_DIR.DIRECTORY_SEPARATOR.$this->header_soap['login'].DIRECTORY_SEPARATOR; - if(!file_exists($merchantDir)){ - mkdir($merchantDir); - } - $posDir = $merchantDir.$posLabel.DIRECTORY_SEPARATOR; - } - if(!file_exists($posDir)){ - mkdir($posDir); - } - $output_file = $posDir.$contractNumber.'.'.$mime[1]; - - try{ - if(file_put_contents($output_file,$base64String)){ - return $this->absoluteURL($output_file).$contractNumber.'.'.$mime[1]; - }else{ - $this->writeTrace("Error : downloadCustomLogo for contract $contractNumber under $posDir failed"); - return paylineSDK::ERR_CODE; - } - }catch (Exception $e){ - $this->writeTrace("Exception : downloadCustomLogo for contract $contractNumber of pos $posLabel - ".$e->getMessage()); - return paylineSDK::ERR_CODE; - } - } - - public function getMerchantSettingsToArray($array){ - /* - * Association between Payment mean types and logos URL - */ - $getPaymentMeansResponse = $this->getPaymentMeans(); - if($getPaymentMeansResponse['result']['code'] != paylineSDK::ERR_CODE){ - $this->paymentMeansLogos = array(); - for($i=0 ; $ipaymentMeansLogos[$getPaymentMeansResponse['listPaymentMean']['paymentMean'][$i]->code] = $getPaymentMeansResponse['listPaymentMean']['paymentMean'][$i]->logoUrl; - } - } - - if(isset($array['logoPath'])){ - $this->customLogoPath = $array['logoPath']; - } - $getMerchantSettingsRes = $this->getMerchantSettings($array); - if(isset($getMerchantSettingsRes['listPointOfSell']['pointOfSell']['label'])){ - // only 1 active point of sell - $aPointOfSell = $getMerchantSettingsRes['listPointOfSell']['pointOfSell']; - $this->addPOSFromArray($aPointOfSell, 0); - }else{ // more than 1 active point of sell - $index = 0; - foreach ($getMerchantSettingsRes['listPointOfSell']['pointOfSell'] as $oPointOfSell){ - if($this->addPOSFromObject($oPointOfSell, $index)){ - $index++; // no incrementation if pos was not added - } - } - } - $res = array('result' => $getMerchantSettingsRes['result'],'POS' => $this->posData); - return $res; - } - - public function getPaymentRecord($array){ - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'paymentRecordId' => $array['paymentRecordId'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getPaymentRecord'); - } - - public function updatePaymentRecord($array){ - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'paymentRecordId' => $array['paymentRecordId'], - 'recurring' => $this->recurring($array['recurring']), - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'updatePaymentRecord'); - } - - public function getBillingRecord($array){ - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'paymentRecordId' => $array['paymentRecordId'], - 'billingRecordId' => $array['billingRecordId'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getBillingRecord'); - } - - public function updateBillingRecord($array){ - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'paymentRecordId' => $array['paymentRecordId'], - 'billingRecordId' => $array['billingRecordId'], - 'billingRecordForUpdate' => $this->billingRecord($array['billingRecordForUpdate']) - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'updateBillingRecord'); - } - - public function getToken($array){ - $WSRequest = array ( - 'cardNumber' => $array['cardNumber'], - 'expirationDate' => $array['expirationDate'], - 'contractNumber' => $array['contractNumber'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getToken'); - } - - public function getTransactionDetails($array){ - if(!isset($array['transactionId']))$array['transactionId'] = null; - if(!isset($array['orderRef']))$array['orderRef'] = null; - if(!isset($array['startDate']))$array['startDate'] = null; - if(!isset($array['endDate']))$array['endDate'] = null; - if(!isset($array['transactionHistory']))$array['transactionHistory'] = null; - if(!isset($array['archiveSearch']))$array['archiveSearch'] = null; - $WSRequest = array ( - 'transactionId' => $array['transactionId'], - 'orderRef' => $array['orderRef'], - 'startDate' => $array['startDate'], - 'endDate' => $array['endDate'], - 'transactionHistory' => $array['transactionHistory'], - 'archiveSearch' => $array['archiveSearch'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::EXTENDED_API,'getTransactionDetails'); - } - public function getWallet($array){ - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'walletId' => $array['walletId'], - 'cardInd' => $array['cardInd'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getWallet'); - } - - public function getWebPaymentDetails($array){ - return $this->webServiceRequest($array,$array,paylineSDK::WEB_API,'getWebPaymentDetails'); - } - - public function getWebWallet($array){ - return $this->webServiceRequest($array,$array,paylineSDK::WEB_API,'getWebWallet'); - } - - public function manageWebWallet($array){ - if(isset($array['cancelURL'])&& strlen($array['cancelURL'])) $this->cancelURL = $array['cancelURL']; - if(isset($array['notificationURL']) && strlen($array['notificationURL'])) $this->notificationURL = $array['notificationURL']; - if(isset($array['returnURL'])&& strlen($array['returnURL'])) $this->returnURL = $array['returnURL']; - if(!isset($array['buyer']))$array['buyer'] = null; - if(!isset($array['billingAddress']))$array['billingAddress'] = null; - if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; - if(!isset($array['owner']))$array['owner'] = null; - if(!isset($array['ownerAddress']))$array['ownerAddress'] = null; - if(!isset($array['contracts'])||!strlen($array['contracts'][0]))$array['contracts'] = ''; - if(!isset($array['walletContracts'])||!strlen($array['walletContracts'][0]))$array['walletContracts'] = ''; - if(isset($array['customPaymentPageCode'])&& strlen($array['customPaymentPageCode'])) $this->customPaymentPageCode = $array['customPaymentPageCode']; - if(isset($array['customPaymentTemplateURL'])&& strlen($array['customPaymentTemplateURL'])) $this->customPaymentTemplateURL = $array['customPaymentTemplateURL']; - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'selectedContractList' => $this->contracts($array['contracts']), - 'updatePersonalDetails' => $array['updatePersonalDetails'], - 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), - 'owner' => $this->owner($array['owner'],$array['ownerAddress']), - 'languageCode' => $array['languageCode'], - 'customPaymentPageCode' => $array['customPaymentPageCode'], - 'securityMode' => $array['securityMode'], - 'returnURL' => $this->returnURL, - 'cancelURL' => $this->cancelURL, - 'notificationURL' => $this->notificationURL, - 'privateDataList' => $this->privates, - 'customPaymentTemplateURL' => $array['customPaymentTemplateURL'], - 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::WEB_API,'manageWebWallet'); - } - - public function transactionsSearch($array){ - $WSRequest = array ( - 'transactionId' => $array['transactionId'], - 'orderRef' => $array['orderRef'], - 'startDate' => $array['startDate'], - 'endDate' => $array['endDate'], - 'contractNumber' => $array['contractNumber'], - 'authorizationNumber' => $array['authorizationNumber'], - 'returnCode' => $array['returnCode'], - 'paymentMean' => $array['paymentMean'], - 'transactionType' => $array['transactionType'], - 'name' => $array['name'], - 'firstName' => $array['firstName'], - 'email' => $array['email'], - 'cardNumber' => $array['cardNumber'], - 'currency' => $array['currency'], - 'minAmount' => $array['minAmount'], - 'maxAmount' => $array['maxAmount'], - 'walletId' => $array['walletId'], - 'sequenceNumber' => $array['sequenceNumber'], - 'token' => $array['token'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::EXTENDED_API,'transactionsSearch'); - } - - public function unBlock($array){ - $WSRequest = array ( - 'transactionID' => $array['transactionID'], - 'transactionDate' => $array['transactionDate'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'unBlock'); - } - - public function updateWallet($array){ - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'cardInd' => $array['cardInd'], - 'wallet' => $this->wallet($array['wallet'],$array['address'],$array['card']), - 'buyer' => $this->buyer($array['buyer'], $array['shippingAddress'],$array['billingAddress']), - 'owner' => $this->owner($array['owner'],$array['ownerAddress']), - 'privateDataList' => $this->privates, - 'authentication3DSecure' =>$this->authentication3DSecure($array['3DSecure']), - 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'updateWallet'); - } - - public function updateWebWallet($array){ - if(isset($array['cancelURL'])&& strlen($array['cancelURL'])) $this->cancelURL = $array['cancelURL']; - if(isset($array['notificationURL']) && strlen($array['notificationURL'])) $this->notificationURL = $array['notificationURL']; - if(isset($array['returnURL'])&& strlen($array['returnURL'])) $this->returnURL = $array['returnURL']; - if(isset($array['customPaymentTemplateURL'])&& strlen($array['customPaymentTemplateURL'])) $this->customPaymentTemplateURL = $array['customPaymentTemplateURL']; - if(isset($array['customPaymentPageCode'])&& strlen($array['customPaymentPageCode'])) $this->customPaymentPageCode = $array['customPaymentPageCode']; - if(isset($array['languageCode'])&& strlen($array['languageCode'])) $this->languageCode = $array['languageCode']; - if(isset($array['securityMode'])&& strlen($array['securityMode'])) $this->securityMode = $array['securityMode']; - if(!isset($array['walletContracts'])||!strlen($array['walletContracts'][0]))$array['walletContracts'] = ''; - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'cardInd' => $array['cardInd'], - 'walletId' => $array['walletId'], - 'updatePersonalDetails' => $array['updatePersonalDetails'], - 'updateOwnerDetails' => $array['updateOwnerDetails'], - 'updatePaymentDetails' => $array['updatePaymentDetails'], - 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), - 'languageCode' => $this->languageCode, - 'customPaymentPageCode' => $this->customPaymentPageCode, - 'securityMode' => $this->securityMode, - 'returnURL' => $this->returnURL, - 'cancelURL' => $this->cancelURL, - 'notificationURL' => $this->notificationURL, - 'privateDataList' => $this->privates, - 'customPaymentTemplateURL' => $this->customPaymentTemplateURL, - 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::WEB_API,'updateWebWallet'); - } - - public function verifyAuthentication($array){ - $WSRequest = array ( - 'contractNumber' => $array['contractNumber'], - 'pares' => $array['pares'], - 'md' => $array['md'], - 'card' => $this->card($array['card']) - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'verifyAuthentication'); - } - - public function verifyEnrollment($array){ - if(!isset($array['orderRef']))$array['orderRef'] = null; - if(!isset($array['userAgent']))$array['userAgent'] = null; - if(!isset($array['mdFieldValue']))$array['mdFieldValue'] = null; - if(!isset($array['walletId']))$array['walletId'] = null; - if(!isset($array['walletCardInd']))$array['walletCardInd'] = null; - if(!isset($array['card']))$array['card'] = null; - $WSRequest = array ( - 'payment' => $this->payment($array['payment']), - 'card' => $this->card($array['card']), - 'orderRef' => $array['orderRef'], - 'userAgent' => $array['userAgent'], - 'mdFieldValue' => $array['mdFieldValue'], - 'walletId' => $array['walletId'], - 'walletCardInd' => $array['walletCardInd'] - ); - return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'verifyEnrollment'); - } -} +$v){ + if (is_object($v)) { + $array[$k] = paylineUtil::responseToArray($v); + } + else { $array[$k] = $v; + } + } + return $array; + + return $response; + } + + static function responseToArrayForGetCards($response){ + + $array = array(); + foreach($response as $k=>$v){ + + if (is_object($v) && ($k != 'cards' ) ) { + $array[$k] = paylineUtil::responseToArrayForGetCards($v); + } + else { + if($k == 'cards' && count($v) == 1 ){ + $array[$k][0] = $v; + }else{ + $array[$k] = $v; + } + } + } + return $array; + + return $response; + } +} + +// +// PL_PAYMENT OBJECT DEFINITION +// +class pl_payment{ + + // ATTRIBUTES LISTING + public $amount; + public $currency; + public $action; + public $mode; + public $method; + public $contractNumber; + public $differedActionDate; +} + +// +// PL_ORDER OBJECT DEFINITION +// +class pl_order{ + + // ATTRIBUTES LISTING + public $ref; + public $origin; + public $country; + public $taxes; + public $amount; + public $currency; + public $date; + public $quantity; + public $comment; + public $details; + public $deliveryTime; + public $deliveryMode; + public $deliveryExpectedDate; + public $deliveryExpectedDelay; + + function __construct() { + $this->date = date('d/m/Y H:i', time()); + $this->details = array(); + } +} + +// +// PL_PRIVATEDATA OBJECT DEFINITION +// +class pl_privateData{ + + // ATTRIBUTES LISTING + public $key ; + public $value; +} + +// +// PL_AUTHORIZATION OBJECT DEFINITION +// +class pl_authorization{ + + // ATTRIBUTES LISTING + public $number; + public $date; +} + +// +// PL_ADDRESS OBJECT DEFINITION +// +class pl_address{ + + // ATTRIBUTES LISTING + public $title; + public $firstName; + public $lastName; + public $name; + public $street1; + public $street2; + public $cityName; + public $zipCode; + public $country; + public $county; + public $state; + public $phoneType; + public $phone; +} + +// +// PL_OWNERADDRESS OBJECT DEFINITION +// +class pl_ownerAddress{ + + // ATTRIBUTES LISTING + public $street; + public $cityName; + public $zipCode; + public $country; + public $phone; +} + +// +// PL_BUYER OBJECT DEFINITION +// +class pl_buyer{ + + // ATTRIBUTES LISTING + public $title; + public $lastName; + public $firstName; + public $email; + public $customerId; + public $walletId; + public $walletDisplayed; + public $walletSecured; + public $walletCardInd; + public $shippingAdress; + public $billingAddress; + public $accountCreateDate; + public $accountAverageAmount; + public $accountOrderCount; + public $ip; + public $mobilePhone; + public $legalStatus; + public $legalDocument; + public $birthDate; + public $fingerprintID; + + function __construct() { + $this->accountCreateDate = date('d/m/y', time()); + } +} + +// +// PL_OWNER OBJECT DEFINITION +// +class pl_owner{ + + // ATTRIBUTES LISTING + public $lastName; + public $firstName; + public $billingAddress; + public $issueCardDate; +} + +// +// PL_ORDERDETAIL OBJECT DEFINITION +// +class pl_orderDetail{ + + // ATTRIBUTES LISTING + public $ref; + public $price; + public $quantity; + public $comment; + public $category; + public $subcategory1; + public $subcategory2; + public $brand; + public $additionalData; + public $taxRate; +} + +// +// PL_CARD OBJECT DEFINITION +// +class pl_card{ + + // ATTRIBUTES LISTING + public $number; + public $type; + public $expirationDate; + public $cvx; + public $ownerBirthdayDate; + public $password; + public $cardPresent; + public $cardholder; + public $token; + + function __construct($type) { + $this->accountCreateDate = date('d/m/y', time()); + } +} + + +// +// PL_TRANSACTION OBJECT DEFINITION +// +class pl_transaction{ + + // ATTRIBUTES LISTING + public $id; + public $isPossibleFraud; + public $isDuplicated; + public $date; +} + + +// +// PL_RESULT OBJECT DEFINITION +// +class pl_result{ + + // ATTRIBUTES LISTING + public $code; + public $shortMessage; + public $longMessage; +} + +// +// PL_CAPTURE OBJECT DEFINITION +// +class pl_capture{ + + // ATTRIBUTES LISTING + public $transactionID; + public $payment; + public $sequenceNumber; + + function __construct() { + $this->payment = new pl_payment(); + } +} + +// +// PL_REFUND OBJECT DEFINITION +// +class pl_refund extends pl_capture { + function __construct() { + parent::__construct(); + } +} + +// +// PL_WALLET OBJECT DEFINITION +// +class pl_wallet{ + + // ATTRIBUTES LISTING + public $walletId; + public $lastName; + public $firstName; + public $email; + public $shippingAddress; + public $card; + public $comment; + public $default; + public $cardStatus; + + function __construct() { + } +} + +// +// PL_RECURRING OBJECT DEFINITION +// +class pl_recurring{ + + // ATTRIBUTES LISTING + public $firstAmount; + public $amount; + public $billingCycle; + public $billingLeft; + public $billingDay; + public $startDate; + public $endDate; + public $newAmount; + public $amountModificationDate; + + function __construct() { + } +} + +// +// PL_BILLINGRECORD OBJECT DEFINITION +// +class pl_billingRecord{ + + // ATTRIBUTES LISTING + public $date; + public $amount; + public $status; + public $executionDate; + + function __construct() { + } +} + +// +// PL_AUTHENTIFICATION 3D SECURE +// +class pl_authentication3DSecure{ + + // ATTRIBUTES LISTING + public $md ; + public $pares ; + public $xid ; + public $eci ; + public $cavv ; + public $cavvAlgorithm ; + public $vadsResult ; + public $typeSecurisation; + + function __construct() { + } +} + +// +// PL_BANKACCOUNTDATA +// +class pl_bankAccountData{ + + + // ATTRIBUTES LISTING + public $countryCode ; + public $bankCode ; + public $accountNumber ; + public $key ; + + + function __construct() { + } +} + +// +// PL_CHEQUE +// +class pl_cheque{ + + // ATTRIBUTES LISTING + public $number ; + + function __construct() { + } +} + +final class paylineLog { + private $filename; + private $path; + + public function __construct($filename, $path=null) { + $this->filename = $filename; + if($path == null){ + $tmp = explode(DIRECTORY_SEPARATOR ,dirname(__FILE__)); + + // up one level from the current directory + for($i=0,$s = sizeof($tmp)-1; $i<$s; $i++){ + $this->path .= $tmp[$i].DIRECTORY_SEPARATOR; + } + $this->path .= 'logs'.DIRECTORY_SEPARATOR; + }else{ + $this->path = $path; + } + } + + public function write($message) { + $file = $this->path.$this->filename; + $handle = fopen($file, 'a+'); + fwrite($handle, date('Y-m-d G:i:s') . ' - ' . $message . "\n"); + fclose($handle); + } +} + +// +// PAYLINESDK CLASS +// +class paylineSDK{ + + // kit version + const KIT_VERSION = 'module Magento 1.8.5.8'; + + // trace log + var $logger; + var $flagLog; // 0 : pas de log / 1 : log par défaut / 2 : chemin personnalisé (pathLog) + var $pathLog; + + // environement flags + const ENV_DEV = "DEV"; + const ENV_HOMO = "HOMO"; + const ENV_PROD = "PROD"; + + // SOAP URL's + const PAYLINE_NAMESPACE = 'http://obj.ws.payline.experian.com'; + const WSDL = 'v4.44.wsdl'; + const DEV_ENDPOINT = 'https://ws.dev.payline.com/V4/services/'; + const HOMO_ENDPOINT = 'https://homologation.payline.com/V4/services/'; + const PROD_ENDPOINT = 'https://services.payline.com/V4/services/'; + + // getToken servlet URL + const DEV_GET_TOKEN_SERVLET = "https://webpayment.dev.payline.com/webpayment/getToken"; + const HOMO_GET_TOKEN_SERVLET = "https://homologation-webpayment.payline.com/webpayment/getToken"; + const PROD_GET_TOKEN_SERVLET = "https://webpayment.payline.com/webpayment/getToken"; + + // Widget JavaScript + const HOMO_WDGT_JS = "https://homologation-payment.payline.com/scripts/widget-min.js"; + const PROD_WDGT_JS = "https://payment.payline.com/scripts/widget-min.js"; + const DEV_WDGT_JS = "https://webpayment.dev.payline.com/payline-widget/scripts/widget-min.js"; + + // Widget css + const DEV_WDGT_CSS = "https://webpayment.dev.payline.com/payline-widget/styles/widget-min.css"; + const HOMO_WDGT_CSS = "https://homologation-payment.payline.com/styles/widget-min.css"; + const PROD_WDGT_CSS = "https://payment.payline.com/styles/widget-min.css"; + + + // Administration center + const DEV_CA = 'https://admin.dev.payline.aixlan.local:9363'; + const HOMO_CA = 'https://homologation-admin.payline.com'; + const PROD_CA = 'https://admin.payline.com'; + + // APIs + const DIRECT_API = 'DirectPaymentAPI'; + const EXTENDED_API = 'ExtendedAPI'; + const WEB_API = 'WebPaymentAPI'; + + // current endpoint + private $webServicesEndpoint; + + // current url to get token + private $servletTokenUrl; + + private $widgetJavascriptUrl; + private $widgetCssUrl; + + // SOAP ACTIONS CONSTANTS + const soap_result = 'result'; + const soap_authorization = 'authorization'; + const soap_card = 'card'; + const soap_order = 'order'; + const soap_orderDetail = 'orderDetail'; + const soap_payment = 'payment'; + const soap_transaction = 'transaction'; + const soap_privateData = 'privateData'; + const soap_buyer = 'buyer'; + const soap_owner = 'owner'; + const soap_address = 'address'; + const soap_ownerAddress = 'addressOwner'; + const soap_capture = 'capture'; + const soap_refund = 'refund'; + const soap_refund_auth = 'refundAuthorization'; + const soap_authentication3DSecure = 'authentication3DSecure'; + const soap_bankAccountData = 'bankAccountData'; + const soap_cheque = 'cheque'; + + const ERR_CODE = 'XXXXX'; + + // ARRAY + public $header_soap; + public $items; + public $privates; + + // OPTIONS + public $cancelURL; + public $securityMode; + public $notificationURL; + public $returnURL; + public $customPaymentTemplateURL; + public $customPaymentPageCode; + public $languageCode; + + // WALLET + public $walletIdList; + + // custom logo path + const DEFAULT_LOGO_DIR = 'customLogos'; + var $customLogoPath = ''; + + // getMerchantSettings Array + private $posData; + private $paymentMeansLogos; + + /** + * contructor of PAYLINESDK CLASS + **/ + function __construct($merchant_id, $access_key, $proxy_host, $proxy_port, $proxy_login, $proxy_password, $environment, $pathLog = null) { + if(is_null($pathLog)){ + $this->flagLog = 1; + }elseif (strlen($pathLog) == 0){ + $this->flagLog = 0; + }else{ + $this->flagLog = 2; + $this->pathLog = $pathLog; + } + + $this->writeTrace('----------------------------------------------------------'); + $this->writeTrace('paylineSDK::__construct('.$this->hideChars($merchant_id,6,1).', '.$this->hideChars($access_key,1,3).", $proxy_host, $proxy_port, $proxy_login, ".$this->hideChars($proxy_password,1,1).", $environment)"); + $this->header_soap = array(); + $this->header_soap['login'] = $merchant_id; + $this->header_soap['password'] = $access_key; + if($proxy_host != ''){ + $this->header_soap['proxy_host'] = $proxy_host; + $this->header_soap['proxy_port'] = $proxy_port; + $this->header_soap['proxy_login'] = $proxy_login; + $this->header_soap['proxy_password'] = $proxy_password; + } + + if(strcmp($environment,paylineSDK::ENV_DEV)==0){ + $this->webServicesEndpoint = paylineSDK::DEV_ENDPOINT; + $this->widgetJavascriptUrl = paylineSDK::DEV_WDGT_JS; + $this->widgetCssUrl = paylineSDK::DEV_WDGT_CSS; + }elseif(strcmp($environment,paylineSDK::ENV_PROD)==0){ + $this->webServicesEndpoint = paylineSDK::PROD_ENDPOINT; + $this->servletTokenUrl = paylineSDK::PROD_GET_TOKEN_SERVLET; + $this->widgetJavascriptUrl = paylineSDK::PROD_WDGT_JS; + $this->widgetCssUrl = paylineSDK::PROD_WDGT_CSS; + }elseif(strcmp($environment,paylineSDK::ENV_HOMO)==0){ + $this->webServicesEndpoint = paylineSDK::HOMO_ENDPOINT; + $this->servletTokenUrl = paylineSDK::HOMO_GET_TOKEN_SERVLET; + $this->widgetJavascriptUrl = paylineSDK::HOMO_WDGT_JS; + $this->widgetCssUrl = paylineSDK::HOMO_WDGT_CSS; + } + + $this->header_soap['style'] = SOAP_DOCUMENT; + $this->header_soap['use'] = SOAP_LITERAL; + $this->items = array(); + $this->privates = array(); + $this->walletIdList = array(); + + ini_set('user_agent', "PHP\r\nversion: ".paylineSDK::KIT_VERSION); + } + + /** + * function payment + * @params : $array : array. the array keys are listed in pl_payment CLASS. + * @return : SoapVar : object + * @description : build pl_payment instance from $array and make SoapVar object for payment. + **/ + protected function payment($array) { + $payment = new pl_payment(); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $payment)&&(strlen($v))){ + $payment->$k = $v; + } + } + } + return new SoapVar($payment, SOAP_ENC_OBJECT, paylineSDK::soap_payment, paylineSDK::PAYLINE_NAMESPACE); + } + + /** + * function order + * @params : $array : array. the array keys are listed in pl_order CLASS. + * @return : SoapVar : object + * @description : build pl_order instance from $array and make SoapVar object for order. + **/ + protected function order($array) { + $order = new pl_order(); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $order)&&(strlen($v))){ + $order->$k = $v; + } + } + } + $allDetails = array(); + // insert orderDetails + $order->details = $this->items; + return new SoapVar($order, SOAP_ENC_OBJECT, paylineSDK::soap_order, paylineSDK::PAYLINE_NAMESPACE); + } + + /** + * function address + * @params : $address : array. the array keys are listed in pl_address CLASS. + * @return : SoapVar : object + * @description : build pl_address instance from $array and make SoapVar object for address. + **/ + protected function address($array) { + $address = new pl_address(); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $address)&&(strlen($v)))$address->$k = $v; + } + } + return new SoapVar($address, SOAP_ENC_OBJECT, paylineSDK::soap_address, paylineSDK::PAYLINE_NAMESPACE); + } + + /** + * function ownerAddress + * @params : $address : array. the array keys are listed in pl_address CLASS. + * @return : SoapVar : object + * @description : build pl_ownerAddress instance from $array and make SoapVar object for address. + **/ + protected function ownerAddress($array) { + $address = new pl_ownerAddress(); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $address)&&(strlen($v)))$address->$k = $v; + } + } + return new SoapVar($address, SOAP_ENC_OBJECT, paylineSDK::soap_ownerAddress, paylineSDK::PAYLINE_NAMESPACE); + } + + /** + * function buyer + * @params : $array : array. the array keys are listed in pl_buyer CLASS. + * @params : $shippingAdress : array. the array keys are listed in pl_address CLASS. + * @params : $billingAddress : array. the array keys are listed in pl_address CLASS. + * @return : SoapVar : object + * @description : build pl_buyer instance from $array and $address and make SoapVar object for buyer. + **/ + protected function buyer($array,$shippingAdress,$billingAddress) { + $buyer = new pl_buyer(); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $buyer)&&(strlen($v)))$buyer->$k = $v; + } + } + $buyer->shippingAdress = $this->address($shippingAdress); + $buyer->billingAddress = $this->address($billingAddress); + return new SoapVar($buyer, SOAP_ENC_OBJECT, paylineSDK::soap_buyer, paylineSDK::PAYLINE_NAMESPACE); + } + + /** + * function owner + * @params : $array : array. the array keys are listed in pl_buyer CLASS. + * @params : $shippingAdress : array. the array keys are listed in pl_address CLASS. + * @params : $billingAddress : array. the array keys are listed in pl_address CLASS. + * @return : SoapVar : object + * @description : build pl_buyer instance from $array and $address and make SoapVar object for buyer. + **/ + protected function owner($array,$Address) { + if($array != null){ + $owner = new pl_owner(); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $owner)&&(strlen($v)))$owner->$k = $v; + } + } + $owner->billingAddress = $this->ownerAddress($Address); + return new SoapVar($owner, SOAP_ENC_OBJECT, paylineSDK::soap_owner, paylineSDK::PAYLINE_NAMESPACE); + }else{ + return null; + } + } + + /** + * function contracts + * @params : $contracts : array. array of contracts + * @return : $contracts : array. the same as params if exist, or an array with default contract defined in + * configuration + * @description : Add datas to contract array + **/ + protected function contracts($contracts) { + if($contracts && is_array($contracts)){ + return $contracts; + } + return null; + } + + /** + * function secondContracts + * @params : $secondContracts : array. array of contracts + * @return : $secondContracts : array. the same as params if exist, null otherwise + * @description : Add datas to contract array + **/ + protected function secondContracts($secondContracts) { + if($secondContracts && is_array($secondContracts)){ + return $secondContracts; + } + return null; + } + + /** + * function authentification 3Dsecure + * @params : $array : array. the array keys are listed in pl_card CLASS. + * @return : SoapVar : object + * @description : build pl_authentication3DSecure instance from $array and make SoapVar object for authentication3DSecure. + **/ + protected function authentication3DSecure($array) { + $authentication3DSecure = new pl_authentication3DSecure($array); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $authentication3DSecure)&&(strlen($v))){ + $authentication3DSecure->$k = $v; + } + } + } + return new SoapVar($authentication3DSecure, SOAP_ENC_OBJECT, paylineSDK::soap_authentication3DSecure, paylineSDK::PAYLINE_NAMESPACE); + } + + /** + * function authorization + * @params : $array : array. the array keys are listed in pl_card CLASS. + * @return : SoapVar : object + * @description : build pl_authentication3DSecure instance from $array and make SoapVar object for authentication3DSecure. + **/ + protected function authorization($array) { + $authorization = new pl_authorization($array); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $authorization)&&(strlen($v))){ + $authorization->$k = $v; + } + } + } + return new SoapVar($authorization, SOAP_ENC_OBJECT, paylineSDK::soap_authorization, paylineSDK::PAYLINE_NAMESPACE); + } + + /** + * function card + * @params : $array : array. the array keys are listed in pl_card CLASS. + * @return : SoapVar : object + * @description : build pl_card instance from $array and make SoapVar object for card. + **/ + protected function card($array) { + $card = new pl_card($array['type']); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $card)&&(strlen($v))){ + $card->$k = $v; + } + } + } + return new SoapVar($card, SOAP_ENC_OBJECT, paylineSDK::soap_card, paylineSDK::PAYLINE_NAMESPACE); + } + + + + /** + * function bankAccountData + * @params : $array : array. the array keys are listed in pl_bankAccountData CLASS. + * @return : SoapVar : object + * @description : build pl_bankAccountData instance from $array and make SoapVar object for bankAccountData. + **/ + protected function bankAccountData($array) { + $bankAccountData = new pl_bankAccountData($array); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $bankAccountData)&&(strlen($v))){ + $bankAccountData->$k = $v; + } + } + } + return new SoapVar($bankAccountData, SOAP_ENC_OBJECT, paylineSDK::soap_bankAccountData, paylineSDK::PAYLINE_NAMESPACE); + } + + /** + * function cheque + * @params : $array : array. the array keys are listed in pl_cheque CLASS. + * @return : SoapVar : object + * @description : build pl_authentication3DSecure instance from $array and make SoapVar object for cheque. + **/ + protected function cheque($array) { + $cheque = new pl_cheque($array); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $cheque)&&(strlen($v))){ + $cheque->$k = $v; + } + } + } + return new SoapVar($cheque, SOAP_ENC_OBJECT, paylineSDK::soap_cheque, paylineSDK::PAYLINE_NAMESPACE); + } + + /****************************************************/ + // WALLET // + /****************************************************/ + + /** + * function wallet + * @params : array : array. the array keys are listed in pl_wallet CLASS. + * @params : address : array. the array keys are listed in pl_address CLASS. + * @params : card : array. the array keys are listed in pl_card CLASS. + * @return : wallet: pl_wallet Object. + * @description : build a wallet object. + **/ + protected function wallet($array,$address,$card) { + $wallet = new pl_wallet(); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $wallet)&&(strlen($v)))$wallet->$k = $v; + } + } + + $wallet->shippingAddress = $this->address($address); + $wallet->card = $this->card($card); + + return $wallet; + } + + /** + * function recurring + * @params : array : array. the array keys are listed in pl_recurring CLASS. + * @return : recurring object. + * @description : build a recurring object. + **/ + protected function recurring($array) { + if($array){ + $recurring = new pl_recurring(); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $recurring)&&(strlen($v)))$recurring->$k = $v; + } + } + return $recurring; + } + else return null; + } + + /** + * function billingRecord + * @params : array : array. the array keys are listed in pl_billingRecord CLASS. + * @return : billingRecord object. + * @description : build a billingRecord object. + **/ + protected function billingRecord($array) { + if($array){ + $billingRecord = new pl_billingRecord(); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $billingRecord)&&(strlen($v)))$billingRecord->$k = $v; + } + } + return $billingRecord; + } + else return null; + } + + /** + * function setItem + * @params : $item : array. the array keys are listed in PL_ORDERDETAIL CLASS. + * @description : Make $item SoapVar object and insert in items array + **/ + public function setItem($item) { + $orderDetail = new pl_orderDetail(); + if($item && is_array($item)){ + foreach($item as $k=>$v){ + if(array_key_exists($k, $orderDetail)&&(strlen($v)))$orderDetail->$k = $v; + } + } + $this->items[] = new SoapVar($orderDetail, SOAP_ENC_OBJECT, paylineSDK::soap_orderDetail, paylineSDK::PAYLINE_NAMESPACE); + } + + /** + * function setPrivate + * @params : $private : array. the array keys are listed in PRIVATE CLASS. + * @description : Make $setPrivate SoapVar object and insert in privates array + **/ + public function setPrivate($array) { + $private = new pl_privateData(); + if($array && is_array($array)){ + foreach($array as $k=>$v){ + if(array_key_exists($k, $private)&&(strlen($v)))$private->$k = $v; + } + } + $this->privates[] = new SoapVar($private, SOAP_ENC_OBJECT, paylineSDK::soap_privateData, paylineSDK::PAYLINE_NAMESPACE); + } + + /** + * function setWalletIdList + * @params : sting : string if wallet id separated by ';'. + * @return : + * @description : make an array of wallet id . + **/ + public function setWalletIdList($walletIdList) { + if ($walletIdList) $this->walletIdList = explode(";", $walletIdList); + if(empty($walletIdList))$this->walletIdList = array(0) ; + } + + /** + * Hide characters in a string + * @param String $inString : the string to hide + * @param int $n1 : number of characters shown at the begining of the string + * @param int $n2 : number of characters shown at end begining of the string + */ + private function hideChars($inString, $n1, $n2){ + $inStringLength = strlen($inString); + if($inStringLength < ($n1+$n2)){ + return $inString; + } + $outString = substr($inString,0,$n1); + $outString .= substr("********************",0,$inStringLength-($n1+$n2)); + $outString .= substr($inString,-($n2)); + return $outString; + } + + /** + * @method writeTrace + * @desc write a trace in Payline log file + * @param $trace : the string to add in the log file + */ + public function writeTrace($trace){ + if($this->flagLog == 0){ + return; + }else{ + if(!isset($this->logger)){ + if($this->flagLog == 1){ // log dans le répertoire par défaut + $this->logger = new paylineLog(date('Y-m-d',time()).'.log'); + } + if($this->flagLog == 2){ // log dans un répertoire spécifié + $this->logger = new paylineLog(date('Y-m-d',time()).'.log',$this->pathLog); + } + } + $this->logger->write($trace); + } + } + + /** + * Custom base64 url encoding. Replace unsafe url chars + * + * @param string $input + * @return string + */ + public function base64_url_encode($input) + { + return strtr(base64_encode($input), '+/=', '-_,'); + } + + /** + * Custom base64 url decode. Replace custom url safe values with normal + * base64 characters before decoding. + * + * @param string $input + * @return string + */ + public function base64_url_decode($input) + { + return base64_decode(strtr($input, '-_,', '+/=')); + } + + // MCRYPT_RIJNDAEL_128 : AES compliant + public function getEncrypt($message, $accessKey){ + $block = mcrypt_get_block_size('rijndael_128', 'ecb'); + $pad = $block - (strlen($message) % $block); + $message .= str_repeat(chr($pad), $pad); + return $this->base64_url_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $accessKey, $message, MCRYPT_MODE_ECB)); + } + + public function getDecrypt($message, $accessKey){ + $message = $this->base64_url_decode($message); + $message = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $accessKey, $message, MCRYPT_MODE_ECB); + $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); + $pad = ord($message[($len = strlen($message)) - 1]); + $len = strlen($message); + $pad = ord($message[$len-1]); + $return = substr($message, 0, strlen($message) - $pad); + $this->writeTrace("getDecrypt($message, $accessKey) = $return"); + return $return; + } + + public function gzdecode($data,&$filename='',&$error='',$maxlength=null) + { + $this->writeTrace("gzdecode($data,$filename,$error,$maxlength)"); + $len = strlen($data); + if ($len < 18 || strcmp(substr($data,0,2),"\x1f\x8b")) { + $error = "Not in GZIP format."; + return null; // Not GZIP format (See RFC 1952) + } + $method = ord(substr($data,2,1)); // Compression method + $flags = ord(substr($data,3,1)); // Flags + if ($flags & 31 != $flags) { + $error = "Reserved bits not allowed."; + return null; + } + // NOTE: $mtime may be negative (PHP integer limitations) + $mtime = unpack("V", substr($data,4,4)); + $mtime = $mtime[1]; + $xfl = substr($data,8,1); + $os = substr($data,8,1); + $headerlen = 10; + $extralen = 0; + $extra = ""; + if ($flags & 4) { + // 2-byte length prefixed EXTRA data in header + if ($len - $headerlen - 2 < 8) { + return false; // invalid + } + $extralen = unpack("v",substr($data,8,2)); + $extralen = $extralen[1]; + if ($len - $headerlen - 2 - $extralen < 8) { + return false; // invalid + } + $extra = substr($data,10,$extralen); + $headerlen += 2 + $extralen; + } + $filenamelen = 0; + $filename = ""; + if ($flags & 8) { + // C-style string + if ($len - $headerlen - 1 < 8) { + return false; // invalid + } + $filenamelen = strpos(substr($data,$headerlen),chr(0)); + if ($filenamelen === false || $len - $headerlen - $filenamelen - 1 < 8) { + return false; // invalid + } + $filename = substr($data,$headerlen,$filenamelen); + $headerlen += $filenamelen + 1; + } + $commentlen = 0; + $comment = ""; + if ($flags & 16) { + // C-style string COMMENT data in header + if ($len - $headerlen - 1 < 8) { + return false; // invalid + } + $commentlen = strpos(substr($data,$headerlen),chr(0)); + if ($commentlen === false || $len - $headerlen - $commentlen - 1 < 8) { + return false; // Invalid header format + } + $comment = substr($data,$headerlen,$commentlen); + $headerlen += $commentlen + 1; + } + $headercrc = ""; + if ($flags & 2) { + // 2-bytes (lowest order) of CRC32 on header present + if ($len - $headerlen - 2 < 8) { + return false; // invalid + } + $calccrc = crc32(substr($data,0,$headerlen)) & 0xffff; + $headercrc = unpack("v", substr($data,$headerlen,2)); + $headercrc = $headercrc[1]; + if ($headercrc != $calccrc) { + $error = "Header checksum failed."; + return false; // Bad header CRC + } + $headerlen += 2; + } + // GZIP FOOTER + $datacrc = unpack("V",substr($data,-8,4)); + $datacrc = sprintf('%u',$datacrc[1] & 0xFFFFFFFF); + $isize = unpack("V",substr($data,-4)); + $isize = $isize[1]; + // decompression: + $bodylen = $len-$headerlen-8; + if ($bodylen < 1) { + // IMPLEMENTATION BUG! + return null; + } + $body = substr($data,$headerlen,$bodylen); + $data = ""; + if ($bodylen > 0) { + switch ($method) { + case 8: + // Currently the only supported compression method: + $data = gzinflate($body,$maxlength); + break; + default: + $error = "Unknown compression method."; + return false; + } + } // zero-byte body content is allowed + // Verifiy CRC32 + $crc = sprintf("%u",crc32($data)); + $crcOK = $crc == $datacrc; + $lenOK = $isize == strlen($data); + if (!$lenOK || !$crcOK) { + $error = ( $lenOK ? '' : 'Length check FAILED. ') . ( $crcOK ? '' : 'Checksum FAILED.'); + return false; + } + return $data; + } + + private function webServiceRequest($array,$WSRequest,$PaylineAPI,$Method){ + $reqTrace = "Request : $PaylineAPI.$Method"; + $resTrace = ''; + try{ + $client = new SoapClient(dirname(__FILE__).'/'.paylineSDK::WSDL, $this->header_soap); + $client->__setLocation ($this->webServicesEndpoint.$PaylineAPI); + + if(isset($array['version'])&& strlen($array['version'])) + $WSRequest['version'] = $array['version']; + else + $WSRequest['version'] = ''; + if(isset($array['media'])&& strlen($array['media'])) + $WSRequest['media'] = $array['media']; + else + $WSRequest['media'] = ''; + + switch($Method){ + case 'createMerchant': + $WSresponse = $client->createMerchant($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'createWallet': + $reqTrace .= '(contract = '.$array['contractNumber'].' - walletId = '.$array['wallet']['walletId'].' - card = '.$this->hideChars($array['card']['number'],4,4).')'; + $WSresponse = $client->createWallet($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'createWebWallet': + $reqTrace .= '(contract = '.$array['contractNumber'].' - walletId = '.$array['buyer']['walletId'].')'; + $WSresponse = $client->createWebWallet($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + if($response['result']['code'] == '00000'){ + $resTrace = ' - token = '.$response['token']; + } + break; + case 'updatePaymentRecord': + $reqTrace .= '(contract = '.$array['contractNumber'].' - paymentRecordId = '.$array['paymentRecordId'].')'; + $WSresponse = $client->updatePaymentRecord($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'getBillingRecord': + $reqTrace .= '(contract = '.$array['contractNumber'].' - paymentRecordId = '.$array['paymentRecordId'].' - billingRecordId = '.$array['billingRecordId'].')'; + $WSresponse = $client->getBillingRecord($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'updateBillingRecord': + $reqTrace .= '(contract = '.$array['contractNumber'].' - paymentRecordId = '.$array['paymentRecordId'].' - billingRecordId = '.$array['billingRecordId'].')'; + $WSresponse = $client->updateBillingRecord($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'disablePaymentRecord': + $reqTrace .= '(contract = '.$array['contractNumber'].' - paymentRecordId = '.$array['paymentRecordId'].')'; + $WSresponse = $client->disablePaymentRecord($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'disableWallet': + $reqTrace .= '(contract = '.$array['contractNumber'].' - walletIdList = '.implode(';', $this->walletIdList).')'; + $WSresponse = $client->disableWallet($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'doAuthorization': + $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - amount = '.$array['payment']['amount'].')'; + $WSresponse = $client->doAuthorization($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + $resTrace = ' - transactionID = '.$response['transaction']['id']; + break; + case 'doCapture': + $reqTrace .= '(transactionID = '.$array['transactionID'].' - amount = '.$array['payment']['amount'].')'; + $WSresponse = $client->doCapture($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + $resTrace = ' - transactionID = '.$response['transaction']['id']; + break; + case 'doCredit': + $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - order.ref = '.$array['order']['ref'].' - card = '.$this->hideChars($array['card']['number'],4,4).')'; + $WSresponse = $client->doCredit($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + $resTrace = ' - transactionID = '.$response['transaction']['id']; + break; + case 'doDebit': + $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - order.ref = '.$array['order']['ref'].' - card = '.$this->hideChars($array['card']['number'],4,4).')'; + $WSresponse = $client->doDebit($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + $resTrace = ' - transactionID = '.$response['transaction']['id']; + break; + case 'doImmediateWalletPayment': + $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - walletId = '.$array['walletId'].' - order.ref = '.$array['order']['ref'].')'; + $WSresponse = $client->doImmediateWalletPayment($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + $resTrace = ' - transactionID = '.$response['transaction']['id']; + break; + case 'doReAuthorization': + $reqTrace .= '(transactionID = '.$array['transactionID'].' - amount = '.$array['payment']['amount'].')'; + $WSresponse = $client->doReAuthorization($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + $resTrace = ' - transactionID = '.$response['transaction']['id']; + break; + case 'doRecurrentWalletPayment': + $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - walletId = '.$array['walletId'].' - order.ref = '.$array['order']['ref'].')'; + $WSresponse = $client->doRecurrentWalletPayment($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + if($response['result']['code'] == '02500'){ + $resTrace = ' - paymentRecordId = '.$response['paymentRecordId']; + } + break; + case 'doRefund': + $reqTrace .= '(transactionID = '.$array['transactionID'].' - amount = '.$array['payment']['amount'].')'; + $WSresponse = $client->doRefund($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + $resTrace = ' - transactionID = '.$response['transaction']['id']; + break; + case 'doReset': + $reqTrace .= '(transactionID = '.$array['transactionID'].')'; + $WSresponse = $client->doReset($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + $resTrace = ' - transactionID = '.$response['transaction']['id']; + break; + case 'doScheduledWalletPayment': + $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - walletId = '.$array['walletId'].' - order.ref = '.$array['order']['ref'].')'; + $WSresponse = $client->doScheduledWalletPayment($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + if($response['result']['code'] == '02500'){ + $resTrace = ' - paymentRecordId = '.$response['paymentRecordId']; + } + break; + case 'doScoringCheque': + $WSresponse = $client->doScoringCheque($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'doWebPayment': + $reqTrace .= '(order.ref = '.$array['order']['ref'].')'; + $WSresponse = $client->doWebPayment($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + if($response['result']['code'] == '00000'){ + $resTrace = ' - token = '.$response['token']; + } + break; + case 'enableWallet': + $reqTrace .= '(walletId = '.$array['walletId'].')'; + $WSresponse = $client->enableWallet($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'getAlertDetails': + $reqTrace .= '(alertId = '.$array['AlertId'].' - transactionId = '.$array['TransactionId'].')'; + $WSresponse = $client->getAlertDetails($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'getBalance': + $reqTrace .= '(contract = '.$array['contractNumber'].' - cardID = '.$this->hideChars($array['cardID'],4,4).')'; + $WSresponse = $client->getBalance($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'getCards': + $reqTrace .= '(contract - '.$array['contractNumber'].' - walletId = '.$array['walletId'].' - cardInd = '.$array['cardInd'].')'; + $WSresponse = $client->getCards($WSRequest); + $response = paylineUtil::responseToArrayForGetCards($WSresponse); + break; + case 'getEncryptionKey': + $WSresponse = $client->getEncryptionKey($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'getMerchantSettings': + $WSresponse = $client->getMerchantSettings($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'getPaymentRecord': + $reqTrace .= '(contract = '.$array['contractNumber'].' - paymentRecordId = '.$array['paymentRecordId'].')'; + $WSresponse = $client->getPaymentRecord($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'getToken': + $reqTrace .= '(contract = '.$array['contractNumber'].' - cardNumber = '.$this->hideChars($array['cardNumber'],4,4).')'; + $WSresponse = $client->getToken($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + if($response['result']['code'] == '02500'){ + $resTrace = ' - token = '.$response['token']; + } + break; + case 'getTransactionDetails': + $reqTrace = '(transactionId = '.$array['transactionId'].')'; + $WSresponse = $client->getTransactionDetails($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'getWallet': + $reqTrace .= '(contract = '.$array['contractNumber'].' - walletId = '.$array['walletId'].' - cardInd = '.$array['cardInd'].')'; + $WSresponse = $client->getWallet($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'getWebPaymentDetails': + $reqTrace .= '(token = '.$array['token'].')'; + $WSresponse = $client->getWebPaymentDetails($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + if(isset($response['transaction']['id'])){ + $resTrace = ' - transactionId = '.$response['transaction']['id']; + } + break; + case 'getWebWallet': + $reqTrace .= '(token = '.$array['token'].')'; + $WSresponse = $client->getWebWallet($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + if(isset($response['wallet']['card'])){ + $resTrace = ' - card = '.$this->hideChars($response['wallet']['card']['number'],4,4); + } + break; + case 'manageWebWallet' : + $reqTrace .= '(contract = '.$array['contractNumber'].' - walletId = '.$array['buyer']['walletId'].')'; + $WSresponse = $client->manageWebWallet($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + if($response['result']['code'] == '00000'){ + $resTrace = ' - token = '.$response['token']; + } + break; + case 'transactionsSearch': + $reqTrace .= '('; + foreach ($array as $key => $value) { + $reqTrace .= $value != '' ? "$key = $value - " : ''; + } + $reqTrace .= ')'; + $WSresponse = $client->transactionsSearch($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'unBlock': + $reqTrace .= '(transactionID = '.$array['transactionID'].')'; + $WSresponse = $client->unBlock($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'updateWallet': + $reqTrace .= '(walletId = '.$array['wallet']['walletId'].')'; + $WSresponse = $client->updateWallet($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'updateWebWallet': + $reqTrace .= '(walletId = '.$array['walletId'].')'; + $WSresponse = $client->updateWebWallet($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + if($response['result']['code'] == '00000'){ + $resTrace = ' - token = '.$response['token']; + } + break; + case 'verifyAuthentication': + $reqTrace .= '(contract = '.$array['contractNumber'].' - card = '.$this->hideChars($array['card']['number'],4,4).')'; + $WSresponse = $client->verifyAuthentication($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + case 'verifyEnrollment': + if(!empty($array['card']['number']) and !empty($array['payment']['contractNumber'])) { + $reqTrace .= '(contract = '.$array['payment']['contractNumber'].' - card = '.$this->hideChars($array['card']['number'],4,4).')'; + } + $WSresponse = $client->verifyEnrollment($WSRequest); + $response = paylineUtil::responseToArray($WSresponse); + break; + + } + $this->writeTrace($reqTrace); + $this->writeTrace('Response : code = '.$response['result']['code'].$resTrace); + return $response; + }catch ( Exception $e ) { + $this->writeTrace($reqTrace); + $this->writeTrace("Exception : ".$e->getMessage()); + $ERROR = array(); + $ERROR['result']['code'] = paylineSDK::ERR_CODE; + $ERROR['result']['longMessage'] = $e->getMessage(); + $ERROR['result']['shortMessage'] = $e->getMessage(); + return $ERROR; + } + } + + public function createWallet($array){ + if(!isset($array['walletContracts'])||!strlen($array['walletContracts'][0]))$array['walletContracts'] = ''; + if(!isset($array['buyer']))$array['buyer'] = null; + if(!isset($array['billingAddress']))$array['billingAddress'] = null; + if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; + if(!isset($array['owner']))$array['owner'] = null; + if(!isset($array['ownerAddress']))$array['ownerAddress'] = null; + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'wallet' => $this->wallet($array['wallet'],$array['address'],$array['card']), + 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), + 'owner' => $this->owner($array['owner'],$array['ownerAddress']), + 'privateDataList' => $this->privates, + 'authentication3DSecure' =>$this->authentication3DSecure($array['3DSecure']), + 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'createWallet'); + } + + public function createWebWallet($array){ + if(isset($array['customPaymentPageCode'])&& strlen($array['customPaymentPageCode'])) $this->customPaymentPageCode = $array['customPaymentPageCode']; + if(isset($array['cancelURL'])&& strlen($array['cancelURL'])) $this->cancelURL = $array['cancelURL']; + if(isset($array['notificationURL']) && strlen($array['notificationURL'])) $this->notificationURL = $array['notificationURL']; + if(isset($array['returnURL'])&& strlen($array['returnURL'])) $this->returnURL = $array['returnURL']; + if(isset($array['customPaymentTemplateURL'])&& strlen($array['customPaymentTemplateURL'])) $this->customPaymentTemplateURL = $array['customPaymentTemplateURL']; + if(isset($array['customPaymentPageCode'])&& strlen($array['customPaymentPageCode'])) $this->customPaymentPageCode = $array['customPaymentPageCode']; + if(isset($array['languageCode'])&& strlen($array['languageCode'])) $this->languageCode = $array['languageCode']; + if(isset($array['securityMode'])&& strlen($array['securityMode'])) $this->securityMode = $array['securityMode']; + if(!isset($array['contracts'])||!strlen($array['contracts'][0]))$array['contracts'] = ''; + if(!isset($array['walletContracts'])||!strlen($array['walletContracts'][0]))$array['walletContracts'] = ''; + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'selectedContractList' => $this->contracts($array['contracts']), + 'updatePersonalDetails' => $array['updatePersonalDetails'], + 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), + 'languageCode' => $this->languageCode, + 'customPaymentPageCode' => $this->customPaymentPageCode, + 'securityMode' => $this->securityMode, + 'returnURL' => $this->returnURL, + 'cancelURL' => $this->cancelURL, + 'notificationURL' => $this->notificationURL, + 'privateDataList' => $this->privates, + 'customPaymentTemplateURL' => $this->customPaymentTemplateURL, + 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::WEB_API,'createWebWallet'); + } + + public function disablePaymentRecord($array){ + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'paymentRecordId' => $array['paymentRecordId'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'disablePaymentRecord'); + } + + public function disableWallet($array){ + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'walletIdList' => $this->walletIdList, + 'cardInd' => $array['cardInd'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'disableWallet'); + } + + public function doAuthorization($array){ + if(!isset($array['buyer']))$array['buyer'] = null; + if(!isset($array['owner']))$array['owner'] = null; + if(!isset($array['billingAddress']))$array['billingAddress'] = null; + if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; + if(!isset($array['ownerAddress']))$array['ownerAddress'] = null; + if(!isset($array['3DSecure']))$array['3DSecure'] = null; + if(!isset($array['bankAccountData']))$array['bankAccountData'] = null; + $WSRequest = array ( + 'payment' => $this->payment($array['payment']), + 'card' => $this->card($array['card']), + 'order' => $this->order($array['order']), + 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), + 'owner' => $this->owner($array['owner'],$array['ownerAddress']), + 'privateDataList' => $this->privates, + 'authentication3DSecure' =>$this->authentication3DSecure($array['3DSecure']), + 'bankAccountData' => $this->bankAccountData($array['bankAccountData']) + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doAuthorization'); + } + + public function doCapture($array){ + $WSRequest = array ( + 'transactionID' =>$array['transactionID'], + 'payment' => $this->payment($array['payment']), + 'privateDataList' => $this->privates, + 'sequenceNumber'=>$array['sequenceNumber'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doCapture'); + } + + public function doCredit($array){ + if(!isset($array['buyer']))$array['buyer'] = null; + if(!isset($array['billingAddress']))$array['billingAddress'] = null; + if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; + $WSRequest = array ( + 'payment' => $this->payment($array['payment']), + 'card' => $this->card($array['card']), + 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), + 'privateDataList' => $this->privates, + 'order' => $this->order($array['order']), + 'comment' =>$array['comment'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doCredit'); + } + + public function doDebit($array){ + if(!isset($array['buyer']))$array['buyer'] = null; + if(!isset($array['billingAddress']))$array['billingAddress'] = null; + if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; + $WSRequest = array ( + 'payment' => $this->payment($array['payment']), + 'card' => $this->card($array['card']), + 'order' => $this->order($array['order']), + 'privateDataList' => $this->privates, + 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), + 'authentication3DSecure' =>$this->authentication3DSecure($array['3DSecure']), + 'authorization' =>$this->authorization($array['authorization']) + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doDebit'); + } + + public function doImmediateWalletPayment($array){ + if(!isset($array['buyer']))$array['buyer'] = null; + if(!isset($array['billingAddress']))$array['billingAddress'] = null; + if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; + if(!isset($array['3DSecure']))$array['3DSecure'] = null; + $WSRequest = array ( + 'payment' => $this->payment($array['payment']), + 'order' => $this->order($array['order']), + 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), + 'walletId' => $array['walletId'], + 'cardInd' => $array['cardInd'], + 'cvx' => $array['walletCvx'], + 'privateDataList' => $this->privates, + 'authentication3DSecure' =>$this->authentication3DSecure($array['3DSecure']) + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doImmediateWalletPayment'); + } + + public function doReAuthorization($array){ + $WSRequest = array ( + 'transactionID' => $array['transactionID'], + 'payment' => $this->payment($array['payment']), + 'order' => $this->order($array['order']), + 'privateDataList' => $this->privates + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doReAuthorization'); + } + + public function doRecurrentWalletPayment($array){ + if(!isset($array['orderRef']))$array['orderRef'] = null; + if(!isset($array['orderDate']))$array['orderDate'] = null; + if(!isset($array['scheduledDate']))$array['scheduledDate'] = null; + $WSRequest = array ( + 'payment' => $this->payment($array['payment']), + 'orderRef' => $array['orderRef'], + 'orderDate' => $array['orderDate'], + 'scheduledDate' => $array['scheduledDate'], + 'walletId' => $array['walletId'], + 'cardInd' => $array['cardInd'], + 'recurring' => $this->recurring($array['recurring']), + 'privateDataList' => $this->privates, + 'order' => $this->order($array['order']) + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doRecurrentWalletPayment'); + } + + public function doRefund($array){ + $WSRequest = array ( + 'transactionID' =>$array['transactionID'], + 'payment' =>$this->payment($array['payment']), + 'comment' =>$array['comment'], + 'privateDataList' => $this->privates, + 'sequenceNumber'=>$array['sequenceNumber'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doRefund'); + } + + public function doReset($array){ + $WSRequest = array ( + 'transactionID' => $array['transactionID'], + 'comment' => $array['comment'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doReset'); + } + + public function doScheduledWalletPayment($array){ + if(!isset($array['orderRef']))$array['orderRef'] = null; + if(!isset($array['orderDate']))$array['orderDate'] = null; + $WSRequest = array ( + 'payment' => $this->payment($array['payment']), + 'orderRef' => $array['orderRef'], + 'orderDate' => $array['orderDate'], + 'scheduledDate' => $array['scheduledDate'], + 'walletId' => $array['walletId'], + 'cardInd' => $array['cardInd'], + 'order' => $this->order($array['order']), + 'privateDataList' => $this->privates + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doScheduledWalletPayment'); + } + + public function doScoringCheque($array){ + $WSRequest = array ( + 'payment' => $this->payment($array['payment']), + 'cheque' => $this->cheque($array['cheque']), + 'order' => $this->order($array['order']), + 'privateDataList' => $this->privates + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'doScoringCheque'); + } + + public function doWebPayment($array){ + if(isset($array['cancelURL'])&& strlen($array['cancelURL'])) $this->cancelURL = $array['cancelURL']; + if(isset($array['notificationURL']) && strlen($array['notificationURL'])) $this->notificationURL = $array['notificationURL']; + if(isset($array['returnURL'])&& strlen($array['returnURL'])) $this->returnURL = $array['returnURL']; + if(isset($array['customPaymentTemplateURL'])&& strlen($array['customPaymentTemplateURL'])) $this->customPaymentTemplateURL = $array['customPaymentTemplateURL']; + if(isset($array['customPaymentPageCode'])&& strlen($array['customPaymentPageCode'])) $this->customPaymentPageCode = $array['customPaymentPageCode']; + if(isset($array['languageCode'])&& strlen($array['languageCode'])) $this->languageCode = $array['languageCode']; + if(isset($array['securityMode'])&& strlen($array['securityMode'])) $this->securityMode = $array['securityMode']; + if(!isset($array['payment']))$array['payment'] = null; + if(!isset($array['contracts'])||!strlen($array['contracts'][0]))$array['contracts'] = ''; + if(!isset($array['secondContracts'])||!strlen($array['secondContracts'][0]))$array['secondContracts'] = ''; + if(!isset($array['walletContracts'])||!strlen($array['walletContracts'][0]))$array['walletContracts'] = ''; + if(!isset($array['buyer']))$array['buyer'] = null; + if(!isset($array['billingAddress']))$array['billingAddress'] = null; + if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; + if(!isset($array['recurring']))$array['recurring'] = null; + + $WSRequest = array ( + 'payment' => $this->payment($array['payment']), + 'returnURL' => $this->returnURL, + 'cancelURL' => $this->cancelURL, + 'order' => $this->order($array['order']), + 'notificationURL' => $this->notificationURL, + 'customPaymentTemplateURL' => $this->customPaymentTemplateURL, + 'selectedContractList' => $this->contracts($array['contracts']), + 'secondSelectedContractList' => $this->secondContracts($array['secondContracts']), + 'privateDataList' => $this->privates, + 'languageCode' => $this->languageCode, + 'customPaymentPageCode' => $this->customPaymentPageCode, + 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), + 'securityMode' => $this->securityMode, + 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) + ); + + + if(isset($array['payment']['mode'])){ + if(($array['payment']['mode'] == "REC") || ($array['payment']['mode'] == "NX")) { + $WSRequest['recurring'] = $this->recurring($array['recurring']); + } + } + return $this->webServiceRequest($array,$WSRequest,paylineSDK::WEB_API,'doWebPayment'); + } + + public function enableWallet($array){ + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'walletId' => $array['walletId'], + 'cardInd' => $array['cardInd'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'enableWallet'); + } + + public function getServletTokenUrl(){ + return $this->servletTokenUrl; + } + + public function getWidgetJavascriptUrl(){ + return $this->widgetJavascriptUrl; + } + + public function getWidgetCssUrl(){ + return $this->widgetCssUrl; + } + + public function getAlertDetails($array){ + $WSRequest = array( + 'AlertId' => $array['AlertId'], + 'TransactionId' => $array['TransactionId'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::EXTENDED_API,'getAlertDetails'); + } + + public function getBalance($array){ + $WSRequest = array( + 'contractNumber' => $array['contractNumber'], + 'cardID' => $array['cardID'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getBalance'); + } + + public function getCards($array){ + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'walletId' => $array['walletId'], + 'cardInd' => $array['cardInd'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getCards'); + } + + public function getEncryptionKey($array){ + $WSRequest = array(); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getEncryptionKey'); + } + + public function getMerchantSettings($array){ + $WSRequest = array(); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getMerchantSettings'); + } + + private function getPaymentMeans(){ + $this->writeTrace('getPaymentMeans'); + try{ + $client = new SoapClient(dirname(__FILE__).'/PaylineByMonext.wsdl', $this->header_soap); + $WSresponse = $client->getPaymentMeans(); + $response = paylineUtil::responseToArray($WSresponse); + $this->writeTrace($response['result']); + return $response; + }catch ( Exception $e ) { + $this->writeTrace("Exception : ".$e->getMessage()); + $ERROR = array(); + $ERROR['result']['code'] = paylineSDK::ERR_CODE; + $ERROR['result']['longMessage'] = $e->getMessage(); + $ERROR['result']['shortMessage'] = $e->getMessage(); + return $ERROR; + } + } + + private function addPOSFromObject($oPointOfSell,$pos){ + if(isset($oPointOfSell->contracts->contract)){ + $this->posData[$pos] = array(); + $this->posData[$pos]['label'] = $oPointOfSell->label; + $this->posData[$pos]['contracts'] = array(); + if(sizeof($oPointOfSell->contracts->contract) > 1){ + // more than 1 active contract in this point of sell + $ctr = 0; + foreach ($oPointOfSell->contracts->contract as $contract){ + $this->posData[$pos]['contracts'][$ctr] = array(); + $this->posData[$pos]['contracts'][$ctr]['cardType'] = $contract->cardType; + $this->posData[$pos]['contracts'][$ctr]['label'] = $contract->label; + $this->posData[$pos]['contracts'][$ctr]['contractNumber'] = $contract->contractNumber; + $this->posData[$pos]['contracts'][$ctr]['logo'] = $this->paymentMeansLogos[$this->posData[$pos]['contracts'][$ctr]['cardType']]; // default logo + if($contract->logoEnable){ + $this->posData[$pos]['contracts'][$ctr]['logo'] = $this->downloadCustomLogo($contract->normalLogo, $contract->normalLogoMime, $contract->contractNumber, $oPointOfSell->label); + } + $ctr++; + } + }else{ // only 1 active contract in this point of sell + $this->posData[$pos]['contracts'][0] = array(); + $this->posData[$pos]['contracts'][0]['cardType'] = $oPointOfSell->contracts->contract->cardType; + $this->posData[$pos]['contracts'][0]['label'] = $oPointOfSell->contracts->contract->label; + $this->posData[$pos]['contracts'][0]['contractNumber'] = $oPointOfSell->contracts->contract->contractNumber; + $this->posData[$pos]['contracts'][0]['logo'] = $this->paymentMeansLogos[$this->posData[$pos]['contracts'][0]['cardType']]; // default logo + if($oPointOfSell->contracts->contract->logoEnable){ + $this->posData[$pos]['contracts'][0]['logo'] = $this->downloadCustomLogo($oPointOfSell->contracts->contract->normalLogo, $oPointOfSell->contracts->contract->normalLogoMime, $oPointOfSell->contracts->contract->contractNumber, $oPointOfSell->label); + } + } + }else{ // no contract in this point of sell + return false; + } + + return true; + } + + private function addPOSFromArray($aPointOfSell,$pos){ + if(isset($aPointOfSell['contracts']['contract'])){ + $this->posData[$pos] = array(); + $this->posData[$pos]['label'] = $aPointOfSell['label']; + $this->posData[$pos]['contracts'] = array(); + if(isset($aPointOfSell['contracts']['contract']['label'])){ + // only 1 active contract in this point of sell + $this->posData[$pos]['contracts'][0] = array(); + $this->posData[$pos]['contracts'][0]['cardType'] = $aPointOfSell['contracts']['contract']['cardType']; + $this->posData[$pos]['contracts'][0]['label'] = $aPointOfSell['contracts']['contract']['label']; + $this->posData[$pos]['contracts'][0]['contractNumber'] = $aPointOfSell['contracts']['contract']['contractNumber']; + $this->posData[$pos]['contracts'][0]['logo'] = $this->paymentMeansLogos[$this->posData[$pos]['contracts'][0]['cardType']]; // default logo + if($aPointOfSell['contracts']['contract']['logoEnable']){ + $this->posData[$pos]['contracts'][0]['logo'] = $this->downloadCustomLogo($aPointOfSell['contracts']['contract']['normalLogo'], $aPointOfSell['contracts']['contract']['normalLogoMime'], $aPointOfSell['contracts']['contract']['contractNumber'], $aPointOfSell['label']); + } + }else{ // more than 1 active contract in this point of sell + $ctr = 0; + foreach ($aPointOfSell['contracts']['contract'] as $contract){ + $this->posData[$pos]['contracts'][$ctr] = array(); + $this->posData[$pos]['contracts'][$ctr]['cardType'] = $contract->cardType; + $this->posData[$pos]['contracts'][$ctr]['label'] = $contract->label; + $this->posData[$pos]['contracts'][$ctr]['contractNumber'] = $contract->contractNumber; + $this->posData[$pos]['contracts'][$ctr]['logo'] = $this->paymentMeansLogos[$this->posData[$pos]['contracts'][$ctr]['cardType']]; // default logo + if($contract->logoEnable){ + $this->posData[$pos]['contracts'][$ctr]['logo'] = $this->downloadCustomLogo($contract->normalLogo, $contract->normalLogoMime, $contract->contractNumber, $aPointOfSell['label']); + } + $ctr++; + } + } + }else{ // no contract in this point of sell + return false; + } + return true; + } + + private function absoluteURL($path) { + $dir = str_replace('\\', '/', dirname($path)); + return $_SERVER['HTTP_ORIGIN'].'/'.substr($dir, strlen($_SERVER['DOCUMENT_ROOT'])).'/'; + } + + private function downloadCustomLogo($base64String,$mimeType,$contractNumber,$posLabel){ + $mime = explode('/', $mimeType); + if($this->customLogoPath != null){ + if(!file_exists($this->customLogoPath)){ + mkdir($this->customLogoPath); + } + $posDir = $this->customLogoPath.$posLabel.DIRECTORY_SEPARATOR; + }else{ + $merchantDir = dirname(__DIR__).DIRECTORY_SEPARATOR.paylineSDK::DEFAULT_LOGO_DIR.DIRECTORY_SEPARATOR.$this->header_soap['login'].DIRECTORY_SEPARATOR; + if(!file_exists($merchantDir)){ + mkdir($merchantDir); + } + $posDir = $merchantDir.$posLabel.DIRECTORY_SEPARATOR; + } + if(!file_exists($posDir)){ + mkdir($posDir); + } + $output_file = $posDir.$contractNumber.'.'.$mime[1]; + + try{ + if(file_put_contents($output_file,$base64String)){ + return $this->absoluteURL($output_file).$contractNumber.'.'.$mime[1]; + }else{ + $this->writeTrace("Error : downloadCustomLogo for contract $contractNumber under $posDir failed"); + return paylineSDK::ERR_CODE; + } + }catch (Exception $e){ + $this->writeTrace("Exception : downloadCustomLogo for contract $contractNumber of pos $posLabel - ".$e->getMessage()); + return paylineSDK::ERR_CODE; + } + } + + public function getMerchantSettingsToArray($array){ + /* + * Association between Payment mean types and logos URL + */ + $getPaymentMeansResponse = $this->getPaymentMeans(); + if($getPaymentMeansResponse['result']['code'] != paylineSDK::ERR_CODE){ + $this->paymentMeansLogos = array(); + for($i=0 ; $ipaymentMeansLogos[$getPaymentMeansResponse['listPaymentMean']['paymentMean'][$i]->code] = $getPaymentMeansResponse['listPaymentMean']['paymentMean'][$i]->logoUrl; + } + } + + if(isset($array['logoPath'])){ + $this->customLogoPath = $array['logoPath']; + } + $getMerchantSettingsRes = $this->getMerchantSettings($array); + if(isset($getMerchantSettingsRes['listPointOfSell']['pointOfSell']['label'])){ + // only 1 active point of sell + $aPointOfSell = $getMerchantSettingsRes['listPointOfSell']['pointOfSell']; + $this->addPOSFromArray($aPointOfSell, 0); + }else{ // more than 1 active point of sell + $index = 0; + foreach ($getMerchantSettingsRes['listPointOfSell']['pointOfSell'] as $oPointOfSell){ + if($this->addPOSFromObject($oPointOfSell, $index)){ + $index++; // no incrementation if pos was not added + } + } + } + $res = array('result' => $getMerchantSettingsRes['result'],'POS' => $this->posData); + return $res; + } + + public function getPaymentRecord($array){ + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'paymentRecordId' => $array['paymentRecordId'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getPaymentRecord'); + } + + public function updatePaymentRecord($array){ + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'paymentRecordId' => $array['paymentRecordId'], + 'recurring' => $this->recurring($array['recurring']), + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'updatePaymentRecord'); + } + + public function getBillingRecord($array){ + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'paymentRecordId' => $array['paymentRecordId'], + 'billingRecordId' => $array['billingRecordId'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getBillingRecord'); + } + + public function updateBillingRecord($array){ + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'paymentRecordId' => $array['paymentRecordId'], + 'billingRecordId' => $array['billingRecordId'], + 'billingRecordForUpdate' => $this->billingRecord($array['billingRecordForUpdate']) + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'updateBillingRecord'); + } + + public function getToken($array){ + $WSRequest = array ( + 'cardNumber' => $array['cardNumber'], + 'expirationDate' => $array['expirationDate'], + 'contractNumber' => $array['contractNumber'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getToken'); + } + + public function getTransactionDetails($array){ + if(!isset($array['transactionId']))$array['transactionId'] = null; + if(!isset($array['orderRef']))$array['orderRef'] = null; + if(!isset($array['startDate']))$array['startDate'] = null; + if(!isset($array['endDate']))$array['endDate'] = null; + if(!isset($array['transactionHistory']))$array['transactionHistory'] = null; + if(!isset($array['archiveSearch']))$array['archiveSearch'] = null; + $WSRequest = array ( + 'transactionId' => $array['transactionId'], + 'orderRef' => $array['orderRef'], + 'startDate' => $array['startDate'], + 'endDate' => $array['endDate'], + 'transactionHistory' => $array['transactionHistory'], + 'archiveSearch' => $array['archiveSearch'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::EXTENDED_API,'getTransactionDetails'); + } + public function getWallet($array){ + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'walletId' => $array['walletId'], + 'cardInd' => $array['cardInd'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'getWallet'); + } + + public function getWebPaymentDetails($array){ + return $this->webServiceRequest($array,$array,paylineSDK::WEB_API,'getWebPaymentDetails'); + } + + public function getWebWallet($array){ + return $this->webServiceRequest($array,$array,paylineSDK::WEB_API,'getWebWallet'); + } + + public function manageWebWallet($array){ + if(isset($array['cancelURL'])&& strlen($array['cancelURL'])) $this->cancelURL = $array['cancelURL']; + if(isset($array['notificationURL']) && strlen($array['notificationURL'])) $this->notificationURL = $array['notificationURL']; + if(isset($array['returnURL'])&& strlen($array['returnURL'])) $this->returnURL = $array['returnURL']; + if(!isset($array['buyer']))$array['buyer'] = null; + if(!isset($array['billingAddress']))$array['billingAddress'] = null; + if(!isset($array['shippingAddress']))$array['shippingAddress'] = null; + if(!isset($array['owner']))$array['owner'] = null; + if(!isset($array['ownerAddress']))$array['ownerAddress'] = null; + if(!isset($array['contracts'])||!strlen($array['contracts'][0]))$array['contracts'] = ''; + if(!isset($array['walletContracts'])||!strlen($array['walletContracts'][0]))$array['walletContracts'] = ''; + if(isset($array['customPaymentPageCode'])&& strlen($array['customPaymentPageCode'])) $this->customPaymentPageCode = $array['customPaymentPageCode']; + if(isset($array['customPaymentTemplateURL'])&& strlen($array['customPaymentTemplateURL'])) $this->customPaymentTemplateURL = $array['customPaymentTemplateURL']; + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'selectedContractList' => $this->contracts($array['contracts']), + 'updatePersonalDetails' => $array['updatePersonalDetails'], + 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), + 'owner' => $this->owner($array['owner'],$array['ownerAddress']), + 'languageCode' => $array['languageCode'], + 'customPaymentPageCode' => $array['customPaymentPageCode'], + 'securityMode' => $array['securityMode'], + 'returnURL' => $this->returnURL, + 'cancelURL' => $this->cancelURL, + 'notificationURL' => $this->notificationURL, + 'privateDataList' => $this->privates, + 'customPaymentTemplateURL' => $array['customPaymentTemplateURL'], + 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::WEB_API,'manageWebWallet'); + } + + public function transactionsSearch($array){ + $WSRequest = array ( + 'transactionId' => $array['transactionId'], + 'orderRef' => $array['orderRef'], + 'startDate' => $array['startDate'], + 'endDate' => $array['endDate'], + 'contractNumber' => $array['contractNumber'], + 'authorizationNumber' => $array['authorizationNumber'], + 'returnCode' => $array['returnCode'], + 'paymentMean' => $array['paymentMean'], + 'transactionType' => $array['transactionType'], + 'name' => $array['name'], + 'firstName' => $array['firstName'], + 'email' => $array['email'], + 'cardNumber' => $array['cardNumber'], + 'currency' => $array['currency'], + 'minAmount' => $array['minAmount'], + 'maxAmount' => $array['maxAmount'], + 'walletId' => $array['walletId'], + 'sequenceNumber' => $array['sequenceNumber'], + 'token' => $array['token'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::EXTENDED_API,'transactionsSearch'); + } + + public function unBlock($array){ + $WSRequest = array ( + 'transactionID' => $array['transactionID'], + 'transactionDate' => $array['transactionDate'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'unBlock'); + } + + public function updateWallet($array){ + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'cardInd' => $array['cardInd'], + 'wallet' => $this->wallet($array['wallet'],$array['address'],$array['card']), + 'buyer' => $this->buyer($array['buyer'], $array['shippingAddress'],$array['billingAddress']), + 'owner' => $this->owner($array['owner'],$array['ownerAddress']), + 'privateDataList' => $this->privates, + 'authentication3DSecure' =>$this->authentication3DSecure($array['3DSecure']), + 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'updateWallet'); + } + + public function updateWebWallet($array){ + if(isset($array['cancelURL'])&& strlen($array['cancelURL'])) $this->cancelURL = $array['cancelURL']; + if(isset($array['notificationURL']) && strlen($array['notificationURL'])) $this->notificationURL = $array['notificationURL']; + if(isset($array['returnURL'])&& strlen($array['returnURL'])) $this->returnURL = $array['returnURL']; + if(isset($array['customPaymentTemplateURL'])&& strlen($array['customPaymentTemplateURL'])) $this->customPaymentTemplateURL = $array['customPaymentTemplateURL']; + if(isset($array['customPaymentPageCode'])&& strlen($array['customPaymentPageCode'])) $this->customPaymentPageCode = $array['customPaymentPageCode']; + if(isset($array['languageCode'])&& strlen($array['languageCode'])) $this->languageCode = $array['languageCode']; + if(isset($array['securityMode'])&& strlen($array['securityMode'])) $this->securityMode = $array['securityMode']; + if(!isset($array['walletContracts'])||!strlen($array['walletContracts'][0]))$array['walletContracts'] = ''; + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'cardInd' => $array['cardInd'], + 'walletId' => $array['walletId'], + 'updatePersonalDetails' => $array['updatePersonalDetails'], + 'updateOwnerDetails' => $array['updateOwnerDetails'], + 'updatePaymentDetails' => $array['updatePaymentDetails'], + 'buyer' => $this->buyer($array['buyer'],$array['shippingAddress'],$array['billingAddress']), + 'languageCode' => $this->languageCode, + 'customPaymentPageCode' => $this->customPaymentPageCode, + 'securityMode' => $this->securityMode, + 'returnURL' => $this->returnURL, + 'cancelURL' => $this->cancelURL, + 'notificationURL' => $this->notificationURL, + 'privateDataList' => $this->privates, + 'customPaymentTemplateURL' => $this->customPaymentTemplateURL, + 'contractNumberWalletList' => $this->secondContracts($array['walletContracts']) + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::WEB_API,'updateWebWallet'); + } + + public function verifyAuthentication($array){ + $WSRequest = array ( + 'contractNumber' => $array['contractNumber'], + 'pares' => $array['pares'], + 'md' => $array['md'], + 'card' => $this->card($array['card']) + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'verifyAuthentication'); + } + + public function verifyEnrollment($array){ + if(!isset($array['orderRef']))$array['orderRef'] = null; + if(!isset($array['userAgent']))$array['userAgent'] = null; + if(!isset($array['mdFieldValue']))$array['mdFieldValue'] = null; + if(!isset($array['walletId']))$array['walletId'] = null; + if(!isset($array['walletCardInd']))$array['walletCardInd'] = null; + if(!isset($array['card']))$array['card'] = null; + $WSRequest = array ( + 'payment' => $this->payment($array['payment']), + 'card' => $this->card($array['card']), + 'orderRef' => $array['orderRef'], + 'userAgent' => $array['userAgent'], + 'mdFieldValue' => $array['mdFieldValue'], + 'walletId' => $array['walletId'], + 'walletCardInd' => $array['walletCardInd'] + ); + return $this->webServiceRequest($array,$WSRequest,paylineSDK::DIRECT_API,'verifyEnrollment'); + } +} diff --git a/app/design/frontend/base/default/template/payline/checkout/onepage/widget-opcheckout-js-init.phtml b/app/design/frontend/base/default/template/payline/checkout/onepage/widget-opcheckout-js-init.phtml index 68a7e32..c6b0cfd 100644 --- a/app/design/frontend/base/default/template/payline/checkout/onepage/widget-opcheckout-js-init.phtml +++ b/app/design/frontend/base/default/template/payline/checkout/onepage/widget-opcheckout-js-init.phtml @@ -1,93 +1,100 @@ - - + + diff --git a/app/design/frontend/base/default/template/payline/checkout/onepage/widget-opcheckout-js.phtml b/app/design/frontend/base/default/template/payline/checkout/onepage/widget-opcheckout-js.phtml deleted file mode 100644 index fa0d59b..0000000 --- a/app/design/frontend/base/default/template/payline/checkout/onepage/widget-opcheckout-js.phtml +++ /dev/null @@ -1,94 +0,0 @@ - - diff --git a/app/design/frontend/base/default/template/payline/checkout/onepage/widget-update.phtml b/app/design/frontend/base/default/template/payline/checkout/onepage/widget-update.phtml deleted file mode 100644 index b1d3ce7..0000000 --- a/app/design/frontend/base/default/template/payline/checkout/onepage/widget-update.phtml +++ /dev/null @@ -1,14 +0,0 @@ -array('amount'=>$this->getQuoteBaseGrandTotal()), - 'order'=>array('amount'=>$this->getQuoteBaseGrandTotal())); -?> - \ No newline at end of file diff --git a/modman b/modman new file mode 100644 index 0000000..3faa104 --- /dev/null +++ b/modman @@ -0,0 +1,12 @@ +# Module Monext_Payline +app/code/community/Monext/Payline app/code/community/Monext/Payline +app/locale/en_US/Monext_Payline.csv app/locale/en_US/Monext_Payline.csv +app/locale/fr_FR/Monext_Payline.csv app/locale/fr_FR/Monext_Payline.csv +app/etc/modules/Monext_Payline.xml app/etc/modules/Monext_Payline.xml +app/design/frontend/base/default/template/payline app/design/frontend/base/default/template/payline +app/design/frontend/base/default/layout/payline.xml app/design/frontend/base/default/layout/payline.xml +app/design/adminhtml/default/default/template/payline app/design/adminhtml/default/default/template/payline +app/design/adminhtml/default/default/layout/payline.xml app/design/adminhtml/default/default/layout/payline.xml +skin/frontend/base/default/images/monext skin/frontend/base/default/images/monext +skin/frontend/base/default/css/payline.css skin/frontend/base/default/css/payline.css +skin/frontend/base/default/js/payline.js skin/frontend/base/default/js/payline.js \ No newline at end of file diff --git a/skin/frontend/base/default/js/payline.js b/skin/frontend/base/default/js/payline.js index cffc03b..9e5f4d2 100644 --- a/skin/frontend/base/default/js/payline.js +++ b/skin/frontend/base/default/js/payline.js @@ -1,515 +1,562 @@ -function paylineTrySkipPaymentMethod() { - if (!paylinePaymentSavedTransport) { - return; - } - - var paylinePaymentInputNames = []; - - var paylineIsUniquePaymentChoice = true; - - // Retrive all radio groups - $$('#opc-payment input[type=radio]').each(function (radio) { - if (paylinePaymentInputNames.indexOf(radio.name)==-1) - paylinePaymentInputNames.push(radio.name); - else - paylineIsUniquePaymentChoice = false; - }); - - // If only one input by group - if (paylineIsUniquePaymentChoice) { - // Check all boxes - paylinePaymentInputNames.each(function (name) { - $$('#opc-payment input[name="' + name + '"]').first().checked = true; - }); - // Go to review step - checkout.setStepResponse(paylinePaymentSavedTransport); - } -} - -var PaylineWidgetWrapper = Class.create(); -PaylineWidgetWrapper.prototype = { - initialize: function(data_token, data_template, save_url, custom_methods, init_quote_total, currency_code, payment_template) { - this.dataToken = data_token; - this.dataTemplate = data_template; - this.saveUrl = save_url; - this.paymentTemplate = payment_template; - - /*switch(this.dataTemplate) { - case 'lightbox': - this.rootTabSelector = 'pmLayout-column-pmContainer-mycustompm'; - break; - case 'tab': - this.rootTabSelector = 'pmLayout-tab-tab_mycustompm'; - break; - case 'column': - this.rootTabSelector = 'pmLayout-column-pmLogo-mycustompm'; - break; - default: - this.rootTabSelector = false; - }*/ - - this.rootTabSelector = 'pmLayout-.*-mycustompm'; - - this.initQuoteGrandTotal = init_quote_total; - this.currencyCode = currency_code; - this.finalQuoteGrandTotal = 0; - this.finalPaymentMethods = {}; - this.observer = false; - - this.customPmMethods = []; - this.allPaymentMethods = {}; - this.preparePmMethods(custom_methods); - }, - - - - setFinalQuoteGrandTotal: function(grantotal) - { - this.finalQuoteGrandTotal = grantotal; - }, - - setFinalPaymentMethods: function(methods) - { - this.finalPaymentMethods = methods; - }, - - initPayline: function(noAgreement){ - - if(typeof Payline.Api != 'undefined') { - - var elemProgress = $('payment-progress-opcheckout'); - if (elemProgress) { - var elemDd = elemProgress.select('dd').first(); - elemProgress.select('dt').each(function (item) { - item.addClassName('complete'); - - if(typeof elemDd != 'undefined') { - elemDd.remove(); - } - item.insert({after:'
' - + $('checkout-review-table').select('tfoot').first().innerHTML - + '
'} - ); - }); - $('checkout-review-table-wrapper').hide(); - } - - - if(!$("PaylineWidget")) { - $('checkout-review-load').insert({after: '
'}); - Payline.Api.init(this.dataToken, this.dataTemplate); - - if(noAgreement) { - // Need a MutationObserver to check widget state ... too bad - this.observer = new MutationObserver(function(mutations) { - mutations.forEach(function(mutation) { - - var re = new RegExp('pl-pmLayout-.*-mycustompm'+'(\\w+)',"ig"); - var result = re.exec(mutation.target.id); - - var callshowWidget = false; - //if(result && mutation.addedNodes.length>0) { - if(result) { - callshowWidget = true; - this.allPaymentMethods[result[1]].checked = true; - } - - if(callshowWidget) { - $H(this.allPaymentMethods).each(function(pair) { - if(!pair.value.checked) { - callshowWidget = false; - } - }); - - if(callshowWidget) { - this.showWidget(true); - } - } - }.bind(this)); - }.bind(this)); - - // configuration of the observer: - var config = { attributes: true, subtree:true, childList: true}; - - // pass in the target node, as well as the observer options - this.observer.observe($("PaylineWidget"), config); - } - } - Payline.Api.hide(); - } - }, - - showWidget: function(observer){ - if(typeof Payline.Api != 'undefined') { - $('review-buttons-container').hide(); - - $$('.magento-payline-custom-html [id*=payment_form]').each(function(elem){ - elem.style.display = ''; - }); - - if(observer) { - if(this.observer) { - // Stop observing - this.observer.disconnect(); - } - } else { - Payline.Api.show(); - } - - this.setPmMethodTabs(); - } else { - alert('Payline is undefined!'); - } - }, - - setPmMethodTabs: function() - { - $$('div[id*="pmLayout-"][class*="pl-card"]').each(function(divTab){ - var re = new RegExp(this.rootTabSelector+'(\\w+)',"ig"); - var result = re.exec(divTab.id); - var tabSpan = divTab.select('span.pl-card-logo').first(); - if (tabSpan && result) { - tabSpan.setAttribute('style', 'background:none; width:auto !important'); - - if(this.allPaymentMethods[result[1]]) { - tabSpan.update(this.allPaymentMethods[result[1]].title); - } else { - tabSpan.update(result[1]); - } - - var divPayment = divTab.up('div').up('div'); - if(this.finalPaymentMethods && this.finalPaymentMethods[result[1]]) { - divPayment.show(); - } else { - divPayment.hide(); - } - } - - - }.bind(this)); - }, - - preparePmMethods: function(custom_methods) { - custom_methods.each(function(payment){ - this.allPaymentMethods[payment.code] = {title:payment.title, checked:false, code:payment.code}; - this.customPmMethods.push({"paymentMethodId":("myCustomPm"+payment.code), - "html": this.paymentTemplate.evaluate({paymentHtml: payment.html, paymentCode: payment.code}) - }); - }.bind(this)); - }, - - getPmMethods: function() - { - return this.customPmMethods; - }, - - saveCustomPayment: function(method) { - if (checkout.loadWaiting!=false) return; - - var params = 'paymentmethod='+method; - if (review.agreementsForm) { - params += '&'+Form.serialize(review.agreementsForm); - } - params.save = true; - - var request = new Ajax.Request( - this.saveUrl, - { - method:'post', - parameters:params, - onComplete: review.onComplete, - onSuccess: review.onSave, - onFailure: checkout.ajaxFailure.bind(checkout) - } - ); - } - -} - - -var PaylineDirectMethod = Class.create(); -PaylineDirectMethod.prototype = { - initialize: function(code, tokenUrl,cryptedKeys,accessKeyRef,tokenReturnURL){ - // Payment code - this.code = code; - // Token list by method - this.tokenUrl=tokenUrl; - // Internal crypted key - this.cryptedKeys=cryptedKeys; - // Payline user key - this.accessKeyRef=accessKeyRef; - // Return url for post redirection - this.tokenReturnURL = tokenReturnURL; - // Regex to find back real name for data - this.regexPayment= /^payment\[(.+)\]/; - // Keep all values - this.paymentInputs= $H({}); - // Errors code and label - this.errors = {}; - // Initialize inputs changes to fill paymentInputs - this.onChangeInputs = this.checkInputChange.bind(this); - // Check inputs changes - this.followInputs(); - - this.onComplete = this.resetLoadWaiting.bindAsEventListener(this); - }, - // Set user error by code - setErrors: function(errors){ - this.errors = errors; - }, - showError: function(errorCode){ - - if (this.errors[errorCode]) { - var errorMsg = 'Error ' + errorCode + ': "' + this.errors[errorCode] + '"'; - } else { - var errorMsg = 'Unexpected error: ' + errorCode; - } - - alert(errorMsg); - }, - // Retrieve real name from input name - getPaymentInputName: function(input) - { - matchPayment = this.regexPayment.exec(input.name); - if (matchPayment) { - return matchPayment[1]; - } else { - return false; - } - }, - // Init observe on payments inputs - followInputs: function (container) { - - $("payment_form_"+this.code).select('input', 'select').each(function(input){ - inputName= this.getPaymentInputName(input); - if (inputName) { - input.observe('change', this.onChangeInputs ); - } - }.bind(this)); - }, - // Keep the paymentInputs up to date - checkInputChange: function (evt) { - var input = Event.element(evt); - - inputName= this.getPaymentInputName(input); - if (inputName) { - this.paymentInputs.set(inputName, input.value); - } - }, - // Prepare data to send to payline - save: function(){ - var isPayline = false; - $$('input[name=payment[method]]').each(function(elem){ - if(elem.checked && elem.getAttribute('value')==this.code) { - isPayline = true; - } - }.bind(this)); - - // Check if we have some work to do - if (!isPayline) { - payment.save(); - } else { - if (checkout.loadWaiting!=false) return; - var validator = new Validation(payment.form); - if (validator.validate()) { - checkout.setLoadWaiting('payment'); - var requestParameters= { - data: this.cryptedKeys[this.paymentInputs.get('cc_type')], - accessKeyRef: this.accessKeyRef, - cardNumber: this.paymentInputs.get('cc_number'), - cardExpirationDate: this.paymentInputs.get('cc_exp_month') + this.paymentInputs.get('cc_exp_year'), - cardCvx: this.paymentInputs.get('cc_cid') - }; - - if(this.canUseCors()) { - this.saveWithAjax(requestParameters); - } else { - this.saveWithPost(requestParameters); - } - } - } - }, - - resetLoadWaiting: function(){ - checkout.setLoadWaiting(false); - }, - - // Test browser capability to make cross domain calls - canUseCors: function() - { - // Cors detection is dactivated by default - return false; - - var cors = false; - if ('withCredentials' in new XMLHttpRequest()) { - // Supports cross-domain requests - cors = true; - } - else if(typeof XDomainRequest !== "undefined"){ - // Use IE-specific "CORS" code with XDR but we know IE capabilities :-( - if(Prototype.Browser.IE) { - var ua = navigator.userAgent; - var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); - if (re.exec(ua) != null) { - rv = parseFloat( RegExp.$1 ); - // Problem detected on IE8 - if(rv > 8.0 ) { - cors = true; - } - } - } - } - return cors; - }, - // Call payline to get the token and then go to review - saveWithAjax: function (requestParameters) - { - var paramArray = new Array(); - $H(requestParameters).each(function(pair){ - paramArray.push(pair.key + '=' + pair.value); - }); - - var request = new Ajax.Request(this.tokenUrl, { - method: 'post', - // Using postBody avoid to use encodeURIComponent with parameters - postBody: paramArray.join('&'), - contentType: 'application/x-www-form-urlencoded', - onCreate: function(response) { // here comes the fix - // request.transport.setRequestHeader = Prototype.emptyFunction; - if (response.request.isSameOrigin()) { - return; - } - - var t = response.transport; - t.setRequestHeader = t.setRequestHeader.wrap(function(original, k, v) { - if (/^(accept|accept-language|content-language)$/i.test(k)) - return original(k, v); - if (/^content-type$/i.test(k) && /^(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)(;.+)?$/i.test(v)) - return original(k, v); - return; - }); - }, - onComplete: this.onComplete, - onSuccess: function(transport) { - response={}; - if(transport.responseJSON) { - response = transport.responseJSON; - } else if (transport.responseText) { - result = transport.responseText.split('='); - if(result) { - response[result[0]] = result[1]; - } - } else { - response = {errorCode:1, message:'No result'}; - } - - if(typeof response.data!=='undefined') { - this.saveStep(response.data); - } else if (response.errorCode) { - this.showError(response.errorCode) - } else { - this.showError('ajax_call'); - } - }.bind(this), - onFailure: function() { - alert('Failed to call secure server'); - } - }); - }, - saveWithPost: function (requestParameters) - { - requestParameters.returnURL = this.tokenReturnURL; - - var frameId = 'output_token_response'; - var form = new Element('form', { id: 'form_post_token', action: this.tokenUrl, method: 'post',target:frameId }); - $H(requestParameters).each(function(input){ - var formInput = new Element('input', { 'type': 'hidden', 'name':input.key, 'value':input.value}); - form.insert({top:formInput}); - }); - - var iframe = new Element('iframe', { id: frameId,name:frameId, style:'display:none', width:0, height:0 }); - - // Old school event attachement to prevent IE8 bugs - if(iframe.attachEvent) { - iframe.attachEvent('onload', this.postIframeLoad.bind(this)); - } else { - iframe.onload = this.postIframeLoad.bind(this); - } - - document.body.appendChild(iframe); - - iframe.insert({after:form}); - form.submit(); - }, - - postIframeLoad: function(event) - { - var iframe = Event.element(event); - var idoc= iframe.contentDocument || iframe.contentWindow.document; - var parWindow = idoc.defaultView || idoc.parentWindow; - - // Prevent check when onload is fired when iframe added to dom - // have to wait for submit - if(parWindow.document.body.innerHTML) { - var regexToken= /^(.+)=(.+)$/; - var matchResponse = regexToken.exec(parWindow.document.body.innerHTML); - if(matchResponse && matchResponse[1]=='data') { - this.saveStep(matchResponse[2]); - } else if (matchResponse && matchResponse[1]=='errorCode' && this.errors[matchResponse[2]]) { - this.showError(matchResponse[2]); - } else { - this.showError('frame_content'); - } - iframe.remove(); - this.resetLoadWaiting(); - } - }, - - // Bypass the payment save method - saveStep: function(token) - { - var saveParameters = {}; - saveParameters['payment[method]']= this.code; - saveParameters['payment[card_token_pan]']= token; - saveParameters['payment[subscribe_wallet]']= this.paymentInputs.get('subscribe_wallet'); - saveParameters['payment[cc_type]']= this.paymentInputs.get('cc_type'); - saveParameters['payment[cc_last4]']= $(this.code + '_cc_number').value.substr(-4); - saveParameters['payment[cc_exp_month]']= this.paymentInputs.get('cc_exp_month'); - saveParameters['payment[cc_exp_year]']= this.paymentInputs.get('cc_exp_year'); - saveParameters['payment[cc_cid]']= this.paymentInputs.get('cc_cid'); - saveParameters['payment[assign_session]']= 1; - // Manual post data to avoid posting extra data by payment class - new Ajax.Request(payment.saveUrl, { - method:'post', - parameters: saveParameters, - onComplete: function(transport){ - this.resetForm(token); - payment.nextStep(transport); - }.bind(this), - onSuccess: function(){ - checkout.setLoadWaiting(false); - }, - onFailure: checkout.ajaxFailure.bind(checkout) - }); - }, - // Prevent review to post data - resetForm: function(token) - { -// ['cc_number', 'expiration', 'expiration_yr', 'cc_cid', 'card_token_pan'].each(function(el) { - ['card_token_pan', 'cc_last4', 'cc_number', 'expiration', 'expiration_yr'].each(function(el) { - element = $(this.code + '_' + el); - if (element) { - switch(el) - { - case 'card_token_pan': - element.setValue(token); - break; - default: - element.clear(); - } - } - }.bind(this)); - // Then unselect cards - $$('input[name=payment[cc_type]]').invoke('setValue', false); - } -} +function paylineTrySkipPaymentMethod() { + if (!paylinePaymentSavedTransport) { + return; + } + + var paylinePaymentInputNames = []; + + var paylineIsUniquePaymentChoice = true; + + // Retrive all radio groups + $$('#opc-payment input[type=radio]').each(function (radio) { + if (paylinePaymentInputNames.indexOf(radio.name)==-1) + paylinePaymentInputNames.push(radio.name); + else + paylineIsUniquePaymentChoice = false; + }); + + // If only one input by group + if (paylineIsUniquePaymentChoice) { + // Check all boxes + paylinePaymentInputNames.each(function (name) { + $$('#opc-payment input[name="' + name + '"]').first().checked = true; + }); + // Go to review step + checkout.setStepResponse(paylinePaymentSavedTransport); + } +} + +var PaylineWidgetWrapper = Class.create(); +PaylineWidgetWrapper.prototype = { + initialize: function(data_token, data_template, save_url, custom_methods, init_quote_total, currency_code, payment_template) { + this.dataToken = data_token; + this.dataTemplate = data_template; + this.saveUrl = save_url; + this.paymentTemplate = payment_template; + + /*switch(this.dataTemplate) { + case 'lightbox': + this.rootTabSelector = 'pmLayout-column-pmContainer-mycustompm'; + break; + case 'tab': + this.rootTabSelector = 'pmLayout-tab-tab_mycustompm'; + break; + case 'column': + this.rootTabSelector = 'pmLayout-column-pmLogo-mycustompm'; + break; + default: + this.rootTabSelector = false; + }*/ + + this.rootTabSelector = 'pmLayout-.*-mycustompm'; + + this.initQuoteGrandTotal = init_quote_total; + this.currencyCode = currency_code; + this.finalQuoteGrandTotal = 0; + this.finalPaymentMethods = {}; + this.observer = false; + + this.customPmMethods = []; + this.allPaymentMethods = {}; + + this.widgetInitialized = false; + + this.widgetReady = false; + + this.preparePmMethods(custom_methods); + }, + + + + setFinalQuoteGrandTotal: function(grantotal) + { + this.finalQuoteGrandTotal = grantotal; + }, + + setFinalPaymentMethods: function(methods) + { + this.finalPaymentMethods = methods; + }, + + initPayline: function(noAgreement){ + + var $checkoutReview = $('checkout-review-load'); + + if(!$checkoutReview) { + console.log('Cannot found DOM anchor for payline.'); + return ''; + } + + if(typeof Payline != 'undefined' && typeof Payline.Api != 'undefined') { + + var elemProgress = $('payment-progress-opcheckout'); + if (elemProgress) { + var elemDd = elemProgress.select('dd').first(); + elemProgress.select('dt').each(function (item) { + item.addClassName('complete'); + + if(typeof elemDd != 'undefined') { + elemDd.remove(); + } + item.insert({after:'
' + + $('checkout-review-table').select('tfoot').first().innerHTML + + '
'} + ); + }); + $('checkout-review-table-wrapper').hide(); + } + + + if(!$("PaylineWidget")) { + + $checkoutReview.insert({after: '
'}); + + Payline.Api.init(this.dataToken, this.dataTemplate); + + this.widgetInitialized = true; + + this.insertBeforeHtml(); + + /* + if(noAgreement) { + // Need a MutationObserver to check widget state ... too bad + this.observer = new MutationObserver(function(mutations) { + mutations.forEach(function(mutation) { + + var re = new RegExp('pl-pmLayout-.*-mycustompm'+'(\\w+)',"ig"); + var result = re.exec(mutation.target.id); + + var callshowWidget = false; + //if(result && mutation.addedNodes.length>0) { + if(result) { + callshowWidget = true; + this.allPaymentMethods[result[1]].checked = true; + } + + if(callshowWidget) { + $H(this.allPaymentMethods).each(function(pair) { + if(!pair.value.checked) { + callshowWidget = false; + } + }); + + if(callshowWidget) { + this.showWidget(true); + } + } + }.bind(this)); + }.bind(this)); + + + // configuration of the observer: + var config = { attributes: true, subtree:true, childList: true}; + + // pass in the target node, as well as the observer options + this.observer.observe($("PaylineWidget"), config); + + + + } + /* */ + } + + if(!this.widgetReady) { + Payline.Api.hide(); + } + } else { + console.log('Payline.Api is undefined.'); + } + }, + + insertBeforeHtml: function() { + + }, + + insertAfterHtml: function() { + + }, + + showWidget: function(observer){ + if(this.widgetInitialized) { + + $reviewContainer = $('review-buttons-container'); + if($reviewContainer) { + $('review-buttons-container').hide(); + } + + $$('.magento-payline-custom-html [id*=payment_form]').each(function(elem){ + elem.style.display = ''; + }); + + if(observer) { + if(this.observer) { + // Stop observing + this.observer.disconnect(); + } + } else { + Payline.Api.show(); + } + + this.setPmMethodTabs(); + + if(!this.widgetReady) { + this.insertAfterHtml(); + } + + this.widgetReady = true; + } else { + alert('Payline is not initialized!'); + } + }, + + setPmMethodTabs: function() + { + $$('div[id*="pmLayout-"][class*="pl-card"]').each(function(divTab){ + var re = new RegExp(this.rootTabSelector+'(\\w+)',"ig"); + var result = re.exec(divTab.id); + var tabSpan = divTab.select('span.pl-card-logo').first(); + if (tabSpan && result) { + tabSpan.setAttribute('style', 'background:none; width:auto !important'); + + if(this.allPaymentMethods[result[1]]) { + tabSpan.update(this.allPaymentMethods[result[1]].title); + } else { + tabSpan.update(result[1]); + } + + var divPayment = divTab.up('div').up('div'); + if(this.finalPaymentMethods && this.finalPaymentMethods[result[1]]) { + divPayment.show(); + } else { + divPayment.hide(); + } + } + + + }.bind(this)); + }, + + preparePmMethods: function(custom_methods) { + custom_methods.each(function(payment){ + this.allPaymentMethods[payment.code] = {title:payment.title, checked:false, code:payment.code}; + this.customPmMethods.push({"paymentMethodId":("myCustomPm"+payment.code), + "html": this.paymentTemplate.evaluate({paymentHtml: payment.html, paymentCode: payment.code}) + }); + }.bind(this)); + }, + + getPmMethods: function() + { + return this.customPmMethods; + }, + + saveCustomPayment: function(method) { + if (checkout.loadWaiting!=false) return; + + var params = 'paymentmethod='+method; + if (review.agreementsForm) { + params += '&'+Form.serialize(review.agreementsForm); + } + params.save = true; + + var request = new Ajax.Request( + this.saveUrl, + { + method:'post', + parameters:params, + onComplete: review.onComplete, + onSuccess: review.onSave, + onFailure: checkout.ajaxFailure.bind(checkout) + } + ); + } + +} + + +var PaylineDirectMethod = Class.create(); +PaylineDirectMethod.prototype = { + initialize: function(code, tokenUrl,cryptedKeys,accessKeyRef,tokenReturnURL){ + // Payment code + this.code = code; + // Token list by method + this.tokenUrl=tokenUrl; + // Internal crypted key + this.cryptedKeys=cryptedKeys; + // Payline user key + this.accessKeyRef=accessKeyRef; + // Return url for post redirection + this.tokenReturnURL = tokenReturnURL; + // Regex to find back real name for data + this.regexPayment= /^payment\[(.+)\]/; + // Keep all values + this.paymentInputs= $H({}); + // Errors code and label + this.errors = {}; + // Initialize inputs changes to fill paymentInputs + this.onChangeInputs = this.checkInputChange.bind(this); + // Check inputs changes + this.followInputs(); + + this.onComplete = this.resetLoadWaiting.bindAsEventListener(this); + }, + // Set user error by code + setErrors: function(errors){ + this.errors = errors; + }, + showError: function(errorCode){ + + if (this.errors[errorCode]) { + var errorMsg = 'Error ' + errorCode + ': "' + this.errors[errorCode] + '"'; + } else { + var errorMsg = 'Unexpected error: ' + errorCode; + } + + alert(errorMsg); + }, + // Retrieve real name from input name + getPaymentInputName: function(input) + { + matchPayment = this.regexPayment.exec(input.name); + if (matchPayment) { + return matchPayment[1]; + } else { + return false; + } + }, + // Init observe on payments inputs + followInputs: function (container) { + + $("payment_form_"+this.code).select('input', 'select').each(function(input){ + inputName= this.getPaymentInputName(input); + if (inputName) { + input.observe('change', this.onChangeInputs ); + } + }.bind(this)); + }, + // Keep the paymentInputs up to date + checkInputChange: function (evt) { + var input = Event.element(evt); + + inputName= this.getPaymentInputName(input); + if (inputName) { + this.paymentInputs.set(inputName, input.value); + } + }, + // Prepare data to send to payline + save: function(){ + var isPayline = false; + $$('input[name=payment[method]]').each(function(elem){ + if(elem.checked && elem.getAttribute('value')==this.code) { + isPayline = true; + } + }.bind(this)); + + // Check if we have some work to do + if (!isPayline) { + payment.save(); + } else { + if (checkout.loadWaiting!=false) return; + var validator = new Validation(payment.form); + if (validator.validate()) { + checkout.setLoadWaiting('payment'); + var requestParameters= { + data: this.cryptedKeys[this.paymentInputs.get('cc_type')], + accessKeyRef: this.accessKeyRef, + cardNumber: this.paymentInputs.get('cc_number'), + cardExpirationDate: this.paymentInputs.get('cc_exp_month') + this.paymentInputs.get('cc_exp_year'), + cardCvx: this.paymentInputs.get('cc_cid') + }; + + if(this.canUseCors()) { + this.saveWithAjax(requestParameters); + } else { + this.saveWithPost(requestParameters); + } + } + } + }, + + resetLoadWaiting: function(){ + checkout.setLoadWaiting(false); + }, + + // Test browser capability to make cross domain calls + canUseCors: function() + { + // Cors detection is dactivated by default + return false; + + var cors = false; + if ('withCredentials' in new XMLHttpRequest()) { + // Supports cross-domain requests + cors = true; + } + else if(typeof XDomainRequest !== "undefined"){ + // Use IE-specific "CORS" code with XDR but we know IE capabilities :-( + if(Prototype.Browser.IE) { + var ua = navigator.userAgent; + var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); + if (re.exec(ua) != null) { + rv = parseFloat( RegExp.$1 ); + // Problem detected on IE8 + if(rv > 8.0 ) { + cors = true; + } + } + } + } + return cors; + }, + // Call payline to get the token and then go to review + saveWithAjax: function (requestParameters) + { + var paramArray = new Array(); + $H(requestParameters).each(function(pair){ + paramArray.push(pair.key + '=' + pair.value); + }); + + var request = new Ajax.Request(this.tokenUrl, { + method: 'post', + // Using postBody avoid to use encodeURIComponent with parameters + postBody: paramArray.join('&'), + contentType: 'application/x-www-form-urlencoded', + onCreate: function(response) { // here comes the fix + // request.transport.setRequestHeader = Prototype.emptyFunction; + if (response.request.isSameOrigin()) { + return; + } + + var t = response.transport; + t.setRequestHeader = t.setRequestHeader.wrap(function(original, k, v) { + if (/^(accept|accept-language|content-language)$/i.test(k)) + return original(k, v); + if (/^content-type$/i.test(k) && /^(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)(;.+)?$/i.test(v)) + return original(k, v); + return; + }); + }, + onComplete: this.onComplete, + onSuccess: function(transport) { + response={}; + if(transport.responseJSON) { + response = transport.responseJSON; + } else if (transport.responseText) { + result = transport.responseText.split('='); + if(result) { + response[result[0]] = result[1]; + } + } else { + response = {errorCode:1, message:'No result'}; + } + + if(typeof response.data!=='undefined') { + this.saveStep(response.data); + } else if (response.errorCode) { + this.showError(response.errorCode) + } else { + this.showError('ajax_call'); + } + }.bind(this), + onFailure: function() { + alert('Failed to call secure server'); + } + }); + }, + saveWithPost: function (requestParameters) + { + requestParameters.returnURL = this.tokenReturnURL; + + var frameId = 'output_token_response'; + var form = new Element('form', { id: 'form_post_token', action: this.tokenUrl, method: 'post',target:frameId }); + $H(requestParameters).each(function(input){ + var formInput = new Element('input', { 'type': 'hidden', 'name':input.key, 'value':input.value}); + form.insert({top:formInput}); + }); + + var iframe = new Element('iframe', { id: frameId,name:frameId, style:'display:none', width:0, height:0 }); + + // Old school event attachement to prevent IE8 bugs + if(iframe.attachEvent) { + iframe.attachEvent('onload', this.postIframeLoad.bind(this)); + } else { + iframe.onload = this.postIframeLoad.bind(this); + } + + document.body.appendChild(iframe); + + iframe.insert({after:form}); + form.submit(); + }, + + postIframeLoad: function(event) + { + var iframe = Event.element(event); + var idoc= iframe.contentDocument || iframe.contentWindow.document; + var parWindow = idoc.defaultView || idoc.parentWindow; + + // Prevent check when onload is fired when iframe added to dom + // have to wait for submit + if(parWindow.document.body.innerHTML) { + var regexToken= /^(.+)=(.+)$/; + var matchResponse = regexToken.exec(parWindow.document.body.innerHTML); + if(matchResponse && matchResponse[1]=='data') { + this.saveStep(matchResponse[2]); + } else if (matchResponse && matchResponse[1]=='errorCode' && this.errors[matchResponse[2]]) { + this.showError(matchResponse[2]); + } else { + this.showError('frame_content'); + } + iframe.remove(); + this.resetLoadWaiting(); + } + }, + + // Bypass the payment save method + saveStep: function(token) + { + var saveParameters = {}; + saveParameters['payment[method]']= this.code; + saveParameters['payment[card_token_pan]']= token; + saveParameters['payment[subscribe_wallet]']= this.paymentInputs.get('subscribe_wallet'); + saveParameters['payment[cc_type]']= this.paymentInputs.get('cc_type'); + saveParameters['payment[cc_last4]']= $(this.code + '_cc_number').value.substr(-4); + saveParameters['payment[cc_exp_month]']= this.paymentInputs.get('cc_exp_month'); + saveParameters['payment[cc_exp_year]']= this.paymentInputs.get('cc_exp_year'); + saveParameters['payment[cc_cid]']= this.paymentInputs.get('cc_cid'); + saveParameters['payment[assign_session]']= 1; + // Manual post data to avoid posting extra data by payment class + new Ajax.Request(payment.saveUrl, { + method:'post', + parameters: saveParameters, + onComplete: function(transport){ + this.resetForm(token); + payment.nextStep(transport); + }.bind(this), + onSuccess: function(){ + checkout.setLoadWaiting(false); + }, + onFailure: checkout.ajaxFailure.bind(checkout) + }); + }, + // Prevent review to post data + resetForm: function(token) + { +// ['cc_number', 'expiration', 'expiration_yr', 'cc_cid', 'card_token_pan'].each(function(el) { + ['card_token_pan', 'cc_last4', 'cc_number', 'expiration', 'expiration_yr'].each(function(el) { + element = $(this.code + '_' + el); + if (element) { + switch(el) + { + case 'card_token_pan': + element.setValue(token); + break; + default: + element.clear(); + } + } + }.bind(this)); + // Then unselect cards + $$('input[name=payment[cc_type]]').invoke('setValue', false); + } +} From 959e1365c1be3dfac28fd7f914d927c3a1ba1818 Mon Sep 17 00:00:00 2001 From: Vincent Pietri Date: Fri, 18 May 2018 17:40:37 +0200 Subject: [PATCH 04/20] Shortcut: Functional draft tested with AMAZONPAY --- .../Block/Checkout/Widget/Shortcut/Button.php | 10 + .../Checkout/Widget/Shortcut/Onepage.php | 6 + .../Checkout/Widget/Shortcut/Shipping.php | 21 ++ .../Payline/Block/Wallet/Checkoutbtn.php | 3 +- .../Monext/Payline/Helper/Payment.php | 7 +- .../Monext/Payline/Helper/Widget.php | 33 +- .../Payline/Model/Datasource/Contracts.php | 21 ++ .../Model/Datasource/Shipping/AllMethods.php | 34 ++ .../DefaultMethods.php} | 2 +- .../Payline/controllers/IndexController.php | 17 +- .../controllers/ShortcutController.php | 147 ++++++++ .../community/Monext/Payline/etc/system.xml | 59 +++- .../frontend/base/default/layout/payline.xml | 54 +++ .../payline/checkout/shortcut/button.phtml | 8 + .../payline/checkout/shortcut/onepage.phtml | 328 ++++++++++++++++++ .../payline/checkout/shortcut/shipping.phtml | 51 +++ 16 files changed, 780 insertions(+), 21 deletions(-) create mode 100644 app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Button.php create mode 100644 app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Onepage.php create mode 100644 app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Shipping.php create mode 100644 app/code/community/Monext/Payline/Model/Datasource/Contracts.php create mode 100644 app/code/community/Monext/Payline/Model/Datasource/Shipping/AllMethods.php rename app/code/community/Monext/Payline/Model/Datasource/{Shippingmethods.php => Shipping/DefaultMethods.php} (92%) create mode 100644 app/code/community/Monext/Payline/controllers/ShortcutController.php create mode 100644 app/design/frontend/base/default/template/payline/checkout/shortcut/button.phtml create mode 100644 app/design/frontend/base/default/template/payline/checkout/shortcut/onepage.phtml create mode 100755 app/design/frontend/base/default/template/payline/checkout/shortcut/shipping.phtml diff --git a/app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Button.php b/app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Button.php new file mode 100644 index 0000000..3a1e89f --- /dev/null +++ b/app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Button.php @@ -0,0 +1,10 @@ +getExcludeShippingMethodForWidgetShortcut(); + $shippingRateGroups = parent::getShippingRates(); + foreach ($shippingRateGroups as $code => $_rates) { + foreach ($_rates as $_rateKey=>$_rate) { + if(in_array($_rate->getCode(), $excludeMethods)) { + unset($shippingRateGroups[$code][$_rateKey]); + } + } + } + + return $shippingRateGroups; + } + + +} diff --git a/app/code/community/Monext/Payline/Block/Wallet/Checkoutbtn.php b/app/code/community/Monext/Payline/Block/Wallet/Checkoutbtn.php index 55d96e7..9b1b6e8 100644 --- a/app/code/community/Monext/Payline/Block/Wallet/Checkoutbtn.php +++ b/app/code/community/Monext/Payline/Block/Wallet/Checkoutbtn.php @@ -1,5 +1,6 @@ log("[updateOrder] Mise à jour commande " . $order->getIncrementId() . " (mode $paymentType) avec la transaction $transactionId"); + Mage::helper('payline/logger')->log("[updateOrder] " . $order->getIncrementId() . " (mode $paymentType) with transaction $transactionId"); // By default this process isn't OK $orderOk = false; @@ -494,12 +494,13 @@ public function updateOrder($order, $res, $transactionId, $paymentType = 'CPT') $orderTotal = round($order->getBaseGrandTotal() * 100); $orderRef = $order->getRealOrderId(); $orderCurrency = Mage::helper('payline')->getNumericCurrencyCode($order->getBaseCurrencyCode()); + if($orderTotal != $res['payment']['amount']){ - Mage::helper('payline/logger')->log("ERROR for order $orderRef - paid amount (".$res['payment']['amount'].") does not match order amount ($orderTotal)"); + Mage::helper('payline/logger')->log("[updateOrder] ERROR for order $orderRef - paid amount (".$res['payment']['amount'].") does not match order amount ($orderTotal)"); $orderOk = false; } if($orderCurrency != $res['payment']['currency']){ - Mage::helper('payline/logger')->log("ERROR for order $orderRef - payment currency (".$res['payment']['currency'].") does not match order amount ($orderCurrency)"); + Mage::helper('payline/logger')->log("[updateOrder] ERROR for order $orderRef - payment currency (".$res['payment']['currency'].") does not match order amount ($orderCurrency)"); $orderOk = false; } diff --git a/app/code/community/Monext/Payline/Helper/Widget.php b/app/code/community/Monext/Payline/Helper/Widget.php index bec63d2..10d7158 100644 --- a/app/code/community/Monext/Payline/Helper/Widget.php +++ b/app/code/community/Monext/Payline/Helper/Widget.php @@ -19,7 +19,12 @@ protected function _getReservedOrderId($quote) return $quote->getReservedOrderId(); } - public function getDataToken() + public function getDataTokenForShortcut() + { + return $this->getDataToken(true); + } + + public function getDataToken($forShortcut = false) { if (is_null($this->_token)) { $this->_token = false; @@ -32,6 +37,10 @@ public function getDataToken() $array['version'] = Monext_Payline_Helper_Data::VERSION; $array['payment']['action'] = Mage::getStoreConfig('payment/PaylineCPT/payline_payment_action'); $array['payment']['mode'] = 'CPT'; + + + + $returnUrl = Mage::getUrl('payline/index/cptReturnWidget'); $array['payment']['contractNumber'] = $this->getDefaultContractNumberForWidget(); $array['contracts'] = $this->getContractsForWidget(true); $array['secondContracts'] = $this->getContractsForWidget(false); @@ -40,8 +49,16 @@ public function getDataToken() } + + if($forShortcut) { + $array['payment']['contractNumber'] = $this->getContractNumberForWidgetShortcut(); + $array['contracts'] = array($array['payment']['contractNumber']); + $array['secondContracts'] = array(''); + } + + $paylineSDK = $this->initPayline('CPT', $array['payment']['currency']); - $paylineSDK->returnURL = Mage::getUrl('payline/index/cptReturnWidget'); + $paylineSDK->returnURL = $returnUrl; $paylineSDK->cancelURL = $paylineSDK->returnURL; $paylineSDK->notificationURL = $paylineSDK->returnURL; @@ -107,4 +124,16 @@ public function getDataTemplate() return $this->getCptConfigTemplate(); } + public function getContractNumberForWidgetShortcut() + { + return Mage::getStoreConfig('payline/PaylineSHORTCUT/use_contracts'); + } + + public function getExcludeShippingMethodForWidgetShortcut() + { + $methods = explode(',', Mage::getStoreConfig('payline/PaylineSHORTCUT/exclude_shipping_method')); + + return $methods; + } + } // end class diff --git a/app/code/community/Monext/Payline/Model/Datasource/Contracts.php b/app/code/community/Monext/Payline/Model/Datasource/Contracts.php new file mode 100644 index 0000000..68a8e48 --- /dev/null +++ b/app/code/community/Monext/Payline/Model/Datasource/Contracts.php @@ -0,0 +1,21 @@ +_options === null) { + $options = array(); + + $contracts = Mage::getModel('payline/contract')->getCollection(); + foreach ($contracts as $contract) { + $options[] = array( + 'value' => $contract->getNumber(), + 'label' => $contract->getName() . ' - ' .$contract->getNumber() + ); + } + $this->_options = $options; + } + + return $this->_options; + } +} \ No newline at end of file diff --git a/app/code/community/Monext/Payline/Model/Datasource/Shipping/AllMethods.php b/app/code/community/Monext/Payline/Model/Datasource/Shipping/AllMethods.php new file mode 100644 index 0000000..7dcdeb0 --- /dev/null +++ b/app/code/community/Monext/Payline/Model/Datasource/Shipping/AllMethods.php @@ -0,0 +1,34 @@ +getAllCarriers(); + + $options = array(); + + foreach($carriers as $_ccode => $_carrier) + { + $_methodOptions = array(); + if($_methods = $_carrier->getAllowedMethods()) + { + foreach($_methods as $_mcode => $_method) + { + $_code = $_ccode . '_' . $_mcode; + $_methodOptions[] = array('value' => $_code, 'label' => $_method); + } + + if(!$_title = Mage::getStoreConfig("carriers/$_ccode/title")) + $_title = $_ccode; + + $options[] = array('value' => $_methodOptions, 'label' => $_title); + } + } + + return $options; + } +} \ No newline at end of file diff --git a/app/code/community/Monext/Payline/Model/Datasource/Shippingmethods.php b/app/code/community/Monext/Payline/Model/Datasource/Shipping/DefaultMethods.php similarity index 92% rename from app/code/community/Monext/Payline/Model/Datasource/Shippingmethods.php rename to app/code/community/Monext/Payline/Model/Datasource/Shipping/DefaultMethods.php index 86b1bd0..e396094 100644 --- a/app/code/community/Monext/Payline/Model/Datasource/Shippingmethods.php +++ b/app/code/community/Monext/Payline/Model/Datasource/Shipping/DefaultMethods.php @@ -3,7 +3,7 @@ * Class used as a datasource to display available shipping methods * Only the 3 basic (no user configuration during checkout process) Magento methods are available */ -class Monext_Payline_Model_Datasource_Shippingmethods +class Monext_Payline_Model_Datasource_Shipping_DefaultMethods { public function toOptionArray(){ $availableMethods=array(); diff --git a/app/code/community/Monext/Payline/controllers/IndexController.php b/app/code/community/Monext/Payline/controllers/IndexController.php index 3e07595..cfb5351 100644 --- a/app/code/community/Monext/Payline/controllers/IndexController.php +++ b/app/code/community/Monext/Payline/controllers/IndexController.php @@ -735,19 +735,21 @@ public function cptReturnWidgetAction() if(!$order->getId()) { $onePage = Mage::getSingleton('checkout/type_onepage'); $quote = $onePage->getQuote(); - if($quote and $quote->getId() && $quote->getReservedOrderId()==$tokenData['order_id']) { + if($quote and $quote->getId() and $quote->getReservedOrderId()==$tokenData['order_id']) { $data=array('method'=>'PaylineCPT', 'cc_type'=>$contractNumber); $quote->getPayment()->importData($data); $onePage->saveOrder(); + $onePage->getQuote()->save(); + Mage::helper('payline/logger')->log('[cptReturnWidgetAction] order ' . $tokenData['order_id'] . ' created for quoteId:' . $quote->getId()); $parameters = array('paylinetoken'=>$paylineToken); $this->_forward('cptReturn',NULL,NULL,$parameters); return $this; } else { // Incorrect order_id - throw new Exception('Incorrect quote_id or reserved_order_id '.$paylineToken); + throw new Exception('Incorrect getReservedOrderId (' . $quote->getId() .') for tokenData order_id (' . $tokenData['order_id'] .') for quoteId:' . $quote->getId()); } } else { // Order should not be created @@ -834,13 +836,10 @@ public function cptReturnAction(){ // save wallet if created during this payment if(!empty($webPaymentDetails['privateDataList']) and !empty($webPaymentDetails['privateDataList']['privateData'])) { - foreach ($webPaymentDetails['privateDataList']['privateData'] as $privateDataList){ - if($privateDataList->key == 'newWalletId'){ - if(isset($webPaymentDetails['wallet']) && $webPaymentDetails['wallet']['walletId'] == $privateDataList->value){ // Customer may have unchecked the "Save this information for my next orders" checkbox on payment page. If so, wallet is not created ! - $this->saveWallet($privateDataList->value); - } - } - } + $privateDataList = $webPaymentDetails['privateDataList']['privateData']; + if (!empty($privateDataList['key']) and !empty($privateDataList['value']) and $privateDataList['key'] == 'newWalletId') { + $this->saveWallet($privateDataList['value']); + } } // create invoice if needed diff --git a/app/code/community/Monext/Payline/controllers/ShortcutController.php b/app/code/community/Monext/Payline/controllers/ShortcutController.php new file mode 100644 index 0000000..f51c55c --- /dev/null +++ b/app/code/community/Monext/Payline/controllers/ShortcutController.php @@ -0,0 +1,147 @@ +getContractNumberForWidgetShortcut(); + $data=array('method'=>'PaylineCPT', 'cc_type'=>$contractNumber); + $this->getOnepage()->savePayment($data); + } catch (Exception $e) { + Mage::logException($e); + $this->_redirect('checkout/cart'); + } + } + + public function saveAddressesAction() + { + + $this->getOnepage()->saveCheckoutMethod('guest'); + + + $this->_preparePostData(); + + + $this->saveBillingAction(); + + $result = Mage::helper('core')->jsonDecode($this->getResponse()->getBody()); + if(empty($result['error']) and !empty($result['goto_section']) and $result['goto_section']=='shipping-method' ) { + + } + + $result['post'] = $this->getRequest()->getPost(); + + $this->_prepareDataJSON($result); + } + + public function saveShippingMethodAction() + { + parent::saveShippingMethodAction(); + $result = Mage::helper('core')->jsonDecode($this->getResponse()->getBody()); + if(empty($result['error']) and !empty($result['goto_section']) and $result['goto_section']=='payment' ) { + + + + + +// $contractNumber = Mage::helper('payline/widget')->getContractNumberForWidgetShortcut(); +// $data=array('method'=>'PaylineCPT', 'cc_type'=>$contractNumber); +// $this->getOnepage()->savePayment($data); + + //$this->loadLayout('checkout_onepage_review'); + $result['goto_section'] = 'review'; + $result['update_section'] = array( + 'name' => 'review', + 'html' => $this->_getReviewHtml() + ); + + $result['base_grand_total'] = $this->getOnepage()->getQuote()->getBaseGrandTotal(); + } + $this->_prepareDataJSON($result); + } + + protected function _preparePostData() + { + $billing = array(); + + $commonParams = array('firstName'=>'firstname', 'lastName'=>'lastname', 'email'=>'email'); + + $baseParams = array('street1'=>'street1', 'street2'=>'street2', 'cityName'=>'city', 'zipCode'=>'postcode', 'country'=>'country_id'); + + + + + foreach ($commonParams as $paylineKey=>$mageKey) { + $billing[$mageKey] = $this->getRequest()->getParam($paylineKey); + } + + foreach ($baseParams as $paylineKey=>$mageKey) { + $billing[$mageKey] = $this->getRequest()->getParam($paylineKey); + } + + if(empty($billing['firstname'])) { + $billing['firstname'] = 'n/a'; + } + + //array('save_in_address_book'=>0, 'use_for_shipping'=>1); + + $billing['street'] = array($this->getRequest()->getParam('street1'), $this->getRequest()->getParam('street2')); + $billing['save_in_address_book'] = 0; + $billing['use_for_shipping'] = 1; + + //TODO + //telephone + //region + //region_id + //vat_id + //company + $billing['telephone'] = '0606060606'; + //$billing['street'] = array('rue dummy'); + $billing['region'] = "13"; + $billing['region_id'] = "13"; + + $this->getRequest()->setPost('billing', $billing); + + } + + /** + * Get payment method step html + * + * @return string + */ + protected function _getShippingMethodsHtml() + { + $layout = $this->getLayout(); + $update = $layout->getUpdate(); + $update->load('payline_shortcut_shippingmethod'); + $layout->generateXml(); + $layout->generateBlocks(); + $output = $layout->getOutput(); + return $output; + } + + + /** + * Get payment method step html + * + * @return string + */ + protected function _getReviewHtml() + { + + //return $this->getLayout()->getBlock('root')->toHtml(); + $layout = $this->getLayout(); + $update = $layout->getUpdate(); + $update->load('payline_shortcut_review'); + $layout->generateXml(); + $layout->generateBlocks(); +// $output = $layout->getOutput(); +// return $output; + return $layout->getBlock('root')->toHtml(); + } +} diff --git a/app/code/community/Monext/Payline/etc/system.xml b/app/code/community/Monext/Payline/etc/system.xml index ac7c6c7..c5638a4 100644 --- a/app/code/community/Monext/Payline/etc/system.xml +++ b/app/code/community/Monext/Payline/etc/system.xml @@ -329,7 +329,7 @@ - 203 + 205 1 1 1 @@ -481,9 +481,58 @@ + + + + 210 + 1 + 1 + 1 + payline_payments + 1 + payline/PaylineSHORTCUT/active + text + payline/adminhtml_system_config_fieldset_payment + Select payments in your shopping cart. Payline will process your card payments through the Payline Gateway. + + + + + select + adminhtml/system_config_source_yesno + 10 + 1 + 1 + 1 + + + + Shipping method to not use with shortcut. + payline/datasource_Shipping_AllMethods + multiselect + 20 + 1 + 1 + 1 + + + + payline/datasource_contracts + select + 30 + 1 + 1 + 1 + + + + + + + - 204 + 215 1 1 1 @@ -649,7 +698,7 @@ - 205 + 220 1 1 1 @@ -740,7 +789,7 @@ - 206 + 225 1 1 1 @@ -947,7 +996,7 @@ payment/PaylineWALLET/default_shipping_method Shipping method to use with one click checkout. Flatrate, freeshipping and Tablerates are available - payline/datasource_shippingmethods + payline/datasource_shipping_DefaultMethods select 40 1 diff --git a/app/design/frontend/base/default/layout/payline.xml b/app/design/frontend/base/default/layout/payline.xml index a969459..c0c9e07 100644 --- a/app/design/frontend/base/default/layout/payline.xml +++ b/app/design/frontend/base/default/layout/payline.xml @@ -60,11 +60,17 @@ + + + skin_jsjs/payline.js + + + @@ -207,5 +213,53 @@ + + + + + + + + + + + + skin_jsjs/payline.js + + + + + + + defaultcheckout/cart_item_renderer + groupedcheckout/cart_item_renderer_grouped + configurablecheckout/cart_item_renderer_configurable + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/design/frontend/base/default/template/payline/checkout/shortcut/button.phtml b/app/design/frontend/base/default/template/payline/checkout/shortcut/button.phtml new file mode 100644 index 0000000..97a96dc --- /dev/null +++ b/app/design/frontend/base/default/template/payline/checkout/shortcut/button.phtml @@ -0,0 +1,8 @@ +hasToDisplay()) :?> + +
getDataTokenForShortcut() ?>' + data-template='shortcut' + data-partnerreturnurl='' + >
+ diff --git a/app/design/frontend/base/default/template/payline/checkout/shortcut/onepage.phtml b/app/design/frontend/base/default/template/payline/checkout/shortcut/onepage.phtml new file mode 100644 index 0000000..c4c6f16 --- /dev/null +++ b/app/design/frontend/base/default/template/payline/checkout/shortcut/onepage.phtml @@ -0,0 +1,328 @@ + + + + + + + + + + + + + +
+ +
+ + + + + + + + diff --git a/app/design/frontend/base/default/template/payline/checkout/shortcut/shipping.phtml b/app/design/frontend/base/default/template/payline/checkout/shortcut/shipping.phtml new file mode 100755 index 0000000..b6168c6 --- /dev/null +++ b/app/design/frontend/base/default/template/payline/checkout/shortcut/shipping.phtml @@ -0,0 +1,51 @@ + +getShippingRates(); ?> + +

__('Sorry, no quotes are available for this order at this time.') ?>

+ +
+ + $_rates): ?> +
escapeHtml($this->getCarrierName($code)) ?>
+
+
    + + getCode()."':".(float)$_rate->getPrice(); ?> +
  • + getErrorMessage()): ?> +
      • escapeHtml($_rate->getErrorMessage()) ?>
    + + + getCode(); ?> + + + + + getCode()===$this->getAddressShippingMethod()) echo ' checked="checked"' ?> + class="radio"/> + + + +
  • + +
+
+ +
+ From 1c2de639d498ce59d88e8a17b81f3af641c3b97f Mon Sep 17 00:00:00 2001 From: Vincent Pietri Date: Fri, 25 May 2018 10:01:24 +0200 Subject: [PATCH 05/20] Shortcut: Code refactoring, reusable token, transaction on order --- .../Checkout/Widget/Shortcut/Onepage.php | 2 +- .../Checkout/Widget/Shortcut/Shipping.php | 21 -- .../Widget/Shortcut/Shipping/Additional.php | 7 + .../Widget/Shortcut/Shipping/Available.php | 26 ++ .../Monext/Payline/Helper/Widget.php | 124 ++++++- .../Model/Datasource/Checkout/Method.php | 14 + .../Payline/Model/Datasource/Contracts.php | 2 + .../Payline/controllers/IndexController.php | 77 ++-- .../controllers/ShortcutController.php | 208 +++++++---- .../community/Monext/Payline/etc/system.xml | 17 +- .../frontend/base/default/layout/payline.xml | 11 +- .../payline/checkout/shortcut/button.phtml | 2 +- .../payline/checkout/shortcut/onepage.phtml | 349 +++--------------- .../shortcut/shipping/additional.phtml | 6 + .../available.phtml} | 7 - modman | 3 +- skin/adminhtml/default/default/payline.css | 123 ++++++ skin/frontend/base/default/css/payline.css | 39 ++ skin/frontend/base/default/js/payline.js | 197 ++++++++++ 19 files changed, 796 insertions(+), 439 deletions(-) delete mode 100644 app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Shipping.php create mode 100755 app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Shipping/Additional.php create mode 100644 app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Shipping/Available.php create mode 100644 app/code/community/Monext/Payline/Model/Datasource/Checkout/Method.php create mode 100755 app/design/frontend/base/default/template/payline/checkout/shortcut/shipping/additional.phtml rename app/design/frontend/base/default/template/payline/checkout/shortcut/{shipping.phtml => shipping/available.phtml} (87%) create mode 100755 skin/adminhtml/default/default/payline.css diff --git a/app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Onepage.php b/app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Onepage.php index 16777f8..07a14c4 100644 --- a/app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Onepage.php +++ b/app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Onepage.php @@ -1,6 +1,6 @@ getExcludeShippingMethodForWidgetShortcut(); - $shippingRateGroups = parent::getShippingRates(); - foreach ($shippingRateGroups as $code => $_rates) { - foreach ($_rates as $_rateKey=>$_rate) { - if(in_array($_rate->getCode(), $excludeMethods)) { - unset($shippingRateGroups[$code][$_rateKey]); - } - } - } - - return $shippingRateGroups; - } - - -} diff --git a/app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Shipping/Additional.php b/app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Shipping/Additional.php new file mode 100755 index 0000000..b5bb1d0 --- /dev/null +++ b/app/code/community/Monext/Payline/Block/Checkout/Widget/Shortcut/Shipping/Additional.php @@ -0,0 +1,7 @@ +getAllowedShippingMethodForWidgetShortcut(); + $shippingRateGroups = parent::getShippingRates(); + foreach ($shippingRateGroups as $code => $_rates) { + foreach ($_rates as $_rateKey=>$_rate) { + if(!in_array($_rate->getCode(), $excludeMethods)) { + unset($shippingRateGroups[$code][$_rateKey]); + } + } + if (empty($shippingRateGroups[$code])) { + unset($shippingRateGroups[$code]); + } + + } + + + return $shippingRateGroups; + } + + +} diff --git a/app/code/community/Monext/Payline/Helper/Widget.php b/app/code/community/Monext/Payline/Helper/Widget.php index 10d7158..d1d991e 100644 --- a/app/code/community/Monext/Payline/Helper/Widget.php +++ b/app/code/community/Monext/Payline/Helper/Widget.php @@ -19,9 +19,29 @@ protected function _getReservedOrderId($quote) return $quote->getReservedOrderId(); } - public function getDataTokenForShortcut() + public function getDataTokenForShortcut($cart=true) { - return $this->getDataToken(true); + $checkoutSession = Mage::getSingleton('checkout/session'); + if($cart and $checkoutSession->getPaylineDataToken()) { + $webPaymentDetails = Mage::helper('payline')->initPayline('CPT')->getWebPaymentDetails(array('token' => $checkoutSession->getPaylineDataToken(), 'version' => Monext_Payline_Helper_Data::VERSION)); + + if(isset($webPaymentDetails) and !empty($webPaymentDetails['result'])) { + if($webPaymentDetails['result']['code']!='02306') { + $checkoutSession->unsPaylineDataToken(); + } + } else { + $checkoutSession->unsPaylineDataToken(); + } + } + + if($checkoutSession->getPaylineDataToken()) { + return $checkoutSession->getPaylineDataToken(); + } + + $token = $this->getDataToken(true); + $checkoutSession->setPaylineDataToken($token); + + return $token; } public function getDataToken($forShortcut = false) @@ -38,8 +58,6 @@ public function getDataToken($forShortcut = false) $array['payment']['action'] = Mage::getStoreConfig('payment/PaylineCPT/payline_payment_action'); $array['payment']['mode'] = 'CPT'; - - $returnUrl = Mage::getUrl('payline/index/cptReturnWidget'); $array['payment']['contractNumber'] = $this->getDefaultContractNumberForWidget(); $array['contracts'] = $this->getContractsForWidget(true); @@ -48,21 +66,18 @@ public function getDataToken($forShortcut = false) $array['secondContracts'] = array(''); } - - if($forShortcut) { + $returnUrl = Mage::getUrl('payline/index/cptWidgetShortcut'); $array['payment']['contractNumber'] = $this->getContractNumberForWidgetShortcut(); $array['contracts'] = array($array['payment']['contractNumber']); $array['secondContracts'] = array(''); } - $paylineSDK = $this->initPayline('CPT', $array['payment']['currency']); $paylineSDK->returnURL = $returnUrl; $paylineSDK->cancelURL = $paylineSDK->returnURL; $paylineSDK->notificationURL = $paylineSDK->returnURL; - // WALLET // ADD CONTRACT WALLET ARRAY TO $array $helperPayline = Mage::helper('payline'); @@ -105,10 +120,10 @@ public function getDataToken($forShortcut = false) if(isset($response) and $response['result']['code'] == '00000' and !empty($response['token'])){ $this->_token = $response['token']; Mage::getModel('payline/token') - ->setOrderId($quote->getRealOrderId()) - ->setToken($this->_token) - ->setDateCreate(time()) - ->save(); + ->setOrderId($quote->getRealOrderId()) + ->setToken($this->_token) + ->setDateCreate(time()) + ->save(); } } catch (Exception $e) { @@ -124,16 +139,97 @@ public function getDataTemplate() return $this->getCptConfigTemplate(); } + /** + * @return bool + */ + public function getUseCheckoutGuestMethodForWidgetShortcut() + { + return (Mage::getStoreConfig('payline/PaylineSHORTCUT/checkout_method') == Mage_Checkout_Model_Type_Onepage::METHOD_GUEST); + } + public function getContractNumberForWidgetShortcut() { return Mage::getStoreConfig('payline/PaylineSHORTCUT/use_contracts'); } - public function getExcludeShippingMethodForWidgetShortcut() + public function getAllowedShippingMethodForWidgetShortcut() { - $methods = explode(',', Mage::getStoreConfig('payline/PaylineSHORTCUT/exclude_shipping_method')); + $methods = explode(',', Mage::getStoreConfig('payline/PaylineSHORTCUT/shipping_method_allowed')); return $methods; } + + /** + * @param Mage_Core_Controller_Request_Http $request + * + * @return array + * @throws Exception + */ + public function prepareShortcutPostData($request) + { + if(!$request->getParam('email')) { + throw new Exception('Email from amazon cannot be empty'); + } + + if(!$request->getParam('lastName')) { + throw new Exception('LastName from amazon cannot be empty'); + } + + $shipping = $billing = array('save_in_address_book'=>0); + + $commonParams = array('firstName'=>'firstname', 'lastName'=>'lastname', 'email'=>'email'); + + $baseParams = array('cityName'=>'city', 'zipCode'=>'postcode', 'country'=>'country_id', 'telephone'=>'telephone'); + + foreach ($commonParams as $paylineKey=>$mageKey) { + $shipping[$mageKey] = $billing[$mageKey] = $request->getParam($paylineKey); + } + + foreach ($baseParams as $paylineKey=>$mageKey) { + $shipping[$mageKey] = $request->getParam($paylineKey); + $billing[$mageKey] = $request->getParam('billing'.uc_words($paylineKey)); + } + + $billing = $this->_amazonFormatFullName($billing); + $shipping = $this->_amazonFormatFullName($shipping); + + $shipping['street'] = $billing['street'] = array($request->getParam('street1'), $request->getParam('street2')); + + if($request->getParam('billingStreet1')) { + $billing['street'] = array($request->getParam('billingStreet1'), $request->getParam('billingStreet2')); + } + + //TODO + //telephone + //region + //region_id + //vat_id + //company + if(empty($shipping['telephone'])) { + $billing['telephone'] = $shipping['telephone'] = '0000000000'; + } + + $billing['region'] = $shipping['region'] = "-"; + $billing['region_id'] = $shipping['region_id'] = "1"; + + return array('billing'=>$billing, 'shipping'=>$shipping); + } + + /** + * @param array $data + */ + protected function _amazonFormatFullName($data) + { + if(empty($data['firstname'])) { + if(preg_match('/(.*?)\s(.*)/', $data['lastname'], $match)) { + $data['firstname'] = $match[1]; + $data['lastname'] = $match[2]; + } else { + $data['firstname'] = 'n/a'; + } + } + return $data; + } + } // end class diff --git a/app/code/community/Monext/Payline/Model/Datasource/Checkout/Method.php b/app/code/community/Monext/Payline/Model/Datasource/Checkout/Method.php new file mode 100644 index 0000000..6d5c4a6 --- /dev/null +++ b/app/code/community/Monext/Payline/Model/Datasource/Checkout/Method.php @@ -0,0 +1,14 @@ + Mage_Checkout_Model_Type_Onepage::METHOD_GUEST, 'label' => 'Guest'); + $options[] = array('value' => Mage_Checkout_Model_Type_Onepage::METHOD_REGISTER, 'label' => 'Register and auto log'); + + return $options; + } + + +} diff --git a/app/code/community/Monext/Payline/Model/Datasource/Contracts.php b/app/code/community/Monext/Payline/Model/Datasource/Contracts.php index 68a8e48..1ed770e 100644 --- a/app/code/community/Monext/Payline/Model/Datasource/Contracts.php +++ b/app/code/community/Monext/Payline/Model/Datasource/Contracts.php @@ -1,6 +1,8 @@ _options === null) { diff --git a/app/code/community/Monext/Payline/controllers/IndexController.php b/app/code/community/Monext/Payline/controllers/IndexController.php index cfb5351..3398fed 100644 --- a/app/code/community/Monext/Payline/controllers/IndexController.php +++ b/app/code/community/Monext/Payline/controllers/IndexController.php @@ -390,11 +390,13 @@ public function validateAcsAction() $redirectUrl = Mage::getBaseUrl() . "checkout/onepage/success/"; Mage_Core_Controller_Varien_Action::_redirectSuccess($redirectUrl); } else { - Mage::helper('payline/logger')->log('['.$fromAction.'] ' . $this->order->getIncrementId() . $msgLog); + Mage::helper('payline/logger')->log('[validateAcsAction] ' . $this->order->getIncrementId() . ' refused'); $this->_redirectUrl($this->_getPaymentRefusedRedirectUrl()); - return; + return $this; } } + + return $this; } /** @@ -543,7 +545,7 @@ public function walletAction(){ }else { Mage::helper('payline/payment')->updateStock($this->order); - $msgLog='PAYLINE ERROR during doImmediateWalletPayment: '.$author_result['result']['code']. ' ' . $author_result['result']['shortMessage'] . ' ('.$author_result['result']['longMessage'].')'; + $msgLog='PAYLINE ERROR during doImmediateWalletPayment: '.$doImmediateWalletPaymentResponse['result']['code']. ' ' . $doImmediateWalletPaymentResponse['result']['shortMessage'] . ' ('.$author_result['result']['longMessage'].')'; $this->order->setState(Mage_Sales_Model_Order::STATE_CANCELED,$failedOrderStatus,$msgLog,false); $this->order->save(); @@ -704,6 +706,10 @@ public function cptWidgetCustomAction() } } + public function cptWidgetShortcutAction() + { + $this->_forward('cptReturnWidget',NULL,NULL, array('paylineshortcut'=>1)); + } public function cptReturnWidgetAction() @@ -718,8 +724,7 @@ public function cptReturnWidgetAction() throw new Exception('No token'); } - $tokenModel = Mage::getModel('payline/token')->getCollection()->addFieldToFilter('token',$paylineToken); - $tokenData = $tokenModel->getFirstItem()->getData(); + $tokenData = Mage::getModel('payline/token')->load($paylineToken, 'token')->getData(); // Order is loaded from id associated to the token if(sizeof($tokenData) == 0){ @@ -731,31 +736,33 @@ public function cptReturnWidgetAction() throw new Exception('Cannot find valid contract number'); } - $order = Mage::getModel('sales/order')->loadByIncrementId($tokenData['order_id']); + $orderIncrementId = $tokenData['order_id']; + + $order = Mage::getModel('sales/order')->loadByIncrementId($orderIncrementId); + $onePage = Mage::getSingleton('checkout/type_onepage'); + $quote = $onePage->getQuote(); + if(!$order->getId()) { - $onePage = Mage::getSingleton('checkout/type_onepage'); - $quote = $onePage->getQuote(); - if($quote and $quote->getId() and $quote->getReservedOrderId()==$tokenData['order_id']) { + if($quote and $quote->getId() and $quote->getReservedOrderId()==$orderIncrementId) { + $data=array('method'=>'PaylineCPT', 'cc_type'=>$contractNumber); $quote->getPayment()->importData($data); - $onePage->saveOrder(); - $onePage->getQuote()->save(); - Mage::helper('payline/logger')->log('[cptReturnWidgetAction] order ' . $tokenData['order_id'] . ' created for quoteId:' . $quote->getId()); - $parameters = array('paylinetoken'=>$paylineToken); - $this->_forward('cptReturn',NULL,NULL,$parameters); - return $this; + Mage::helper('payline/logger')->log('[cptReturnWidgetAction] order ' . $orderIncrementId . ' created for quoteId:' . $quote->getId()); } else { // Incorrect order_id - throw new Exception('Incorrect getReservedOrderId (' . $quote->getId() .') for tokenData order_id (' . $tokenData['order_id'] .') for quoteId:' . $quote->getId()); + throw new Exception('Quote getReservedOrderId (' . $quote->getReservedOrderId() .') do not match tokenData (' . $orderIncrementId .') for quoteId:' . $quote->getId()); } - } else { - // Order should not be created - throw new Exception('Order already exist for '.$tokenData['order_id']); + } elseif(!$this->getRequest()->getParam('paylineshortcut')) { + // Order should not be created exept from shortcut + throw new Exception('Order already exist for '.$orderIncrementId); } + $this->_forward('cptReturn',NULL,NULL, array('paylinetoken'=>$paylineToken)); + return $this; + } catch (Exception $e) { //TODO: If payment is done it should be canceled Mage::helper('payline/logger')->log('[cptReturnWidgetAction] '.$e->getMessage()); @@ -779,8 +786,7 @@ public function cptReturnAction(){ $paylineToken = $this->getRequest()->getParam('token'); } - $tokenModel = Mage::getModel('payline/token')->getCollection()->addFieldToFilter('token',$paylineToken); - $tokenData = $tokenModel->getFirstItem()->getData(); + $tokenData = Mage::getModel('payline/token')->load($paylineToken, 'token')->getData(); $queryData = $this->getRequest()->getQuery(); // Order is loaded from id associated to the token @@ -813,11 +819,14 @@ public function cptReturnAction(){ return; } - $tokenForUpdate = Mage::getModel('payline/token')->load($tokenData['id']); + $tokenForUpdate = Mage::getModel('payline/token')->load($tokenData['id']); $webPaymentDetails = Mage::helper('payline')->initPayline('CPT')->getWebPaymentDetails(array('token' => $paylineToken, 'version' => Monext_Payline_Helper_Data::VERSION)); if(isset($webPaymentDetails)){ - if(is_array($webPaymentDetails)){ - if(Mage::helper('payline/payment')->updateOrder($this->order, $webPaymentDetails,$webPaymentDetails['transaction']['id'], 'CPT')){ // payment OK + + if( is_array($webPaymentDetails) and !empty($webPaymentDetails['transaction'])and !empty($webPaymentDetails['transaction']['id']) ){ + if(Mage::helper('payline/payment')->updateOrder($this->order, $webPaymentDetails, $webPaymentDetails['transaction']['id'], 'CPT')) + { + // payment OK $redirectUrl = Mage::getBaseUrl()."checkout/onepage/success/"; // set order status @@ -845,7 +854,8 @@ public function cptReturnAction(){ // create invoice if needed Mage::helper('payline')->automateCreateInvoiceAtShopReturn('CPT', $this->order); - }else{ // payment NOT OK + } else { + // payment NOT OK $msgLog='PAYMENT KO : '.$webPaymentDetails['result']['code']. ' ' . $webPaymentDetails['result']['shortMessage'] . ' ('.$webPaymentDetails['result']['longMessage'].')'; $tokenForUpdate->setResultCode($webPaymentDetails['result']['code']); @@ -860,42 +870,43 @@ public function cptReturnAction(){ paylineSDK::ERR_CODE // communication issue between Payline and the store ); - if(!in_array($webPaymentDetails['result']['code'], $pendingCodes)){ + if(!in_array($webPaymentDetails['result']['code'], $pendingCodes)) + { if ($webPaymentDetails['result']['code'] == '00000') { // payment is OK, but a mismatch with order was detected $paymentDataMismatchStatus = Mage::getStoreConfig('payment/payline_common/payment_mismatch_order_status'); $this->order->setState(Mage_Sales_Model_Order::STATE_CANCELED,$paymentDataMismatchStatus,$msgLog,false); - }elseif ($webPaymentDetails['result']['code'] == '02304' || $webPaymentDetails['result']['code'] == '02324' || $webPaymentDetails['result']['code'] == '02534') { + } elseif ( in_array($webPaymentDetails['result']['code'], array('02304', '02324', '02534'))) { $abandonedStatus = Mage::getStoreConfig('payment/payline_common/resignation_order_status'); $this->order->setState(Mage_Sales_Model_Order::STATE_CANCELED,$abandonedStatus,$msgLog,false); - }elseif ($webPaymentDetails['result']['code'] == '02319') { + } elseif ($webPaymentDetails['result']['code'] == '02319') { Mage::getSingleton('core/session')->addError(Mage::helper('payline')->__('Your payment is canceled')); $canceledStatus = Mage::getStoreConfig('payment/payline_common/canceled_order_status'); $this->order->setState(Mage_Sales_Model_Order::STATE_CANCELED,$canceledStatus,$msgLog,false); - }else { + } else { Mage::getSingleton('core/session')->addError(Mage::helper('payline')->__('Your payment is refused')); $failedOrderStatus = Mage::getStoreConfig('payment/payline_common/failed_order_status'); $this->order->setState(Mage_Sales_Model_Order::STATE_CANCELED,$failedOrderStatus,$msgLog,false); } $tokenForUpdate->setStatus(2); // KO $redirectUrl = $this->_getPaymentRefusedRedirectUrl(); - }else{ + } else { Mage::getSingleton('core/session')->addError(Mage::helper('payline')->__('Your payment is saved')); $waitOrderStatus = Mage::getStoreConfig('payment/payline_common/wait_order_status'); $this->order->setState(Mage_Sales_Model_Order::STATE_PROCESSING,$waitOrderStatus,$msgLog,false); $tokenForUpdate->setStatus(3); // to be determined $redirectUrl = Mage::getBaseUrl()."checkout/onepage/success/"; } - Mage::helper('payline/logger')->log('[cptReturnAction] ' .$this->order->getIncrementId().$msgLog); + Mage::helper('payline/logger')->log('[cptReturnAction] ' .$this->order->getIncrementId() . ' ' . $msgLog); } $tokenForUpdate->setDateUpdate(date('Y-m-d G:i:s')); $tokenForUpdate->save(); }elseif(is_string($webPaymentDetails)){ - Mage::helper('payline/logger')->log('[cptReturnAction] order '.$this->order->getIncrementId().' - ERROR - '.$webPaymentDetails); + Mage::helper('payline/logger')->log('[cptReturnAction] order '.$this->order->getIncrementId() . ' - ERROR - ' . $webPaymentDetails); return; } }else{ - Mage::helper('payline/logger')->log('[cptReturnAction] order '.$this->order->getIncrementId().' : unknown error during update'); + Mage::helper('payline/logger')->log('[cptReturnAction] order '.$this->order->getIncrementId() . ' : unknown error during update'); return; } $this->order->save(); diff --git a/app/code/community/Monext/Payline/controllers/ShortcutController.php b/app/code/community/Monext/Payline/controllers/ShortcutController.php index f51c55c..4171d6b 100644 --- a/app/code/community/Monext/Payline/controllers/ShortcutController.php +++ b/app/code/community/Monext/Payline/controllers/ShortcutController.php @@ -4,11 +4,31 @@ class Monext_Payline_ShortcutController extends Mage_Checkout_OnepageController { + /** + * @var Mage_Customer_Model_Session + */ + protected $_customerSession; + + /** + * @var Mage_Customer_Model_Customer + */ + protected $_customer = false; + + /** + * Payline shortcut checkout page + */ public function indexAction() { + if(!$this->_canShowReview()) { + $this->getLayout()->getUpdate()->addHandle('payline_shortcut_review_hide_handler'); + } + parent::indexAction(); try { + if ($this->_useCheckoutGuestMethod()) { + $this->getOnepage()->saveCheckoutMethod(Mage_Checkout_Model_Type_Onepage::METHOD_GUEST); + } $contractNumber = Mage::helper('payline/widget')->getContractNumberForWidgetShortcut(); $data=array('method'=>'PaylineCPT', 'cc_type'=>$contractNumber); $this->getOnepage()->savePayment($data); @@ -18,42 +38,60 @@ public function indexAction() } } + /** + * + */ public function saveAddressesAction() { + try { + $postData = Mage::helper('payline/widget')->prepareShortcutPostData($this->getRequest()); + $resultAutoAccount = array(); + if (!$this->_useCheckoutGuestMethod()) { + $resultAutoAccount = $this->_autoAccountCreateOrMatch($postData['billing']); + if($this->_customer and $this->_customer->getId()) { + Mage::getSingleton('customer/session')->setCustomer($this->_customer); + $this->getOnepage()->getQuote()->assignCustomer($this->_customer); + } else { + $this->getOnepage()->getQuote()->setCheckoutMethod(Mage_Checkout_Model_Type_Onepage::METHOD_REGISTER); + $password = $this->_customer->generatePassword(); + $postData['billing']['customer_password'] = $password; + $postData['billing']['confirm_password'] = $password; + } + } + + $this->getRequest()->setPost('billing', $postData['billing']); + $this->getRequest()->setPost('shipping', $postData['shipping']); + + $this->saveBillingAction(); + $result = Mage::helper('core')->jsonDecode($this->getResponse()->getBody()); + if(empty($result['error']) and !empty($result['goto_section']) and $result['goto_section']=='shipping' ) { + $this->saveShippingAction(); + $result = Mage::helper('core')->jsonDecode($this->getResponse()->getBody()); + if(empty($result['error']) and !empty($result['goto_section']) and $result['goto_section']=='shipping_method' ) { + + } + } - $this->getOnepage()->saveCheckoutMethod('guest'); - - - $this->_preparePostData(); - - - $this->saveBillingAction(); - - $result = Mage::helper('core')->jsonDecode($this->getResponse()->getBody()); - if(empty($result['error']) and !empty($result['goto_section']) and $result['goto_section']=='shipping-method' ) { - + } catch (Exception $e) { + Mage::logException($e); + $result['error'] = $this->__($e->getMessage()); } - $result['post'] = $this->getRequest()->getPost(); - + $result= array_merge($resultAutoAccount, $result); $this->_prepareDataJSON($result); } + + /** + * + */ public function saveShippingMethodAction() { parent::saveShippingMethodAction(); + $result = Mage::helper('core')->jsonDecode($this->getResponse()->getBody()); if(empty($result['error']) and !empty($result['goto_section']) and $result['goto_section']=='payment' ) { - - - - -// $contractNumber = Mage::helper('payline/widget')->getContractNumberForWidgetShortcut(); -// $data=array('method'=>'PaylineCPT', 'cc_type'=>$contractNumber); -// $this->getOnepage()->savePayment($data); - - //$this->loadLayout('checkout_onepage_review'); $result['goto_section'] = 'review'; $result['update_section'] = array( 'name' => 'review', @@ -65,48 +103,17 @@ public function saveShippingMethodAction() $this->_prepareDataJSON($result); } - protected function _preparePostData() + public function saveOrderAction() { - $billing = array(); - - $commonParams = array('firstName'=>'firstname', 'lastName'=>'lastname', 'email'=>'email'); - - $baseParams = array('street1'=>'street1', 'street2'=>'street2', 'cityName'=>'city', 'zipCode'=>'postcode', 'country'=>'country_id'); + $this->getOnepage()->getQuote()->collectTotals(); + parent::saveOrderAction(); - - - foreach ($commonParams as $paylineKey=>$mageKey) { - $billing[$mageKey] = $this->getRequest()->getParam($paylineKey); - } - - foreach ($baseParams as $paylineKey=>$mageKey) { - $billing[$mageKey] = $this->getRequest()->getParam($paylineKey); - } - - if(empty($billing['firstname'])) { - $billing['firstname'] = 'n/a'; + $result = Mage::helper('core')->jsonDecode($this->getResponse()->getBody()); + if(empty($result['error']) and !empty($result['success']) ) { + $result['redirect'] = Mage::getUrl('checkout/onepage/success'); } - - //array('save_in_address_book'=>0, 'use_for_shipping'=>1); - - $billing['street'] = array($this->getRequest()->getParam('street1'), $this->getRequest()->getParam('street2')); - $billing['save_in_address_book'] = 0; - $billing['use_for_shipping'] = 1; - - //TODO - //telephone - //region - //region_id - //vat_id - //company - $billing['telephone'] = '0606060606'; - //$billing['street'] = array('rue dummy'); - $billing['region'] = "13"; - $billing['region_id'] = "13"; - - $this->getRequest()->setPost('billing', $billing); - + $this->_prepareDataJSON($result); } /** @@ -133,15 +140,90 @@ protected function _getShippingMethodsHtml() */ protected function _getReviewHtml() { + if(!$this->_canShowReview()) { + return ''; + } - //return $this->getLayout()->getBlock('root')->toHtml(); $layout = $this->getLayout(); $update = $layout->getUpdate(); $update->load('payline_shortcut_review'); $layout->generateXml(); $layout->generateBlocks(); -// $output = $layout->getOutput(); -// return $output; return $layout->getBlock('root')->toHtml(); } + + + + protected function _autoAccountCreateOrMatch($data) + { + $result = array(); + $session = $this->_getCustomerSession(); + $this->_customer = $customer = Mage::getModel('customer/customer'); + $this->_customer = $customer->setWebsiteId(Mage::app()->getWebsite()->getId()); + + if($session->getPaylineCustomerId()) { + + $this->_customer->load($session->getPaylineCustomerId()); + if(!$this->_customer->getId()) { + $session->unsPaylineCustomerId(); + } else { + $result['already_identified'] = true; + return $result; + } + } + + try { + $email = $data['email']; + + if($session->isLoggedIn()) { + $result['is_logged'] = true; + if($session->getCustomer()->getEmail()!==$email) { + //TODO: + $result['email_mismatch'] = true; + } + return false; + } + + $this->_customer->loadByEmail($data['email']); + if($this->_customer->getId()) { + $session->setPaylineCustomerId($this->_customer->getId()); + } + + } catch (Exception $e) { + Mage::logException($e); + $result['error'] = $this->__($e->getMessage()); + } + + return $result; + } + + /** + * Retrieve customer session model object + * + * @return Mage_Customer_Model_Session + */ + protected function _getCustomerSession() + { + return Mage::getSingleton('customer/session'); + } + + /** + * @return bool + */ + protected function _useCheckoutGuestMethod() + { + return Mage::helper('payline/widget')->getUseCheckoutGuestMethodForWidgetShortcut(); + } + + protected function _canShowReview() + { + $address = $this->getOnepage()->getQuote()->getShippingAddress(); + if(!$address->getId() or !$address->getShippingMethod()) { + return false; + } + + return true; + } + + } diff --git a/app/code/community/Monext/Payline/etc/system.xml b/app/code/community/Monext/Payline/etc/system.xml index c5638a4..bbf86bc 100644 --- a/app/code/community/Monext/Payline/etc/system.xml +++ b/app/code/community/Monext/Payline/etc/system.xml @@ -505,16 +505,16 @@ 1 1 - - - Shipping method to not use with shortcut. + + + Shipping method to use with shortcut. payline/datasource_Shipping_AllMethods multiselect 20 1 1 1 - + payline/datasource_contracts @@ -524,6 +524,15 @@ 1 1 + + + payline/datasource_checkout_method + select + 40 + 1 + 1 + 1 + diff --git a/app/design/frontend/base/default/layout/payline.xml b/app/design/frontend/base/default/layout/payline.xml index c0c9e07..3f76111 100644 --- a/app/design/frontend/base/default/layout/payline.xml +++ b/app/design/frontend/base/default/layout/payline.xml @@ -67,10 +67,10 @@ + - @@ -213,6 +213,10 @@ + + + + @@ -229,7 +233,6 @@ - defaultcheckout/cart_item_renderer groupedcheckout/cart_item_renderer_grouped @@ -254,7 +257,9 @@ - + + + diff --git a/app/design/frontend/base/default/template/payline/checkout/shortcut/button.phtml b/app/design/frontend/base/default/template/payline/checkout/shortcut/button.phtml index 97a96dc..80f332a 100644 --- a/app/design/frontend/base/default/template/payline/checkout/shortcut/button.phtml +++ b/app/design/frontend/base/default/template/payline/checkout/shortcut/button.phtml @@ -1,7 +1,7 @@ hasToDisplay()) :?>
getDataTokenForShortcut() ?>' + data-token='getDataTokenForShortcut(true) ?>' data-template='shortcut' data-partnerreturnurl='' >
diff --git a/app/design/frontend/base/default/template/payline/checkout/shortcut/onepage.phtml b/app/design/frontend/base/default/template/payline/checkout/shortcut/onepage.phtml index c4c6f16..d87c47f 100644 --- a/app/design/frontend/base/default/template/payline/checkout/shortcut/onepage.phtml +++ b/app/design/frontend/base/default/template/payline/checkout/shortcut/onepage.phtml @@ -1,328 +1,95 @@ - - - - - - - -
- +
+

__('Pay with shortcut'); ?>

+
+ +
- -