function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
piya_tonpiya_ton 

Need help for currency converter

I would like to convert the amount from USD to local currency if the opportunity stage is closed won.

 

The following website which I would like to connect with, http://www.webservicex.net/CurrencyConvertor.asmx?op=ConversionRate, how can I connect to the website.

 

I am quite new for developer. Here is the code when I tried:

 

trigger CurrencyConversion on Opportunity (after update) {
    if(opp.StageName == 'Closed Won')
    {
       
    }
}

 

Thanks,

Tony

spraetzspraetz

You cannot do callouts to external sites within a trigger context.  So you will need to write a @future method with callouts=true which will be invoked by the trigger to do the callout and record update for you.

 

To learn more about callouts, check out the HTTP methods in the Apex doc. 

 

Here is a skeleton of the @future method that you will need to invoke from your Apex Trigger:

 

public class Util{
    @Future(callout=true)
    public static void updateAmount(ID opportunityId){
        Opportunity opp = [SELECT <fields> FROM Opportunity WHERE id = :opportunityId];
    
        //Callout to your external service
        Http h = new Http();   
        HttpRequest req = new HttpRequest();
        req.setEndpoint('http://your.url');
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        //Write a function to parse the results and return the $ amount.
        Decimal result = Util.parseResult(res.getBody());

        //Update the fields on your record.
        opp.currency_field = result;
        update opp;
    }
}

 

 

 

piya_tonpiya_ton

Thanks spraetz! I am the beginner for APEX code. I have another question to ask you. To be honest, I really don't understand your source code. So now I am trying to create the simple code and try using your code later. I am trying to copy the Amount field to Local Amount field by using trigger. I am not whether sure trigger can do it or not.

 

The following below is the code I tried on SFDC and there is no error. However, when I tried changing the stage to close. The Local Amount Field is still blank field. Could you help to advise:

 

trigger ConversionRate on Opportunity (after update) {
    Opportunity o = new Opportunity();
    List<OpportunityStage> Opportunity = [SELECT o.IsClosed FROM OpportunityStage o WHERE o.IsClosed = true];
    if(o.IsClosed == true){
    o.Local_Amount__c = o.Amount;
    }
    //update o.Local_Amount__c;
}

 

Thanks!