Showing posts with label Integration. Show all posts
Showing posts with label Integration. Show all posts

Feb 23, 2015

MailChimp Authentication In Salesforce - Easy Steps (Authentication Part 3)

I hope following post might have helped you in authentication:


So here is the third part of the series, authentication with MailChimp

The whole process of authentication with Mailchimp is divided into some simple steps :

Step 1:- First of all to authenticate with Mailchimp, you must have an account on Mailchimp if not then sign up here.

Step 2:- Now create an app by selecting your name under the logo and select account.


Step 3:- Here as you can see in the given image below, select registered app and register an app here.


Step 4:- Once you've entered the details for your Company and Application and saved them, your client_id and client_secret will be displayed at the bottom of the "edit" page for your application.

Note: - Keep in mind that Redirect Uri is the Uriof your page where you want to be redirected with the "code" parameter.

Step 5:- Now create an apex class and paste the below code in it.


publicwithsharingclassMailChimpIntegrationController
{
 public string client_id = 'Your ClientId';
 public string client_secret = 'Your ClientSecret';
 public string authorize_uri = 'https://login.mailchimp.com/oauth2/authorize';
 public string redirect_uri = 'https://c.na15.visual.force.com/apex/MailChimpIntegrationPage';
 
 publicMailChimpIntegrationController()
 {}
 
 publicPagereferenceauthorizeMailChimp()
 {
  authorize_uri = authorize_uri + '?response_type=code&client_id=' + client_id + '&redirect_uri=' + Encodingutil.urlEncode(redirect_uri , 'UTF-8');
PageReferencepg = newPageReference(authorize_uri) ;  
returnpg ;
 }
 
 publicvoidmailChimpAccessToken()
 {
  string code = ApexPages.currentPage().getParameters().get('code') ;  
  HttpRequestreq = newHttpRequest();  
req.setMethod('POST');  
req.setEndpoint('https://login.mailchimp.com/oauth2/token'); 
req.setHeader('content-type', 'application/x-www-form-urlencoded'); 
req.setHeader('Accept', 'application/json'); 
        String messageBody = 'grant_type=authorization_code&client_id=' + client_id + '&client_secret=' + client_secret + '&code=' + code + '&redirect_uri=' + Encodingutil.urlEncode(redirect_uri , 'UTF-8');
req.setHeader('Content-length', String.valueOf(messageBody.length()));  
req.setBody(messageBody);  
req.setTimeout(60*1000);  

        Http h = newHttp();  
        String resp;  
HttpResponse res = h.send(req);  
resp = res.getBody(); 

system.debug('+++++----json---with---Access-----token----++++++'+resp);
 }
}


Step 6:- Now create a visualforce page and paste the below code in it.



 
   
   
 


Step 7:- At last create a new remote site setting with value as below

-> Remote Site Name : MailChimp
-> Remote Site URL : https://login.mailchimp.com
-> Active : True


I hope now you can manipulate the code according to the need. As these simple buttons on VFP shows you how to authenticate and get the access tokens.

Cheers!

May 11, 2014

Google Drive Authentication In Salesforce - Easy Steps (Authentication Part 2)

Now where comes part 2 of authentication. This time it's with Google Drive.

In this blog Authentication with Google is explained so developers can get started.

Step 1 : Create  account on google (hope you already have), then go to developer console to create a project. Now click on project which is newly created then click on APIs and auth > APIs and make Drive API "on".

Step 2 : Now "Create New Client ID " which will look something like this :


Now we will use this info in salesforce to authenticate.

Step 3 : Create this apex class in Salesforce

public class GoogleDriveController
{
    //Fetched from URL
    private String code ;
    private string key = '134427681112-ld4vp2l1jut3aj2fktip776081nhn8l3.apps.googleusercontent.com' ;
    private string secret = 'hdHNk4GjNtkR4nNL1SqCfRk_' ;
    private string redirect_uri = 'https://c.ap1.visual.force.com/apex/GoogleDrivePage' ;
    
    public GoogleDriveController()
    {
        code = ApexPages.currentPage().getParameters().get('code') ;
        //Get the access token once we have code
        if(code != '' && code != null)
        {
            AccessToken() ;
        }
    }
    
    public PageReference DriveAuth()
    {
        //Authenticating
        PageReference pg = new PageReference(GoogleDriveAuthUri (key , redirect_uri)) ;
        return pg ;
    }
    
    public String GoogleDriveAuthUri(String Clientkey,String redirect_uri)
    {
        String key = EncodingUtil.urlEncode(Clientkey,'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
        String authuri = '';
        authuri = 'https://accounts.google.com/o/oauth2/auth?'+
        'client_id='+key+
        '&response_type=code'+
        '&scope=https://www.googleapis.com/auth/drive'+
        '&redirect_uri='+uri+
        '&state=security_token%3D138r5719ru3e1%26url%3Dhttps://oa2cb.example.com/myHome&'+
        '&login_hint=jsmith@example.com&'+
        'access_type=offline';
        return authuri;
    }
    
    
    public void AccessToken()
    {
        //Getting access token from google
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('https://accounts.google.com/o/oauth2/token');
        req.setHeader('content-type', 'application/x-www-form-urlencoded');
        String messageBody = 'code='+code+'&client_id='+key+'&client_secret='+secret+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
        req.setHeader('Content-length', String.valueOf(messageBody.length()));
        req.setBody(messageBody);
        req.setTimeout(60*1000);

        Http h = new Http();
        String resp;
        HttpResponse res = h.send(req);
        resp = res.getBody();
        
        System.debug(' You can parse the response to get the access token ::: ' + resp);
   }
}


Step 4 : Create this visualforce page (GoogleDrivePage) in Salesforce



    
        
    




Step 5 : Replace the code :

You can replace these three variables according to your settings (created in step 2)

private string key = '134427681112-ld4vp2l1jut3aj2fktip776081nhn8l3.apps.googleusercontent.com' ;
private string secret = 'hdHNk4GjNtkR4nNL1SqCfRk_' ;
private string redirect_uri = 'https://c.ap1.visual.force.com/apex/GoogleDrivePage' ;

Step 6 : Don't forget to create remote site setting :


Step 7 : All set to go, now hit the page "https:// ..... /apex/GoogleDrivePage", make sure your debug is on. Once authenticated with google debug will print the access token.


Now you can use this access token for further requests.

Please note, code is not beautified as this is just to explain how you can authenticate google with salesforce. A lot more creativity can be applied here.


Happy Coding!!

May 9, 2014

Dropbox Authentication In Salesforce - Easy Setup (Authentication Part 1)

From log time managing data is a big deal, and a lot are concerned with it. Multiple options are available to handle this, out of them Dropbox, Box.com, Amazon are the main ones.

In this blog Authentication with Dropbox is explained so developers can get started.

Step 1 : Create an account on Dropbox, then go to this link and create an app. It will create "App Key" and "App Secret" which we will be using in Salesforce. Leave the OAuth2 section blank for now.


Step 2 : Go to salesforce and create this apex class (DropboxController) :

public class DropboxController
{
    //Fetched from URL
    String code ;
    
    public DropboxController()
    {
        code = ApexPages.currentPage().getParameters().get('code') ;
        //Get the access token once we have code
        if(code != '' && code != null)
        {
            AccessToken() ;
        }
    }
    
    public PageReference DropAuth()
    {
        //Authenticating
        PageReference pg = new PageReference('https://www.dropbox.com/1/oauth2/authorize?response_type=code&client_id=vaabb5qz4jv28t5&redirect_uri=https://c.ap1.visual.force.com/apex/DropboxPage&state=Mytesting') ;
        return pg ;
    }
    
    public void AccessToken()
    {
        //Getting access token from dropbox
        String tokenuri = 'https://api.dropbox.com/1/oauth2/token?grant_type=authorization_code&code='+code+'&redirect_uri=https://c.ap1.visual.force.com/apex/DropboxPage'; 
        HttpRequest req = new HttpRequest();
        req.setEndpoint(tokenuri);
        req.setMethod('POST');
        req.setTimeout(60*1000);
          
        Blob headerValue = Blob.valueOf('vaabb5qz4jv28t5' + ':' + 'dpmmll522bep6pt');
        String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
        req.setHeader('Authorization', authorizationHeader);
        Http h = new Http();
        String resp;
        HttpResponse res = h.send(req);
        resp = res.getBody();
        
        System.debug(' You can parse the response to get the access token ::: ' + resp);
   }
}


Step 3 : Now create visualforce page (DropboxPage) :



    
        
    




Step 4 : Replace the code with your values

1 . As you can see we have this in code :

PageReference pg = new PageReference('https://www.dropbox.com/1/oauth2/authorize?response_type=code&client_id=vaabb5qz4jv28t5&redirect_uri=https://c.ap1.visual.force.com/apex/DropboxPage&state=Mytesting') ;


You have to replace "client_id" with your "App Key" (redirect_uri is the complete page URL which we've just created). Now as visualforce page is created you can fill the OAuth2 section as shown in the screenshot above in dropbox.

2. Replace "dpmmll522bep6pt" in this line
Blob headerValue = Blob.valueOf('vaabb5qz4jv28t5' + ':' + 'dpmmll522bep6pt');
with you "App Secret"

Step 5 : Don't forget to set the remote site settings for dropbox



Now all set to go. Open the page "https:// ..... /apex/DropboxPage" and hit "Dropbox Authentication". In the debug you will get the access token which you can further use to hit Dropbox APIs.

Please note, code is not beautified as this is just to explain how you can authenticate dropbox with salesforce. A lot more creativity can be applied here.

From here everything is set and you are ready to hit the dropbox API and fetch the data or store the data. Complete documentation is here.

Happy Coding!!

Jan 15, 2012

Integrating Google Maps in Salesforce

Requirement is to show the location of my Account on Google Maps. It looks difficult but actually it is very simple to implement.


Just create a new visualforce page with this code
<apex:page standardController="Account">

<script src="http://maps.google.com/maps?file=api">
</script>

<script type="text/javascript">

var map = null;
var geocoder = null;

var address = "{!Account.BillingStreet}, {!Account.BillingPostalCode} {!Account.BillingCity}, {!Account.BillingState}, {!Account.BillingCountry}";

function initialize() {
if(GBrowserIsCompatible())
{
  map = new GMap2(document.getElementById("MyMap"));
  map.addControl(new GMapTypeControl());
  map.addControl(new GLargeMapControl3D());
  
  geocoder = new GClientGeocoder();
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        document.getElementById("MyMap").innerHTML = address + " not found";
      } else {
        map.setCenter(point, 13);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        marker.bindInfoWindowHtml("Account Name : <b><i> {!Account.Name} </i></b> <br/> Address : "+address);
      }
    }
  );
}
}
</script>


<div id="MyMap" style="width:100%;height:300px"></div>
<script>
    initialize() ;
</script>

</apex:page>
As you can see that I have used standard controller so you need to pass the account Id in URL. Let's say if the page name is "GoogleMaps" then the URL will look something like this : ".../apex/GoogleMaps?id=YOUR_ACCOUNT_ID".






When you click on the balloon it will show you the Account name and the address, you can change it according to your need by changing the code of line "marker.bindInfoWindowHtml"


Use this page as in line visualforce page on native layout and enjoy the Google maps with Salesforce.


References
http://code.google.com/apis/maps/documentation/webservices/
http://code.google.com/apis/maps/index.html