function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
D VelD Vel 

Named Credentials not working for my Rest Callout

I am trying to understand how to set up the Named Credentials & OAuth Provider in Salesforce for calling the External REST API. Before setting this up I tested the call to the REST API through Apex like and it works fine
public class TestD365API {
    public final String clientId = 'xxxxxxx';
    public final String clientSecret = 'xxxxxx';
    public final String tenant_id = 'xxxx';
    public final String resource = 'https://abc.dynamics.com';

    public String getD365Customer(){             
        String reqbody = 'grant_type=client_credentials&client_id='+clientId+'&client_secret='+clientSecret+'&tenant_id='+tenant_id+'&resource='+resource;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqbody);
        req.setMethod('POST');
        req.setEndpoint('https://login.microsoftonline.com/tenant/oauth2/token');
        HttpResponse res = h.send(req);
        deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
        String atoken = resp1.access_token;
        System.debug('Access Token=========' + atoken);

        Http http1 = new Http();
        HttpRequest req1 = new HttpRequest();
        req1.setEndpoint('https://abc.dynamics.com/data/Customers');
        req1.setMethod('GET');
        req1.setHeader('Authorization','Bearer '+atoken);
        HttpResponse res1 = http1.send(req1);
        System.debug('Response Body=========' + res1.getBody());
        return res1.getBody();                
    }  

    public class deserializeResponse
    {
        public String token_type;
        public String expires_in;
        public String ext_expires_in;
        public String expires_on;
        public String not_before;
        public String resource;
        public String access_token;
    }
}
I am passing 5 parameters in the request body to get the bearer token from the Authorization Provider and passing the token to the Rest endpoint and retrieving the data back.
Now trying to use Named credentials instead like below
User-added imagewhere in the Authorize URL I am giving as https://login.microsoftonline.com/tenant/oauth2/authorize?grant_type=client_credentials&tenant_id=xxxxxxxxxxx
And changed my Apex Code like

User-added image​​​​​​​I am not sure how to pass all the parameters (grant_type,tenant_id, client_id,client_secret,resource) to the Auth Provider and the bearer token to the Rest API endpoint through Named Credentials and get the response back. I am sure this is not the firewall/issue on Client end as I am able to test it through Apex Code. Any help is appreciated.
 
Syed Sajjad 20Syed Sajjad 20
Hi All,( Pls help)


I would like to send information (from lead to an external system). I am doing a HTTP POST from salesforce. But getting a 400 Bad Request. Not sure what the issue is?
I have added my end point to the remote site settings as well. 
Not sure if the way I am setting the header right? Please advice. 

Below is the code that I use from my class. 

public class SendToBubble {
public Lead Ld;

    public SendToBubble(ApexPages.StandardController controller) {
        
        
        this.Ld = (Lead)controller.getRecord();
        
         Ld = [Select Id,Lead.Goal_CSA_Score__c, Lead.CSA_Score__c, Lead.of_Tires_Replaced__c,Savings_Fuel_Card__c,Lead.Drivers_Replaced__c, Where_Buy_Fuel__c, Gallons_per_Month__c, FirstName, LastName, Bubble_UID__c, ENT_UNITS_EST_PWR__c, Phone, Email, Company, ENT_PHY_STATE__c  from Lead where Id =: Ld.Id];
   
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        
        request.setEndpoint('https://tvc-roi-calculator.bubbleapps.io/version-test/api/1.1/wf/createProspectFromSFDC');
        
        request.setHeader('Authorization', 'Bearer ' + 'b477fbcc6b11d818d4e0187c03bdabfb');
        
        request.setHeader('Content-Type', 'application/json;charset=UTF-8');
        request.setHeader( 'Accept', 'application/json' );

        
        request.setMethod('POST');
        
        
        JSONGenerator gen = JSON.createGenerator(true);   
        gen.writeStartObject();   
        
        If(Ld.FirstName!=null){
        gen.writeStringField('First Name ', Ld.FirstName);
        }
        
        If(Ld.LastName!=null){
        gen.writeStringField('Last Name',Ld.LastName);
        }
        
        If(Ld.Company!=null){
        gen.writeStringField('Company Name',Ld.Company);
        }
        
        If(Ld.Phone!=null){
        gen.writeStringField('Phone ', Ld.Phone);
        }
        
        If(Ld.Email!=null){
        gen.writeStringField('Email',Ld.Email);
        }
        
        If(Ld.ENT_PHY_STATE__c!=null){
        gen.writeStringField('State',Ld.ENT_PHY_STATE__c);
        }
        // new fields
       
        if(Ld.ENT_UNITS_EST_PWR__c != null){
        gen.writeNumberField('ESTIMATED VEHICLES', Ld.ENT_UNITS_EST_PWR__c);
        }
        
        if(Ld.Where_Buy_Fuel__c != null){
        gen.writeStringField('Where Buy Fuel', Ld.Where_Buy_Fuel__c);
        }
        
        if(Ld.Gallons_per_Month__c != null){
        gen.writeNumberField('Gallons per Month', Ld.Gallons_per_Month__c);
        }
        
        if(Ld.Drivers_Replaced__c != null){
        gen.writeNumberField('# Drivers Replaced', Ld.Drivers_Replaced__c);
        }
        
        if(Ld.Savings_Fuel_Card__c != null){
        gen.writeStringField('Savings-Fuel Card', Ld.Savings_Fuel_Card__c);
        }
        
        if(Ld.of_Tires_Replaced__c != null){
        gen.writeNumberField('# of Tires Replaced', Ld.of_Tires_Replaced__c);
        }
        
        if(Ld.CSA_Score__c != null){
        gen.writeNumberField('CSA Score', Ld.CSA_Score__c);
        }
        
        if(Ld.Goal_CSA_Score__c != null){
        gen.writeNumberField('Goal CSA Score', Ld.Goal_CSA_Score__c);
        }
      
        If(Ld.Id!=null){
        gen.writeStringField('Lead ID',Ld.Id);
        }
        
        gen.writeEndObject();   
        String jsonS = gen.getAsString();
        System.debug('jsonMaterials'+jsonS);
        // Set the body as a JSON object
        request.setbody(jsonS);
   
   
        system.debug('MGMMGM'+jsonS);
        
        HttpResponse response = http.send(request);
        // Parse the JSON response
        if (response.getStatusCode() != 201) {
            System.debug('The status code returned was not expected: ' +
                response.getStatusCode() + ' ' + response.getStatus());
        } else {
            System.debug('SYEDSYED'+response.getBody());
        }
        
        }
        
        public pagereference Redirect(){
        
        PageReference vfPage1 = new PageReference('https://tvc-roi-calculator.bubbleapps.io/version-test/fleet_calculator_sales?uid='+Ld.Bubble_UID__c);
        vfPage1.setRedirect(true);
        return vfPage1;
        
        } 

}