Home / Web Development / API / Request access token from Salesforce via REST API – PHP
Request access token from Salesforce via REST API – PHP

Request access token from Salesforce via REST API – PHP

In this post I’m going explain about how to get the access token form salesforce.com via OAUTH 2.0 username and password flow. If you had chosen this flow means, this article is for you.

While developing hybrid salesforce mobile application using ui frameworks like sencha touch, angular js, jquery mobile into phonegap, you’ve to hard code the username and password of the salesforce account and make post request to https://test.salesforce.com/services/oauth2/token from javascript. This methodology of getting access token form the salesforce is highly insecure and not recommended. Also if any user credentials changing means, you can’t modify the applications installed.

In this situation you have to go for some server side scripting language for getting access token in secure way.
Here I’ve used PHP in this tutorial.


//This class will return the Access token of Salesforce via OAUTH 2.0 username - password flow
class SF_TOKEN {
	public function processApi(){
		$func = strtolower(trim(str_replace("/","",$_REQUEST['action'])));
		if((int)method_exists($this,$func) > 0)
			$this->$func();
		else
			$this->response(0,"No methods found!");
	}
	
	//Function which returns the access token
	private function gettoken() {
		if ($_SERVER['REQUEST_METHOD'] != 'POST')
				$this->response(0,"Unauthorized request!");
		$url = "https://test.salesforce.com/services/oauth2/token";
		
		$postdata = http_build_query(
			array(
				'grant_type' => 'password',
				'client_id' => 'client_id here',
				'client_secret' => 'client_secret here',
				'username' => 'username here',
				'password' => 'password here'
			)
		);
		$opts = array('http' =>
			array(
				'method'  => 'POST',
				'header'  => 'Content-type: application/x-www-form-urlencoded',
				'content' => $postdata
			)
		);
		$context  = stream_context_create($opts);
		$result = file_get_contents($url, false, $context);
		if($result) {
			$this->response(1,$result);
		} else {
			$this->response(0,$result);
		}
	}
	
	//Response method
	private function response($success, $message) {
		$response["results"] = array();
		$post["success"] = (int) $success;
		$post["message"] = $message;
		array_push($response["results"], $post);
		echo json_encode($response);
		exit;
	}
}
$sf_token = new SF_TOKEN;
$sf_token->processApi();

The above class will return you the below response, if you make ajax http post request from javascript.

{"results": [{"success": 1, "message": "{"id": "https://test.salesforce.com/id/xxxxxxxxxx/xxxxxxx", "issued_at": "1396282387795", "token_type": "Bearer", "instance_url": "https://cs6.salesforce.com", "signature":"xxxxxxxxxxxxxxxx", "access_token": "xxxxxxxxxxxxxxxxxxxxxx"}"}]}

The above practice will take more response time than calling salesforce directly from client side application. Though direct call is insecure, server side scripting is the only way to go.

For further clarification, please feel free to comment.

About Mohanraj Balasubramaniam

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>