1

I am trying to create account from one salesforce instance to another. Below are the configration i did.

SF 1 instance -

I created an apex rest serevice:

@RestResource(urlMapping='/Account/*')
global with sharing class MyRestResource {

  @HttpPost
    global static String doPost(String name,
        String phone, String website) {
        Account account = new Account();
        account.Name = name;
        account.phone = phone;
        account.website = website;
        insert account;
        return account.Id;
    }
}

Connected App setting - enter image description here

SF 2 instance -

Apex Class -

public class Apex_Rest_DemoController {

    public String response{get;set;}
    public String accName{get;set;}
    public String accPhone{get;set;}
    public String accWebsite{get;set;}

    public PageReference CreateAccount() {
    //find access token using Auth 2.0 
    String Access_Token='3MVG9ZL0ppGP5UrALttsUDH0KHNDNtwEUY9mZplPcSE5WktD5rRloVwv.8TEYtaSPkyWGjzQUZCLofRAzwZEU';
    Httprequest req=new httprequest();
    String domainName='ap2.salesforce.com';
    String endPointURL='https://'+domainName+'/services/data/v34.0/sobjects/Account';
    req.setendpoint(endPointURL);
    req.setHeader('Content-Type', 'application/xml; charset=utf-8');
    req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+accName+'</name><phone>'+accPhone+'</phone><website >'+accWebsite+'</website > </request>');
    req.setmethod('POST');
    req.setHeader('Authorization','Authorization: Bearer '+Access_Token);
    Http http = new Http();
    HTTPResponse res = http.send(req);
    response=res.getbody();
    System.debug('****************res.getStatusCode();'+res.getStatusCode());
    System.debug('****************res.getbody();'+res.getbody());
    return null;
    }
}

VF Page -

<apex:page controller="Apex_Rest_DemoController">
<apex:form >
<apex:pageBlock >
<apex:pageBlockButtons >
    <apex:commandButton value="Create Account in SF1 instance" action="{!CreateAccount}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection >
    <apex:pageBlockSectionItem >
    <apex:outputLabel for="aname" value="Name"></apex:outputLabel>
    <apex:inputText value="{!accName}" id="aname"/>
    </apex:pageBlockSectionItem>
    <apex:pageBlockSectionItem >
    <apex:outputLabel for="aphone" value="Phone"></apex:outputLabel>
    <apex:inputText value="{!accPhone}" id="aphone"/>
    </apex:pageBlockSectionItem>
    <apex:pageBlockSectionItem >
    <apex:outputLabel for="aw" value="Website"></apex:outputLabel>
    <apex:inputText value="{!accWebsite}" id="aw"/>
    </apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>

<apex:pageBlock title="Response">
<apex:pageBlockSection >
    <apex:outputText value="{!Response}"></apex:outputText>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Remote site settings -

Remote Site URL https://ap2.salesforce.com

When i click the button i am getting response error -

[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]

Please help me where i am doing wrong.

Regards

  • How did you get access token ? – Mohith Shrivastava Jul 18 '15 at 14:27
  • Access token means security token...I hvnt used it here.. Please let me know how to use it in rest api...I have used cosumer key from connected app as access token in my code – hellraizer Jul 18 '15 at 16:30
1

The first issue I see is that you need to add the "access and manage your data (API)" scope.

Next, I'm not sure where the following token came from:

 //find access token using Auth 2.0 
    String Access_Token='3MVG9ZL0ppGP5UrALttsUDH0KHNDNtwEUY9mZplPcSE5WktD5rRloVwv.8TEYtaSPkyWGjzQUZCLofRAzwZEU';

You can't hard code the token as it will expire. You need to go through the oAuth flow. This pretty much requires that the action is always initiated directly by a user on a VF page (as they must login to salesforce to prove their identity).

There is a special type of oAuth flow meant for applications where the token is only retrieved once by the user and then refreshed by the application when it expires. I have never done this on SF so I can't really give more info on it.

If this needs to be called from a trigger or scheduled process it will likely be easier to use the the Partner Id to obtain a Session Token instead of oAuth. This article explains the process start to finish.

1

Here is an example controller that one of my test VF pages uses to test the oAuth flow. Other classes can use it as well to authorize, the connected app uses the sample vf page as the callback:

    public class oAuth_Controller{

    private auth_response rt;

    public pagereference auth_Step_1(){


        String auth_url = 'https://login.salesforce.com/services/oauth2/authorize';
        String params =  
                            '?response_type=code' +
                            '&client_id=' + encodingUtil.urlencode('YOURCLIENTID','UTF-8') +
                            '&redirect_uri=https://na1.salesforce.com/apex/{YOURVFPAGE}' +                           '&prompt=consent' + 
                            '&scope=' + encodingUtil.URLEncode('full refresh_token','UTF-8') +
                            '&state=step2';
            pageReference pr = New PageReference(auth_url + params);
            return pr;
    }

    public pagereference auth_Step_2(){

        if(apexPages.currentPage().getParameters().get('state') != 'step2')
            return null;


        HttpRequest req = new HttpRequest();
        Http http = new Http();

        String auth_url = 'https://login.salesforce.com/services/oauth2/token';
        String params =  
                            '?code=' + apexPages.currentPage().getParameters().get('code') +
                            '&grant_type=authorization_code' + 
                            '&client_id=' + encodingUtil.urlencode('YOURCLIENTID','UTF-8') +
                            '&client_secret=YOURSECRET' + 
                            '&redirect_uri=https://na1.salesforce.com/apex/YOURVFPAGENAME';

        req.setMethod('POST');
        req.setEndpoint(auth_url + params);

        HTTPResponse resp = http.send(req);

        rt = (auth_response)json.deserialize(resp.getBody(),auth_response.class);
        //Do something with the results
        return null;

    }

    public void getnewtoken(){

        HttpRequest req = new HttpRequest();
        Http http = new Http();

        String auth_url = 'https://login.salesforce.com/services/oauth2/token';
        String params =  

                            '?grant_type=refresh_token' + 
                            '&client_id=' + encodingUtil.urlencode('YOURCLIENTID','UTF-8') +
                            '&client_secret=YOURSECRET' + 
                            '&refresh_token=' + encodingUtil.URLEncode(YOURREFRESHTOKEN,'UTF-8');

        req.setMethod('POST');
        req.setEndpoint(auth_url + params);

        HTTPResponse resp = http.send(req);


    }

/*******************************************
*
*   Revoke refresh token
*
*******************************************/


public static void revoke_refresh_token(){


    HttpRequest req = new HttpRequest();
    Http http = new Http();

    req.setMethod('GET');
    req.setEndpoint(podProtocolAndHost + '/services/oauth2/revoke?token=' + EncodingUtil.URLEncode(REFRESHTOKENTOREVOKE,'UTF-8'));


    HTTPResponse resp = http.send(req);

}


    private class auth_response{

        public string refresh_token;
        public string access_token;

    }


}

The Sample VF page looks like this:

<apex:page controller="oAuth_Controller" action="{!auth_step_2}">
  <apex:form >
  <apex:commandButton action="{!auth_step_1}" value="click" rerender="msgs"/>
  <apex:commandButton action="{!getit}" value="click2" rerender="msgs"/>
  <apex:commandButton action="{!revoke_it}" value="click3" rerender="msgs"/>
  </apex:form>
  <!-- Begin Default Content REMOVE THIS -->
  <apex:outPutPanel id="msgs">
      {!$CurrentPage.parameters.access_token}
  </apex:outPutPanel>
</apex:page>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.