In this blog we will learn how we can create a web service resource and grant permission to this resource using code in PrestaShop 1.7.
Sometimes we don’t have access to the Web Services tab on the Advanced Settings > Web Services page. So we can manage things related to web services in sign code. Let’s understand things with code.
As we know, if we want to add a new web service resource in PrestaShop 1.7, then we need to register a hook.
$this->registerHook('addWebserviceResources');
After this, we need to register the resource using this hook.
/** * Add a specific_management resource * This hook is only in PS17 * * @param array $resources * @return void */ public function hookAddWebserviceResources($params) $params['resources']['RESOURCE_NAME'] = array('description' => 'RESOURCE_DESCRIPTION'); return $params['resources'];
If the resource is associated with a specific management, follow the code below
public function hookAddWebserviceResources($params) $params['resources']['RESOURCE_NAME'] = array('description' => 'RESOURCE_DESCRIPTION', 'specific_management' => true); return $params['resources'];
Now we need to add some custom code to your install function to handle things at runtime during module installation.
public function install() !$this->registerHook('addWebserviceResources') ) return false; Configuration::updateValue('PS_WEBSERVICE', 1); // Code added to enable prestashop webservice $apiAccess = new WebserviceKey(); $apiAccess->key = $this->generateWebserviceKey(32); // Function to generate 32 character alphanumeric ws key $apiAcesss->save(); $account_id = $apiAccess->id; $permissions = array( 'RESOURCE_NAME' => ['GET' => 1, 'POST' => 1, 'PUT' => 1, 'DELETE' => 1, 'HEAD' => 1] ); $response = WebserviceKey::setPermissionForAccount($apiAccess->id, $permissions); return true; // Custom function to generate 32 character alphanumeric ws key function generateWebserviceKey($length) $key = ''; $keys = array_merge(range(0, 9), range('a', 'z')); for ($i = 0; $i < $length; $i++) $key .= $keys[array_rand($keys)]; return strtoupper($key);
Now you can see that the web service key and permission are automatically generated when we install the module.
That’s all this blog is about. I hope it helps you.
If you face any problems or doubts in the above procedure, feel free to contact us through the comment section.
You can also explore our PrestaShop development services and a large selection of quality PrestaShop modules.
For any doubts, contact us at [email protected]