3

Code:

global class CurrencyExchangeRateScheduler implements Schedulable
{
    public String sessionId;

    public CurrencyExchangeRateScheduler()
    {
        String username = 'username';
        String password = 'password+security_token';

        partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap();

        partnerSoapSforceCom.LoginResult loginResult = sp.login(username, password);

        sessionId = loginResult.sessionId;

    }

    global void execute(SchedulableContext ctx)
    {
        UpdateDailyCurrencyExchangeRate(sessionId);
    }

    @Future(callout=true)
    public static void UpdateDailyCurrencyExchangeRate(string sessionId)
    {
        system.debug('sessionId: '+sessionId);
        ...

        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setHeader('Authorization', 'OAuth ' + sessionId);
        req.setHeader('Content-Type', 'application/json');
        req.setMethod('POST');

        for(CurrencyType currType : currencies)
        {
            if(!currType.IsCorporate)
            {
                req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v28.0/sobjects/CurrencyType/'+currType.id+'?_HttpMethod=PATCH');

                req.setBody('{ "ConversionRate" : 2.5 }');

                HttpResponse response = h.send(req);    

                system.debug('response: '+response);
             }
        }
    }
}

Debug: response: System.HttpResponse[Status=Unauthorized, StatusCode=401]

I also tried with the Authorization header as Bearer + sessionId.

But again the same issue.

The code works perfectly fine when I am loggedin to the org. But when the class is scheduled and I am not loggedin, the response status is 'Unauthorized' and the currency table is not updated.

How can I get the session Id when User is not loggedin?

1
  • Swati -- you state elsewhere on this page that you tried within your @future to login and get a new sessionId. Please update your post to show how you did that and what results you get as that approach should work
    – cropredy
    Commented Sep 16, 2014 at 0:42

3 Answers 3

2

When you schedule a class its execution is postpone to the future time.

While actually executing it the session id you passed may not be valid, so you have 2 options.

1) Extended the session validity by -> Setup->Security Controls-> Session settings and set session time out to MAX (12 hours) (Hopefully your code will be extended in next 12 hours)

2) Modify your UpdateDailyCurrencyExchangeRate method to include login call.

@Future(callout=true)
public static void UpdateDailyCurrencyExchangeRate()
{

    String username = 'username';
    String password = 'password+security_token';

    partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap();

    partnerSoapSforceCom.LoginResult loginResult = sp.login(username, password);

    sessionId = loginResult.sessionId;

    system.debug('sessionId: '+sessionId);


    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setHeader('Authorization', 'OAuth ' + sessionId);
    req.setHeader('Content-Type', 'application/json');
    req.setMethod('POST');

    for(CurrencyType currType : currencies)
    {
        if(!currType.IsCorporate)
        {
            req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v28.0/sobjects/CurrencyType/'+currType.id+'?_HttpMethod=PATCH');

            req.setBody('{ "ConversionRate" : 2.5 }');

            HttpResponse response = h.send(req);    

            system.debug('response: '+response);
         }
    }
}
2
  • I had already implemented the option 1 but it didn't work.
    – Swati
    Commented Sep 17, 2014 at 5:59
  • I get a compilation error: Invalid type: partnerSoapSforceCom.Soap Commented Dec 13, 2016 at 10:44
1

The below link helps you to fix your issue. i too had previously same issue so i started a thread and got the solution. Check it once. SessionID problem in Schedule Batch class

3
  • This didnt work for me. I tried this solution also.
    – Swati
    Commented Sep 15, 2014 at 13:20
  • What error you are getting when you try this because it works perfectly for me.
    – sunny
    Commented Sep 16, 2014 at 6:49
  • I have the same issue with this approach. The code works perfectly fine when I am loggedin to the org. But when the class is scheduled and I am not loggedin, the response status is 'Unauthorized' and the currency table is not updated.
    – Swati
    Commented Sep 17, 2014 at 5:58
-1

If authentication error occurs as 401-Unauthorized Header, even after using the correct http headers, try replacing the org instance in the endpoint with instance_url returned from authentication token web callout.

        Http h1 = new Http();   
        HttpRequest req1 = new HttpRequest();
        **req1.setHeader('Authorization','Bearer '+ objAuthenticationInfo.access_token);**
        req1.setHeader('Content-Type','application/json');
        req1.setHeader('Accept','application/json');
        req1.setMethod('GET');
        req1.setEndpoint(objAuthenticationInfo.instance_url+'/services/data/v47.0/query/?q=SELECT+name+from+account');
        HttpResponse res1 = h1.send(req1);
1
  • This does not apply here. The user is not executing their own OAuth flow, and this code seems to be pasted from a very different context.
    – David Reed
    Commented Feb 17, 2020 at 3:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .