You are here

function commerce_square_settings_form in Commerce Square Connect 7

Square settings form.

Parameters

array $form: The form.

array $form_state: The form state.

Return value

array The form.

1 string reference to 'commerce_square_settings_form'
commerce_square_menu in ./commerce_square.module
Implements hook_menu().

File

includes/commerce_square.admin.inc, line 237
Provides admin menu callbacks for Commerce Square.

Code

function commerce_square_settings_form(array $form, array &$form_state) {
  $settings = variable_get('commerce_square_settings', commerce_square_default_settings()) + commerce_square_default_settings();
  libraries_load('square');
  $successful_connection = FALSE;

  // Check current API and give warning if upgrade is needed.
  // SDK does not provide methods to getVersion or getReleaseDate,
  // so user agent string parsing is required.
  $sdk_string = explode('/', Configuration::getDefaultConfiguration()
    ->getUserAgent());
  $sdk_version = $sdk_string[1];
  $sdk_numbers = explode('.', $sdk_version);
  $sdk_date = $sdk_numbers[1];
  if ($sdk_date < 20190313) {
    drupal_set_message(t('Your Square SDK version, @version, is out of date and may stop working when deprecated methods are removed. Please upgrade to 2.20190313.0 or higher.', array(
      '@version' => $sdk_version,
    )), 'warning');
  }

  // If site is configured with Square app credentials AND we are being
  // returned to the form from Square with an application code, then
  // proceed to exchange application code for an access token.
  // Empty $form_state['input'] handles case when stale $_GET['code'] persists
  // after failed authorization attempt: input is empty when form reloads after
  // being redirected back from Square in initial authorization step.
  if (empty($form_state['input']) && !empty($_GET['code']) && !empty($settings['live_app_id']) && !empty($settings['app_secret'])) {

    // Use newer OAuth API ObtainToken endpoint with grant_type parameter,
    // available since version 20190313.
    if ($sdk_date >= 20190313 && class_exists('SquareConnect\\Api\\OAuthApi') && method_exists('SquareConnect\\Model\\ObtainTokenRequest', 'setGrantType')) {

      // If all checks out, use OAuth API to communicate with Square.
      $oauth_api = new OAuthApi();
      $request_body = new ObtainTokenRequest();
      $request_body
        ->setClientId($settings['live_app_id']);
      $request_body
        ->setClientSecret($settings['app_secret']);
      $request_body
        ->setGrantType('authorization_code');
      $request_body
        ->setCode(check_plain($_GET['code']));
      try {
        $result = $oauth_api
          ->obtainToken($request_body);
      } catch (Exception $e) {
        drupal_set_message(t('There was an error saving the OAuth token: @error', array(
          '@error' => $e
            ->getMessage(),
        )), 'error');
      }
      $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);
        $successful_connection = TRUE;
        drupal_set_message(t('Your Drupal Commerce store and Square have been successfully connected.'));
      }
      else {

        // Failure message, but only if something was NOT already caught as

        //error $e during obtainToken() request.
        if (!isset($e)) {
          drupal_set_message(t('There was an error saving the OAuth token: no token was returned.'), 'error');
        }
      }
    }
    else {

      // @TODO: remove this section when API/SDK versions relying on it
      // are no longer supported by Square.
      // Use the older curl-based method to communicate with Square.
      $data = array(
        'client_id' => $settings['live_app_id'],
        'client_secret' => $settings['app_secret'],
        'code' => check_plain($_GET['code']),
      );
      $data_string = json_encode($data);
      $ch = curl_init('https://connect.squareup.com/oauth2/token');
      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),
      ));
      $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);
        $successful_connection = TRUE;
        drupal_set_message(t('Your Drupal Commerce store and Square have been successfully connected, but consider upgrading to a newer version of the Square SDK.'));
      }
      else {
        drupal_set_message(t('There was an error saving the OAuth token. Try upgrading to a newer version of the Square SDK.'), 'error');
      }
    }
  }
  if (empty($form_state['input']) && !$successful_connection) {
    drupal_set_message(t('After clicking save you will be redirected to Square to sign in and connect your Drupal Commerce store. If the save button does not work, try loading the page in its own window and not as an overlay: /admin/commerce/config/square'), 'warning');
  }
  $form['credentials'] = array(
    '#type' => 'fieldset',
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
    '#title' => t('Application credentials'),
    '#description' => t('You can get these by selecting your app <a href="https://connect.squareup.com/apps">here</a>.'),
  );
  $form['credentials']['app_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Application Name'),
    '#default_value' => $settings['app_name'],
    '#required' => TRUE,
  );
  $form['credentials']['live_app_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Application ID'),
    '#default_value' => $settings['live_app_id'],
    '#required' => TRUE,
  );
  $form['credentials']['app_secret'] = array(
    '#type' => 'textfield',
    '#title' => t('Application Secret'),
    '#description' => t('You can get this by selecting your app <a href="https://connect.squareup.com/apps">here</a> and clicking on the OAuth tab.'),
    '#default_value' => $settings['app_secret'],
    '#required' => TRUE,
  );
  $form['credentials']['redirect_url'] = array(
    '#type' => 'item',
    '#title' => t('Redirect URL'),
    '#markup' => url('admin/commerce_square/oauth/obtain', array(
      'absolute' => TRUE,
    )),
    '#description' => t('Copy this URL and use it for the redirect URL field in your app OAuth settings.'),
  );
  $form['credentials']['live_access_token'] = array(
    '#type' => 'value',
    '#default_value' => $settings['live_access_token'],
  );
  $form['credentials']['live_access_token_expiry'] = array(
    '#type' => 'value',
    '#default_value' => $settings['live_access_token_expiry'],
  );
  $form['sandbox'] = array(
    '#type' => 'fieldset',
    '#description' => t('You can get these by selecting your app <a href="https://connect.squareup.com/apps">here</a>.'),
    '#collapsible' => FALSE,
    '#collapsed' => FALSE,
    '#title' => t('Sandbox'),
  );
  $form['sandbox']['test_app_id'] = array(
    '#type' => 'textfield',
    '#title' => t('Sandbox Application ID'),
    '#default_value' => $settings['test_app_id'],
    '#required' => TRUE,
  );
  $form['sandbox']['test_access_token'] = array(
    '#type' => 'textfield',
    '#title' => t('Sandbox Access Token'),
    '#default_value' => $settings['test_access_token'],
    '#required' => TRUE,
  );
  $form['actions']['#type'] = 'actions';
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save configuration'),
  );
  if (form_get_errors()) {
    drupal_set_message(t('The settings have not been saved because of the errors.'), 'error');
  }
  if (!isset($form['#theme'])) {
    $form['#theme'] = 'system_settings_form';
  }
  return $form;
}