18

This is the code that I'm using to get the value from a specific field saved via the admin panel.

protected $_paymentData;
protected $_scopeConfig;
protected $logger;

public function __construct(
    \Magento\Framework\Model\Context $context,
    \Magento\Framework\Registry $registry,
    \Magento\Framework\Api\ExtensionAttributesFactory $extensionFactory,
    \Magento\Framework\Api\AttributeValueFactory $customAttributeFactory,
    \Magento\Payment\Helper\Data $paymentData,
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    \Magento\Payment\Model\Method\Logger $logger,
    \Magento\Framework\Module\ModuleListInterface $moduleList,
    \Magento\Framework\Stdlib\DateTime\TimezoneInterface $localeDate,
    \Magento\Directory\Model\CountryFactory $countryFactory,
    \Stripe\Stripe $stripe,
    \Inchoo\Stripe\Model\StripeFactory $stripeFactory,
    array $data = array()
) {
    parent::__construct(
        $context,
        $registry,
        $extensionFactory,
        $customAttributeFactory,
        $paymentData,
        $scopeConfig,
        $logger,
        $moduleList,
        $localeDate,
        null,
        null,
        $data
    );
    $this->_scopeConfig = $scopeConfig;
    $this->logger = $logger;
    $this->initializeData($data);
}
 public function getPaymentKey(){
   $key= $this->_scopeConfig->getValue('payment/webpay/keyid');
    echo $key;
    exit; 
}

Echo Result: idfrk3-45pfnrkhwneirgplbmisniepssnie:hirtw45

True Key: p92GBhcQl7TklHOsWcxBk4eOmL6wpQWBG9nT2Qcf

6 Answers 6

40

\Magento\Framework\App\Config\ScopeConfigInterface::getValue will return the decrypted value. When ScopeConfigInterface::getValue returns an encrypted value, the configuration option is setup incorrectly. A correct implementation of an encrypted configuration value is:

Vendor/Module/etc/adminhtml/system.xml

Here we add an obscure configuration value in the path payment/webpay/keyid the critical things here is ensuring the field has type="obscure" and uses Magento\Config\Model\Config\Backend\Encrypted for the backend_model. This is how Magento knows to use a masked form field and encrypt any user input on save.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <section id="payment">
            <group id="webpay">
                <field id="keyid" translate="label" type="obscure" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="0">
                    <label>Key Id</label>
                    <backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
                </field>
            </group>
        </section>
    </system>
</config>

Vendor/Module/etc/config.xml

Adding backend_model="Magento\Config\Model\Config\Backend\Encrypted" here tells Magento the config value should be decrypted when retrieved with ScopeConfigInterface::getValue

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <payment>
            <webpay>
                <keyid backend_model="Magento\Config\Model\Config\Backend\Encrypted" />
            </webpay>
        </payment>
    </default>
</config>

Vendor/Module/etc/di.xml

This adds the configuration path to the sensitive array and prevents the path's value from being included when dumping the store configuration.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Config\Model\Config\TypePool">
        <arguments>
            <argument name="sensitive" xsi:type="array">
                <item name="payment/webpay/keyid" xsi:type="string">1</item>
            </argument>
        </arguments>
    </type>
</config>
3
  • 2
    There seem to be some scenarios where this doesn't work, in my case it was working before and it broke after I moved the field into an included group xml config. The above suggestions were implemented, but not working
    – snez
    Apr 8, 2019 at 10:43
  • @snez have you tried to re-save the configuration after you moved it? Aug 14, 2019 at 13:24
  • pushing up as if the config path is not declared to sensitive, Magento\Framework\App\Config\Storage\WriterInterface unable to save proper obscured value to the database without using Magento\Framework\Encryption\EncryptorInterface when creating data patches
    – Mammouth
    Jan 17, 2022 at 15:11
34

Finally Get Success In Decrypt code...

protected $_encryptor;

public function __construct(
    \Magento\Framework\Encryption\EncryptorInterface $encryptor,
) {
    $this->_encryptor = $encryptor;
    parent::__construct($context);
}
$test = 'dfrk3-45pfnrkhwneirgplbmisniepssnie';
$test = $this->_encryptor->decrypt($test);
echo $test;

Share and help others..

3
  • It returns blank value. How can i get output in readable format? Jun 1, 2018 at 7:06
  • can you share issue code? Jul 13, 2018 at 7:03
  • This is not the best approach. This should be fixed through configuration as described in answer of Pmclain. Apr 24 at 8:51
25

If you have n98-magerun2.phar installed, you can get a decrypted config value with something like:

php bin/n98-magerun2.phar config:store:get --decrypt payment/webpay/keyid

You can also set encrypted config values from the command line with something like:

php bin/n98-magerun2.phar config:store:set --encrypt payment/webpay/keyid NEW_KEY_ID_VALUE_HERE

You can get n98-magerun2.phar from here: https://github.com/netz98/n98-magerun2

2
  • 6
    isn't n98 the greatest thing ? Apr 12, 2019 at 6:20
  • 2
    This also works in n98-magerun (for Magento 1) Feb 14, 2020 at 3:37
2

In case you want to decrypt some value using some key. Put below code into decrypt-config-value.php in the root of your magento project. This code need 2 constants to work properly

  1. ENV_CRYPT is the environment crypt key, you can find this in the file app/code/env.php. Remember EACH environment has a different key, so you CAN'T get the production value with the staging key. You MUST use the production key to get production values. Line 21.

  2. PATH_ENC_DATA is the path where the encrypted variable is saved. Line 24.

<?php

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');


######################################################################################################################

/**
 * ONLY 2 REQUIREMENTS
 */
// Available in the file: app/etc/env.php crypt => key =>
const ENV_CRYPT = 'e601ed01ef0c5a8766d373fdc4f8b23d';

//Path where is located the encrypted data
const PATH_ENC_DATA = 'path/to_encrypted/data';

/**
 * @var \Magento\Framework\Encryption\EncryptorInterfaceFactory $ef
 */
$ef = $objectManager->get('Magento\Framework\Encryption\EncryptorInterfaceFactory');

class CustomDeploymentConfig extends \Magento\Framework\App\DeploymentConfig
{
    public function get($key = null, $defaultValue = null)
    {
        return ENV_CRYPT;
    }
}

/**
 * @var CustomDeploymentConfig $d
 */
$d = $objectManager->get(CustomDeploymentConfig::class);

/**
 * @var \Magento\Framework\Encryption\EncryptorInterface $e
 */
$e = $ef->create(['deploymentConfig' => $d]);

$resourceConnection = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resourceConnection->getConnection();
$query = "SELECT value FROM core_config_data WHERE path = '" . PATH_ENC_DATA . "';";
$result = $connection->fetchOne($query);

echo ">>>", $e->decrypt($result), "<<<\n";

Run php decrypt-config-value.php using console.

0

You can try with below method for payment encryption method to get value,

You have to replace \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig, with below class path, \Magento\Payment\Gateway\ConfigInterface This is works fine,

   <?php
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Vendor\Module\Gateway\Http;

use Magento\Payment\Gateway\Http\TransferBuilder;
use Magento\Payment\Gateway\Http\TransferFactoryInterface;
use Magento\Payment\Gateway\Http\TransferInterface;
use Magento\Payment\Gateway\ConfigInterface;

class TransferFactory implements TransferFactoryInterface
{
    private $config;

    private $transferBuilder;

    public function __construct(
        ConfigInterface $config,
        TransferBuilder $transferBuilder
    ) {
        $this->config = $config;
        $this->transferBuilder = $transferBuilder;
    }


    public function getPaymentKey()
    {
        echo $this->config->getValue('payment/webpay/keyid')
    }
}
7
  • Is this work for you? Jul 11, 2016 at 11:28
  • Fatal error: Cannot instantiate interface Magento\Payment\Gateway\ConfigInterface in E:\wamp\www\magento2_8\vendor\magento\framework\ObjectManager\Factory\Dynamic\Developer.php on line 73 Jul 11, 2016 at 11:35
  • have you solved problem? Jul 11, 2016 at 12:01
  • no getting Fatal error: Cannot instantiate interface Magento\Payment\Gateway\ConfigInterface in E:\wamp\www\magento2_8\vendor\magento\framework\ObjectManager\Factory\Dynamic\De‌​veloper.php on line 73 error. Jul 11, 2016 at 12:02
  • try with above updated code and remove var folder. Jul 11, 2016 at 12:07
-1

Try with below code for json decode value,

class Paymentmodule
{
    protected $jsonEncoder;
    protected $jsonDecoder;

    public function __construct(
        ..//
        \Magento\Framework\Json\DecoderInterface $jsonDecoder
    ) {
        ..//
        $this->jsonDecoder = $jsonDecoder;
    }

    public function getPaymentKey()
    {
        $key= $this->_scopeConfig->getValue('payment/webpay/keyid');
        $config = $this->jsonDecoder->decode($key);
        echo $key;
    }

}
12
  • 1
    Decoding failed: Syntax error";i:1;s:10720:"#0 E:\wamp\www\magento2_8\vendor\magento\framework\Json\Decoder.php(20): Zend_Json::decode('0:2:234SyEIM4aj...') #1 E:\wamp\www\magento2_8\vendor\magento\module-checkout\Controller\Onepage\Success.php(58): Magento\Framework\Json\Decoder->decode('0:2:234SyEIM4aj...') Jul 11, 2016 at 10:40
  • any idea about this error? Jul 11, 2016 at 10:47
  • i have no idea about it, because this is for payment method, i have worked for above method for simple query Jul 11, 2016 at 10:48
  • syntax error i think define another types. Jul 11, 2016 at 10:51
  • working fine in simple query?? Jul 11, 2016 at 10:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.