This post is related to how to integrate Salesforce and Bitly to create short urls to include in communication Messages.
Step 1. Sign-up for Bitly
To use the Bitly API you will need to register. You can sign-up using Twitter, Facebook, or create a new login with their service. I chose to create a Bitly specific login using below url.
https://bitly.com/a/sign_in?rd=/a/oauth_apps
Step 2. Create Bitly Apex Classes
I developed below class, that encapsulates the Bitly http callouts.
global class bitly
{
Public String mode;
Public String sUrl;public string getbitly ()
{
String shorten;
XmlStreamReader reader;
HttpResponse res;//First, build the http request
Http h = new Http();
HttpRequest req = buildWebServiceRequest(sURL);//Second, invoke web service call
if (mode==’live’) { res = invokeWebService(h, req); }if (mode==’live’) { reader = res.getXmlStreamReader(); }
else
{
String str = ‘Foo bar’;
reader = new XmlStreamReader(str);
}
return readXMLResponse(reader,’shortUrl’);
}public static HttpRequest buildWebServiceRequest(String purl)
{
String endpoint;
HttpRequest req = new HttpRequest();
endpoint = ‘http://api.bit.ly/shorten?version=2.0.1&format=xml&longUrl=’+purl +’&history=1&login=BitlyAPPName&apiKey=R_42d58b4eda1c412b8ef30577442428e4’;
req.setEndpoint(endpoint);
req.setMethod(‘GET’);
return req;
}public static HttpResponse invokeWebService(Http h, HttpRequest req)
{ //Invoke Web Service
HttpResponse res = h.send(req);
return res;
}public static String readXMLResponse(XmlStreamReader reader, String sxmltag)
{ string retValue;
// Read through the XML
while(reader.hasNext())
{
if (reader.getEventType() == XmlTag.START_ELEMENT)
{
if (reader.getLocalName() == sxmltag)
{
reader.next();
if (reader.getEventType() == XmlTag.characters)
{
retValue = reader.getText();
}
}
}
reader.next();
}
return retValue;
}
}
Whenever you implement it you just need to change BitlyAPPName and apikey from endpoint.
For calling bitly class use below lines
bitly b = new bitly();
b.mode = ‘live’;
b.sUrl = ‘ https://trailhead.salesforce.com/en/modules/asynchronous_apex/units/async_apex_batch’;
system.debug(‘Check BitLy short url – ‘ + b.getbitly() );
You will output as “Check BitLy short url – http://sforce.co/2z5XCBB