Salesforce Spring 18: Quick Preview

Salesforce Spring 18: Quick Preview

Happy New Year Everyone. And god bless to them who had hardcoded 2017 in there code. Salesforce has just release Spring 18 and this time also the main focus remains n Einstein and Lightning. In this release there are many good feature are introduced. So let’s take a quick look at them.

spring-18-logo-268x300
Spring 18
  1. Gather Feedback with Salesforce Surveys (Generally Available)

Salesforce now has introduced Surveys. Create beautiful, easy-to-use forms for collecting feedback and data from your users or customers. Add different types of questions to gather the data you need. All your valuable survey data is stored in your org, so you can harness the power of Salesforce to view data, create reports and dashboards, and share insights with your company.

  1. Enable the New URL Format for Lightning Experience and the Salesforce

Salesforce is changing the URL format used by Lightning Experience standard apps and the Salesforce mobile app. The new URL format is more readable and addresses the issue of being directed to an unexpected location when accessing Lightning Experience URLs before authenticating. This update doesn’t apply to console apps and communities.

For example:

Custom or installed Lightning components that parse a URL may break or behave differently after this change, especially components with logic that relies on window.location or the aura:locationChange event.

  1. Einstein

Einstein Opportunity Scoring: Artificial Intelligence for Opportunities (Generally Available)

Salesforce has expanded the Sales Cloud Einstein product suite with Einstein Opportunity Scoring. Now we can prioritize our way to more business. This feature is new in Lightning Experience and Salesforce Classic.

Einstein Forecasting: Intelligent Predictions About our Sales Teams (Beta)

Let Einstein take the guesswork out of forecasting. Use artificial intelligence to get more certainty and visibility into how your sales teams are doing. This feature is new in both Lightning Experience and Salesforce Classic.

Einstein Lead Scoring: Clearer Predictive Factors and Detection of Rank and Department

Get a clearer view of the reasons behind each score. And see better scores with rank and department information. These changes apply to both Lightning Experience and Salesforce Classic.

Einstein Insights: Access Account and Opportunity Insights from Your Mobile Device (Pilot)

Einstein Insights are now. See predictions about which deals are likely to be won, reminders to follow up, and notifications when key moments in a deal take place. Reps can take action directly from the insights, including editing the related record or sending emails to relevant contacts. This change applies to Salesforce for iOS and Salesforce for Android.

Einstein Platform Services APIs

Use the Einstein Platform Services APIs to easily AI-enable your apps with image recognition and natural language processing. Using the Einstein Vision APIs, you can leverage pre-trained classifiers or train your own custom classifiers to solve a vast array of specialized image recognition use cases. With the Einstein Language APIs, you can harness the power of natural language processing to analyze text and infer the sentiment or intent behind that text. Make your apps smarter, and look like a genius at the same time.

  1. Stay on Top of Duplicate Records by Using Duplicate Jobs PERMISSIONS

Good clean data builds the trust of your sales team. It also helps you work toward complying with various data protection and privacy regulations. So you’ve got everything to gain by getting a global view of duplicate records. Use duplicate jobs with standard or custom matching rules to scan your Salesforce business or person accounts, contacts, or leads for duplicates. Share job results with others and merge the duplicates—all within Salesforce. Use information about duplicate jobs we’ve run to track the progress in reducing duplicate records. This feature is new in Lightning Experience.

  1. Salesforce IoT: IoT REST API, New Context UI, IoT Usage Monitoring, and Email Alerts

Use Salesforce IoT Explorer Edition to process events from connected devices in near real time and create meaningful interactions with your customers. Explorer offers built-in integration with Salesforce data and lets you leverage your Customer Relationship Management (CRM) investments in Salesforce. This release includes a new IoT REST API to retrieve and manipulate orchestrations and their related components, and a new user interface for contexts. Also, Salesforce is introducing an IoT usage monitoring page, email alerts, and the ability to export and delete IoT data for data privacy.

  1. Use without sharing for @AuraEnabled Apex Controllers with Implicit Sharing (Critical Update)

This critical update changes the behavior of @AuraEnabled Apex controllers that don’t specify with sharing or without sharing to default to without sharing. This change relaxes the security for controllers that don’t explicitly set sharing behavior using these keywords. It’s a best practice to always use with sharing in Apex controllers used with Lightning components.

  1. Find Dynamically Created Components

We can now use cmp.find() to find a component that we have create dynamically with $A.createComponent().

  1. Remove Instance Names from URLs for Visualforce, Community Builder, Site.com Studio, and Content Files (Critical Update)

Salesforce is stabilizing the hostname of Visualforce, Community Builder, Site.com Studio, and content file URLs by removing instance names from URLs. This critical update applies to orgs that have a deployed My Domain. It will be activated automatically on March 16, 2019.

Prior to Winter ’18, Visualforce, Community Builder, Site.com Studio, and content file URLs included the instance name of the org, even when a My Domain name was deployed. An instance name identifies where your Salesforce org is hosted. When Salesforce remove the instance name from our URLs, hostnames change.

Here are two examples:

  • mydomain–c.visualforce.com replaces mydomain–c.na1.visual.force.com
  • mydomain–c.documentforce.com replaces mydomain–c.na1.content.force.com

Note: All *.content.force.com URLs will be replaced with *.documentforce.com.

  1. Employ Validation Rule Formulas with Custom Metadata Types

If we use validation rules, you know how helpful they can be, but you have to hard code some of the values. Now you can store values you previously had to hard code in custom metadata types and reference them in your validation rules.

Example: Use a validation rule formula to limit discounts on certain brands to 10%. You can use validation rules without custom metadata. However, to change an amount, you must update the hardcoded value. If you have multiple validation rules that check the discount amount, you have to manage all of them. Instead, use a validation rule formula with custom metadata types.

  1. Create a custom metadata type. In this example, we named it DiscountLimits.
  2. Create a custom field for your type. We named it maxDiscount.
  3. Create a record. We named it FoodDiscount.

When done, you can reference the custom metadata type in your validation rule. The syntax is:

$CustomMetadata.CustomMetadataTypeAPIName.RecordAPIName.FieldAPIName

Make sure to use the correct suffixes. For the custom metadata type, use __mdt. For fields, use __c. Records require no suffix.

Your validation rule for this example looks something like this:

Discount > $CustomMetadata.DiscountLimits__mdt.FoodDiscount.maxDiscount__c

  1. In Spring 18 Salesforce added two new methods in list class. They are

contains(listElement)

Returns true if the list contains the specified element.

indexOf(listElement)

Returns the index of the first occurrence of the specified element in this list. If this list does not contain the element, returns -1.

So now we no longer dependent on set to check for duplicate key at the same time we can maintain order as well.

  1. Collect Debug Logs for Guest Users Without Setting Cookies

In Winter ’17, Salesforce introduced a change that required guest users to set browser cookies to activate debug logging. people didn’t like the Winter ’17 change. Setting cookies is complicated, and the change made collecting debug logs for public users’ asynchronous activity impossible. Now public users no longer need a debug_logs browser cookie to trigger logging. This change applies to both Lightning Experience and Salesforce Classic.

  1. Avoid Huge Debug Logs for Managed Package Code

Debug logs no longer include ENTERING_MANAGED_PKG events when your log level for the Apex Code category is INFO or DEBUG. To log ENTERING_MANAGED_PKG events, set your Apex Code log level to FINE, FINER, or FINEST.

Advertisements

Salesforce Einstein Vision: Quick Overview

Salesforce Einstein Vision: Quick Overview

Einstein Vision is part of the Einstein Platform Services technologies, and you can use it to AI-enable your apps. Leverage pre-trained classifiers, or train your own custom classifiers to solve a vast array of specialized image-recognition use cases. Developers can bring the power of image recognition to CRM and third-party applications so that end users across sales, service, and marketing can discover new insights about their customers and predict outcomes that lead to smarter decisions.

Einstein Vision includes these APIs:

  • Einstein Image Classification—Enables developers to train deep learning models to recognize and classify images at scale.
  • Einstein Object Detection (Pilot)—Enables developers to train models to recognize and count multiple distinct objects within an image, providing granular details like the size and location of each object.

0089e22-vision_terms_graphic.png

Today we will cover the Einstein Image Classification . As we have a very good Apex wrapper provided by Salesforce dev team here. Which you can use to make all request of Einstein while it handle all the heavy work in background for you.

But if you don’t want to install a full library to test these requests then I will share quick code sample which you can use to create your own request.

Before we start first you need to make sure that you have completed all prerequisite steps. You need a valid Einstein token to call API and few base classes to make request.

After all this setup our org is ready to make our first prediction. For our demo purpose we will use Bike vs Car model. Here I have commented Token Id, Dataset Id and Model Id you can enter your related Id there.

First  to make a request we need the access token, Here we take help of our base classes which we have included. To get the access token we will use JWT access token helper.

 

Then we need to make our Dataset: A data set is a folder which contains the images. Here we pass the data in multipart/form-data format.

Dataset can be created Asyn or syn. In our example we are creating Asynchronously.

Next we will train our dataset to identify the images. You will get Dataset ID from previous request.

this command train the Dataset and create a Model. Model creation process takes time based on number of images which you have provided. In our example number of picture is less so it will complete early.

You can also check the status

Once the Dataset is trained we are ready to make our first prediction.

For prediction we will use this image

18

 

And the response we get is

Screenshot_2.png

 

So we get Almost 100% for this image. You can make your own Dataset and can play with them.

Let me know what you like most about Einstein in comments. If you want to add something share with me in comments section.

Happy Programming 🙂

Connect Salesforce with Authorize.Net

Connect Salesforce with Authorize.Net

Hi All, We all know about authorize.net. Its the most common payment gateway used to make payment transaction from Website. We can also use it with Salesforce to setup payment gateway where our users can make a purchase and do payments as well.

Its very easy to connect Salesforce with Authorize.net. In this post we will use Sandbox account to make transaction but you can follow same steps for live transactions.

  • First Sign up for a Sandbox account here. Screenshot_2.pngNow you will get Login Id and Transaction Key. Store them in some place so that we can use them later.

Screenshot_1

  •  Now there are various method from which we can make a payment, Authorize a payment, Charge a card later and void the transaction. In case of Production URl we need to change the base URl.
  • Also make sure you add the base URL in remote site setting.

Screenshot_3.png


public with sharing class AuthorizePayment {

private string APIkey = '********';
private string transKey = '************';
private string Amt = '5';
private string cardNum = '5424000000000015';
private string expdate = '1220';
private string cvvCode = '999';

//Method to make payment and charge the card
public void makePayment(){
//Getting access token from Paypal
HttpRequest req1 = new HttpRequest();
req1.setMethod('POST');
req1.setEndpoint('https://apitest.authorize.net/xml/v1/request.api');
req1.setHeader('content-type', 'application/json');
/*
Production URL: https://api.authorize.net/xml/v1/request.api

XSD URL: https://api.authorize.net/xml/v1/schema/AnetApiSchema.xsd
*/

string messageBody1 ='{"createTransactionRequest":{"merchantAuthentication":{"name":"'+APIkey+'","transactionKey":"'+transKey+'"},'
+'"refId":"123456","transactionRequest":{"transactionType":"authCaptureTransaction","amount":"'+Amt+'","payment":{"creditCard":'
+'{"cardNumber":"'+cardNum+'","expirationDate":"'+expdate+'","cardCode":"'+cvvCode+'"}},"lineItems":{"lineItem":{"itemId":"1","name":"vase",'
+'"description":"Cannes logo","quantity":"18","unitPrice":"45.00"}},"tax":{"amount":"4.26","name":"level2 tax name","description":"level2 tax"},'
+'"duty":{"amount":"8.55","name":"duty name","description":"duty description"},"shipping":{"amount":"4.26","name":"level2 tax name",'+
'"description":"level2 tax"},"poNumber":"456654","customer":{"id":"99999456654"},"billTo":{"firstName":"Ellen","lastName":"Johnson",'+
'"company":"Souveniropolis","address":"14 Main Street","city":"Pecan Springs","state":"TX","zip":"44628","country":"USA"},"shipTo":'+
'{"firstName":"China","lastName":"Bayles","company":"Thyme for Tea","address":"12 Main Street","city":"Pecan Springs","state":"TX","zip":"44628",'+
'"country":"USA"},"customerIP":"192.168.1.1","transactionSettings":{"setting":{"settingName":"testRequest","settingValue":"false"}},'+
'"userFields":{"userField":[{"name":"MerchantDefinedFieldName1","value":"MerchantDefinedFieldValue1"},{"name":"favorite_color","value":"blue"}]}}}}';

req1.setHeader('Content-length', String.valueOf(messageBody1.length()));
req1.setBody(messageBody1);

req1.setTimeout(60*1000);
Http h1 = new Http();
String resp1;
HttpResponse res1 = h1.send(req1);
resp1 = res1.getBody();
Map<String,object> responseMap =(Map<String,object>)JSON.deserializeUntyped(res1.getBody().substring(1,res1.getBody().length())) ;
for(string keyStr : responseMap.keyset())
system.debug(keyStr+'-----------Response------------------>>>>'+responseMap.get(keyStr));
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Confirm, resp1));

}

//Method to authorize the card to make the payment later
public void authorizecard(){
HttpRequest req1 = new HttpRequest();
req1.setMethod('POST');
req1.setEndpoint('https://apitest.authorize.net/xml/v1/request.api');
req1.setHeader('content-type', 'application/json');
/*
Production URL: https://api.authorize.net/xml/v1/request.api

XSD URL: https://api.authorize.net/xml/v1/schema/AnetApiSchema.xsd
*/

string messageBody1 ='{ "createTransactionRequest": { "merchantAuthentication": { "name":"'+APIkey+'","transactionKey":"'+transKey+'" }, '+
'"refId": "123456", "transactionRequest": { "transactionType": "authOnlyTransaction", "amount": "'+Amt+'", "payment": { "creditCard": '+
'{ "cardNumber":"'+cardNum+'","expirationDate":"'+expdate+'","cardCode":"'+cvvCode+'" } }, "lineItems": { "lineItem": { "itemId": "1", '+
'"name": "vase", "description": "Cannes logo", "quantity": "18", "unitPrice": "45.00" } }, "tax": { "amount": "4.26", "name": "level2 tax name",'+
'"description": "level2 tax" }, "duty": { "amount": "8.55", "name": "duty name", "description": "duty description" }, "shipping": '+
'{ "amount": "4.26", "name": "level2 tax name", "description": "level2 tax" }, "poNumber": "456654", "customer": { "id": "99999456654" },'+
' "billTo": { "firstName": "Ellen", "lastName": "Johnson", "company": "Souveniropolis", "address": "14 Main Street", "city": "Pecan Springs",'+
' "state": "TX", "zip": "44628", "country": "USA" }, "shipTo": { "firstName": "China", "lastName": "Bayles", "company": "Thyme for Tea", '+
'"address": "12 Main Street", "city": "Pecan Springs", "state": "TX", "zip": "44628", "country": "USA" }, "customerIP": "192.168.1.1", '+
'"transactionSettings": { "setting": { "settingName": "testRequest", "settingValue": "false" } }, "userFields": { "userField": [ '+
'{ "name": "MerchantDefinedFieldName1", "value": "MerchantDefinedFieldValue1" }, { "name": "favorite_color", "value": "blue" } ] } } } }';

req1.setHeader('Content-length', String.valueOf(messageBody1.length()));
req1.setBody(messageBody1);

req1.setTimeout(60*1000);
Http h1 = new Http();
String resp1;
HttpResponse res1 = h1.send(req1);
resp1 = res1.getBody();
Map<String,object> responseMap =(Map<String,object>)JSON.deserializeUntyped(res1.getBody().substring(1,res1.getBody().length())) ;
for(string keyStr : responseMap.keyset())
system.debug(keyStr+'-----------Response------------------>>>>'+responseMap.get(keyStr));
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Confirm, resp1));

}

//Method for refund the settled payment
public void refundPay(){
HttpRequest req1 = new HttpRequest();
req1.setMethod('POST');
req1.setEndpoint('https://apitest.authorize.net/xml/v1/request.api');
req1.setHeader('content-type', 'application/json');
/*
Production URL: https://api.authorize.net/xml/v1/request.api

XSD URL: https://api.authorize.net/xml/v1/schema/AnetApiSchema.xsd
*/

string messageBody1 ='{ "createTransactionRequest": { "merchantAuthentication": { "name":"'+APIkey+'","transactionKey":"'+transKey+'" },'+
' "refId": "123456", "transactionRequest": { "transactionType": "refundTransaction", "amount": "5.00", "payment": { "creditCard": '+
'{ "cardNumber":"'+cardNum+'","expirationDate":"'+expdate+'" } }, "refTransId": "60024747323" } } }';

req1.setHeader('Content-length', String.valueOf(messageBody1.length()));
req1.setBody(messageBody1);

req1.setTimeout(60*1000);
Http h1 = new Http();
String resp1;
HttpResponse res1 = h1.send(req1);
resp1 = res1.getBody();
Map<String,object> responseMap =(Map<String,object>)JSON.deserializeUntyped(res1.getBody().substring(1,res1.getBody().length())) ;
for(string keyStr : responseMap.keyset())
system.debug(keyStr+'-----------Response------------------>>>>'+responseMap.get(keyStr));
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Confirm, resp1));

}

//method for cancel the unseattled payment
public void voidPay(){
HttpRequest req1 = new HttpRequest();
req1.setMethod('POST');
req1.setEndpoint('https://apitest.authorize.net/xml/v1/request.api');
req1.setHeader('content-type', 'application/json');
/*
Production URL: https://api.authorize.net/xml/v1/request.api

XSD URL: https://api.authorize.net/xml/v1/schema/AnetApiSchema.xsd
*/

string messageBody1 ='{ "createTransactionRequest": { "merchantAuthentication": { "name":"'+APIkey+'","transactionKey":"'+transKey+'" },'+
'"refId": "123456", "transactionRequest": { "transactionType": "voidTransaction", "refTransId": "60024747323" } } }';

req1.setHeader('Content-length', String.valueOf(messageBody1.length()));
req1.setBody(messageBody1);

req1.setTimeout(60*1000);
Http h1 = new Http();
String resp1;
HttpResponse res1 = h1.send(req1);
resp1 = res1.getBody();Map<String,object> responseMap =(Map<String,object>)JSON.deserializeUntyped(res1.getBody().substring(1,res1.getBody().length())) ;
for(string keyStr : responseMap.keyset())
system.debug(keyStr+'-----------Response------------------>>>>'+responseMap.get(keyStr));
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Confirm, resp1));
}

}

  • From the transaction response you will get the transId which you can n cancellation and other processes. You can read more about them in detail from here.

So now you can setup a payment gateway in your force.com site or for internal user. If you like this post or want to add something let me know in comments section.

Happy Programming 🙂

Connect Salesforce with Box.com Part 2

Connect Salesforce with Box.com Part 2

Hi All, In my previous post Connect Salesforce with Box.com (The Integration series) I have shared how can you create a Box.com app and authorize the user from Salesforce.

In this post I am sharing two utility method to create a folder on box.com and upload a file on box.com. There are various other methods are available but for starting I have found these two most useful.

So first create a folder in box.com platform you can use this method.


private void createfolder(String fileName, string parentid)
{
String url = 'https://api.box.com/2.0/folders';
string authorizationHeader = 'Bearer '+Accesstoken ;

HttpRequest req = new HttpRequest();
req.setheader('Authorization',authorizationHeader);
req.setBody('{"name":"'+fileName+'", "parent":{"id":"0"}}');
req.setMethod('POST');
req.setEndpoint(url);

Http h = new Http();
Httpresponse resp = h.send(req);
System.debug(resp.getbody()+'-----------------------'+resp); 
}

 

To upload a file in Box.com platform use this utility method.

 


private void uploadFileCode(String folderId,Attachment file,String token){
String boundary = '----------------------------356sdf986eff';
String header = '--'+boundary+'\nContent-Disposition: form-data; name=&quot;file&quot;; filename=&quot;'+fileName+'&quot;;\nContent-Type: application/octet-stream';

String footer = '--'+boundary+'--';
String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
while(headerEncoded.endsWith('=')){
header+=' ';
headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
}
String bodyEncoded = EncodingUtil.base64Encode(file.body);

Blob bodyBlob = null;
String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());
if(last4Bytes.endsWith('==')) {

last4Bytes = last4Bytes.substring(0,2) + '0K';
bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;

String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
} else if(last4Bytes.endsWith('=')) {
last4Bytes = last4Bytes.substring(0,3) + 'N';
bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;

footer = '\n' + footer;
String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
} else {
// Prepend the CR LF to the footer
footer = '\r\n' + footer;
String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
}

String sUrl = 'https://upload.box.com/api/2.0/files/content?parent_id='+folderId;
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type','multipart/form-data; boundary='+boundary);
req.setMethod('POST');
req.setEndpoint(sUrl);
req.setBodyAsBlob(bodyBlob);
req.setTimeout(60000);
req.setHeader('Authorization', 'Bearer '+token);
req.setHeader('Content-Length',String.valueof(req.getBodyAsBlob().size()));
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getbody()+'-----------------------'+res);
}

These are the two methods which you can use to create a folder and upload file.

Do you have anything to add or like this post or any other thing to share please share them in comments.

 

Connect Salesforce with Box.com

Connect Salesforce with Box.com

Hi All, We all know that’s how costly it is to store data in Salesforce.com. So we always want to store data in third party so that we can reduce the cost. Thats why today I am sharing the authorization process between Salesforce and Box.com in my Integration series.

For this first you need to go to Box.com for a Developer account which you can create here.

After successful account creation you need to create an App to get the key and token. You can create an app here.

After creation your app will look like this.

Screenshot_6

 

 

Give your Visualforce page url as redirect URL. Now use the below code to perform the authorization process.

Controller:

public with sharing class BoxComIntegration {
    //Fetched from URL
    private String code ;
    private string key = 'llpm**************2ks8';
    private string secret = 'LMh**************jCmK2fDHK' ;
    private string redirect_uri = 'https://c.ap1.visual.force.com/apex/BoxComUpload';
    
    public BoxComIntegration()
    {
        code = ApexPages.currentPage().getParameters().get('code') ;  
        //Get the access token once we have code
        if(code != '' && code != null)
        {
            AccessToken() ;
        }
        
    }
    
    public PageReference BoxAuth()
    {
        //Authenticating
        PageReference pg = new PageReference(BoxAuthUri (key , redirect_uri)) ;
        return pg ;
    }
    
    public String BoxAuthUri(String Clientkey,String redirect_uri)
    {
        String key = EncodingUtil.urlEncode(Clientkey,'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
        String authuri = '';
        authuri = 'https://account.box.com/api/oauth2/authorize?'+
        'client_id='+key+
        '&response_type=code'+
        '&redirect_uri='+uri+
        '&state=security_token%3D138r5719ru3e1%26urldfrgdgvrev';
        
        return authuri;
    }
    
    
    public void AccessToken()
    {
        //Getting access token from google
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('https://api.box.com/oauth2/token');
        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();
         Map<String,object> responseMap =(Map<String,object>)JSON.deserializeUntyped(res.getBody()) ;  
          String token =  String.valueOf(responseMap.get('access_token'));
         system.debug('***************'+token);
   }
}

VF Page:

<apex:page controller="BoxComIntegration">
<apex:form >
    <apex:pageblock > 
        <apex:commandbutton action="{!BoxAuth}" value="Authentication">
    </apex:commandbutton></apex:pageblock>
</apex:form>
</apex:page>

Screenshot_7

Also add two Base URLs in remote site setting. And now you are all set when you run this code you will get access token and using that token you can easily upload, download the files.

Screenshot_8

Let me know if you like this post. Do you have anything to add in the post. let me know in comments section.

Also check second post of Integration series connect salesforce with box com part 2