Determining Salesforce Server Pod and if Sandbox via Apex

Recently, I’ve developed some apex classes that were doing callouts to external endpoints like CastIron and Worldpay. I was developing those in a sandbox and from that sandbox called to test endpoints. However, when that code was migrated to production, we obviously wanted those to point to the production endpoints. At first, I used Custom Settings to hold the endpoint value, but I had to change that each time I refreshed. I wanted to store both the test and production endpoints in the custom settings and have the code determine which to use based on if it was being called in a Sandbox or not. Unfortunately, there isn’t a IsSandbox() method in Apex. So, I figured out my own.

I started off using the X-Salesforce-Forwarded-To request header listed in the pagereference documentation because it gave me a consistent value for users accessing Salesforce via the standard interface, Partner Portal, and Sites. However, because you’re using ApexPages.currentPage(), this only works if the code is called from a page controller or extension. In my tests, I tried using URL.getSalesforceBaseUrl(), which can be called from regular classes, but it was inconsistent what was received. For example, I tried calling GetHost() and GetAuthority() from the system log and got cs12.salesforce.com. But with with internal and portal users, a visualforce page returned c.cs12.visual.force.com. Conversely, when using sites I received SiteName.SandboxName.cs12.force.com. So, my approach was determine which method to use based on where the call was coming from in order to get consistent results.

Parsing out the domains gave me the exact pod that I was on (ex NA1 or CS12) and from that I could determine if that pod was a sandbox or not from whether it started with a “c”. (You can see the full list of available Salesforce pods at http://trust.salesforce.com/trust/status/)