You are here

public function Salesforce::requestToken in Salesforce Suite 7.3

OAuth step 2: Exchange an authorization code for an access token.

Parameters

string $code: Code from Salesforce.

File

includes/salesforce.inc, line 421
Objects, properties, and methods to communicate with the Salesforce REST API

Class

Salesforce
Ability to authorize and communicate with the Salesforce REST API.

Code

public function requestToken($code) {
  $data = drupal_http_build_query(array(
    'code' => $code,
    'grant_type' => 'authorization_code',
    'client_id' => $this->consumer_key,
    'client_secret' => $this->consumer_secret,
    'redirect_uri' => $this
      ->redirectUrl(),
  ));
  $url = $this->login_url . '/services/oauth2/token';
  $headers = array(
    // This is an undocumented requirement on SF's end.
    'Content-Type' => 'application/x-www-form-urlencoded',
  );
  $response = $this
    ->httpRequest($url, $data, $headers, 'POST');
  $data = drupal_json_decode($response->data);
  if ($response->code != 200) {
    $error = isset($data['error_description']) ? $data['error_description'] : $response->error;
    throw new SalesforceException($error, $response->code);
  }

  // Ensure all required attributes are returned. They can be omitted if the
  // OAUTH scope is inadequate.
  $required = array(
    'refresh_token',
    'access_token',
    'id',
    'instance_url',
  );
  foreach ($required as $key) {
    if (!isset($data[$key])) {
      return FALSE;
    }
  }
  $this
    ->setRefreshToken($data['refresh_token']);
  $this
    ->setAccessToken($data['access_token']);
  $this
    ->setIdentity($data['id']);
  $this
    ->setInstanceUrl($data['instance_url']);
  return TRUE;
}