I need to do some batch processing (e.g. end-of-day posting of invoices) using server-side code with no user interaction.
So, how do a perform the Authentication dance in this scenario?
The guide ( https://developer.sage.com/api/accounting/guides/authentication/ ) and Postman examples both use redirection to a login page, where the user selects their country and enters their username and password. But in my server-side scenario, there is no user involved.
Do I need to handle the redirections and username/password in my server-side code? Is there some other way to get the token using client_id and client_secret?
Thanks for your help.
what you want to achieve is possible if you can give it an initial manual user interaction. Please, follow these steps:
1. Go through the Postman examples manually till you come to the point where you have an access token and a refresh token (i.e. finish section "2. Exchange the authorization code for the access token" in the guide). Alternatively, make the user go through the auth process in order to have him enter his password. In any case, at the end of this step you need to have a refresh token for later use in your batch job.
2. Save the refresh token on your server. From your server, whenever needed, issue a request to the OAuth service to exchange the refresh token for an access token as described in section "Renew an Access Token". This access token can now be used to make an API request. With this step, the first refresh token will become invalid, as it can only be exchanged for an access token once. But with in the response returning the new access token you will always get another new refresh token—save it and use it when repeating this step. You will have to repeat this step often, as the access token is valid only 5 minutes, whereas the refresh token is valid for 31 days.
Hope this helps; I am happy to give you further assistance if need be.
I implemented your suggestion and it works well.
I still wish that the Sage user could grant permission to the app (using the client_id) ahead of time, without being prompted for it later. That's not part of Oauth2, but it something that Sage could implement.
I am happy to read it works! The permission grant you suggest reminds me of e.g. the way Github does it ("Authorized Github Apps"). I will bring this up in the team discussion. Thank you!