You are here

class SquareSettings in Commerce Square Connect 8

Hierarchy

Expanded class hierarchy of SquareSettings

1 string reference to 'SquareSettings'
commerce_square.routing.yml in ./commerce_square.routing.yml
commerce_square.routing.yml

File

src/Form/SquareSettings.php, line 14

Namespace

Drupal\commerce_square\Form
View source
class SquareSettings extends ConfigFormBase {
  protected $permissionScope = [
    'MERCHANT_PROFILE_READ',
    'PAYMENTS_READ',
    'PAYMENTS_WRITE',
    'CUSTOMERS_READ',
    'CUSTOMERS_WRITE',
    'ORDERS_WRITE',
  ];

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'commerce_square.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'commerce_square_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $config = $this
      ->config('commerce_square.settings');
    $code = $this
      ->getRequest()->query
      ->get('code');
    if (!empty($code)) {
      try {

        /** @var \Drupal\commerce_square\Connect $connect */
        $connect = \Drupal::service('commerce_square.connect');
        $client = $connect
          ->getClient('production');
        $oauth_api = new OAuthApi($client);
        $obtain_token_request = new ObtainTokenRequest();
        $obtain_token_request
          ->setClientId($config
          ->get('production_app_id'))
          ->setClientSecret($config
          ->get('app_secret'))
          ->setCode($code)
          ->setGrantType('authorization_code');
        $token_response = $oauth_api
          ->obtainToken($obtain_token_request);
        $state = \Drupal::state();
        $state
          ->setMultiple([
          'commerce_square.production_access_token' => $token_response
            ->getAccessToken(),
          'commerce_square.production_access_token_expiry' => strtotime($token_response
            ->getExpiresAt()),
          'commerce_square.production_refresh_token' => $token_response
            ->getRefreshToken(),
        ]);
        $this
          ->messenger()
          ->addStatus($this
          ->t('Your Drupal Commerce store and Square have been successfully connected.'));
      } catch (ApiException $e) {
        $this
          ->messenger()
          ->addError($e
          ->getResponseBody()->message);
      }

      // Redirect back to the form so the OAuth code is removed from the URL.
      return new RedirectResponse(Url::fromRoute('commerce_square.settings')
        ->toString());
    }
    if (!$form_state
      ->isProcessingInput()) {
      $this
        ->messenger()
        ->addWarning($this
        ->t('After clicking save you will be redirected to Square to sign in and connect your Drupal Commerce store.'));
    }
    $form['oauth'] = [
      '#type' => 'fieldset',
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
      '#title' => $this
        ->t('OAuth'),
    ];
    $form['oauth']['instructions'] = [
      '#markup' => $this
        ->t('<p>Configure the OAuth information for your Square Connect application. You can get this by selecting your app <a href="https://connect.squareup.com/apps">here</a> and clicking on the OAuth tab.</p>'),
    ];
    $form['oauth']['app_secret'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Application Secret'),
      '#default_value' => $config
        ->get('app_secret'),
      '#description' => $this
        ->t('<p>The Application Secret identifies your application to Square for OAuth authentication.</p>'),
      '#required' => TRUE,
    ];
    $form['oauth']['redirect_url'] = [
      '#type' => 'item',
      '#title' => $this
        ->t('Redirect URL'),
      '#markup' => Url::fromRoute('commerce_square.oauth.obtain', [], [
        'absolute' => TRUE,
      ])
        ->toString(),
      '#description' => $this
        ->t('Copy this URL and use it for the redirect URL field in your app OAuth settings.'),
    ];
    $form['credentials'] = [
      '#type' => 'fieldset',
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
      '#title' => $this
        ->t('Credentials'),
    ];
    $form['credentials']['introduction'] = [
      '#markup' => $this
        ->t('Provide the production application ID for your application.'),
    ];
    $form['credentials']['app_name'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Application Name'),
      '#default_value' => $config
        ->get('app_name'),
      '#required' => TRUE,
    ];
    $form['credentials']['production_app_id'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Application ID'),
      '#default_value' => $config
        ->get('production_app_id'),
      '#required' => TRUE,
    ];
    $form['sandbox'] = [
      '#type' => 'fieldset',
      '#collapsible' => FALSE,
      '#collapsed' => FALSE,
      '#title' => $this
        ->t('Sandbox'),
    ];
    $form['sandbox']['instructions'] = [
      '#markup' => $this
        ->t('Enter in your application sandbox environment information.'),
    ];
    $form['sandbox']['sandbox_app_id'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Sandbox Application ID'),
      '#default_value' => $config
        ->get('sandbox_app_id'),
      '#required' => TRUE,
      '#description' => $this
        ->t('<p>The Application Secret identifies your application to Square for OAuth authentication.</p>'),
    ];
    $form['sandbox']['sandbox_access_token'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Sandbox Access Token'),
      '#default_value' => $config
        ->get('sandbox_access_token'),
      '#description' => $this
        ->t('<p>This is one of your sandbox test account authorizations.</p>'),
      '#required' => TRUE,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this
      ->config('commerce_square.settings');
    $config
      ->set('app_name', $form_state
      ->getValue('app_name'))
      ->set('app_secret', $form_state
      ->getValue('app_secret'))
      ->set('sandbox_app_id', $form_state
      ->getValue('sandbox_app_id'))
      ->set('sandbox_access_token', $form_state
      ->getValue('sandbox_access_token'))
      ->set('production_app_id', $form_state
      ->getValue('production_app_id'));
    $config
      ->save();
    $options = [
      'query' => [
        'client_id' => $config
          ->get('production_app_id'),
        'state' => \Drupal::csrfToken()
          ->get(),
        'scope' => implode(' ', $this->permissionScope),
      ],
    ];
    $url = Url::fromUri('https://connect.squareup.com/oauth2/authorize', $options);
    $form_state
      ->setResponse(new TrustedRedirectResponse($url
      ->toString()));
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
SquareSettings::$permissionScope protected property
SquareSettings::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SquareSettings::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SquareSettings::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
SquareSettings::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.