You are here

function commerce_square_renew_access_token in Commerce Square Connect 7

Renew access token.

Triggered by cron via commerce_square_cron().

1 call to commerce_square_renew_access_token()
commerce_square_cron in ./commerce_square.module
Implements hook_cron().

File

./commerce_square.module, line 185
Module file for Commerce Square.

Code

function commerce_square_renew_access_token() {
  $settings = variable_get('commerce_square_settings', commerce_square_default_settings()) + commerce_square_default_settings();
  libraries_load('square');

  // If site has not yet had Square app configured, do nothing.
  if (empty($settings['live_app_id']) || empty($settings['live_access_token'])) {
    return FALSE;
  }

  // OAuth access tokens expire after 30 days. renew a token before it expires.
  // Begin attempting to renew on the 29th day.
  // https://developer.squareup.com/docs/oauth-api/cookbook/renew-oauth-tokens.
  if (!empty($settings['live_access_token_expiry']) && $settings['live_access_token_expiry'] - 86400 < time()) {

    // Use OAuth API and ObtainToken endpoint if SDK version accommodates.
    if (class_exists('SquareConnect\\Api\\OAuthApi') && method_exists('SquareConnect\\Model\\ObtainTokenRequest', 'setRefreshToken')) {
      $oauth_api = new OAuthApi();
      $request_body = new ObtainTokenRequest();

      // Use refresh token, if present, and make request via OAuth API.
      if (!empty($settings['live_access_refresh_token'])) {
        $request_body
          ->setClientId($settings['live_app_id']);
        $request_body
          ->setClientSecret($settings['app_secret']);
        $request_body
          ->setGrantType('refresh_token');
        $request_body
          ->setRefreshToken($settings['live_access_refresh_token']);
        try {
          $result = $oauth_api
            ->obtainToken($request_body);
        } catch (Exception $e) {
          watchdog('commerce_square', 'Square token refresh failed. Message: @message', array(
            '@message' => $e
              ->getMessage(),
          ), WATCHDOG_ERROR);
          return FALSE;
        }
        $access_token = !empty($result) ? $result
          ->getAccessToken() : FALSE;
        if (!empty($access_token)) {
          $settings['live_access_token'] = $access_token;
          $settings['live_access_token_expiry'] = strtotime($result
            ->getExpiresAt());
          $settings['live_access_refresh_token'] = $result
            ->getRefreshToken();
          variable_set('commerce_square_settings', $settings);
          watchdog('commerce_square', 'Square token refresh successful.', array(), WATCHDOG_INFO);
        }
        else {
          watchdog('commerce_square', 'Square token refresh failed: no access token returned by ObtainToken endpoint when using refresh_token.', array(), WATCHDOG_ERROR);
        }
      }
      else {
        $request_body
          ->setClientId($settings['live_app_id']);
        $request_body
          ->setClientSecret($settings['app_secret']);
        $request_body
          ->setGrantType('migration_token');
        $request_body
          ->setMigrationToken($settings['live_access_token']);
        try {
          $result = $oauth_api
            ->obtainToken($request_body);
        } catch (Exception $e) {
          watchdog('commerce_square', 'Square token refresh via migration_token failed. Message: @message', array(
            '@message' => $e
              ->getMessage(),
          ), WATCHDOG_ERROR);
          return FALSE;
        }
        $access_token = !empty($result) ? $result
          ->getAccessToken() : FALSE;
        if (!empty($access_token)) {
          $settings['live_access_token'] = $access_token;
          $settings['live_access_token_expiry'] = strtotime($result
            ->getExpiresAt());
          $settings['live_access_refresh_token'] = $result
            ->getRefreshToken();
          variable_set('commerce_square_settings', $settings);
          watchdog('commerce_square', 'Square token refresh via migration_token successful.', array(), WATCHDOG_INFO);
        }
        else {
          watchdog('commerce_square', 'Square token migration failed: no access token returned by ObtainToken endpoint when using migration_token.', array(), WATCHDOG_ERROR);
        }
      }
    }
    else {
      $data = array(
        'access_token' => $settings['live_access_token'],
      );
      $data_string = json_encode($data);
      $ch = curl_init('https://connect.squareup.com/oauth2/clients/' . $settings['live_app_id'] . '/access-token/renew');
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen($data_string),
        'Authorization: Client ' . $settings['app_secret'],
      ));
      $response = curl_exec($ch);
      $response_body = drupal_json_decode($response);
      if (!empty($response_body['access_token'])) {
        $settings['live_access_token'] = $response_body['access_token'];
        $settings['live_access_token_expiry'] = strtotime($response_body['expires_at']);
        variable_set('commerce_square_settings', $settings);
        watchdog('commerce_square', 'Square token refresh via deprecated RenewToken endpoint successful. Please consider upgrading the Square SDK.', array(), WATCHDOG_INFO);
      }
      else {
        watchdog('commerce_square', 'Square token refresh via deprecated RenewToken endpoint failed. Please consider upgrading the Square SDK.', array(), WATCHDOG_ERROR);
      }
    }
  }
}