You are here

public function FormAssemblyRequest::getToken in FormAssembly 7

Retrieve an active access_token from the database or request a new one.

Parameters

string $code: A hash passed into $_GET['code'] after the user has been redirected back from the auth portal. Needed for new token requests.

Return value

bool|null An access token if available or FALSE if something has gone wrong.

1 call to FormAssemblyRequest::getToken()
FormAssemblyRequest::authorize in includes/FormAssemblyRequest.php
Redirect the user so to authorize the application using OAuth2.0.

File

includes/FormAssemblyRequest.php, line 97
Authorizes the current site and handles API requests to FormAssembly.

Class

FormAssemblyRequest
@file Authorizes the current site and handles API requests to FormAssembly.

Code

public function getToken($code = '') {

  // Retrieve a previously generated token.
  $token = variable_get('formassembly_oauth_access_token', '');
  if (!empty($token)) {
    return $token;
  }

  // Something went wrong - maybe they ended up at this page by accident?
  if (empty($code)) {
    return FALSE;
  }

  // Prepare to request a new access_token.
  $data = array(
    "grant_type" => "authorization_code",
    "type" => "web_server",
    "client_id" => $this->clientId,
    "client_secret" => $this->clientSecret,
    "redirect_uri" => $this->returnUrl,
    "code" => $code,
  );
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $this->apiHost . '/' . $this->tokenEndpoint);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $response = curl_exec($ch);
  unset($ch);
  $response = json_decode($response);
  if (isset($response->access_token)) {
    $this
      ->setToken($response->access_token);
    variable_set('formassembly_oauth_access_token', $this->token);
    return $this->token;
  }
  watchdog('formassembly', 'Could not retrieve access token.', array(), WATCHDOG_ERROR);
  return FALSE;
}