We will work on Apr 26th (Saturday) and will be off from Apr 30th (Wednesday) until May 2nd (Friday) for public holiday in our country

Commit fccbf532 authored by attilak's avatar attilak

- Add admin message to add the API key instead of the username and

password
- Remove username, password (test, live) from admin/store configuration/
required settings. Add API Key instead
- Get secure fields SDK based on isDemo
- Include checkout js components
- Remove CSE library and tokens
parent c7bd96bd
<?php
/**
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Payment Module
*
* Copyright (c) 2018 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*
* Author: Adyen <magento@adyen.com>
*/
namespace Adyen\Payment\AdminMessage;
class APIKeyMessage implements \Magento\Framework\Notification\MessageInterface
{
/**
* @var \Adyen\Payment\Helper\Data
*/
protected $_adyenHelper;
/**
* @var \Magento\AdminNotification\Model\InboxFactory
*/
protected $_inboxFactory;
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $scopeConfigInterface;
/**
* @var \Magento\Store\Model\StoreManagerInterface
*/
protected $storeManagerInterface;
/**
* @var \Magento\Backend\Model\Auth\Session
*/
protected $authSession;
/**
* Message identity
*/
const MESSAGE_IDENTITY = 'Adyen API Key Control message';
/**
* APIKeyMessage constructor.
*
* @param \Adyen\Payment\Helper\Data $adyenHelper
* @param \Magento\AdminNotification\Model\InboxFactory $inboxFactory
* @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigInterface
*/
public function __construct(
\Adyen\Payment\Helper\Data $adyenHelper,
\Magento\AdminNotification\Model\InboxFactory $inboxFactory,
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigInterface,
\Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
\Magento\Backend\Model\Auth\Session $authSession
) {
$this->_adyenHelper = $adyenHelper;
$this->_inboxFactory = $inboxFactory;
$this->scopeConfigInterface = $scopeConfigInterface;
$this->storeManagerInterface = $storeManagerInterface;
$this->authSession = $authSession;
}
/**
* Retrieve unique system message identity
*
* @return string
*/
public function getIdentity()
{
return self::MESSAGE_IDENTITY;
}
/**
* Check whether the system message should be shown
*
* @return bool
*/
public function isDisplayed()
{
// Only execute the query the first time you access the Admin page
if ($this->authSession->isFirstPageAfterLogin() && $this->_adyenHelper->getWsUsername()) {
try {
$title = "Adyen extension requires the API KEY!";
$messageData[] = array(
'severity' => $this->getSeverity(),
'date_added' => date("Y-m-d"),
'title' => $title,
'description' => "Please provide API-KEY for the webserver user " . $this->_adyenHelper->getWsUsername() . " for default/store " . $this->storeManagerInterface->getStore()->getName(),
'url' => "https://docs.adyen.com/developers/plug-ins-and-partners/magento-2/set-up-the-plugin-in-magento#step3configuretheplugininmagento",
);
/*
* The parse function checks if the $versionData message exists in the inbox,
* otherwise it will create it and add it to the inbox.
*/
$this->_inboxFactory->create()->parse(array_reverse($messageData));
/*
* Only show the message if the API Key is not set
*/
if (empty($this->_adyenHelper->getAPIKey())) {
return true;
}
} catch (\Exception $e) {
return false;
}
}
return false;
}
/**
* Retrieve system message text
*
* @return \Magento\Framework\Phrase
*/
public function getText()
{
$message = __("Please provide API-KEY for the webserver user " . $this->_adyenHelper->getWsUsername() . " for default/store" . $this->storeManagerInterface->getStore()->getName());
return __($message);
}
/**
* Retrieve system message severity
*
* @return int
*/
public function getSeverity()
{
return self::SEVERITY_CRITICAL;
}
}
...@@ -33,6 +33,8 @@ class Data extends AbstractHelper ...@@ -33,6 +33,8 @@ class Data extends AbstractHelper
const MODULE_NAME = 'adyen-magento2'; const MODULE_NAME = 'adyen-magento2';
const TEST = 'test'; const TEST = 'test';
const LIVE = 'live'; const LIVE = 'live';
const SECURE_FIELDS_SDK_TEST = "https://checkoutshopper-test.adyen.com/checkoutshopper/assets/js/sdk/checkoutSecuredFields.1.3.0.min.js";
const SECURE_FIELDS_SDK_LIVE = "https://checkoutshopper-live.adyen.com/checkoutshopper/assets/js/sdk/checkoutSecuredFields.1.3.0.min.js";
/** /**
* @var \Magento\Framework\Encryption\EncryptorInterface * @var \Magento\Framework\Encryption\EncryptorInterface
...@@ -94,20 +96,35 @@ class Data extends AbstractHelper ...@@ -94,20 +96,35 @@ class Data extends AbstractHelper
*/ */
protected $adyenLogger; protected $adyenLogger;
/** /**
* Data constructor. * @var \Magento\Framework\UrlInterface
* */
* @param \Magento\Framework\App\Helper\Context $context protected $urlInterface;
* @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
* @param \Magento\Framework\Config\DataInterface $dataStorage /**
* @param \Magento\Directory\Model\Config\Source\Country $country * @var \Adyen\Service\ServiceFactory
* @param \Magento\Framework\Module\ModuleListInterface $moduleList */
* @param \Adyen\Payment\Model\ResourceModel\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory protected $adyenServiceFactory;
* @param \Magento\Framework\View\Asset\Repository $assetRepo
* @param \Magento\Framework\View\Asset\Source $assetSource /**
* Data constructor.
*
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
* @param \Magento\Framework\Config\DataInterface $dataStorage
* @param \Magento\Directory\Model\Config\Source\Country $country
* @param \Magento\Framework\Module\ModuleListInterface $moduleList
* @param \Adyen\Payment\Model\ResourceModel\Billing\Agreement\CollectionFactory $billingAgreementCollectionFactory
* @param \Magento\Framework\View\Asset\Repository $assetRepo
* @param \Magento\Framework\View\Asset\Source $assetSource
* @param \Adyen\Payment\Model\ResourceModel\Notification\CollectionFactory $notificationFactory
* @param \Magento\Tax\Model\Config $taxConfig
* @param \Magento\Tax\Model\Calculation $taxCalculation
* @param \Magento\Framework\App\ProductMetadataInterface $productMetadata * @param \Magento\Framework\App\ProductMetadataInterface $productMetadata
* @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger * @param \Adyen\Payment\Logger\AdyenLogger $adyenLogger
*/ * @param \Magento\Framework\UrlInterface $urlInterface
* @param \Adyen\Service\ServiceFactory $adyenServiceFactory
*/
public function __construct( public function __construct(
\Magento\Framework\App\Helper\Context $context, \Magento\Framework\App\Helper\Context $context,
\Magento\Framework\Encryption\EncryptorInterface $encryptor, \Magento\Framework\Encryption\EncryptorInterface $encryptor,
...@@ -121,7 +138,9 @@ class Data extends AbstractHelper ...@@ -121,7 +138,9 @@ class Data extends AbstractHelper
\Magento\Tax\Model\Config $taxConfig, \Magento\Tax\Model\Config $taxConfig,
\Magento\Tax\Model\Calculation $taxCalculation, \Magento\Tax\Model\Calculation $taxCalculation,
\Magento\Framework\App\ProductMetadataInterface $productMetadata, \Magento\Framework\App\ProductMetadataInterface $productMetadata,
\Adyen\Payment\Logger\AdyenLogger $adyenLogger \Adyen\Payment\Logger\AdyenLogger $adyenLogger,
\Magento\Framework\UrlInterface $urlInterface,
\Adyen\Service\ServiceFactory $adyenServiceFactory
) { ) {
parent::__construct($context); parent::__construct($context);
...@@ -137,6 +156,8 @@ class Data extends AbstractHelper ...@@ -137,6 +156,8 @@ class Data extends AbstractHelper
$this->_taxCalculation = $taxCalculation; $this->_taxCalculation = $taxCalculation;
$this->productMetadata = $productMetadata; $this->productMetadata = $productMetadata;
$this->adyenLogger = $adyenLogger; $this->adyenLogger = $adyenLogger;
$this->urlInterface = $urlInterface;
$this->adyenServiceFactory = $adyenServiceFactory;
} }
/** /**
...@@ -576,35 +597,35 @@ class Data extends AbstractHelper ...@@ -576,35 +597,35 @@ class Data extends AbstractHelper
return $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('notification_password'))); return $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('notification_password')));
} }
/** /**
* @desc Retrieve the webserver username * @desc Retrieve the API key
* @return string * @return string
*/ */
public function getWsUsername($storeId = null) public function getAPIKey($storeId = null)
{ {
if ($this->isDemoMode($storeId)) { if ($this->isDemoMode($storeId)) {
$wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_test', $storeId)); $apiKey = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('api_key_test',
} else { $storeId)));
$wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_live', $storeId)); } else {
} $apiKey = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('api_key_live',
return $wsUsername; $storeId)));
} }
return $apiKey;
}
/** /**
* @desc Retrieve the webserver password * @desc Retrieve the webserver username
* @return string * @return string
*/ */
public function getWsPassword($storeId = null) public function getWsUsername($storeId = null)
{ {
if ($this->isDemoMode($storeId)) { if ($this->isDemoMode($storeId)) {
$wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_test', $wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_test', $storeId));
$storeId))); } else {
} else { $wsUsername = trim($this->getAdyenAbstractConfigData('ws_username_live', $storeId));
$wsPassword = $this->_encryptor->decrypt(trim($this->getAdyenAbstractConfigData('ws_password_live', }
$storeId))); return $wsUsername;
} }
return $wsPassword;
}
/** /**
* @desc Cancels the order * @desc Cancels the order
...@@ -989,35 +1010,19 @@ class Data extends AbstractHelper ...@@ -989,35 +1010,19 @@ class Data extends AbstractHelper
return $notifications->getSize();; return $notifications->getSize();;
} }
/** /**
* @param $storeId * Retrieves secure field sdk url based on the demo mode
* @return mixed *
*/ * @return string
public function getLibraryToken($storeId = null) */
{ public function getSecureFieldsSdk()
if ($this->isDemoMode($storeId)) { {
$libraryToken = $this->getAdyenCcConfigData('cse_library_token_test', $storeId); if ($this->isDemoMode()) {
} else { return self::SECURE_FIELDS_SDK_TEST;
$libraryToken = $this->getAdyenCcConfigData('cse_library_token_live', $storeId); } else {
} return self::SECURE_FIELDS_SDK_LIVE;
return $libraryToken; }
} }
/**
* Returns the hosted location of the client side encryption file
*
* @param null $storeId
* @return string
*/
public function getLibrarySource($storeId = null)
{
$environment = self::LIVE;
if ($this->isDemoMode($storeId)) {
$environment = self::TEST;
}
return "https://" . $environment . ".adyen.com/hpp/cse/js/" . $this->getLibraryToken($storeId) . ".shtml";
}
/** /**
* @param $formFields * @param $formFields
...@@ -1174,13 +1179,11 @@ class Data extends AbstractHelper ...@@ -1174,13 +1179,11 @@ class Data extends AbstractHelper
public function initializeAdyenClient($storeId = null) public function initializeAdyenClient($storeId = null)
{ {
// initialize client // initialize client
$webserviceUsername = $this->getWsUsername($storeId); $apiKey = $this->getAPIKey($storeId);
$webservicePassword = $this->getWsPassword($storeId);
$client = new \Adyen\Client(); $client = new \Adyen\Client();
$client->setApplicationName("Magento 2 plugin"); $client->setApplicationName("Magento 2 plugin");
$client->setUsername($webserviceUsername); $client->setXApiKey($apiKey);
$client->setPassword($webservicePassword);
$client->setAdyenPaymentSource($this->getModuleName(), $this->getModuleVersion()); $client->setAdyenPaymentSource($this->getModuleName(), $this->getModuleVersion());
...@@ -1196,4 +1199,44 @@ class Data extends AbstractHelper ...@@ -1196,4 +1199,44 @@ class Data extends AbstractHelper
return $client; return $client;
} }
/**
* Retrieve origin keys for platform's base url
*
* @return string
* @throws \Adyen\AdyenException
*/
public function getOriginKeyForBaseUrl()
{
$originKey = "";
$baseUrl = $this->urlInterface->getBaseUrl();
if ($originKeys = $this->getOriginKeys($baseUrl)) {
$originKey = $originKeys[$baseUrl];
}
return $originKey;
}
/**
* Get origin keys for a specific url using the adyen api library client
*
* @param $url
* @return mixed
* @throws \Adyen\AdyenException
*/
private function getOriginKeys($url)
{
$params = array(
"originDomains" => array(
$url
)
);
$client = $this->initializeAdyenClient();
$service = $this->adyenServiceFactory->createCheckoutUtility($client);
$respone = $service->originKeys($params);
return $respone['originKeys'];
}
} }
...@@ -130,11 +130,13 @@ class AdyenCcConfigProvider implements ConfigProviderInterface ...@@ -130,11 +130,13 @@ class AdyenCcConfigProvider implements ConfigProviderInterface
$canCreateBillingAgreement = true; $canCreateBillingAgreement = true;
} }
$config['payment'] ['adyenCc']['librarySource'] = $this->_adyenHelper->getLibrarySource();
$config['payment']['adyenCc']['generationTime'] = date("c"); $config['payment']['adyenCc']['generationTime'] = date("c");
$config['payment']['adyenCc']['canCreateBillingAgreement'] = $canCreateBillingAgreement; $config['payment']['adyenCc']['canCreateBillingAgreement'] = $canCreateBillingAgreement;
$config['payment']['adyenCc']['icons'] = $this->getIcons(); $config['payment']['adyenCc']['icons'] = $this->getIcons();
$config['payment']['adyenCc']['originKey'] = $this->_adyenHelper->getOriginKeyForBaseUrl();
$config['payment']['adyenCc']['secureFieldsSource'] = $this->_adyenHelper->getSecureFieldsSdk();
// has installments by default false // has installments by default false
$config['payment']['adyenCc']['hasInstallments'] = false; $config['payment']['adyenCc']['hasInstallments'] = false;
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
<argument name="messages" xsi:type="array"> <argument name="messages" xsi:type="array">
<item name="AdyenCronMessage" xsi:type="string">Adyen\Payment\AdminMessage\CronMessage</item> <item name="AdyenCronMessage" xsi:type="string">Adyen\Payment\AdminMessage\CronMessage</item>
<item name="AdyenVersionMessage" xsi:type="string">Adyen\Payment\AdminMessage\VersionMessage</item> <item name="AdyenVersionMessage" xsi:type="string">Adyen\Payment\AdminMessage\VersionMessage</item>
<item name="AdyenAPIKeyMessage" xsi:type="string">Adyen\Payment\AdminMessage\APIKeyMessage</item>
</argument> </argument>
</arguments> </arguments>
</type> </type>
......
...@@ -47,16 +47,6 @@ ...@@ -47,16 +47,6 @@
<source_model>Adyen\Payment\Model\Config\Source\CcType</source_model> <source_model>Adyen\Payment\Model\Config\Source\CcType</source_model>
<config_path>payment/adyen_cc/cctypes</config_path> <config_path>payment/adyen_cc/cctypes</config_path>
</field> </field>
<field id="cse_library_token_test" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Library token of Test Adyen Web Service User</label>
<tooltip>Copy this from the Test Adyen Customer Area => Settings => Users => System => [web service user]=> Library token.</tooltip>
<config_path>payment/adyen_cc/cse_library_token_test</config_path>
</field>
<field id="cse_library_token_live" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Library token of Live Adyen Web Service User</label>
<tooltip>Copy this from the Live Adyen Customer Area => Settings => Users => System => [web service user]=> Library token.</tooltip>
<config_path>payment/adyen_cc/cse_library_token_live</config_path>
</field>
<group id="adyen_cc_advanced_settings" translate="label" showInDefault="1" showInWebsite="1" sortOrder="150"> <group id="adyen_cc_advanced_settings" translate="label" showInDefault="1" showInWebsite="1" sortOrder="150">
<label>Advanced Settings</label> <label>Advanced Settings</label>
......
...@@ -49,27 +49,17 @@ ...@@ -49,27 +49,17 @@
<config_path>payment/adyen_abstract/notification_password</config_path> <config_path>payment/adyen_abstract/notification_password</config_path>
<tooltip>Set a password of your choice and copy it over to Adyen Customer Area => Settings => Server Communication => Standard Notification => Password.</tooltip> <tooltip>Set a password of your choice and copy it over to Adyen Customer Area => Settings => Server Communication => Standard Notification => Password.</tooltip>
</field> </field>
<field id="ws_username_test" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="0"> <field id="api_key_test" translate="label" type="obscure" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Webservice username for Test</label> <label>API key for Test</label>
<tooltip>Find this in your Test Adyen Customer Area => Settings => Users => System. Normally this will be ws@Company.YourCompanyAccount. Copy and Paste the exact ws user name here.</tooltip> <tooltip>If you don't know your Api-Key, log in to your Test Customer Area. Navigate to Settings > Users > System, and click on your webservice user, normally this will be ws@Company.YourCompanyAccount. Under Checkout token is your API Key.</tooltip>
<config_path>payment/adyen_abstract/ws_username_test</config_path>
</field>
<field id="ws_password_test" translate="label" type="obscure" sortOrder="60" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Webservice Password for Test</label>
<tooltip>Find this in your Test Adyen Customer Area => Settings => Users => System. Click on your web service user and generate a new password. Copy and Paste the exact password here.</tooltip>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model> <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
<config_path>payment/adyen_abstract/ws_password_test</config_path> <config_path>payment/adyen_abstract/api_key_test</config_path>
</field>
<field id="ws_username_live" translate="label" type="text" sortOrder="70" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Webservice username for Live</label>
<tooltip>This is only applicable if you have a Live account. Find this in your Live Adyen Customer Area => Settings => Users => System. Normally this will be ws@Company.YourCompanyAccount. Copy and Paste the exact ws user name here.</tooltip>
<config_path>payment/adyen_abstract/ws_username_live</config_path>
</field> </field>
<field id="ws_password_live" translate="label" type="obscure" sortOrder="80" showInDefault="1" showInWebsite="1" showInStore="0"> <field id="api_key_live" translate="label" type="obscure" sortOrder="60" showInDefault="1" showInWebsite="1" showInStore="0">
<label>Webservice Password for Live</label> <label>API key for Live</label>
<tooltip>This is only applicable if you have a Live account. Find this in your Live Adyen Customer Area => Settings => Users => System. Click on your web service user and generate a new password. Copy and Paste the exact password here.</tooltip> <tooltip>If you don't know your Api-Key, log in to your Live Customer Area. Navigate to Settings > Users > System, and click on your webservice user, normally this will be ws@Company.YourCompanyAccount. Under Checkout token is your API Key.</tooltip>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model> <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
<config_path>payment/adyen_abstract/ws_password_live</config_path> <config_path>payment/adyen_abstract/api_key_live</config_path>
</field> </field>
<field id="capture_mode" translate="label" type="select" sortOrder="90" showInDefault="1" showInWebsite="1" showInStore="1"> <field id="capture_mode" translate="label" type="select" sortOrder="90" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Capture Delay</label> <label>Capture Delay</label>
...@@ -107,4 +97,4 @@ ...@@ -107,4 +97,4 @@
<config_path>payment/adyen_abstract/debug</config_path> <config_path>payment/adyen_abstract/debug</config_path>
</field> </field>
</group> </group>
</include> </include>
\ No newline at end of file
...@@ -25,6 +25,8 @@ ...@@ -25,6 +25,8 @@
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd"> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd">
<head> <head>
<css src="Adyen_Payment::css/styles.css"/> <css src="Adyen_Payment::css/styles.css"/>
<script src="Adyen_Payment::js/adyen.2.0.0.js"></script>
<script src="Adyen_Payment::js/adyen.checkout.js"></script>
</head> </head>
<body> <body>
<referenceBlock name="checkout.root"> <referenceBlock name="checkout.root">
......
This source diff could not be displayed because it is too large. You can view the blob instead.
var AdyenCheckout = (function () {
'use strict';
return {
oneClickForms: [],
dobDateFormat: "yy-mm-dd",
securedFieldsData: {},
allowedCards: [],
cseEncryptedForm: null,
checkout: null,
updateCardType: function ( cardType, friendlyName ) {
$( ".cse-cardtype" ).removeClass( "cse-cardtype-style-active" );
if ( cardType === "unknown" ) {
return;
}
var activeCard = document.getElementById( 'cse-card-' + cardType );
if ( activeCard !== null ) {
activeCard.className = "cse-cardtype cse-cardtype-style-active cse-cardtype-" + cardType;
}
},
enableCardTypeDetection: function ( allowedCards, cardLogosContainer ) {
var cardTypesHTML = "";
this.allowedCards = allowedCards;
for ( var i = allowedCards.length; i-- > 0; ) {
cardTypesHTML = cardTypesHTML + this.getCardSpan( allowedCards[ i ] );
}
cardLogosContainer.innerHTML = cardTypesHTML;
},
getCardSpan: function ( type ) {
return "<span id=\"cse-card-" + type + "\" class=\"cse-cardtype cse-cardtype-style-active cse-cardtype-" + type + "\"></span>";
},
getCardBrand: function () {
if ( this.securedFieldsData.brand ) {
return this.securedFieldsData.brand;
}
var creditCardNumberElement = document.getElementById( 'creditCardNumber' );
if ( creditCardNumberElement ) {
var creditCardNumber = creditCardNumberElement.value.replace( / /g, '' );
return window.adyen.cardTypes.determine( creditCardNumber );
}
},
isAllowedCard: function () {
var brand = this.getCardBrand();
return (brand !== null && this.allowedCards.indexOf( brand ) !== -1);
},
validateForm: function () {
var paymentMethod = $( 'input[type=radio][name=paymentMethod]:checked' ).val();
if ( paymentMethod === "" ) {
window.alert( "Please select a payment method" );
return false;
}
// Check if it is a valid card and encrypt
if ( paymentMethod === "adyen_cc" ) {
if ( !this.isAllowedCard() ) {
window.alert( 'This credit card is not allowed' );
return false;
}
if ( this.cseEncryptedForm ) {
// CSE
this.fillCSEToken( this.cseEncryptedForm );
} else {
// SECURED FIELDS
$( 'input[name="encryptedCardNumber"]' ).val( this.securedFieldsData.new.cardNumber );
$( 'input[name="encryptedExpiryMonth"]' ).val( this.securedFieldsData.new.expiryMonth );
$( 'input[name="encryptedExpiryYear"]' ).val( this.securedFieldsData.new.expiryYear );
$( 'input[name="encryptedSecurityCode"]' ).val( this.securedFieldsData.new.securityCode );
}
} else if ( paymentMethod.indexOf( "adyen_oneclick_" ) === 0 ) {
var recurringReference = paymentMethod.slice( "adyen_oneclick_".length );
$( "#selectedReference" ).val( recurringReference );
if ( this.oneClickForms[ recurringReference ] ) {
// CSE
this.fillCSEToken( this.oneClickForms[ recurringReference ] );
} else {
$( 'input[name="encryptedSecurityCode"]' ).val( this.securedFieldsData[ recurringReference ].securityCode );
}
} else {
// if issuerId is present let the customer select it
var issuer = $( '#p_method_adyen_hpp_' + paymentMethod + '_issuer' );
if ( issuer ) {
if ( issuer.val() === "" ) {
window.alert( 'Please select issuer' );
return false;
}
}
}
// Remove SF injected elements
$( '#encrypted-hostedCardNumberField' ).remove();
$( '#encrypted-month' ).remove();
$( '#encrypted-year' ).remove();
$( '#encrypted-hostedSecurityCodeField' ).remove();
$( 'input[name="txvariant"]' ).remove();
return true;
},
fillCSEToken: function ( form ) {
var cseToken = form.encrypt();
if ( cseToken === false ) {
window.alert( 'This credit card is not valid' );
return false;
}
$( "#cseToken" ).val( cseToken );
},
/**
* Set Custom values for certain payment methods
*/
setCustomPaymentMethodValues: function () {
var paymentMethod = $( 'input[type=radio][name=paymentMethod]:checked' ).val();
var dob = $( '#p_method_adyen_hpp_' + paymentMethod + '_dob' );
if ( dob ) {
$( "#dob" ).val( dob.val() );
}
var ssn = $( '#p_method_adyen_hpp_' + paymentMethod + '_ssn' );
if ( ssn ) {
$( "#socialSecurityNumber" ).val( ssn.val() );
}
},
createForm: function () {
// The form element to encrypt.
var form = document.getElementById( 'adyen-encrypted-form' );
// Form and encryption options. See adyen.encrypt.simple.html for details.
var options = {};
options.cvcIgnoreBins = '6703'; // Ignore CVC for BCMC
// Create the form.
// Note that the method is on the adyen object, not the adyen.encrypt object.
this.cseEncryptedForm = window.adyen.createEncryptedForm( form, options );
this.cseEncryptedForm.addCardTypeDetection( this.updateCardType );
return this.cseEncryptedForm;
},
createOneClickForm: function ( recurringReference ) {
// The form element to encrypt.
var form = document.getElementById( 'adyen-encrypted-form' );
// Form and encryption options. See adyen.encrypt.simple.html for details.
var options = {};
options.fieldNameAttribute = "data-encrypted-name-" + recurringReference;
options.enableValidations = false;
// Create the form.
// Note that the method is on the adyen object, not the adyen.encrypt object.
var encryptedForm = window.adyen.createEncryptedForm( form, options );
this.oneClickForms[ recurringReference ] = encryptedForm;
return encryptedForm;
},
/**
* Create DatePicker for Date of Birth field
*
* @param element
*/
createDobDatePicker: function ( element ) {
$( "." + element ).datepicker( {
dateFormat: this.dobDateFormat,
changeMonth: true,
changeYear: true,
yearRange: "-120:+0"
} );
},
togglePaymentMethod: function ( paymentMethod ) {
$( ".payment_method_details" ).hide();
$( ".chckt-pm__details" ).hide();
$( "#dd_method_" + paymentMethod ).show();
$( "#adyen_hpp_" + paymentMethod + "_container" ).show();
},
createDfValue: function () {
window.dfDo( "dfValue" );
},
createSecuredFieldsForm: function ( originKey, rootNode ) {
var self = this;
var securedFieldsConfiguration = {
configObject: {
originKey: originKey,
cardGroupTypes: self.allowedCards
},
rootNode: rootNode
};
var securedFields = window.csf( securedFieldsConfiguration );
securedFields.onBrand( function ( brandObject ) {
if ( brandObject.brand ) {
self.securedFieldsData.brand = brandObject.brand;
self.updateCardType( brandObject.brand, null );
}
} );
window.addEventListener( "message", this.securedFieldsListener( this ), false );
return securedFields;
},
securedFieldsListener: function ( self ) {
return function ( message ) {
if ( !("data" in message) ) {
return;
}
try {
var data = JSON.parse( message.data );
if ( "encryptionSuccess" in data && data.encryptionSuccess === true ) {
var fieldName = data.cseKey;
var encryptedData = data[ fieldName ];
var securedFieldsData = self.securedFieldsData;
var parts = fieldName.split( "-" );
var card = "new";
if ( parts.length === 2 ) {
card = parts[ 1 ];
}
if ( !(card in securedFieldsData) ) {
securedFieldsData[ card ] = {};
}
switch ( data.fieldType ) {
case "hostedCardNumberField":
securedFieldsData[ card ].cardNumber = encryptedData;
break;
case "month":
securedFieldsData[ card ].expiryMonth = encryptedData;
break;
case "year":
securedFieldsData[ card ].expiryYear = encryptedData;
break;
case "hostedSecurityCodeField":
securedFieldsData[ card ].securityCode = encryptedData;
break;
}
}
} catch (e) {
//not json data
}
};
},
initiateCheckout: function (locale) {
var configuration = {
locale: locale // shopper's locale
};
this.checkout = new Adyen.Checkout(configuration);
},
initiateIdeal: function (idealItems) {
var idealNode = document.getElementById('adyen_hpp_ideal_container');
var ideal = this.checkout.create('ideal', {
items: idealItems, // The array of issuers coming from the /paymentMethods api call
showImage: true, // Optional, defaults to true
onChange: handleChange // Gets triggered whenever a user selects a bank// Gets triggered once the state is valid
});
function handleChange(event) {
var issuerIdField = document.getElementById('issuerId');
var issuerId = event.data.issuer;
issuerIdField.value = issuerId;
}
try {
ideal.mount(idealNode);
} catch (e) {
console.log('Something went wrong trying to mount the iDEAL component: ${e}');
}
}
};
})();
...@@ -70,12 +70,12 @@ define( ...@@ -70,12 +70,12 @@ define(
installments.setInstallments(0); installments.setInstallments(0);
// include secure fields sdk javascript
// include dynamic cse javascript var secureFieldsScriptTag = document.createElement('script');
var dfScriptTag = document.createElement('script'); secureFieldsScriptTag.id = "secure-fields-script-tag";
dfScriptTag.src = this.getLibrarySource(); secureFieldsScriptTag.src = this.getSecureFieldsSource();
dfScriptTag.type = "text/javascript"; secureFieldsScriptTag.type = "text/javascript";
document.body.appendChild(dfScriptTag); document.body.appendChild(secureFieldsScriptTag)
//Set credit card number to credit card data object //Set credit card number to credit card data object
this.creditCardNumber.subscribe(function (value) { this.creditCardNumber.subscribe(function (value) {
...@@ -134,6 +134,9 @@ define( ...@@ -134,6 +134,9 @@ define(
getCode: function () { getCode: function () {
return 'adyen_cc'; return 'adyen_cc';
}, },
getOriginKey: function () {
return window.checkoutConfig.payment.adyenCc.originKey;
},
getData: function () { getData: function () {
return { return {
'method': this.item.method, 'method': this.item.method,
...@@ -178,9 +181,9 @@ define( ...@@ -178,9 +181,9 @@ define(
var cardData = { var cardData = {
number: this.creditCardNumber(), number: this.creditCardNumber(),
cvc: this.creditCardVerificationNumber(), cvc: this.creditCardVerificationNumber(),
holderName: this.creditCardOwner(),
expiryMonth: this.creditCardExpMonth(), expiryMonth: this.creditCardExpMonth(),
expiryYear: this.creditCardExpYear(), expiryYear: this.creditCardExpYear(),
holderName: this.creditCardOwner(),
generationtime: generationtime generationtime: generationtime
}; };
...@@ -227,9 +230,8 @@ define( ...@@ -227,9 +230,8 @@ define(
getCSEKey: function () { getCSEKey: function () {
return window.checkoutConfig.payment.adyenCc.cseKey; return window.checkoutConfig.payment.adyenCc.cseKey;
}, },
getLibrarySource: function () { getSecureFieldsSource: function () {
return window.checkoutConfig.payment.adyenCc.librarySource; return window.checkoutConfig.payment.adyenCc.secureFieldsSource;
}, },
getGenerationTime: function () { getGenerationTime: function () {
return window.checkoutConfig.payment.adyenCc.generationTime; return window.checkoutConfig.payment.adyenCc.generationTime;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment