Skip to content

Instantly share code, notes, and snippets.

@AltiusRupert
Last active July 5, 2024 09:24
Show Gist options
  • Save AltiusRupert/0670513bb4a4a2c3af09d7d51633705a to your computer and use it in GitHub Desktop.
Save AltiusRupert/0670513bb4a4a2c3af09d7d51633705a to your computer and use it in GitHub Desktop.
Create Salesforce Named Credentials via Apex
// see https://salesforce.stackexchange.com/questions/165551/possible-to-update-namedcredential-from-apex
MetadataService.NamedCredential credential = new MetadataService.NamedCredential();
credential.fullName = 'Demo_Credential';
credential.label = 'Demo Credential';
credential.endpoint = 'https://www.DEMO2.com';
credential.principalType = 'NamedUser';
credential.protocol = 'NoAuthentication';
system.debug(createMetadata(credential));
system.debug(updateMetadata(credential));
// How to : "Named Credentials: How to Start OAuth flow?"
// https://salesforce.stackexchange.com/questions/139482/named-credentials-how-to-start-oauth-flow
// Warning : Salesforce bug refreshing Named Credentials (calling Salesforce) via OAuth2 flow
// Blog : https://www.gscloudsolutions.com/blogpost/Using-Named-Credentials-with-the-Apex-Wrapper-Salesforce-Metadata-API-apex-mdapi?blogpost=true
// Bug : "Oauth token does not auto refresh when the named credential is used with Salesforce SOAP API end-point" :
// https://help.salesforce.com/articleView?id=000264621&language=en_US&type=1
@ghoshdipan-ck
Copy link

Hi @AltiusRupert I don't think this works. Throwing the following error - Error: Line: 2, Column: 1
Error: Invalid type: MetadataService.NamedCredential

@RupertBarrow
Copy link

RupertBarrow commented Jul 5, 2024

Hi @ghoshdipan-ck ,

It looks like some of these fields (eg endpoint) were deprecated in API version 56.0 :
https://developer.salesforce.com/docs/atlas.en-us.api_meta.meta/api_meta/meta_namedcredential.htm

Have a look here to see if you can update this example for a more recent API version :
https://help.salesforce.com/s/articleView?id=sf.named_credentials_define.htm&type=5

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment