Showing posts with label webservice. Show all posts
Showing posts with label webservice. Show all posts

Wednesday, November 25, 2015

How to do Avalara tax API Integration With Salesforce?

Special thanks to Ashish Agarwal

Step 1: go to below link and fill the form to get your token and secret

               http://developer.avalara.com/api-get-started/

after submitting the form you will receive an email to your email address. Go there and click on the developer area link provided in email. In this email you will get your login ID and password also.

On developer page you will prompted to give your Id and password . Please fill provide them and login.

Now reset your new password and save.

Step 2: Now go to setting tab and click on Reset Licence Key and then click on generate button.

Step 3: Now check your email .you will find an email from avalara support .open it and get your account number and Licence Key.

Step 4: Setup Avatax Select the Country and set Jurisdictions see below image


Step 5: Now go to SETUP | ADMINISTER | SECURITY CONTROLS | REMOTE SITE SETTINGS and create a new Remote site.

Give remote site name avalara and Remote site url as “https://development.avalara.net “ .

Step 6 : Now create a apex class namely “avalaraController” and copy the code from below link and paste it .

Apex Class:
public class avalaraController
 {

//string variable to show api result
    public string result{get;set;}
//string variable to hold amount of line item
    public String amount { get; set; }
//string varriable to hold quantity of line item
    public String count { get; set; }
//string varriable to hold postal code of address
    public String PostalCode { get; set; }
//line 1 of address
    public String Line1 { get; set; }
//line 2 of address
    public String Line2 { get; set; }

//method to get tex value from avalara tex api    
public String RestRequest(String body,String endPoint,String method){
        
         Blob headerValue = Blob.valueOf("acount no"+':'+"Licence key");
         String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
                
         //accessing end point for avalara request type
        
         Http h=new Http();
         HttpRequest req = new HttpRequest();
         req.setMethod(method);
  
         req.setHeader('Authorization', authorizationHeader);
         req.setEndPoint(endPoint);
         req.setBody(body);
         HttpResponse res = h.send(req);
         result = res.getBody();
         return result;



}

//method to get Text
       public void getTex(){
//calling method to create json body for request body from user provided data
        
         String texString = createTexRequestBody();
         RestRequest(texString ,"https://development.avalara.net/1.0/tax/get" ,'POST');
               }
  //method to validate address             
      public void validateAddress() {
     
        endpoint = 'https://development.avalara.net/1.0/address/validate?Line1='+EncodingUtil.urlEncode(Line1+Line2,'UTF-8')+'&PostalCode='+EncodingUtil.urlEncode(PostalCode,'UTF-8');
        RestRequest('' ,endPoint ,'GET');
    }
 //method to create json string for rest request body        
      public String createTexRequestBody(){
      
      
       JSONGenerator gen= JSON.createGenerator(true);
        gen.writeStartObject();
        gen.writeStringField('DocDate', '2013-06-19');
        gen.writeStringField('CustomerCode', 'CUST1');
        gen.writeFieldName('Addresses');
        gen.writeStartArray();
        gen.writeStartObject();
        gen.writeStringField('AddressCode', '1');
        gen.writeStringField('Line1',Line1 );
        gen.writeStringField('Line2', Line2 );
        
        gen.writeStringField('PostalCode',PostalCode);
        gen.writeEndObject();
        gen.writeEndArray();
        gen.writeFieldName('Lines');
        gen.writeStartArray();
        gen.writeStartObject();
        gen.writeStringField('LineNo', '1');
        gen.writeStringField('DestinationCode', '1');
        gen.writeStringField('OriginCode', '1');
        gen.writeNumberField('Qty',Integer.valueOf(count));
        gen.writeNumberField('Amount',Integer.valueOf(amount));
        
        gen.writeEndObject();
        gen.writeEndArray();
        gen.writeEndObject();
        return gen.getAsString();
      
      
      }

}

Now in header section of the code replace account Number with your account no and licence key with your licence key provided in email and DocDate should be the date given in the AVATAX Starting date.

Step 7: Now create a visualforce page and give it name as “ avalara” and copy the code from following link and paste it in page
Visualforce Page:

    
        
 
                
                    HP Printer
                

                    Quatity
                
                
                    amount
                
                        
                            
                
                    Address Line1 
                       
                

                    Address  Line2  
                    
                

                    PostalCode 
                    
                
{!tax}
            
            
            
                
                    
Loading...
{!result}


Run your visualforce page and fill the form with quantity ,amount(price) and any right address with valid postal code(required) ( only america and canada address).

And click on get Tex.

And you will find the response.

Check the response string and you will find tax for amount you entered.


Output:

How to do Integration between two different organizations in salesforce Using REST API and REST Web Service and Apex Web Service?

For this post, I will offer a simple explanation of the complex, yet interesting areas essential for the complete understanding of Salesforce Integration’s capabilities. The business scenario quoted, along with the working code samples, will be a good starting point for entering into the world of non-declarative ways for integrating with Salesforce. Here’s what I’ll cover:

Understanding authentication and its prerequisites
OAuth authentication flows for REST API calls
Apex triggers and callouts
REST API, REST web services, and Apex web services

1) Authentication and Its Prerequisites
Authenticating a client application is the first and foremost step while building an interface.

The authentication method depends on your chosen call type (REST or SOAP). Let’s see how to do it using REST.

Before moving any further, let’s frame a business scenario. We’ll use two Salesforce instances that exchange Account details. When a new Account is created in one org, it will flow down to the other Salesforce org, and in return the source org will get the Salesforce Record ID of the created record. These two orgs are:

Source Salesforce org (used for callout) – Source
Target Salesforce org (used for receiving requests) – Target

Following our business scenario, we can say that authentication is a collection of the following sub-steps. Though actual authentication calls a trigger from the Apex code, consider these steps as the prerequisites because without them being completed first, the authentication calls won’t work.

Choosing OAuth Endpoint (to be invoked from Source org)
Choosing OAuth Authentication flow (to be used by Source org)

Remote Site Setting in Source Org.




Connected App enables Salesforce to recognize and authenticate an external application as a new entry point. OAuth is used for this authentication. We need to create a Connected App record in Target org. Below is an illustration.

Connected App in Target Org.




callback url should be specified in the remote site setting
Once after saving the record the client id and clientSecret are generated.

Create a Trigger to make an asynchronous call from source org to target org

Trigger on account Object:


trigger SendAccount on Account(after insert)
{
for(Account a : Trigger.new){
SendAccountFromSource.createAccount(a.Name, a.Id);
}
}

Apex Class to make a callout :

Replace the clientid,secret,username and password's of your org.
public class SendAccountFromSource {
private final String clientId = 'Clent Id from App';
private final String clientSecret = 'clientSecretfrom app';
private final String username = 'username';
private final String password = 'passwordwithsecuritytoken';
public class deserializeResponse
{
public String id;
public String access_token;
}
public String ReturnAccessToken (SendAccountFromSource acount)
{
String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setBody(reqbody);
req.setMethod('POST');
req.setEndpoint('https://ap2.salesforce.com/services/oauth2/token');
HttpResponse res = h.send(req);
deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
return resp1.access_token;
}
@future(callout=true)
public static void createAccount(String accName, String accId) 
{
SendAccountFromSource acount = new SendAccountFromSource();
String accessToken = acount.ReturnAccessToken (acount);

if(accessToken != null)
{
String endPoint = 'https://ap2.salesforce.com/services/data/v32.0/sobjects/Account/';
String jsonstr = '{"Name" : "' + accName + '"}';
Http h2 = new Http();
HttpRequest req1 = new HttpRequest();
req1.setHeader('Authorization','Bearer ' + accessToken);
req1.setHeader('Content-Type','application/json');
req1.setHeader('accept','application/json');
req1.setBody(jsonstr);
req1.setMethod('POST');
req1.setEndpoint(endPoint);
HttpResponse res1 = h2.send(req1);

deserializeResponse resp2 = (deserializeResponse)JSON.deserialize(res1.getbody(),deserializeResponse.class);
Account a = [SELECT Id FROM Account WHERE Id = :accId];
a.externalId__c = resp2.id;
update a;
}
}
}
Explanation –
1 Setting the REST API resource to create an Account (sObject)
2 Creating the JSON string to be sent as the input
3 Setting the Header to include the access token
4 Querying the Account record in Source Org so it can be updated
5 Setting the custom foreign key field on Account in Source Org with the extracted Account ID from the response.

Till here we have worked with Rest API.

REST Webservices

When working with rest webservices we need to change the code in the createAccount method in SendAccountFromSource class . Which looks like
if(accessToken != null)
{
String endPoint = 'https://ap2.salesforce.com/services/apexrest/v1/createAccount/';
String jsonstr = '{"AccName" : "' + accName + '"}';

Http h2 = new Http();
HttpRequest req1 = new HttpRequest();
req1.setHeader('Authorization','Bearer ' + accessToken);
req1.setHeader('Content-Type','application/json');
req1.setHeader('accept','application/json');
req1.setBody(jsonstr);
req1.setMethod('POST');
req1.setEndpoint(endPoint);
HttpResponse res1 = h2.send(req1);

String trimmedResponse = res1.getBody().unescapeCsv().remove('\\');
deserializeResponse resp2 = (deserializeResponse)JSON.deserialize(trimmedResponse, deserializeResponse.class);
Account a = [SELECT Id FROM Account WHERE Id = :accId];
a.externalId__c= resp2.id;
update a;
}

Here in this example we need to change the endpoint url that is pointing to createAccount class in the target org. Create a new rest web service class createAccount in target org.

@RestResource(urlMapping='/v1/createAccount/*')
global with sharing class createAccount 
{
@HttpPost
global static String createAccount(String AccName)
{
Account a = new Account();
a.Name = AccName;
insert a;
String returnResponse = JSON.serialize(a);
return returnResponse;
}
}
Explanation –
1 Exposing the web service using the @RestResource annotation
2 Exposing method as REST resource to be called when HTTP Post request is made to this web service
3 Creating a new Account in Target org and setting the name as passed from Source org
4 Serializing the response (Account details) before sending
5 Sending the response.

Apex Web Service

Finally, the third option is the Apex Web Service that uses SOAP to handle integration. The class written at the target needs to be exposed as a global Web Service.

global class CreateAccountApexWS 
{
global class sAccount
{
webservice String name;
}
webservice static String createAccount(sAccount sAcct)
{
Account acct = new Account();
acct.Name = sAcct.name;
insert acct;
String returnResponse = JSON.serialize(acct);
return returnResponse;
}
}
Explanation –
1 Creating a Global class that can be accessed from anywhere
2 Using the webservice keyword to expose class variable as an input to the web service
3 Using the webservice keyword to expose the class method as a custom SOAP Web Service

Tuesday, November 24, 2015

How to call apex class from custom button(Javascript) in salesforce

In this beloow i showed you custom Lead conversion .
Here I have taken a custom object Students,
In that i have created one custom button called convert.
If we click on the convert the account,contact and opportunity should create.

First we need to Create on global class and the method you intend to call from the javascript must be a Webservice Method.
Apex Class:
global class customLead
{
 public Students__c objStudents{get;set;}
  
    webservice static void coversion(string student) 
    { 
    Students__c objStudents=new Students__c();
    
         objStudents=[SELECT ID,Name FROM Students__c WHERE id=:student];
         
         Account objAcc=new Account();
         objAcc.Name=objStudents.Name;
         Insert objAcc;
         
         contact Objcon=new contact();
         Objcon.Lastname=objStudents.Name;
         Insert Objcon;
         
        
         Opportunity objOpp= new Opportunity();
         objOpp.Name=objStudents.Name;
         objOpp.StageName='Active';
         objOpp.CloseDate=System.Today();

         Insert objOpp;
    }
}

Goto -->Setup-->Objects-->Students--->Buttons,links and Actions section
Click new Button or link.

Enter the Name of the button
Behaviour: Execute Javascript
Content Source :On-Click Javascript




Java Script Code:

{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/30.0/apex.js")}

    var result =sforce.apex.execute("customLead","coversion",{student:"{!Students__c.Id}"});
    alert("result ");

window.location.reload();

Saturday, November 21, 2015

How to Return PageReference from a webservice method

In your Class use a String as a Returntype
and create your reference like this in your webservice class
return String.valueOf( new PageReference('/'+Case.Id).getUrl());
and in your Button, you have to catch your return String and reload the page:
var newurl = sforce.apex.execute("TestClass","CreateTestRecords", {id:"{!Case.Id}"});
parent.location.href = newurl; //refresh the page