Some tips for doing OAuth Integration with Magento

I am not a PHP developer but recently I have been asked to build a Lambda service written in Ruby which calls Magento API via its OAuth Integration. That might sound simple because 3rd-party API integration is not something new and I have done lots of similar tasks before. However, that's not as easy as it looks.

Even though Magento has a detailed guideline and even an example of how to do it, but it's not 100% clear and I had to spend a great deal of time to fix issues found during the integration. I think it would be useful to put some important notes here so hopefully it would help some poor guys like me.

1. Pay attention to the permissions

If you read it here: https://devdocs.magento.com/guides/v2.4/get-started/create-integration.html, you will see that we need to create api.xml to define what resources the API has access to. Each resource will be defined like the following:

<resource name="Magento_Sales::reorder" />

The question is: Where can I find all resources and their permission?

Answer: In the Magento Admin, you can go to System -> User Roles (in Permission section), click on a particular role and select the Role Resources tab.

In the Resource Access dropdown, select "Custom". It should show you all the permissions in the Tree format. Inspect the HTML code of each permission and find the permission key there.

Another important thing: In Magento, resources are organized in hierarchical structure. It means if you need a specific permission, you have to list its containing permissions as well. For example, if you need the ability to fetch Orders from Magento, you would need to have all the following resources in the api.xml. This is of course from the tree I mentioned above.

Magento_Sales::sales
Magento_Sales::sales_operation
Magento_Sales::sales_order
Magento_Sales::actions
Magento_Sales::actions_view

2. Remove entry in database if you want to refresh the module code

If you have already installed a integration module and then you want to change something in module code (like updating its API permission as above), and you don't see any updates after running the setup command again, it could be because the module is cached and not reloaded. You have to access to the magento database and remove a specific entry from a table.

DELETE FROM `setup_module` WHERE module='Module_Name_Here';

Then run the usual commands to install the module

3. Delete token in database if you want to re-authorize

If you got an issue during the OAuth handshake (while exchanging for the refresh token and access token), it could be that the old tokens have been generated and stored in the database.

To make everything blank, you have to remove those tokens from the database

DELETE FROM oauth_token;