The named credential contain the URL of the callout endpoint and usually you would want to use different endpoints and authentication for sandboxes and production
A simple and easy way to make the named credentials more dynamic is to create named credentials for each environment and name them accordingly, for example appended with _DEV or _QA. If these named credentials are all in the production org then they will be copied automatically to the refreshed sandboxes with the correct credentials.
public static final String NAMED_CREDENTIAL = 'callout:namedCredentialName';
private static String sandboxNamespace {
get {
if (sandboxNamespace == null) {
if (!SystemUtils.isSandboxInstance()) {
sandboxNamespace = '';
} else {
if (MetadataUtils.getSandboxType() != 'qa') {
sandboxNamespace = '_DEV';
} else {
sandboxNamespace = '_QA';
}
}
}
return sandboxNamespace;
}
set;
}
@TestVisible
private static String getNamedCredentialEndpoint(String endpointName) {
return NAMED_CREDENTIAL + sandboxNamespace + endpointName;
}
}
The getNameCredentialEndpoint method can then be used in Apex to fetch the endpoint dynamically when setting up the HTTP callout
req.setEndpoint(getNameCredentialEndpoint('endpoint');

Leave a comment