How to handle token expiration in .NET Shopify applications

I’m working on a .NET application that integrates with Shopify using their .NET SDK. I managed to obtain an access token successfully, but I’m running into issues because the token appears to expire after a certain period.

My app includes a background service that needs to communicate with Shopify stores automatically, so I can’t rely on user interaction to renew authentication through a browser.

I need help with these options:

  1. Is it possible to obtain a long-lasting access token?
  2. Can I get a refresh token to generate new temporary tokens programmatically?

Additionally, I’m wondering if there’s a standard HTTP status code that indicates when a token has expired.

Any guidance would be appreciated!

For Shopify private apps, access tokens don’t actually expire unless you regenerate them manually in the admin panel. If you’re dealing with expiring tokens, you’re likely using a public app with OAuth authentication. In that case, Shopify doesn’t provide refresh tokens - once the merchant uninstalls or the token expires, you need to go through the OAuth flow again. Regarding HTTP status codes, you’ll typically receive a 401 Unauthorized when the token is invalid or expired. I’ve found it useful to implement a retry mechanism that detects 401 responses and triggers a re-authentication flow. For background services, consider switching to a private app if possible, as those tokens remain valid indefinitely. Otherwise, you’ll need to implement proper error handling and have a mechanism to notify the merchant when re-authentication is required.

I’ve encountered similar challenges when building automated Shopify integrations. The key distinction here is understanding which type of app you’re building. If you’re creating a custom app for your own store, you can generate admin API access tokens that don’t expire - these are perfect for background services since they remain valid until manually revoked. However, if you’re building a public app that other merchants will install, you’re stuck with OAuth tokens that can become invalid when merchants uninstall your app or revoke permissions. One approach I’ve used successfully is implementing a token validation check before making API calls. When you receive a 401 response, you can catch this in your background service and either attempt to refresh the connection or log the issue for manual intervention. Another consideration is using webhooks wherever possible to reduce the frequency of API calls from your background service, which minimizes the risk of hitting expired token issues during critical operations.