• SK9
  • NEWBIE
  • 0 Points
  • Member since 2017

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 3
    Questions
  • 2
    Replies
Hi, 
I am struggling with sending a REST Callout from one Salesforce org to another. I am not able to get the access token. Here is my code snippet - 
** Callback url in the connected app on target org - https://<domainName>.my.salesforce.com/services/oauth2/token


String clientId = 'consumer key  from the connected app in the target org';
String clientSecret = 'consumer secret from the connected app in the target org';
String username = 'my username in the target org';
String password = 'my password in the target org';

HttpRequest req = new HttpRequest();
Http h = new Http();
String reqbody = 'grant_type=password&client_id='+ clientId + '&client_secret='+clientSecret + '&username=' + username + '&password='+ password;
req.setMethod('POST'); 
req.setEndpoint('https://test.salesforce.com/services/oauth2/token'); 
HttpResponse res = h.send(req); 
System.debug(res.getBody()); 
deserializeResponse der = (deserializeResponse) JSON.deserialize(res.getBody(), deserializeResponse.class);
String accessToken = der.access_token;
**** I get an error Here - {"error":"invalid_grant","error_description":"authentication failure"}

HttpRequest req2 = new HttpRequest(); 
req2.setEndpoint('https://<domainName>.my.salesforce.com/services/apexrest/<RestResourceClassName>/<HttpPost method name>'); 
req2.setHeader('Authorization','Bearer ' + accessToken); 
req2.setHeader('Content-Type', 'application/json');
req2.setMethod('POST'); 
req2.setBody( body ); 
Http h2 = new Http(); 
HttpResponse res2 = h2.send(req2);
**** Second callout error is as a result of null access token i believe  - [{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]
 
  • March 31, 2019
  • Like
  • 0
Hi,
I am sending a Http Callout from Apex with a payload that contains data from multiple objects. When I test it, some of the records return success while some return this error - 
System.HttpResponse[Status=Unknown, StatusCode=851]"|0x7d9abad5
{"exception_cls":"InvalidServiceRequestException","exception_msg":"Something went wrong, please check logs."}
I am assuming there is something in the Payload data which Salesforce is not able to transmit properly. When I send the same payload via CURL it succeeds, so there is no error on the receiving end as well. How should I proceed with this? Here is a sample of my code - 
OpportunityCalloutHelper  ih = new OpportunityCalloutHelper();
        OpportunityCalloutHelper.ItineraryWrapper itiObj = ih.getItineraryWrapper(opp);
        String itiObjStr = JSON.serialize( itiObj );
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint(url);
        req.setMethod('POST');
        req.setBody(itiObjStr);
        req.setHeader('Content-Type', 'application/json');
        HttpResponse res = h.send(req);
  • March 20, 2019
  • Like
  • 0
Lightning form in force.com sites not inserting lead records. I had to create a Web to lead form in lightning and host it in force.com sites. Since force.com sites can include only visualforce pages, I created a VF page and included a lightning component in it. When I submit the form via force.com sites, it does not insert the record and no error is returned. However, if I host this same lightning component as a standalone component on Account layout, the records are getting inserted.

Visualforce page -
<apex:page standardStylesheets="false" showHeader="false" sidebar="false" standardController="Lead" >
   <apex:includeLightning />
    <div id="lightning" />
    <script>
    $Lightning.use("c:InquiryFormApp",    // name of the Lightning app
        function() {                  // Callback once framework and app loaded
            $Lightning.createComponent(
                "c:createLeadRecord", // top-level component of your app
                { },                  // attributes to set on the component when created
                "lightning",   // the DOM location to insert the component
                function(cmp) {
                    // callback when component is created and active on the page
                }
            );
        },
        '/AppInquiry'  // Community endpoint
    );
</script>                                              
</apex:page>

Lightning App -

<aura:application access="GLOBAL" extends="ltng:outApp" implements="ltng:allowGuestAccess">
    <aura:dependency resource="c:createLeadRecord"/> 
</aura:application>


Lightning component -

<!-- Include Static Resource-->

<!-- Define Attribute-->
<aura:attribute name="candidate" type="Lead" default="{'sobjectType': 'Lead',
                     'LastName': ''
                   }"/>
<div class="container-fluid">
    <h3>Please Enter The Candidate Information</h3>

    <div class="form-group">
        <label>Last Name</label>
        <ui:inputText class="form-control" value="{!v.candidate.LastName}"/>
    </div>


</div>
<div class="col-md-4 text-center">
    <ui:button class="btn btn-default" press="{!c.create}">Create</ui:button>

Lightning component controller -
({
    create : function(component, event, helper) {
        console.log('Create record');
        //getting the candidate information
        var candidate = component.get("v.candidate");
        //Calling the Apex Function
        var action = component.get("c.createRecord");
        //Setting the Apex Parameter
        action.setParams({
            candidate : candidate
        });

        //Setting the Callback
        action.setCallback(this,function(a){
            //get the response state
            var state = a.getState();
            //check if result is successfull
            if(state == "SUCCESS"){
                //Reset Form
                var newCandidate = {'sobjectType': 'Lead',
                                    'LastName': ''
                                   };
                //resetting the Values in the form
                component.set("v.candidate",newCandidate);
                alert('Record is Created Successfully');
            } else if(state == "ERROR"){
                alert('Error in calling server side action');
            }
        });

        //adds the server-side action to the queue        
        $A.enqueueAction(action);

    }
})

Apex controller -
global class CreateLeadRecord {
    /**
   * Create a new lead Record
   *
   * @param Lead candidate  candidate record to be inserted
   * 
   */  
    @AuraEnabled
    public static void createRecord (Lead candidate){

        try{
            System.debug(': CreateCandidateRecord::createRecord::candidate'+candidate);

            if(candidate != null){
                insert candidate;
            }

        } catch (Exception ex){
            system.debug(': exception is-'+ex.getMessage());
        }
        //return candidate.Id;
    }
Please suggest something by which I'll be able to create a Web to Lead form using Lightning and Force.com Sites.
 
  • November 27, 2017
  • Like
  • 0
Hi, 
I am struggling with sending a REST Callout from one Salesforce org to another. I am not able to get the access token. Here is my code snippet - 
** Callback url in the connected app on target org - https://<domainName>.my.salesforce.com/services/oauth2/token


String clientId = 'consumer key  from the connected app in the target org';
String clientSecret = 'consumer secret from the connected app in the target org';
String username = 'my username in the target org';
String password = 'my password in the target org';

HttpRequest req = new HttpRequest();
Http h = new Http();
String reqbody = 'grant_type=password&client_id='+ clientId + '&client_secret='+clientSecret + '&username=' + username + '&password='+ password;
req.setMethod('POST'); 
req.setEndpoint('https://test.salesforce.com/services/oauth2/token'); 
HttpResponse res = h.send(req); 
System.debug(res.getBody()); 
deserializeResponse der = (deserializeResponse) JSON.deserialize(res.getBody(), deserializeResponse.class);
String accessToken = der.access_token;
**** I get an error Here - {"error":"invalid_grant","error_description":"authentication failure"}

HttpRequest req2 = new HttpRequest(); 
req2.setEndpoint('https://<domainName>.my.salesforce.com/services/apexrest/<RestResourceClassName>/<HttpPost method name>'); 
req2.setHeader('Authorization','Bearer ' + accessToken); 
req2.setHeader('Content-Type', 'application/json');
req2.setMethod('POST'); 
req2.setBody( body ); 
Http h2 = new Http(); 
HttpResponse res2 = h2.send(req2);
**** Second callout error is as a result of null access token i believe  - [{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]
 
  • March 31, 2019
  • Like
  • 0