Exemplo n.º 1
0
 /**
  * @desc Authenticate using sha1 Merchant signature
  * @see success Action during checkout
  * @param Varien_Object $response
  */
 protected function _signAuthenticate(Varien_Object $response)
 {
     if ($this->_getConfigData('demoMode') === 'Y') {
         $secretWord = $this->_getConfigData('secret_wordt', 'adyen_hpp');
     } else {
         $secretWord = $this->_getConfigData('secret_wordp', 'adyen_hpp');
     }
     // do it like this because $_GET is converting dot to underscore
     $queryString = $_SERVER['QUERY_STRING'];
     $result = array();
     $pairs = explode("&", $queryString);
     foreach ($pairs as $pair) {
         $nv = explode("=", $pair);
         $name = urldecode($nv[0]);
         $value = urldecode($nv[1]);
         $result[$name] = $value;
     }
     // do not use merchantSig in calculation
     unset($result['merchantSig']);
     // Sort the array by key using SORT_STRING order
     ksort($result, SORT_STRING);
     $signData = implode(":", array_map(array($this, 'escapeString'), array_merge(array_keys($result), array_values($result))));
     $signMac = Zend_Crypt_Hmac::compute(pack("H*", $secretWord), 'sha256', $signData);
     $localStringToHash = base64_encode(pack('H*', $signMac));
     if (strcmp($localStringToHash, $response->getData('merchantSig')) === 0) {
         return true;
     }
     return false;
 }
 private static function _generateHmacKey($params = null, $apiKey = null)
 {
     $logger = self::getLoggerHandler();
     $signatureData = CitrusPay_RequestData::_generateSignatureData($params, $apiKey);
     $logger->info("Signature data is " . $signatureData);
     $hmackey = Zend_Crypt_Hmac::compute($apiKey, "sha1", $signatureData);
     $logger->info("Signature Key generated is " . $hmackey);
     return $hmackey;
 }
 /**
  * Generate the mac key name. Must be the same function as used in the InsuranceFunctions.php
  *
  * @param string $requesthash Request hash of request
  */
 private function _generateAuthKey($requesthash)
 {
     $config = Zend_Registry::get('params');
     $secret = null;
     // Capture HMAC secret key
     if (isset($config->dms) && isset($config->dms->localcache) && isset($config->dms->localcache->hmacsecret)) {
         $secret = $config->dms->localcache->hmacsecret;
     }
     if ($secret == null) {
         throw new Exception('hmac secret not set');
     }
     return strtoupper(Zend_Crypt_Hmac::compute($secret, 'sha256', $requesthash));
 }
Exemplo n.º 4
0
 /**
  * @desc Authenticate using sha1 Merchant signature
  * @see success Action during checkout
  * @param Varien_Object $response
  */
 protected function _signAuthenticate(Varien_Object $response)
 {
     if ($this->_getConfigData('demoMode') === 'Y') {
         $secretWord = $this->_getConfigData('secret_wordt', 'adyen_hpp');
     } else {
         $secretWord = $this->_getConfigData('secret_wordp', 'adyen_hpp');
     }
     $sign = $response->getData('authResult') . $response->getData('pspReference') . $response->getData('merchantReference') . $response->getData('skinCode');
     $signMac = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $sign);
     $localStringToHash = base64_encode(pack('H*', $signMac));
     if (strcmp($localStringToHash, $response->getData('merchantSig')) === 0) {
         return true;
     }
     return false;
 }
Exemplo n.º 5
0
 public function processCashResponse()
 {
     $response = $_REQUEST;
     $varienObj = new Varien_Object();
     foreach ($response as $code => $value) {
         if ($code == 'amount') {
             if (is_object($value)) {
                 $value = $value->value;
             }
             $code = 'value';
         }
         $varienObj->setData($code, $value);
     }
     $pspReference = $varienObj->getData('pspReference');
     $merchantReference = $varienObj->getData('merchantReference');
     $skinCode = $varienObj->getData('skinCode');
     $paymentAmount = $varienObj->getData('paymentAmount');
     $currencyCode = $varienObj->getData('currencyCode');
     $customPaymentMethod = $varienObj->getData('c_cash');
     $paymentMethod = $varienObj->getData('paymentMethod');
     $merchantSig = $varienObj->getData('merchantSig');
     $sign = $pspReference . $merchantReference . $skinCode . $paymentAmount . $currencyCode . $customPaymentMethod . $paymentMethod;
     $secretWord = $this->_getSecretWord();
     $signMac = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $sign);
     $calMerchantSig = base64_encode(pack('H*', $signMac));
     // check if signatures are the same
     if ($calMerchantSig == $merchantSig) {
         //get order && payment objects
         $order = Mage::getModel('sales/order');
         //error
         $orderExist = $this->_incrementIdExist($varienObj, $merchantReference);
         if (empty($orderExist)) {
             $this->_writeLog("unknown order : {$merchantReference}");
         } else {
             $order->loadByIncrementId($merchantReference);
             $comment = Mage::helper('adyen')->__('Adyen Cash Result URL Notification: <br /> pspReference: %s <br /> paymentMethod: %s', $pspReference, $paymentMethod);
             $status = true;
             $history = Mage::getModel('sales/order_status_history')->setStatus($status)->setComment($comment)->setEntityName("order")->setOrder($order);
             $history->save();
             return $status;
         }
     }
     return false;
 }
 /**
  * Signed S3 Upload Policy
  *
  * @param string $policy            Base64 Encoded string that is the upload policy
  * @return string                   SHA1 encoded S3 Upload Policy
  */
 protected function _signS3UploadPolicy($policy)
 {
     $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA1', $policy, Zend_Crypt_Hmac::BINARY);
     return $hmac;
 }
Exemplo n.º 7
0
 /**
  * Computes the RFC 2104-compliant HMAC signature for request parameters
  *
  * This implements the Amazon Web Services signature, as per the following
  * specification:
  *
  * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  *    excluding <tt>Signature</tt>, the value of which is being created),
  *    ignoring case.
  *
  * 2. Iterate over the sorted list and append the parameter name (in its
  *    original case) and then its value. Do not URL-encode the parameter
  *    values before constructing this string. Do not use any separator
  *    characters when appending strings.
  *
  * @param array  $parameters the parameters for which to get the signature.
  * @param string $secretKey  the secret key to use to sign the parameters.
  *
  * @return string the signed data.
  */
 protected function _signParameters(array $paramaters)
 {
     $data = "POST\n";
     $data .= $this->getEndpoint()->getHost() . "\n";
     $data .= "/\n";
     uksort($paramaters, 'strcmp');
     unset($paramaters['Signature']);
     $arrData = array();
     foreach ($paramaters as $key => $value) {
         $value = urlencode($value);
         $value = str_replace("%7E", "~", $value);
         $value = str_replace("+", "%20", $value);
         $arrData[] = urlencode($key) . '=' . $value;
     }
     $data .= implode('&', $arrData);
     // require_once 'Zend/Crypt/Hmac.php';
     $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA256', $data, Zend_Crypt_Hmac::BINARY);
     return base64_encode($hmac);
 }
Exemplo n.º 8
0
 /**
  * Computes the RFC 2104-compliant HMAC signature for request parameters
  *
  * This implements the Amazon Web Services signature, as per the following
  * specification:
  *
  * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  *    excluding <tt>Signature</tt>, the value of which is being created),
  *    ignoring case.
  *
  * 2. Iterate over the sorted list and append the parameter name (in its
  *    original case) and then its value. Do not URL-encode the parameter
  *    values before constructing this string. Do not use any separator
  *    characters when appending strings.
  *
  * @param  string $queue_url  Queue URL
  * @param  array  $parameters the parameters for which to get the signature.
  *
  * @return string the signed data.
  */
 protected function _signParameters($url, array &$paramaters)
 {
     $data = $this->_httpMethod . "\n";
     $data .= parse_url($url, PHP_URL_HOST) . "\n";
     $data .= '' == ($path = parse_url($url, PHP_URL_PATH)) ? '/' : $path;
     $data .= "\n";
     uksort($paramaters, 'strcmp');
     unset($paramaters['Signature']);
     $arrData = array();
     foreach ($paramaters as $key => $value) {
         $arrData[] = $key . '=' . str_replace('%7E', '~', rawurlencode($value));
     }
     $data .= implode('&', $arrData);
     $hmac = Zend_Crypt_Hmac::compute($this->_secretKey, 'SHA256', $data, Zend_Crypt_Hmac::BINARY);
     $paramaters['Signature'] = base64_encode($hmac);
     return $data;
 }
Exemplo n.º 9
0
 /**
  * Computes the RFC 2104-compliant HMAC signature for request parameters
  *
  * This implements the Amazon Web Services signature, as per the following
  * specification:
  *
  * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  *    excluding <tt>Signature</tt>, the value of which is being created),
  *    ignoring case.
  *
  * 2. Iterate over the sorted list and append the parameter name (in its
  *    original case) and then its value. Do not URL-encode the parameter
  *    values before constructing this string. Do not use any separator
  *    characters when appending strings.
  *
  * @param array  $parameters the parameters for which to get the signature.
  * @param string $secretKey  the secret key to use to sign the parameters.
  *
  * @return string the signed data.
  */
 protected function signParameters(array $paramaters)
 {
     $data = "POST\n";
     $data .= $this->_getRegion() . $this->_ec2Endpoint . "\n";
     $data .= "/\n";
     uksort($paramaters, 'strcmp');
     unset($paramaters['Signature']);
     $arrData = array();
     foreach ($paramaters as $key => $value) {
         $arrData[] = $key . '=' . str_replace("%7E", "~", rawurlencode($value));
     }
     $data .= implode('&', $arrData);
     require_once 'Zend/Crypt/Hmac.php';
     $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA256', $data, Zend_Crypt_Hmac::BINARY);
     return base64_encode($hmac);
 }
Exemplo n.º 10
0
 /**
  * Add the S3 Authorization signature to the request headers
  *
  * @param  string $method
  * @param  string $path
  * @param  array &$headers
  * @return string
  */
 protected function addSignature($method, $path, &$headers)
 {
     if (!is_array($headers)) {
         $headers = array($headers);
     }
     $type = $md5 = $date = '';
     // Search for the Content-type, Content-MD5 and Date headers
     foreach ($headers as $key => $val) {
         if (strcasecmp($key, 'content-type') == 0) {
             $type = $val;
         } else {
             if (strcasecmp($key, 'content-md5') == 0) {
                 $md5 = $val;
             } else {
                 if (strcasecmp($key, 'date') == 0) {
                     $date = $val;
                 }
             }
         }
     }
     // If we have an x-amz-date header, use that instead of the normal Date
     if (isset($headers['x-amz-date']) && isset($date)) {
         $date = '';
     }
     $sig_str = "{$method}\n{$md5}\n{$type}\n{$date}\n";
     // For x-amz- headers, combine like keys, lowercase them, sort them
     // alphabetically and remove excess spaces around values
     $amz_headers = array();
     foreach ($headers as $key => $val) {
         $key = strtolower($key);
         if (substr($key, 0, 6) == 'x-amz-') {
             if (is_array($val)) {
                 $amz_headers[$key] = $val;
             } else {
                 $amz_headers[$key][] = preg_replace('/\\s+/', ' ', $val);
             }
         }
     }
     if (!empty($amz_headers)) {
         ksort($amz_headers);
         foreach ($amz_headers as $key => $val) {
             $sig_str .= $key . ':' . implode(',', $val) . "\n";
         }
     }
     $sig_str .= '/' . parse_url($path, PHP_URL_PATH);
     if (strpos($path, '?location') !== false) {
         $sig_str .= '?location';
     } else {
         if (strpos($path, '?acl') !== false) {
             $sig_str .= '?acl';
         } else {
             if (strpos($path, '?torrent') !== false) {
                 $sig_str .= '?torrent';
             }
         }
     }
     $signature = base64_encode(Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'sha1', utf8_encode($sig_str), Zend_Crypt_Hmac::BINARY));
     $headers['Authorization'] = 'AWS ' . $this->_getAccessKey() . ':' . $signature;
     return $sig_str;
 }
Exemplo n.º 11
0
 /**
  * Compute Signature for Authentication with Amazon Product Advertising Webservices
  *
  * @param  string $baseUri
  * @param  string $secretKey
  * @param  array $options
  * @return string
  */
 public static function computeSignature($baseUri, $secretKey, array $options)
 {
     // require_once "Zend/Crypt/Hmac.php";
     $signature = self::buildRawSignature($baseUri, $options);
     return base64_encode(Zend_Crypt_Hmac::compute($secretKey, 'sha256', $signature, Zend_Crypt_Hmac::BINARY));
 }
Exemplo n.º 12
0
 /**
  * Computes the RFC 2104-compliant HMAC signature for request parameters
  *
  * This implements the Amazon Web Services signature, as per the following
  * specification:
  *
  * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  *    excluding <tt>Signature</tt>, the value of which is being created),
  *    ignoring case.
  *
  * 2. Iterate over the sorted list and append the parameter name (in its
  *    original case) and then its value. Do not URL-encode the parameter
  *    values before constructing this string. Do not use any separator
  *    characters when appending strings.
  *
  * @param array  $parameters the parameters for which to get the signature.
  * @param string $secretKey  the secret key to use to sign the parameters.
  *
  * @return string the signed data.
  */
 protected function signParameters(array $paramaters)
 {
     $data = '';
     uksort($paramaters, 'strcasecmp');
     unset($paramaters['Signature']);
     foreach ($paramaters as $key => $value) {
         $data .= $key . $value;
     }
     require_once 'Zend/Crypt/Hmac.php';
     $hmac = Zend_Crypt_Hmac::compute($this->getSecretKey(), 'SHA1', $data, Zend_Crypt_Hmac::BINARY);
     return base64_encode($hmac);
 }
Exemplo n.º 13
0
 /**
  * Computes the RFC 2104-compliant HMAC signature for request parameters
  *
  * This implements the Amazon Web Services signature, as per the following
  * specification:
  *
  * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  *    excluding <tt>Signature</tt>, the value of which is being created),
  *    ignoring case.
  *
  * 2. Iterate over the sorted list and append the parameter name (in its
  *    original case) and then its value. Do not URL-encode the parameter
  *    values before constructing this string. Do not use any separator
  *    characters when appending strings.
  *
  * @param  string $queue_url  Queue URL
  * @param  array  $parameters the parameters for which to get the signature.
  *
  * @return string the signed data.
  */
 protected function _signParameters($url, array &$paramaters)
 {
     $data = '';
     uksort($paramaters, 'strcasecmp');
     unset($paramaters['Signature']);
     foreach ($paramaters as $key => $value) {
         $data .= $key . $value;
     }
     $hmac = Zend_Crypt_Hmac::compute($this->_secretKey, 'SHA1', $data, Zend_Crypt_Hmac::BINARY);
     $paramaters['Signature'] = base64_encode($hmac);
     return $data;
 }
Exemplo n.º 14
0
 /**
  * Verify a user password
  *
  * @param User $user User entity
  * @param string $password Password to be verified
  * @return bool True if password matches
  */
 public static function verifyPassword(User $user, $password)
 {
     return Bcrypt::verify(Hmac::compute(Zend_Registry::get('staticSalt'), 'sha512', $password), '$2y$14$' . $user->getPassword());
 }
Exemplo n.º 15
0
 public function getFormFields()
 {
     $this->_initOrder();
     $order = $this->_order;
     $realOrderId = $order->getRealOrderId();
     $orderCurrencyCode = $order->getOrderCurrencyCode();
     // check if paybymail has it's own skin
     $skinCode = trim($this->_getConfigData('skin_code', 'adyen_pay_by_mail', $order->getStoreId()));
     if ($skinCode == "") {
         // use HPP skin and HMAC
         $skinCode = trim($this->_getConfigData('skinCode', 'adyen_hpp', $order->getStoreId()));
         $secretWord = $this->_getSecretWord($order->getStoreId(), 'adyen_hpp');
     } else {
         // use paybymail skin and hmac
         $secretWord = $this->_getSecretWord($order->getStoreId(), 'adyen_pay_by_mail');
     }
     $amount = Mage::helper('adyen')->formatAmount($order->getGrandTotal(), $orderCurrencyCode);
     $merchantAccount = trim($this->_getConfigData('merchantAccount', null, $order->getStoreId()));
     $shopperEmail = $order->getCustomerEmail();
     $customerId = $order->getCustomerId();
     $shopperIP = $order->getRemoteIp();
     $browserInfo = $_SERVER['HTTP_USER_AGENT'];
     $shopperLocale = trim($this->_getConfigData('shopperlocale', null, $order->getStoreId()));
     $shopperLocale = !empty($shopperLocale) ? $shopperLocale : Mage::app()->getLocale()->getLocaleCode();
     $countryCode = trim($this->_getConfigData('countryCode', null, $order->getStoreId()));
     $countryCode = !empty($countryCode) ? $countryCode : false;
     // if directory lookup is enabled use the billingadress as countrycode
     if ($countryCode == false) {
         if (is_object($order->getBillingAddress()) && $order->getBillingAddress()->getCountry() != "") {
             $countryCode = $order->getBillingAddress()->getCountry();
         }
     }
     $adyFields = array();
     $deliveryDays = (int) $this->_getConfigData('delivery_days', 'adyen_hpp', $order->getStoreId());
     $deliveryDays = !empty($deliveryDays) ? $deliveryDays : 5;
     $adyFields['merchantAccount'] = $merchantAccount;
     $adyFields['merchantReference'] = $realOrderId;
     $adyFields['paymentAmount'] = (int) $amount;
     $adyFields['currencyCode'] = $orderCurrencyCode;
     $adyFields['shipBeforeDate'] = date("Y-m-d", mktime(date("H"), date("i"), date("s"), date("m"), date("j") + $deliveryDays, date("Y")));
     $adyFields['skinCode'] = $skinCode;
     $adyFields['shopperLocale'] = $shopperLocale;
     $adyFields['countryCode'] = $countryCode;
     //order data
     $items = $order->getAllItems();
     $shipmentAmount = number_format($order->getShippingAmount() + $order->getShippingTaxAmount(), 2, ',', ' ');
     $prodDetails = Mage::helper('adyen')->__('Shipment cost: %s %s <br />', $shipmentAmount, $orderCurrencyCode);
     $prodDetails .= Mage::helper('adyen')->__('Order rows: <br />');
     foreach ($items as $item) {
         if ($item->getParentItem()) {
             continue;
         }
         $name = $item->getName();
         $qtyOrdered = $this->_numberFormat($item->getQtyOrdered(), '0');
         $rowTotal = number_format($item->getRowTotalInclTax(), 2, ',', ' ');
         $prodDetails .= Mage::helper('adyen')->__('%s ( Qty: %s ) (Price: %s %s ) <br />', $name, $qtyOrdered, $rowTotal, $orderCurrencyCode);
     }
     $adyFields['orderData'] = base64_encode(gzencode($prodDetails));
     //depreacated by Adyen
     $sessionValidity = (int) trim($this->_getConfigData('session_validity', 'adyen_pay_by_mail', $order->getStoreId()));
     if ($sessionValidity == "") {
         $sessionValidity = 3;
     }
     $adyFields['sessionValidity'] = date("c", strtotime("+" . $sessionValidity . " days"));
     $adyFields['shopperEmail'] = $shopperEmail;
     // recurring
     $recurringType = trim($this->_getConfigData('recurringtypes', 'adyen_abstract', $order->getStoreId()));
     $adyFields['recurringContract'] = $recurringType;
     $adyFields['shopperReference'] = !empty($customerId) ? $customerId : self::GUEST_ID . $realOrderId;
     //blocked methods
     $adyFields['blockedMethods'] = "";
     /*
      * This feld will be appended as-is to the return URL when the shopper completes, or abandons, the payment and
      * returns to your shop; it is typically used to transmit a session ID. This feld has a maximum of 128 characters
      * This is an optional field and not necessary by default
      */
     $adyFields['merchantReturnData'] = "";
     $openinvoiceType = $this->_getConfigData('openinvoicetypes', 'adyen_openinvoice', $order->getStoreId());
     if ($this->_code == "adyen_openinvoice" || $this->getInfoInstance()->getCcType() == "klarna" || $this->getInfoInstance()->getCcType() == "afterpay_default") {
         $adyFields['billingAddressType'] = "1";
         $adyFields['deliveryAddressType'] = "1";
         $adyFields['shopperType'] = "1";
     } else {
         $adyFields['billingAddressType'] = "";
         $adyFields['deliveryAddressType'] = "";
         $adyFields['shopperType'] = "";
     }
     //the data that needs to be signed is a concatenated string of the form data
     $sign = $adyFields['paymentAmount'] . $adyFields['currencyCode'] . $adyFields['shipBeforeDate'] . $adyFields['merchantReference'] . $adyFields['skinCode'] . $adyFields['merchantAccount'] . $adyFields['sessionValidity'] . $adyFields['shopperEmail'] . $adyFields['shopperReference'] . $adyFields['recurringContract'] . $adyFields['blockedMethods'] . $adyFields['merchantReturnData'] . $adyFields['billingAddressType'] . $adyFields['deliveryAddressType'] . $adyFields['shopperType'];
     // Sort the array by key using SORT_STRING order
     ksort($adyFields, SORT_STRING);
     // Generate the signing data string
     $signData = implode(":", array_map(array($this, 'escapeString'), array_merge(array_keys($adyFields), array_values($adyFields))));
     //Generate SHA256 HMAC encrypted merchant signature
     $signMac = Zend_Crypt_Hmac::compute(pack("H*", $secretWord), 'sha256', $signData);
     $adyFields['merchantSig'] = base64_encode(pack('H*', $signMac));
     Mage::log($adyFields, self::DEBUG_LEVEL, 'adyen_http-request.log', true);
     return $adyFields;
 }
Exemplo n.º 16
0
 /**
  * @desc prepare params array to send it to gateway page via POST
  * @return array
  */
 public function getFormFields()
 {
     $this->_initOrder();
     $order = $this->_order;
     $realOrderId = $order->getRealOrderId();
     $orderCurrencyCode = $order->getOrderCurrencyCode();
     $skinCode = trim($this->_getConfigData('skinCode', 'adyen_hpp'));
     $amount = Mage::helper('adyen')->formatAmount($order->getGrandTotal(), $orderCurrencyCode);
     $merchantAccount = trim($this->_getConfigData('merchantAccount'));
     $shopperEmail = $order->getCustomerEmail();
     $customerId = $order->getCustomerId();
     $shopperIP = $order->getRemoteIp();
     $browserInfo = $_SERVER['HTTP_USER_AGENT'];
     $shopperLocale = trim($this->_getConfigData('shopperlocale'));
     $shopperLocale = !empty($shopperLocale) ? $shopperLocale : Mage::app()->getLocale()->getLocaleCode();
     $countryCode = trim($this->_getConfigData('countryCode'));
     $countryCode = !empty($countryCode) ? $countryCode : false;
     // if directory lookup is enabled use the billingadress as countrycode
     if ($countryCode == false) {
         if (is_object($order->getBillingAddress()) && $order->getBillingAddress()->getCountry() != "") {
             $countryCode = $order->getBillingAddress()->getCountry();
         }
     }
     $adyFields = array();
     $deliveryDays = (int) $this->_getConfigData('delivery_days', 'adyen_hpp');
     $deliveryDays = !empty($deliveryDays) ? $deliveryDays : 5;
     $adyFields['merchantAccount'] = $merchantAccount;
     $adyFields['merchantReference'] = $realOrderId;
     $adyFields['paymentAmount'] = (int) $amount;
     $adyFields['currencyCode'] = $orderCurrencyCode;
     $adyFields['shipBeforeDate'] = date("Y-m-d", mktime(date("H"), date("i"), date("s"), date("m"), date("j") + $deliveryDays, date("Y")));
     $adyFields['skinCode'] = $skinCode;
     $adyFields['shopperLocale'] = $shopperLocale;
     $adyFields['countryCode'] = $countryCode;
     $adyFields['shopperIP'] = $shopperIP;
     $adyFields['browserInfo'] = $browserInfo;
     //order data
     $items = $order->getAllItems();
     $shipmentAmount = number_format($order->getShippingAmount() + $order->getShippingTaxAmount(), 2, ',', ' ');
     $prodDetails = Mage::helper('adyen')->__('Shipment cost: %s %s <br />', $shipmentAmount, $orderCurrencyCode);
     $prodDetails .= Mage::helper('adyen')->__('Order rows: <br />');
     foreach ($items as $item) {
         if ($item->getParentItem()) {
             continue;
         }
         $name = $item->getName();
         $qtyOrdered = $this->_numberFormat($item->getQtyOrdered(), '0');
         $rowTotal = number_format($item->getRowTotalInclTax(), 2, ',', ' ');
         $prodDetails .= Mage::helper('adyen')->__('%s ( Qty: %s ) (Price: %s %s ) <br />', $name, $qtyOrdered, $rowTotal, $orderCurrencyCode);
     }
     $adyFields['orderData'] = base64_encode(gzencode($prodDetails));
     //depreacated by Adyen
     $adyFields['sessionValidity'] = date(DATE_ATOM, mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y")));
     $adyFields['shopperEmail'] = $shopperEmail;
     // recurring
     $recurringType = trim($this->_getConfigData('recurringtypes', 'adyen_abstract'));
     // Paypal does not allow ONECLICK,RECURRING will be fixed on adyen platform but this is the quickfix for now
     if ($this->getInfoInstance()->getMethod() == "adyen_hpp_paypal" && $recurringType == 'ONECLICK,RECURRING') {
         $recurringType = "RECURRING";
     }
     if ($customerId) {
         $customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
         $customerId = $customer->getData('adyen_customer_ref') ?: $customer->getData('increment_id') ?: $customerId;
     }
     $adyFields['recurringContract'] = $recurringType;
     $adyFields['shopperReference'] = !empty($customerId) ? $customerId : self::GUEST_ID . $realOrderId;
     //blocked methods
     $adyFields['blockedMethods'] = "";
     /*
      * This feld will be appended as-is to the return URL when the shopper completes, or abandons, the payment and
      * returns to your shop; it is typically used to transmit a session ID. This feld has a maximum of 128 characters
      * This is an optional field and not necessary by default
      */
     $adyFields['merchantReturnData'] = "";
     $openinvoiceType = $this->_getConfigData('openinvoicetypes', 'adyen_openinvoice');
     if ($this->_code == "adyen_openinvoice" || $this->getInfoInstance()->getCcType() == "klarna" || $this->getInfoInstance()->getCcType() == "afterpay_default") {
         $adyFields['billingAddressType'] = "1";
         $adyFields['deliveryAddressType'] = "1";
         // get shopperType setting
         $shopperType = $this->_getConfigData("shoppertype", "adyen_openinvoice");
         if ($shopperType == '1') {
             $adyFields['shopperType'] = "";
         } else {
             $adyFields['shopperType'] = "1";
         }
     } else {
         // for other payment methods like creditcard don't show avs address field in skin
         $adyFields['billingAddressType'] = "2";
         // Only set DeliveryAddressType to hidden and in request if there is a shipping address otherwise keep it empty
         $deliveryAddress = $order->getShippingAddress();
         if ($deliveryAddress != null) {
             $adyFields['deliveryAddressType'] = "2";
         } else {
             $adyFields['deliveryAddressType'] = "";
         }
         $adyFields['shopperType'] = "";
     }
     // get extra fields
     $adyFields = Mage::getModel('adyen/adyen_openinvoice')->getOptionalFormFields($adyFields, $this->_order);
     // For IDEAL add isuerId into request so bank selection is skipped
     if (strpos($this->getInfoInstance()->getCcType(), "ideal") !== false) {
         $adyFields['issuerId'] = $this->getInfoInstance()->getPoNumber();
     }
     // if option to put Return Url in request from magento is enabled add this in the request
     $returnUrlInRequest = $this->_getConfigData('return_url_in_request', 'adyen_hpp');
     if ($returnUrlInRequest) {
         $url = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK, true) . "adyen/process/success";
         $adyFields['resURL'] = $url;
     }
     $secretWord = $this->_getSecretWord();
     if ($this->_code == "adyen_openinvoice") {
         $brandCode = $this->_getConfigData('openinvoicetypes', 'adyen_openinvoice');
         $adyFields['brandCode'] = $brandCode;
     } else {
         $brandCode = $this->getInfoInstance()->getCcType();
         if ($brandCode) {
             $adyFields['brandCode'] = $brandCode;
         }
     }
     // set offset to 0
     $adyFields['offset'] = "0";
     // eventHandler to overwrite the adyFields without changing module code
     $adyFields = new Varien_Object($adyFields);
     Mage::dispatchEvent('adyen_payment_hpp_fields', array('order' => $order, 'fields' => $adyFields));
     $adyFields = $adyFields->getData();
     // Sort the array by key using SORT_STRING order
     ksort($adyFields, SORT_STRING);
     // Generate the signing data string
     $signData = implode(":", array_map(array($this, 'escapeString'), array_merge(array_keys($adyFields), array_values($adyFields))));
     $signMac = Zend_Crypt_Hmac::compute(pack("H*", $secretWord), 'sha256', $signData);
     $adyFields['merchantSig'] = base64_encode(pack('H*', $signMac));
     // pos over hpp
     //         disable this because no one using this and it will always show POS payment method
     //         $terminalcode = 'redirect';
     //         $adyFields['pos.serial_number'] = $terminalcode;
     //         // calculate signatature pos
     //         $strsign = "merchantSig:pos.serial_number|" . $adyFields['merchantSig'] . ":" . $terminalcode;
     //         $signPOS = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $strsign);
     //         $adyFields['pos.sig'] = base64_encode(pack('H*', $signPOS));
     Mage::log($adyFields, self::DEBUG_LEVEL, 'adyen_http-request.log', true);
     //        print_r($adyFields);die();
     return $adyFields;
 }
Exemplo n.º 17
0
 public function processCashResponse()
 {
     $response = $_REQUEST;
     $varienObj = new Varien_Object();
     foreach ($response as $code => $value) {
         if ($code == 'amount') {
             if (is_object($value)) {
                 $value = $value->value;
             }
             $code = 'value';
         }
         $varienObj->setData($code, $value);
     }
     $pspReference = $varienObj->getData('pspReference');
     $merchantReference = $varienObj->getData('merchantReference');
     $skinCode = $varienObj->getData('skinCode');
     $paymentAmount = $varienObj->getData('paymentAmount');
     $currencyCode = $varienObj->getData('currencyCode');
     $customPaymentMethod = $varienObj->getData('c_cash');
     $paymentMethod = $varienObj->getData('paymentMethod');
     $merchantSig = $varienObj->getData('merchantSig');
     $sign = $pspReference . $merchantReference . $skinCode . $paymentAmount . $currencyCode . $customPaymentMethod . $paymentMethod;
     $secretWord = $this->_getSecretWord();
     $signMac = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $sign);
     $calMerchantSig = base64_encode(pack('H*', $signMac));
     // check if signatures are the same
     if ($calMerchantSig == $merchantSig) {
         //get order && payment objects
         $order = Mage::getModel('sales/order');
         //error
         $orderExist = $this->_incrementIdExist($varienObj, $merchantReference);
         if (empty($orderExist)) {
             $this->_writeLog("unknown order : {$merchantReference}");
         } else {
             $order->loadByIncrementId($merchantReference);
             $comment = Mage::helper('adyen')->__('Adyen Cash Result URL Notification: <br /> pspReference: %s <br /> paymentMethod: %s', $pspReference, $paymentMethod);
             $status = true;
             $history = Mage::getModel('sales/order_status_history')->setStatus($status)->setComment($comment)->setEntityName("order")->setOrder($order);
             $history->save();
             if ($this->_getConfigData('cash_drawer', 'adyen_pos')) {
                 $printerIp = trim($this->_getConfigData('cash_drawer_printer_ip', 'adyen_pos'));
                 if ($printerIp != "") {
                     $drawCodeConfig = trim($this->_getConfigData('cash_drawer_code', 'adyen_pos'));
                     if ($drawCodeConfig != "") {
                         // split comm based
                         $drawCodes = explode(",", $drawCodeConfig);
                         // open the cash drawer
                         try {
                             $esc = "";
                             $fp = fsockopen($printerIp, 9100);
                             fwrite($fp, $esc . "@");
                             $write = "";
                             $count = 0;
                             foreach ($drawCodes as $drawCode) {
                                 // first code 27 must be special character to let it work
                                 if ($count == 0 && $drawCode == "27") {
                                     $write .= $esc;
                                 } else {
                                     $write .= chr($drawCode);
                                 }
                                 ++$count;
                             }
                             // example: fwrite($fp, $esc . chr(112) . chr(48) . chr(55) . chr(121));
                             fwrite($fp, $write);
                             // close connection
                             fclose($fp);
                         } catch (Exception $e) {
                             Mage::logException($e);
                             Mage::throwException($e->getMessage());
                         }
                     } else {
                         Mage::log("Cash drawer Code not filled in check your Adyen POS settings", Zend_Log::DEBUG, "adyen_notification.log", true);
                         Mage::throwException('Cash drawer Code not filled in check your Adyen POS settings');
                     }
                 } else {
                     Mage::log("Cash drawer Code not filled in check your Adyen POS settings", Zend_Log::DEBUG, "adyen_notification.log", true);
                     Mage::throwException('Cash drawer IP not filled in check your Adyen POS settings');
                 }
             }
             return $status;
         }
     }
     return false;
 }
Exemplo n.º 18
0
 public function testHmac_InternalSHA1_7()
 {
     $this->markTestIncomplete('Native md5/sha1 functions to be supported as last resort');
     $data = 'Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data';
     $key = str_repeat("ª", 80);
     $hmac = Zend_Crypt_Hmac::compute($key, 'SHA1', $data, Zend_Crypt_Hmac::STRING, true);
     $this->assertEquals('e8e99d0f45237d786d6bbaa7965c7808bbff1a91', $hmac);
 }
Exemplo n.º 19
0
 /**
  * Sign a request
  *
  * @param  array $params
  * @param  mixed $method
  * @param  mixed $url
  * @return string
  */
 public function sign(array $params, $method = null, $url = null)
 {
     $binaryHash = Zend_Crypt_Hmac::compute($this->_key, $this->_hashAlgorithm, $this->_getBaseSignatureString($params, $method, $url), Zend_Crypt_Hmac::BINARY);
     return base64_encode($binaryHash);
 }
Exemplo n.º 20
0
 protected function addSignatureAws4($method, $path, array $params, array &$headers)
 {
     // http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html
     // task 1: create a canonical request
     $canonicalQueryArray = array();
     if (!empty($params)) {
         ksort($params);
         foreach ($params as $paramKey => $paramValue) {
             $canonicalQueryArray[] = sprintf('%s=%s', urlencode($paramKey), urlencode($paramValue));
         }
     }
     $canonicalQueryString = implode('&', $canonicalQueryArray);
     $canonicalHeaders = '';
     $signedHeadersArray = array();
     $hashedPayload = '';
     $timestamp = '';
     $headerKeys = array_combine(array_map('strtolower', array_keys($headers)), array_keys($headers));
     ksort($headerKeys);
     foreach ($headerKeys as $headerKeyLower => $headerKey) {
         $canonicalHeaders .= sprintf("%s:%s\n", $headerKeyLower, $headers[$headerKey]);
         $signedHeadersArray[] = $headerKeyLower;
         switch ($headerKey) {
             case 'x-amz-content-sha256':
                 $hashedPayload = $headers[$headerKey];
                 break;
             case 'x-amz-date':
                 $timestamp = $headers[$headerKey];
                 break;
         }
     }
     $signedHeadersString = implode(';', $signedHeadersArray);
     $canonicalRequest = sprintf("%s\n%s\n%s\n%s\n%s\n%s", $method, $path, $canonicalQueryString, $canonicalHeaders, $signedHeadersString, $hashedPayload);
     // task 2: create a string to sign
     $date = substr($timestamp, 0, strpos($timestamp, 'T'));
     $scope = sprintf('%s/%s/s3/aws4_request', $date, $this->_region);
     $stringToSign = sprintf("AWS4-HMAC-SHA256\n%s\n%s\n%s", $timestamp, $scope, Zend_Crypt::hash('sha256', $canonicalRequest));
     // task 3: calculate signature
     $dateKey = Zend_Crypt_Hmac::compute('AWS4' . $this->_getSecretKey(), 'sha256', $date, Zend_Crypt_Hmac::BINARY);
     $dateRegionKey = Zend_Crypt_Hmac::compute($dateKey, 'sha256', $this->_region, Zend_Crypt_Hmac::BINARY);
     $dateRegionServiceKey = Zend_Crypt_Hmac::compute($dateRegionKey, 'sha256', 's3', Zend_Crypt_Hmac::BINARY);
     $signingKey = Zend_Crypt_Hmac::compute($dateRegionServiceKey, 'sha256', 'aws4_request', Zend_Crypt_Hmac::BINARY);
     $signature = Zend_Crypt_Hmac::compute($signingKey, 'sha256', $stringToSign);
     $headers['Authorization'] = sprintf('AWS4-HMAC-SHA256 Credential=%s/%s,SignedHeaders=%s,Signature=%s', $this->_getAccessKey(), $scope, $signedHeadersString, $signature);
     return $signature;
 }
Exemplo n.º 21
0
 public function getOptionalFormFields($adyFields, $order)
 {
     if (empty($order)) {
         return $adyFields;
     }
     $helper = Mage::helper('adyen');
     $secretWord = $this->_getSecretWord();
     $billingAddress = $order->getBillingAddress();
     $adyFields['shopper.firstName'] = $billingAddress->getFirstname();
     $adyFields['shopper.lastName'] = $billingAddress->getLastname();
     $adyFields['billingAddress.street'] = $helper->getStreet($billingAddress)->getName();
     $adyFields['billingAddress.houseNumberOrName'] = $helper->getStreet($billingAddress)->getHouseNumber();
     $adyFields['billingAddress.city'] = $billingAddress->getCity();
     $adyFields['billingAddress.postalCode'] = $billingAddress->getPostcode();
     $adyFields['billingAddress.stateOrProvince'] = $billingAddress->getRegionCode();
     $adyFields['billingAddress.country'] = $billingAddress->getCountryId();
     $sign = $adyFields['billingAddress.street'] . $adyFields['billingAddress.houseNumberOrName'] . $adyFields['billingAddress.city'] . $adyFields['billingAddress.postalCode'] . $adyFields['billingAddress.stateOrProvince'] . $adyFields['billingAddress.country'];
     //Generate HMAC encrypted merchant signature
     $signMac = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $sign);
     $adyFields['billingAddressSig'] = base64_encode(pack('H*', $signMac));
     $deliveryAddress = $order->getShippingAddress();
     if ($deliveryAddress != null) {
         $adyFields['deliveryAddress.street'] = $helper->getStreet($deliveryAddress)->getName();
         $adyFields['deliveryAddress.houseNumberOrName'] = $helper->getStreet($deliveryAddress)->getHouseNumber();
         $adyFields['deliveryAddress.city'] = $deliveryAddress->getCity();
         $adyFields['deliveryAddress.postalCode'] = $deliveryAddress->getPostcode();
         $adyFields['deliveryAddress.stateOrProvince'] = $deliveryAddress->getRegionCode();
         $adyFields['deliveryAddress.country'] = $deliveryAddress->getCountryId();
         $sign = $adyFields['deliveryAddress.street'] . $adyFields['deliveryAddress.houseNumberOrName'] . $adyFields['deliveryAddress.city'] . $adyFields['deliveryAddress.postalCode'] . $adyFields['deliveryAddress.stateOrProvince'] . $adyFields['deliveryAddress.country'];
         //Generate HMAC encrypted merchant signature
         $secretWord = $this->_getSecretWord();
         $signMac = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $sign);
         $adyFields['deliveryAddressSig'] = base64_encode(pack('H*', $signMac));
     }
     if ($adyFields['shopperReference'] != self::GUEST_ID . $order->getRealOrderId()) {
         $customer = Mage::getModel('customer/customer')->load($adyFields['shopperReference']);
         if ($this->getCustomerAttributeText($customer, 'gender') != "") {
             $adyFields['shopper.gender'] = strtoupper($this->getCustomerAttributeText($customer, 'gender'));
         } else {
             // fix for OneStepCheckout (guest is not logged in but uses email that exists with account)
             $_customer = Mage::getModel('customer/customer');
             if ($order->getCustomerGender()) {
                 $customerGender = $order->getCustomerGender();
             } else {
                 // this is still empty for OneStepCheckout so uses extra saved parameter
                 $payment = $order->getPayment();
                 $customerGender = $payment->getAdditionalInformation('customerGender');
             }
             $adyFields['shopper.gender'] = strtoupper($_customer->getResource()->getAttribute('gender')->getSource()->getOptionText($customerGender));
         }
         $adyFields['shopper.infix'] = $customer->getPrefix();
         $dob = $customer->getDob();
         if (!empty($dob)) {
             $adyFields['shopper.dateOfBirthDayOfMonth'] = $this->getDate($dob, 'd');
             $adyFields['shopper.dateOfBirthMonth'] = $this->getDate($dob, 'm');
             $adyFields['shopper.dateOfBirthYear'] = $this->getDate($dob, 'Y');
         } else {
             // fix for OneStepCheckout (guest is not logged in but uses email that exists with account)
             $dob = $order->getCustomerDob();
             if (!empty($dob)) {
                 $adyFields['shopper.dateOfBirthDayOfMonth'] = $this->getDate($dob, 'd');
                 $adyFields['shopper.dateOfBirthMonth'] = $this->getDate($dob, 'm');
                 $adyFields['shopper.dateOfBirthYear'] = $this->getDate($dob, 'Y');
             }
         }
     } else {
         // checkout as guest use details from the order
         $_customer = Mage::getModel('customer/customer');
         $adyFields['shopper.gender'] = strtoupper($_customer->getResource()->getAttribute('gender')->getSource()->getOptionText($order->getCustomerGender()));
         $adyFields['shopper.infix'] = $order->getCustomerPrefix();
         $dob = $order->getCustomerDob();
         if (!empty($dob)) {
             $adyFields['shopper.dateOfBirthDayOfMonth'] = $this->getDate($dob, 'd');
             $adyFields['shopper.dateOfBirthMonth'] = $this->getDate($dob, 'm');
             $adyFields['shopper.dateOfBirthYear'] = $this->getDate($dob, 'Y');
         }
     }
     // for sweden add here your socialSecurityNumber
     // $adyFields['shopper.socialSecurityNumber'] = "Result of your custom input field";
     $adyFields['shopper.telephoneNumber'] = $billingAddress->getTelephone();
     $openinvoiceType = $this->_getConfigData('openinvoicetypes', 'adyen_openinvoice');
     // get current payment method
     if ($order->getPayment()->getMethod() == "adyen_openinvoice" || $order->getPayment()->getMethodInstance()->getInfoInstance()->getCcType() == "klarna" || $order->getPayment()->getMethodInstance()->getInfoInstance()->getCcType() == "afterpay_default") {
         // initialize values if they are empty
         $adyFields['shopper.gender'] = isset($adyFields['shopper.gender']) ? $adyFields['shopper.gender'] : "";
         $adyFields['shopper.infix'] = isset($adyFields['shopper.infix']) ? $adyFields['shopper.infix'] : "";
         $adyFields['shopper.dateOfBirthDayOfMonth'] = isset($adyFields['shopper.dateOfBirthDayOfMonth']) ? $adyFields['shopper.dateOfBirthDayOfMonth'] : "";
         $adyFields['shopper.dateOfBirthMonth'] = isset($adyFields['shopper.dateOfBirthMonth']) ? $adyFields['shopper.dateOfBirthMonth'] : "";
         $adyFields['shopper.dateOfBirthYear'] = isset($adyFields['shopper.dateOfBirthYear']) ? $adyFields['shopper.dateOfBirthYear'] : "";
         $shoppperSign = $adyFields['shopper.firstName'] . $adyFields['shopper.infix'] . $adyFields['shopper.lastName'] . $adyFields['shopper.gender'] . $adyFields['shopper.dateOfBirthDayOfMonth'] . $adyFields['shopper.dateOfBirthMonth'] . $adyFields['shopper.dateOfBirthYear'] . $adyFields['shopper.telephoneNumber'];
         $shopperSignMac = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $shoppperSign);
         $adyFields['shopperSig'] = base64_encode(pack('H*', $shopperSignMac));
     }
     $count = 0;
     $currency = $order->getOrderCurrencyCode();
     $additional_data_sign = array();
     foreach ($order->getItemsCollection() as $item) {
         //skip dummies
         if ($item->isDummy()) {
             continue;
         }
         ++$count;
         $linename = "line" . $count;
         $additional_data_sign['openinvoicedata.' . $linename . '.currencyCode'] = $currency;
         $additional_data_sign['openinvoicedata.' . $linename . '.description'] = $item->getName();
         $additional_data_sign['openinvoicedata.' . $linename . '.itemAmount'] = $helper->formatAmount($item->getPrice(), $currency);
         $additional_data_sign['openinvoicedata.' . $linename . '.itemVatAmount'] = $item->getTaxAmount() > 0 && $item->getPriceInclTax() > 0 ? $helper->formatAmount($item->getPriceInclTax(), $currency) - $helper->formatAmount($item->getPrice(), $currency) : $helper->formatAmount($item->getTaxAmount(), $currency);
         $additional_data_sign['openinvoicedata.' . $linename . '.numberOfItems'] = (int) $item->getQtyOrdered();
         if ($order->getPayment()->getMethod() == "adyen_openinvoice" && $openinvoiceType == "afterpay_default" || $order->getPayment()->getMethodInstance()->getInfoInstance()->getCcType() == "afterpay_default") {
             $additional_data_sign['openinvoicedata.' . $linename . '.vatCategory'] = "High";
         } else {
             $additional_data_sign['openinvoicedata.' . $linename . '.vatCategory'] = "None";
         }
     }
     //discount cost
     if ($order->getDiscountAmount() > 0 || $order->getDiscountAmount() < 0) {
         $linename = "line" . ++$count;
         $additional_data_sign['openinvoicedata.' . $linename . '.currencyCode'] = $currency;
         $additional_data_sign['openinvoicedata.' . $linename . '.description'] = $helper->__('Total Discount');
         $additional_data_sign['openinvoicedata.' . $linename . '.itemAmount'] = $helper->formatAmount($order->getDiscountAmount(), $currency);
         $additional_data_sign['openinvoicedata.' . $linename . '.itemVatAmount'] = "0";
         $additional_data_sign['openinvoicedata.' . $linename . '.numberOfItems'] = 1;
         if ($order->getPayment()->getMethod() == "adyen_openinvoice" && $openinvoiceType == "afterpay_default" || $order->getPayment()->getMethodInstance()->getInfoInstance()->getCcType() == "afterpay_default") {
             $additional_data_sign['openinvoicedata.' . $linename . '.vatCategory'] = "High";
         } else {
             $additional_data_sign['openinvoicedata.' . $linename . '.vatCategory'] = "None";
         }
     }
     //shipping cost
     if ($order->getShippingAmount() > 0 || $order->getShippingTaxAmount() > 0) {
         $linename = "line" . ++$count;
         $additional_data_sign['openinvoicedata.' . $linename . '.currencyCode'] = $currency;
         $additional_data_sign['openinvoicedata.' . $linename . '.description'] = $order->getShippingDescription();
         $additional_data_sign['openinvoicedata.' . $linename . '.itemAmount'] = $helper->formatAmount($order->getShippingAmount(), $currency);
         $additional_data_sign['openinvoicedata.' . $linename . '.itemVatAmount'] = $helper->formatAmount($order->getShippingTaxAmount(), $currency);
         $additional_data_sign['openinvoicedata.' . $linename . '.numberOfItems'] = 1;
         if ($order->getPayment()->getMethod() == "adyen_openinvoice" && $openinvoiceType == "afterpay_default" || $order->getPayment()->getMethodInstance()->getInfoInstance()->getCcType() == "afterpay_default") {
             $additional_data_sign['openinvoicedata.' . $linename . '.vatCategory'] = "High";
         } else {
             $additional_data_sign['openinvoicedata.' . $linename . '.vatCategory'] = "None";
         }
     }
     if ($order->getPaymentFeeAmount() > 0) {
         $linename = "line" . ++$count;
         $additional_data_sign['openinvoicedata.' . $linename . '.currencyCode'] = $currency;
         $additional_data_sign['openinvoicedata.' . $linename . '.description'] = $helper->__('Payment Fee');
         $additional_data_sign['openinvoicedata.' . $linename . '.itemAmount'] = $helper->formatAmount($order->getPaymentFeeAmount(), $currency);
         $additional_data_sign['openinvoicedata.' . $linename . '.itemVatAmount'] = "0";
         $additional_data_sign['openinvoicedata.' . $linename . '.numberOfItems'] = 1;
         if ($order->getPayment()->getMethod() == "adyen_openinvoice" && $openinvoiceType == "afterpay_default" || $order->getPayment()->getMethodInstance()->getInfoInstance()->getCcType() == "afterpay_default") {
             $additional_data_sign['openinvoicedata.' . $linename . '.vatCategory'] = "High";
         } else {
             $additional_data_sign['openinvoicedata.' . $linename . '.vatCategory'] = "None";
         }
     }
     // Klarna wants tax cost provided in the lines of the products so overal tax cost is not needed anymore
     //        $linename = "line".++$count;
     //        $additional_data_sign['openinvoicedata.' . $linename . '.currencyCode'] = $currency;
     //        $additional_data_sign['openinvoicedata.' . $linename . '.description'] = $helper->__('Tax');
     //        $additional_data_sign['openinvoicedata.' . $linename . '.itemAmount'] = $helper->formatAmount($order->getTaxAmount(), $currency);
     //        $additional_data_sign['openinvoicedata.' . $linename . '.itemVatAmount'] = "0";
     //        $additional_data_sign['openinvoicedata.' . $linename . '.numberOfItems'] = 1;
     //        $additional_data_sign['openinvoicedata.' . $linename . '.vatCategory'] = "None";
     // general for invoicelines
     $additional_data_sign['openinvoicedata.refundDescription'] = "Refund / Correction for " . $adyFields['merchantReference'];
     $additional_data_sign['openinvoicedata.numberOfLines'] = $count;
     // add merchantsignature in additional signature
     $additional_data_sign['merchantSig'] = $adyFields['merchantSig'];
     // generate signature
     ksort($additional_data_sign);
     // signature is first alphabatical keys seperate by : and then | and then the values seperate by :
     foreach ($additional_data_sign as $key => $value) {
         // add to fields
         $adyFields[$key] = $value;
     }
     $keys = implode(':', array_keys($additional_data_sign));
     $values = implode(':', $additional_data_sign);
     $sign_additional_data = trim($keys) . '|' . trim($values);
     $signMac = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $sign_additional_data);
     $adyFields['openinvoicedata.sig'] = base64_encode(pack('H*', $signMac));
     Mage::log($adyFields, self::DEBUG_LEVEL, 'adyen_http-request.log');
     return $adyFields;
 }
Exemplo n.º 22
0
 /**
  * Creates a signature from the provided date
  * 
  * @param  string $data RFC2616-compliant date
  * @return string
  */
 protected function _calculateSignature($date)
 {
     $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA256', $date, Zend_Crypt_Hmac::BINARY);
     return base64_encode($hmac);
 }
Exemplo n.º 23
0
 /**
  * Setter for the hash method.
  *
  * @param string $hash
  * @return Zend_Crypt_Hmac
  */
 protected static function _setHashAlgorithm($hash)
 {
     if (!isset($hash) || empty($hash)) {
         require_once 'Zend/Crypt/Hmac/Exception.php';
         throw new Zend_Crypt_Hmac_Exception('provided hash string is null or empty');
     }
     $hash = strtolower($hash);
     $hashSupported = false;
     if (function_exists('hash_algos') && in_array($hash, hash_algos())) {
         $hashSupported = true;
     }
     if ($hashSupported === false && function_exists('mhash') && in_array($hash, self::$_supportedAlgosMhash)) {
         $hashSupported = true;
     }
     if ($hashSupported === false) {
         require_once 'Zend/Crypt/Hmac/Exception.php';
         throw new Zend_Crypt_Hmac_Exception('hash algorithm provided is not supported on this PHP installation; please enable the hash or mhash extensions');
     }
     self::$_hashAlgorithm = $hash;
 }
Exemplo n.º 24
0
 public function getAvailableHPPTypes()
 {
     $orderCurrencyCode = Mage::helper('checkout/cart')->getQuote()->getQuoteCurrencyCode();
     $skinCode = trim($this->_getConfigData('skinCode', 'adyen_hpp'));
     $merchantAccount = trim($this->_getConfigData('merchantAccount'));
     $amount = Mage::helper('adyen')->formatAmount(Mage::helper('checkout/cart')->getQuote()->getGrandTotal(), $orderCurrencyCode);
     $sessionValidity = date(DATE_ATOM, mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y")));
     $cacheDirectoryLookup = trim($this->_getConfigData('cache_directory_lookup', 'adyen_hpp'));
     $countryCode = trim($this->_getConfigData('countryCode'));
     if (empty($countryCode)) {
         // check if billingcountry is filled in
         if (is_object(Mage::helper('checkout/cart')->getQuote()->getBillingAddress()) && Mage::helper('checkout/cart')->getQuote()->getBillingAddress()->getCountry() != "") {
             $countryCode = Mage::helper('checkout/cart')->getQuote()->getBillingAddress()->getCountry();
         } else {
             $countryCode = "";
             // don't set countryCode so you get all the payment methods
             // You could do ip lookup but availability and performace is not guaranteed
             //         		$ip =  Mage::helper('adyen')->getClientIp();
             //         		$countryCode = file_get_contents('http://api.hostip.info/country.php?ip='.$ip);
         }
     }
     // check if cache setting is on
     if ($cacheDirectoryLookup) {
         // cache name has variables merchantAccount, skinCode, currencycode and country code. Amound is not cached because of performance issues
         $cacheId = 'cache_directory_lookup_request_' . $merchantAccount . "_" . $skinCode . "_" . $orderCurrencyCode . "_" . $countryCode;
         // check if this request is already cached
         if (false !== ($data = Mage::app()->getCache()->load($cacheId))) {
             // return result from cache
             return unserialize($data);
         }
     }
     // directory lookup to search for available payment methods
     $adyFields = array("paymentAmount" => (int) $amount, "currencyCode" => $orderCurrencyCode, "merchantReference" => "Get Payment methods", "skinCode" => $skinCode, "merchantAccount" => $merchantAccount, "sessionValidity" => $sessionValidity, "countryCode" => $countryCode, "shopperLocale" => $countryCode, "merchantSig" => "");
     $sign = $adyFields['paymentAmount'] . $adyFields['currencyCode'] . $adyFields['merchantReference'] . $adyFields['skinCode'] . $adyFields['merchantAccount'] . $adyFields['sessionValidity'];
     //Generate HMAC encrypted merchant signature
     $secretWord = $this->_getSecretWord();
     if ($secretWord == "") {
         Mage::throwException(Mage::helper('adyen')->__('You forgot to fill in HMAC key for Test or Live'));
     }
     $signMac = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $sign);
     $adyFields['merchantSig'] = base64_encode(pack('H*', $signMac));
     $ch = curl_init();
     $isConfigDemoMode = $this->getConfigDataDemoMode();
     if ($isConfigDemoMode) {
         curl_setopt($ch, CURLOPT_URL, "https://test.adyen.com/hpp/directory.shtml");
     } else {
         curl_setopt($ch, CURLOPT_URL, "https://live.adyen.com/hpp/directory.shtml");
     }
     curl_setopt($ch, CURLOPT_HEADER, false);
     curl_setopt($ch, CURLOPT_POST, count($adyFields));
     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($adyFields));
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
     // do not print results if you do curl_exec
     $results = curl_exec($ch);
     if ($results === false) {
         Mage::log("Payment methods are not available on this merchantaccount\\skin result is: " . curl_error($ch), self::DEBUG_LEVEL, 'http-request.log', true);
         Mage::throwException(Mage::helper('adyen')->__('Payment methods are not available on this merchantaccount\\skin'));
     } else {
         /**
          * The $result contains a JSON array containing
          * the available payment methods for the merchant account.
          */
         $results_json = json_decode($results);
         if ($results_json == null) {
             // no valid json so show the error
             Mage::log("Payment methods are empty on this merchantaccount with the selected skin,hmac,amount,country check if these settings are correct results_json result is:" . $results, self::DEBUG_LEVEL, 'http-request.log', true);
             // return empty array
             return array();
         }
         $payment_methods = $results_json->paymentMethods;
         $result_array = array();
         foreach ($payment_methods as $payment_method) {
             // if openinvoice is activated don't show this in HPP options
             if (Mage::getStoreConfig("payment/adyen_openinvoice/active")) {
                 if (Mage::getStoreConfig("payment/adyen_openinvoice/openinvoicetypes") == $payment_method->brandCode) {
                     continue;
                 }
             }
             $result_array[$payment_method->brandCode]['name'] = $payment_method->name;
             if (isset($payment_method->issuers)) {
                 // for ideal go through the issuers
                 if (count($payment_method->issuers) > 0) {
                     foreach ($payment_method->issuers as $issuer) {
                         $result_array[$payment_method->brandCode]['issuers'][$issuer->issuerId] = $issuer->name;
                     }
                 }
                 ksort($result_array[$payment_method->brandCode]['issuers']);
                 // sort on key
             }
         }
     }
     // if cache is on cache this result
     if ($cacheDirectoryLookup) {
         Mage::app()->getCache()->save(serialize($result_array), $cacheId);
     }
     return $result_array;
 }
Exemplo n.º 25
0
 /**
  * @desc prepare params array to send it to gateway page via POST
  * @return array
  */
 public function getFormFields()
 {
     $this->_initOrder();
     $order = $this->_order;
     $realOrderId = $order->getRealOrderId();
     $orderCurrencyCode = $order->getOrderCurrencyCode();
     $skinCode = $this->_getConfigData('skinCode', 'adyen_hpp');
     $amount = $this->_formatAmount($order->getGrandTotal(), $orderCurrencyCode == 'IDR' ? 0 : 2);
     $merchantAccount = $this->_getConfigData('merchantAccount');
     $customerEmail = $order->getCustomerEmail();
     $sesionId = $order->getQuoteId();
     $shopperEmail = !empty($customerEmail) ? $customerEmail : self::DUMMY_EMAIL;
     $customerId = $order->getCustomerId();
     $shopperIP = $order->getRemoteIp();
     $browserInfo = $_SERVER['HTTP_USER_AGENT'];
     $shopperLocale = trim($this->_getConfigData('shopperlocale'));
     $shopperLocale = !empty($shopperLocale) ? $shopperLocale : Mage::app()->getLocale()->getLocaleCode();
     $countryCode = $this->_getConfigData('countryCode');
     $countryCode = !empty($countryCode) ? $countryCode : false;
     $adyFields = array();
     $deliveryDays = (int) $this->_getConfigData('delivery_days', 'adyen_hpp');
     $deliveryDays = !empty($deliveryDays) ? $deliveryDays : 55;
     $adyFields['merchantAccount'] = $merchantAccount;
     $adyFields['merchantReference'] = $realOrderId;
     $adyFields['paymentAmount'] = $amount;
     $adyFields['currencyCode'] = $orderCurrencyCode;
     $adyFields['shipBeforeDate'] = date("Y-m-d", mktime(date("H"), date("i"), date("s"), date("m"), date("j") + $deliveryDays, date("Y")));
     $adyFields['skinCode'] = $skinCode;
     $adyFields['shopperLocale'] = $shopperLocale;
     $adyFields['countryCode'] = $countryCode;
     $adyFields['sesionId'] = $sesionId;
     $adyFields['shopperIP'] = $shopperIP;
     $adyFields['browserInfo'] = $browserInfo;
     //order data
     $items = $order->getAllItems();
     $shipmentAmount = number_format($order->getShippingAmount() + $order->getShippingTaxAmount(), 2, ',', ' ');
     $prodDetails = Mage::helper('adyen')->__('Shipment cost: %s %s <br />', $shipmentAmount, $orderCurrencyCode);
     $prodDetails .= Mage::helper('adyen')->__('Order rows: <br />');
     foreach ($items as $item) {
         if ($item->getParentItem()) {
             continue;
         }
         $name = $item->getName();
         $qtyOrdered = $this->_formatAmount($item->getQtyOrdered(), '0');
         $rowTotal = number_format($item->getRowTotalInclTax(), 2, ',', ' ');
         $prodDetails .= Mage::helper('adyen')->__('%s ( Qty: %s ) (Price: %s %s ) <br />', $name, $qtyOrdered, $rowTotal, $orderCurrencyCode);
     }
     $adyFields['orderData'] = base64_encode(gzencode($prodDetails));
     //depreacated by Adyen
     $adyFields['sessionValidity'] = date(DATE_ATOM, mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y")));
     $adyFields['shopperEmail'] = $customerEmail;
     // recurring
     $adyFields['recurringContract'] = Madia_Adyen_Model_Adyen_Data_Abstract::ONE_CLICK_PAYMENT;
     $adyFields['shopperReference'] = !empty($customerId) ? $customerId : self::GUEST_ID . $realOrderId;
     //blocked methods
     $adyFields['blockedMethods'] = $this->_getBlockMethods();
     //the data that needs to be signed is a concatenated string of the form data
     $sign = $adyFields['paymentAmount'] . $adyFields['currencyCode'] . $adyFields['shipBeforeDate'] . $adyFields['merchantReference'] . $adyFields['skinCode'] . $adyFields['merchantAccount'] . $adyFields['sessionValidity'] . $adyFields['shopperEmail'] . $adyFields['shopperReference'] . $adyFields['recurringContract'] . $adyFields['blockedMethods'];
     //Generate HMAC encrypted merchant signature
     $secretWord = $this->_getSecretWord();
     $signMac = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $sign);
     $adyFields['merchantSig'] = base64_encode(pack('H*', $signMac));
     //openinvoice as option
     if (strpos($this->getInfoInstance()->getCcType(), "openinvoice") !== false) {
         $adyFields = Mage::getModel('adyen/adyen_openinvoice')->getOptionalFormFields($adyFields, $this->_order);
     }
     //IDEAL
     if (strpos($this->getInfoInstance()->getCcType(), "ideal") !== false) {
         $bankData = $this->getInfoInstance()->getPoNumber();
         if (!empty($bankData)) {
             $id = explode(DS, $bankData);
             $adyFields['skipSelection'] = 'true';
             $adyFields['brandCode'] = $this->getInfoInstance()->getCcType();
             $adyFields['idealIssuerId'] = $id['0'];
         }
     }
     if (parent::TEST_ENV) {
         Mage::log($adyFields, self::DEBUG_LEVEL, 'http-request.log', true);
     }
     return $adyFields;
 }
Exemplo n.º 26
0
 /**
  * @desc prepare params array to send it to gateway page via POST
  * @return array
  */
 public function getFormFields()
 {
     $this->_initOrder();
     $order = $this->_order;
     $realOrderId = $order->getRealOrderId();
     $orderCurrencyCode = $order->getOrderCurrencyCode();
     $skinCode = trim($this->_getConfigData('skinCode', 'adyen_hpp'));
     $amount = Mage::helper('adyen')->formatAmount($order->getGrandTotal(), $orderCurrencyCode);
     $merchantAccount = trim($this->_getConfigData('merchantAccount'));
     $shopperEmail = $order->getCustomerEmail();
     $customerId = $order->getCustomerId();
     $shopperIP = $order->getRemoteIp();
     $browserInfo = $_SERVER['HTTP_USER_AGENT'];
     $shopperLocale = trim($this->_getConfigData('shopperlocale'));
     $shopperLocale = !empty($shopperLocale) ? $shopperLocale : Mage::app()->getLocale()->getLocaleCode();
     $countryCode = trim($this->_getConfigData('countryCode'));
     $countryCode = !empty($countryCode) ? $countryCode : false;
     // if directory lookup is enabled use the billingadress as countrycode
     if ($countryCode == false) {
         if (is_object($order->getBillingAddress()) && $order->getBillingAddress()->getCountry() != "") {
             $countryCode = $order->getBillingAddress()->getCountry();
         }
     }
     $adyFields = array();
     $deliveryDays = (int) $this->_getConfigData('delivery_days', 'adyen_hpp');
     $deliveryDays = !empty($deliveryDays) ? $deliveryDays : 5;
     $adyFields['merchantAccount'] = $merchantAccount;
     $adyFields['merchantReference'] = $realOrderId;
     $adyFields['paymentAmount'] = (int) $amount;
     $adyFields['currencyCode'] = $orderCurrencyCode;
     $adyFields['shipBeforeDate'] = date("Y-m-d", mktime(date("H"), date("i"), date("s"), date("m"), date("j") + $deliveryDays, date("Y")));
     $adyFields['skinCode'] = $skinCode;
     $adyFields['shopperLocale'] = $shopperLocale;
     $adyFields['countryCode'] = $countryCode;
     $adyFields['shopperIP'] = $shopperIP;
     $adyFields['browserInfo'] = $browserInfo;
     //order data
     $items = $order->getAllItems();
     $shipmentAmount = number_format($order->getShippingAmount() + $order->getShippingTaxAmount(), 2, ',', ' ');
     $prodDetails = Mage::helper('adyen')->__('Shipment cost: %s %s <br />', $shipmentAmount, $orderCurrencyCode);
     $prodDetails .= Mage::helper('adyen')->__('Order rows: <br />');
     foreach ($items as $item) {
         if ($item->getParentItem()) {
             continue;
         }
         $name = $item->getName();
         $qtyOrdered = $this->_numberFormat($item->getQtyOrdered(), '0');
         $rowTotal = number_format($item->getRowTotalInclTax(), 2, ',', ' ');
         $prodDetails .= Mage::helper('adyen')->__('%s ( Qty: %s ) (Price: %s %s ) <br />', $name, $qtyOrdered, $rowTotal, $orderCurrencyCode);
     }
     $adyFields['orderData'] = base64_encode(gzencode($prodDetails));
     //depreacated by Adyen
     $adyFields['sessionValidity'] = date(DATE_ATOM, mktime(date("H") + 1, date("i"), date("s"), date("m"), date("j"), date("Y")));
     $adyFields['shopperEmail'] = $shopperEmail;
     // recurring
     $recurringType = trim($this->_getConfigData('recurringtypes', 'adyen_abstract'));
     $adyFields['recurringContract'] = $recurringType;
     $adyFields['shopperReference'] = !empty($customerId) ? $customerId : self::GUEST_ID . $realOrderId;
     //blocked methods
     $adyFields['blockedMethods'] = "";
     /*
      * This feld will be appended as-is to the return URL when the shopper completes, or abandons, the payment and
      * returns to your shop; it is typically used to transmit a session ID. This feld has a maximum of 128 characters
      * This is an optional field and not necessary by default
      */
     $adyFields['merchantReturnData'] = "";
     $openinvoiceType = $this->_getConfigData('openinvoicetypes', 'adyen_openinvoice');
     if ($this->_code == "adyen_openinvoice" || $this->getInfoInstance()->getCcType() == "klarna" || $this->getInfoInstance()->getCcType() == "afterpay_default") {
         $adyFields['billingAddressType'] = "1";
         $adyFields['deliveryAddressType'] = "1";
         $adyFields['shopperType'] = "";
     } else {
         $adyFields['billingAddressType'] = "";
         $adyFields['deliveryAddressType'] = "";
         $adyFields['shopperType'] = "";
     }
     //the data that needs to be signed is a concatenated string of the form data
     $sign = $adyFields['paymentAmount'] . $adyFields['currencyCode'] . $adyFields['shipBeforeDate'] . $adyFields['merchantReference'] . $adyFields['skinCode'] . $adyFields['merchantAccount'] . $adyFields['sessionValidity'] . $adyFields['shopperEmail'] . $adyFields['shopperReference'] . $adyFields['recurringContract'] . $adyFields['blockedMethods'] . $adyFields['merchantReturnData'] . $adyFields['billingAddressType'] . $adyFields['deliveryAddressType'] . $adyFields['shopperType'];
     //Generate HMAC encrypted merchant signature
     $secretWord = $this->_getSecretWord();
     $signMac = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $sign);
     $adyFields['merchantSig'] = base64_encode(pack('H*', $signMac));
     // get extra fields
     $adyFields = Mage::getModel('adyen/adyen_openinvoice')->getOptionalFormFields($adyFields, $this->_order);
     //IDEAL
     if (strpos($this->getInfoInstance()->getCcType(), "ideal") !== false) {
         $bankData = $this->getInfoInstance()->getPoNumber();
         if (!empty($bankData)) {
             $id = explode(DS, $bankData);
             $adyFields['skipSelection'] = 'true';
             $adyFields['brandCode'] = $this->getInfoInstance()->getCcType();
             $adyFields['idealIssuerId'] = $id['0'];
         }
     }
     // if option to put Return Url in request from magento is enabled add this in the request
     $returnUrlInRequest = $this->_getConfigData('return_url_in_request', 'adyen_hpp');
     if ($returnUrlInRequest) {
         $url = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK, true) . "adyen/process/success";
         $adyFields['resURL'] = $url;
     }
     // pos over hpp
     //         disable this because no one using this and it will always show POS payment method
     //         $terminalcode = 'redirect';
     //         $adyFields['pos.serial_number'] = $terminalcode;
     //         // calculate signatature pos
     //         $strsign = "merchantSig:pos.serial_number|" . $adyFields['merchantSig'] . ":" . $terminalcode;
     //         $signPOS = Zend_Crypt_Hmac::compute($secretWord, 'sha1', $strsign);
     //         $adyFields['pos.sig'] = base64_encode(pack('H*', $signPOS));
     Mage::log($adyFields, self::DEBUG_LEVEL, 'adyen_http-request.log', true);
     return $adyFields;
 }
Exemplo n.º 27
0
 /**
  * Computes the RFC 2104-compliant HMAC signature for request parameters
  *
  * This implements the Amazon Web Services signature, as per the following
  * specification:
  *
  * 1. Sort all request parameters (including <tt>SignatureVersion</tt> and
  *    excluding <tt>Signature</tt>, the value of which is being created),
  *    ignoring case.
  *
  * 2. Iterate over the sorted list and append the parameter name (in its
  *    original case) and then its value. Do not URL-encode the parameter
  *    values before constructing this string. Do not use any separator
  *    characters when appending strings.
  *
  * @param  string $queue_url  Queue URL
  * @param  array  $parameters the parameters for which to get the signature.
  *
  * @return string the signed data.
  */
 protected function _signParameters($queue_url, array $paramaters)
 {
     $data = "GET\n";
     $data .= $this->_sqsEndpoint . "\n";
     if ($queue_url !== null) {
         $data .= parse_url($queue_url, PHP_URL_PATH);
     } else {
         $data .= '/';
     }
     $data .= "\n";
     uksort($paramaters, 'strcmp');
     unset($paramaters['Signature']);
     $arrData = array();
     foreach ($paramaters as $key => $value) {
         $arrData[] = $key . '=' . str_replace('%7E', '~', urlencode($value));
     }
     $data .= implode('&', $arrData);
     $hmac = Zend_Crypt_Hmac::compute($this->_getSecretKey(), 'SHA256', $data, Zend_Crypt_Hmac::BINARY);
     return base64_encode($hmac);
 }
Exemplo n.º 28
0
 /**
  * Communication between Adyen and the shop must be encoded with Hmac.
  * @param                       $fields
  * @param Mage_Core_Model_Store $store
  *
  * @throws Mage_Core_Exception
  * @throws Zend_Crypt_Hmac_Exception
  */
 protected function _signRequestParams(&$fields, Mage_Core_Model_Store $store)
 {
     unset($fields['merchantSig']);
     $hmacFields = $fields;
     foreach ($this->_requiredHmacFields as $requiredHmacField) {
         if (!isset($fields[$requiredHmacField])) {
             $fields[$requiredHmacField] = '';
         }
     }
     foreach ($fields as $field => $value) {
         if (!in_array($field, $this->_requiredHmacFields) && !in_array($field, $this->_optionalHmacFields)) {
             unset($hmacFields[$field]);
         }
     }
     if (!($hmacKey = $this->_getHmacKey($store))) {
         Mage::throwException(Mage::helper('adyen')->__('You forgot to fill in HMAC key for Test or Live'));
     }
     $signMac = Zend_Crypt_Hmac::compute($hmacKey, 'sha1', implode('', $hmacFields));
     $fields['merchantSig'] = base64_encode(pack('H*', $signMac));
 }
Exemplo n.º 29
0
 public function validateNotificationHmac(Varien_Object $response)
 {
     // validate if signature is valid
     $submitedMerchantAccount = $response->getData('merchantAccountCode');
     $additionalData = $response->getData('additionalData');
     // json
     $additionalDataHmac = $response->getData('additionalData_hmacSignature');
     // httppost
     $hmacSignature = "";
     if (isset($additionalData["hmacSignature"]) && $additionalData["hmacSignature"] != "") {
         $hmacSignature = $additionalData["hmacSignature"];
     } elseif (isset($additionalDataHmac) && $additionalDataHmac != "") {
         $hmacSignature = $additionalDataHmac;
     }
     $notificationHmac = $this->_getConfigData('notification_hmac');
     if ($hmacSignature != "") {
         // create Hmac signature
         $pspReference = trim($response->getData('pspReference'));
         $originalReference = trim($response->getData('originalReference'));
         $merchantReference = trim($response->getData('merchantReference'));
         $valueArray = $response->getData('value');
         // json
         if ($valueArray && is_array($valueArray)) {
             $value = $valueArray['value'];
             $currencyCode = $valueArray['currency'];
         } else {
             // try http post values
             $valueValue = $response->getData('value');
             $currencyValue = $response->getData('currency');
             if (isset($valueValue) && $valueValue != "") {
                 $value = $valueValue;
             } else {
                 $value = "";
             }
             if (isset($currencyValue) && $currencyValue != "") {
                 $currencyCode = $currencyValue;
             } else {
                 $currencyCode = "";
             }
         }
         $eventCode = $response->getData('eventCode');
         $success = $response->getData('success');
         $sign = $pspReference . ":" . $originalReference . ":" . $submitedMerchantAccount . ":" . $merchantReference . ":" . $value . ":" . $currencyCode . ":" . $eventCode . ":" . $success;
         // decodeHex
         $decodeHex = pack('H*', $notificationHmac);
         $signMac = Zend_Crypt_Hmac::compute($decodeHex, 'sha256', $sign);
         $calculatedSign = base64_encode(pack('H*', $signMac));
         // validate signature with the one in the notification
         if (strcmp($calculatedSign, $hmacSignature) == 0) {
             return true;
         } else {
             Mage::log('HMAC Calculation is not correct. The HMAC key in notifications is not the same as Calculated HMAC key. Please check if the HMAC key in notification is the same as magento settings. If not sure generate new HMAC code save notification and put the key in Magento settings as well.', Zend_Log::DEBUG, "adyen_notification.log", true);
             if (strtolower(substr($response->getData('pspReference'), 0, 17)) == "testnotification_" || strtolower(substr($response->getData('pspReference'), 0, 5)) == "test_") {
                 echo 'HMAC Calculation is not correct. The HMAC key in notifications is not the same as Calculated HMAC key. Please check if the HMAC key in notification is the same as magento settings. If not sure generate new HMAC code save notification and put the key in Magento settings as well.';
                 exit;
             }
         }
     } else {
         Mage::log('HMAC is missing in Notification.', Zend_Log::DEBUG, "adyen_notification.log", true);
         if (strtolower(substr($response->getData('pspReference'), 0, 17)) == "testnotification_" || strtolower(substr($response->getData('pspReference'), 0, 5)) == "test_") {
             echo 'HMAC is missing in Notification.';
             exit;
         }
     }
     return false;
 }
Exemplo n.º 30
0
 public function generateHmacKey($data, $apiKey = null)
 {
     $hmackey = Zend_Crypt_Hmac::compute($apiKey, "sha1", $data);
     return $hmackey;
 }