1

I'm using a third party api the requires the user to log in to get an authorization code and access token. I'm able to display the log in on a visualforce page. How can I update the variable on my page to display the html provided by the redirect url? To take it further, once I do all the required authorization, store the returned authorization code and access tokens in my org for later use.

enter image description here

The controller

public class Infusionsoft {

    public static String response {get; set;}

    public static void requestAuthorization(){ 

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

        req.setEndpoint('https://signin.infusionsoft.com/app/oauth/authorize'); 


        string bodyRequest = ''; 
        string bodyResponse = ''; 

        bodyRequest += 'client_id=*************************'; 
        bodyRequest += '&redirect_uri=https://****.infusionsoft.com/API/XMLRPC'; 
        bodyRequest += '&response_type=code';
        bodyRequest += '&scope=full';


        req.setBody(bodyRequest); 
        req.setHeader('Content-Type', 'application/x-www-form-urlencoded'); 
        req.setHeader('Content-length', string.ValueOf(bodyRequest.length())); 

        req.setMethod('POST'); 
        req.setTimeout(10000); 


        HttpResponse res = h.send(req); 
        boolean redirect = false;
        bodyResponse = res.getBody();

            if(res.getStatusCode() >=300 && res.getStatusCode() <= 307 && res.getStatusCode() != 306) {
                do {
                    redirect = false; // reset the value each time
                    String loc = res.getHeader('Location'); // get location of the redirect
                if(loc == null) {
                    redirect = false;
                    continue;
                }
                req = new HttpRequest();
                req.setEndpoint(loc);
                req.setMethod('POST');
                res = h.send(req);
                    if(res.getStatusCode() != 500) { // 500 = fail
                        if(res.getStatusCode() >=300 && res.getStatusCode() <= 307 && res.getStatusCode() != 306) {
                            redirect= true;
                        }
                        // I do special handling here with cookies
                        // if you need to bring a session cookie over to the
                        // redirected page, this is the place to grab that info
                    }
                } while (redirect && Limits.getCallouts() != Limits.getLimitCallouts());
            }
            //congratulations you're outside of the redirects now
            //read what you need from the res object

            System.debug(res.getBody())
            response = res.getBody();       
    } 

    public String getResponse(){
        return response;
    }
}

VF page

<apex:page controller="Infusionsoft" standardStylesheets="false">

    <apex:form>
        <apex:commandButton action="{!requestAuthorization}" value="Authorize Infusionsoft"/>
         <apex:outputText value="{!response}" escape="false" />
    </apex:form>

</apex:page>

Updated code

public static String response {get; set;}
public static String accessToken {get; set;}
public static String accessCode {get; set;}
public PageReference firstRedirect() {
    if( ApexPages.currentPage().getParameters().get('code') != null) {
        accessCode = ApexPages.currentPage().getParameters().get('code');
        System.debug('>>>>>>>accessCode: ' + accessCode);
        return secondRedirect();
    } 
    else {
        return new PageReference('https://signin.infusionsoft.com/app/oauth/authorize?client_id=**********************&redirect_uri=https://touchpointcrm--dev--c.cs19.visual.force.com/apex/InfusionsoftAuthorization&response_type=code&scope=full');
    }
}

public PageReference secondRedirect() {
    if( ApexPages.currentPage().getParameters().get('access_token') != null) {
        accessToken = ApexPages.currentPage().getParameters().get('access_token');
        return new PageReference('https://touchpointcrm--dev--c.cs19.visual.force.com/apex/InfusionsoftAuthorization');
    } else {
        return new PageReference('https://api.infusionsoft.com/token?client_id=********************&client_secret=*********='+ accessCode + '&grant_type=authorization_code&redirect_uri=https://touchpointcrm--dev--c.cs19.visual.force.com/apex/InfusionsoftAuthorization');
    }
}

Screen shot when I get the api url

enter image description here

1 Answer 1

6

That's not how OAuth is intended to be used. What you should be doing is calling that endpoint with a callback URL set to a VF page that can accept the OAuth parameters when successful.

Basically, this means that your page should start off like this:

<apex:page controller="xyz" action="{!firstRedirect}" ...>

Where firstRedirect determines if there's an access token, and determines what to do from there:

public PageReference firstRedirect() {
    if( ApexPages.currentPage().getParameters().get('access_token') != null) {
        // store the access token
    } else {
        return new PageReference('https://signin...');
    }
}

When the user first visits your page, they'll be redirected out to the signin server, and once they login and grant access, you'll get a token back. Make sure you set the callback URL to your VF page so your page can get the token.

5
  • I'm getting an error of "Non-void method might not return a value or might have statement after a return statement." in the if part of my statement. Also, your method is making me leave my entire org and going to a third party site. After I log in it will not redirect back to salesforce.
    – Tyler Zika
    Commented Sep 16, 2016 at 17:28
  • 1
    @TylerZika In the first half, where you store the access token, return null to avoid redirecting (or redirect elsewhere). Also, as far as the second comment, the oauth server will redirect back in to salesforce if you use the correct parameters. Check the manual for your service provider for how to provide a callback url.
    – sfdcfox
    Commented Sep 16, 2016 at 17:32
  • 1
    @TylerZika See this link in their documentation. Basically, provide a parameter like &redirect_uri=https://mydomain.instance.visual.force.com/apex/mypage, and it'll send you back into salesforce with your access token.
    – sfdcfox
    Commented Sep 16, 2016 at 17:49
  • you have been very helpful and I commend you for looking at docs that are not salesforce! I need to get the authorization code in the next redirect first before I get the access token. Trying to figure that out.
    – Tyler Zika
    Commented Sep 16, 2016 at 18:14
  • I update my post with a screen shot and with my current code. For some reason forwarding to the api url doesn't generate an access token even though i have all the parameters requests in the docs..
    – Tyler Zika
    Commented Sep 16, 2016 at 18:42

You must log in to answer this question.

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