[SalesForce] Trigger to use HTTP callout and update record with the results

I have been trying to integrate Google Shortener API into my salesforce org. I wrote a class to make the call out, but am having difficulty bringing the value back into the record. I have a custom object called "referral_advocate__c" with a field called "Short_URL__c". Anytime the field "unique_ID__c" has a value, I am wanting to send this value with a static URL to google shortener and then save the response value to "referral_advocate__c.short_URL__c" on the record. This is the class to make the call out:

public class URLshort {

final string urls = 'https://www.myurl.com';
referral_advocate__c adv = new referral_advocate__c();

@future(callout = true)
public static void URLshortner() {

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

    req.setEndpoint('https://www.googleapis.com/urlshortener/v1/url?key=myapikey');
    req.setMethod('POST');
    req.setHeader('Content-Type','application/json');       
    req.setBody('{"longUrl":+urls + adv.unique_reference_number_c}');


    try {
        res = http.send(req);
        System.debug(res.getBody());
    } catch(System.CalloutException e) {
        System.debug('Callout error: '+ e);
        System.debug(res.toString());
    }


}

}

The after insert trigger on "referral_advocate__c" I wrote is not firing correctly. How do I return the results from this class and update the field "short_URL__C" with the returned value from a trigger?

Best Answer

Your future method will need some input to act upon, so a set of referral_advocate__c Ids (for bulkification purposes; this set of Ids would be built in the trigger on any record that has unique_ID__c != null ):

    set<Id> idSet = new Set<Id>{};
    for(referral_advocate__c r : trigger.new){
        if((r.unique_ID__c != null){
            idSet.add(r.Id);
            if(idSet.size()==100) {
                urlshortner(idset);
                idSet.clear();
            }
        }       
    }
    if (!idSet.isEmpty()){
       URLShortener(idSet);
    }

then also an update action: (forgive any typos / syntax errors, didn't get a chance to try it out in my dev org): Your future method will need some input to act upon, so a set of referall_advocate__c Ids (for bulkification purposes; this set of Ids would be built in the trigger on any record that has short_URL__C != null ), then also an update action:

@future(callout = true)
public static void URLshortner(Set<Id> idSet) {
    List<referral_advocate__c> rList = new List<referral_advocate__c>();
    Http http = new Http();
    for (referral_advocate__c r : [SELECT unique_ID__c FROM referral_advocate__c WHERE Id in :idSet]){
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://www.googleapis.com/urlshortener/v1/url?key=myapikey');
        req.setMethod('POST');
        req.setHeader('Content-Type','application/json');       
        req.setBody(JSON.serialize(
            new Map<String, String> { 'longUrl' => urls + r.unique_ID__c}));
        try {
            HttpResponse res = http.send(req);
            //parse your json response for the value

            r.short_URL__C = retValue;
            rList.add(r);
        } catch(System.CalloutException ce){
            // handle callout error
        }
    } 
    Database.SaveResult results = Database.update(rList, false);
    // handle DML error
}

try something like this to get you started out.

Related Topic