[SalesForce] How to redirect to external url from apex from callout response

I have a class from which I do a callout in apex. After the response of the callout I want to redirect the user to an external url how can I achieve this?.

I have only been able to redirect independent of the callout. In my example below I want to redirect to returnURl instead of 'https://www.goole.com'

public class leadgen {
    private final Lead weblead;  
    public Payment_Hub(ApexPages.StandardController stdController) {
        weblead = (Lead)stdController.getRecord();
    public PageReference saveLead() {
        try {
        catch(System.DMLException e) {
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error'));
            return null;
        PageReference p = new PageReference('https://www.goole.com');
        return p;

    public static void PostPayment(Id LeadId) {
        //Catch is not needed since soql's cant be empty in this case 
        List<obj> ..

        Http http = new Http();
        HttpRequest request = new HttpRequest();
        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 {
            JSON payClass = JSON.parse(response.getBody());

            system.debug('returnURl: '+ payClass.links.checkout.href);
            string returnURl = payClass.links.checkout.href;

Best Answer

Well, first of all you have to ditch the future. :) Considering its a VF Page.

Split the operation in 2 chunks that can happen in independently.

1) DML

2) Callout without future.

Now define an action function that does the callout.

Apex Command Button has an oncomplete attribute which invokes JS when the result of an AJAX update request completes on the client.

So on click of commandbutton you save the record, and then oncomplete calls the actionfunction which does the callout. As you have broken the transaction by coming back to JS . You can then do callout as its a different transaction.

To end user, it would just look like a normal button click.

EDIT : On googling i got an example of this on this blog.