PHP Example

From bMob Rest API
Jump to navigation Jump to search

bMobilized Rest API uses OAuth for Authentication. We have created a PHP example of the Web Server OAuth2 Authorization Flow for your reference. Full documentation for the Web Server OAuth2 Authorization Flow can be found at https://help.salesforce.com/HTViewHelpDoc?id=remoteaccess_oauth_web_server_flow.htm&language=en_US

The full authorization process consists on 4 steps:

  1. User is redirected to the Authorization screen. This step requires the generation of a specially tailored URL. Then the user is redirected to the generated URL.
  2. Credentials and permissions are provided by the user. The user will enter his / her credentials. After that, he / she will allow access to his / her data to the app.
  3. Authorization Token is received. Once credentials and permissions are provided, bMobilized will contact your webserver providing an Authorization token.
  4. Access Token is retrieved. Using the provided Authorization Token, your webserver will request the final Access Token required to use our Rest API.

Let's review each step.

Auth Process steps[edit | edit source]

User is redirected to the Authorization screen[edit | edit source]

The URL is generated using the following parameters:

An example of how to generate the previous URL:


<?php
	include('lib.php');
	
	// oAuth2 Web Server Flow example
	// Based on https://help.salesforce.com/HTViewHelpDoc?id=remoteaccess_oauth_web_server_flow.htm&language=en_US
	// First, we generate the link to redirect the user so that he / she can provide the required credentials and permissions.
	$url = "https://bmobilized.secure.force.com/login/services/oauth2/authorize";
	$fields = array(
		"response_type" => "code",
		"client_id" => "...",
		"scope" => "full refresh_token",
		"redirect_uri" => "..."
	);

	$url .= '?' . toUrlString($fields);
?>
<a href="<?= $url ?>">Login</a>

This working code can be accessed at https://rest.cloudhostedresources.com.

Credentials and permissions are provided by the user[edit | edit source]

This step will happen between the user and our system. No code is required on your side.


Authorization Token is received[edit | edit source]

Once credentials and permissions are provided, bMobilized will contact your webserver providing an Authorization token. The Authorization token will be sent as a URL parameter to the redirect_uri provided in the first step.


Access Token is retrieved[edit | edit source]

Using the received Authorization token, the final Access Token is retrieved. A POST request is sent to a special URL using the following parameters:

  • grant_type: authorization_code
  • client_id: Will be provided to you.
  • client_secret: Will be provided to you.
  • redirect_uri: Same as the first step.
  • code: The Authorization code received.

An example of how to retrieve your Access Token using the provided Authorization Token:


<?php
	include('lib.php');
	
	// oAuth2 Web Server Flow example
	// Based on https://help.salesforce.com/HTViewHelpDoc?id=remoteaccess_oauth_web_server_flow.htm&language=en_US
	
	// If an error URL param is received, we show it to the user.
	if(array_key_exists("error", $_REQUEST)){
		echo "Error: " . $_REQUEST["error_description"];
		exit();
	} else {
		// If we receive the authorization code, we proceed to retrieve the final Access Token and related information
		if(array_key_exists("code", $_REQUEST)){
			$url = "https://bmobilized.secure.force.com/login/services/oauth2/token";
			$fields = array(
				"grant_type" => "authorization_code",
				"client_id" => "...",
				"client_secret" => "...",
				"redirect_uri" => "...",
				"code" => $_REQUEST["code"]
			);
			
			// Let's retrieve the access token
			$ch = curl_init();

			// Set the url, number of POST vars, POST data
			curl_setopt($ch,CURLOPT_URL, $url);
			curl_setopt($ch,CURLOPT_POST, count($fields));
			curl_setopt($ch,CURLOPT_POSTFIELDS, toUrlString($fields));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

			// Execute post
			$result = curl_exec($ch);

			// Close connection
			curl_close($ch);
			
			// We decode the received json response
			$map = json_decode($result, true);
			
			// We will store it in session for future reference
			session_start();
			$_SESSION["auth"] = $map;
		} else {
			exit;
		}
	}
?>

This working code can be accessed at https://rest.cloudhostedresources.com/cb.php.

Accessing the Rest API using the Access Token[edit | edit source]


<?php
	// oAuth2 Web Server Flow example
	// Based on https://help.salesforce.com/HTViewHelpDoc?id=remoteaccess_oauth_web_server_flow.htm&language=en_US

	// Finally, we will retrieve the site list for the authorized user
	// For information about the available Rest API calls, please refer to our documentation
	$ch = curl_init();  

	session_start();
	$auth = $_SESSION["auth"];

	// The instance_url from the authorization information
	// needs to be used to contacting our services
	$url = $auth["instance_url"] . "/services/apexrest/v1/sites";

	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_HEADER, true);

	// The access token needs to be sent as an Authorization Header
	curl_setopt($ch, CURLOPT_HTTPHEADER, array(
		'Authorization: Bearer ' . $auth['access_token']
	));

	$response = curl_exec($ch);
	$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
	$header = substr($response, 0, $header_size);
	$body = substr($response, $header_size);

	curl_close($ch);

	// Formatting the data to show it
	$data = json_decode($body, true);
	$json_string = json_encode($data, JSON_PRETTY_PRINT);
?>
<h1>Site List</h1>
<p><?= $json_string ?></p>

This working code can be accessed at https://rest.cloudhostedresources.com/sitelist.php.

Apendix A: lib.php code[edit | edit source]


<?php
	function toUrlString($fields){
		$fields_string = "";
		foreach($fields as $key=>$value) { $fields_string .= $key.'='.urlencode($value).'&'; }
		rtrim($fields_string, '&');
		return  $fields_string;
	}
?>