top of page
Search

Shorten Case Url and Post to Chatter

  • abhyash
  • Nov 14, 2022
  • 3 min read

V1 Prepared By: Abhyash Timsina – 14 November 2022


Motivation: There are times when you need to shorten URLs, whether it’s for a salesforce instance link or if you are attaching a content document to a record and you need to shorten the public URL. In this example, we go over a scenario where a new case is added, and you need to shorten the URL and post that URL in chatter for your colleagues to see. The solution is simple; however, you need to get a free account with Bitly (the URL shortening service).



My Technical Components




Prerequsite


1. Head over to http://www.bitly.com

2. Sign up for free account (50 bitly links a month)

3. Generate access token from here: https://app.bitly.com/settings/api/ and paste that into UrlShortener_AuthKey label.




Source Code for ShortenUrl Apex Class (with annotation starting with //)


/**
 * Created by Abhyash Timsina on 14/11/2022.
 */

public with sharing class ShortenUrl {

// Must have an initial method as you cannot directly call the future method from a trigger. 
 
    public static void callBitly(Id recordId){
    
    // Pass recordId from trigger into the future method
        callBitlyFuture(recordId);
    }

// Future method to callout to Bitly
    @Future(Callout=true)
    public static void callBitlyFuture(Id recordId){
    
    // Retrieve the case object via the parameter
        Case caseRecord = [SELECT Id, Short_Url__c FROM Case WHERE Id =: recordId];
        Map<String, Object> response = new Map<String,Object>();
        
        // Use bitly endpoint. You can also add the link as a label and refer to the label here
        String endpoint = 'https://api-ssl.bitly.com/v4/shorten';
        
        // Below method retrieves your salesforce instance url and adds the case record id at the end of it
        String publicUrl = Url.getSalesforceBaseUrl().toExternalForm() + '/' + recordId;
        String shortUrl = '';

        System.debug('Public Url: ' + publicUrl);
        
        // REST Callout
        try {
            HttpRequest req = new HttpRequest();
            HttpResponse res = new HttpResponse();
            Http http = new Http();
            
            // Use the access token from your labels
            
            req.setHeader('Authorization', System.Label.UrlShortener_AuthKey);
            req.setHeader('Content-Type', 'application/json');
            req.setHeader('Accept', 'application/json');
            req.setEndpoint(endpoint);
            req.setMethod('POST');

// Long Url is a compulsory field from Bitly API - See - https://dev.bitly.com/api-reference/#createBitlink

                req.setBody(JSON.serialize(new Map<String, Object>{
                        'long_url' => publicUrl}));

                res = http.send(req);
                
                // Add the response int a variable
                response = (Map<String, Object>) JSON.deserializeUntyped(res.getBody());
                System.debug('Str:' + res.getBody());
                
                // Add the value of the link parameter from the response into the shortUrl variable
                
                shortUrl = (String) response.get('link');
                
                // Also pass the link parameter value into the case field for short url 
                caseRecord.Short_Url__c = shortUrl;
                
                // Call method to post to chatter. Passes the short url as parameter
                postChatter(shortUrl);

        }catch (Exception e) {
            System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );
        }
        
        // Update field on case to store the shortened url
        update caseRecord;
    }

    public static void postChatter(String postUrl) {
    
    // Creates an instance of chatter feed item 
        FeedItem post = new FeedItem();
        
        // You can customise the body however you want. Includes the short url link from the parameter
        String body = 'A new case has been created. URL: ' + postUrl;
        // Gets the logged in user's id and sets the chatter poster id
        post.ParentId = UserInfo.getUserId();
        
        // Body is from above string variable
        post.Body = body;
        insert post;
    }


}


ShortenUrlTrigger:


// Trigger when case is created

trigger ShortenUrlTrigger on Case (after insert) {

for(Case c:trigger.new){

// Call the callBitly method from ShortenUrl apex class, passing the new case id as parameter.
        ShortenUrl.callBitly (c.id);
        }
        
}


Outcome:




Package Link:


If you need help in installing and getting this working – please contact me on LinkedIn

 
 
 

Comments


bottom of page