In Magento 2, you can use the built-in functionality to store and retrieve custom configuration values. This is a good place to store your API access token. Here's how you can do it:
- Create a new system.xml file in your module to add a new field in the Magento admin panel where you can input your API token.
<!-- File: app/code/Vendor/Module/etc/adminhtml/system.xml -->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<section id="your_section">
<group id="your_group">
<field id="api_token" translate="label" type="obscure" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
<label>API Token</label>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
</field>
</group>
</section>
</system>
</config>
Now you can set the API token in the Magento admin panel under Stores > Configuration > Your Section > Your Group > API Token.
To retrieve the API token in your code, you can use the ScopeConfigInterface:
<?php
namespace Vendor\Module\Model;
class YourClass
{
protected $scopeConfig;
protected $encryptor;
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Framework\Encryption\EncryptorInterface $encryptor
) {
$this->scopeConfig = $scopeConfig;
$this->encryptor = $encryptor;
}
public function getApiToken()
{
$encryptedToken = $this->scopeConfig->getValue(
'your_section/your_group/api_token',
\Magento\Store\Model\ScopeInterface::SCOPE_STORE
);
return $this->encryptor->decrypt($encryptedToken);
}
}
Remember to replace Vendor, Module, your_section, your_group, and YourClass with your actual vendor name, module name, section ID, group ID, and class name.
Also, to set a configuration value programmatically in Magento 2,
you can use the
Magento\Framework\App\Config\Storage\WriterInterface and Magento\Framework\App\Config\ScopeConfigInterface classes.
Example:
<?php
namespace Vendor\Module\Model;
class YourClass
{
protected $configWriter;
public function __construct(
\Magento\Framework\App\Config\Storage\WriterInterface $configWriter
) {
$this->configWriter = $configWriter;
}
public function setApiToken($value)
{
$this->configWriter->save(
'your_section/your_group/api_token',
$value,
$scope = \Magento\Framework\App\Config\ScopeConfigInterface::SCOPE_TYPE_DEFAULT,
$scopeId = 0
);
}
}
The save method takes four parameters:
the path of the configuration value, the value to save, the scope of the configuration value (default, websites, or stores), and the ID of the scope.