commerce_square-8.x-1.x-dev/commerce_square.post_update.php
commerce_square.post_update.php
<?php
/**
* @file
* Post update functions for Commerce Square.
*/
use Drupal\commerce_square\ErrorHelper;
use Drupal\Core\Url;
use Drupal\Core\Utility\UpdateException;
use Square\Environment;
use Square\Exceptions\ApiException;
use Square\Models\ObtainTokenRequest;
/**
* Permission scope has changed and OAuth token needs to be regenerated.
*/
function commerce_square_post_update_oauth_token_warning() {
$messenger = \Drupal::messenger();
$messenger->addWarning(t('The Square integration requires the ORDERS_WRITE permission to add purchase details for orders sent to Square. You must <a href=":link">reauthorize with Square</a>', [
// Url generation is odd in the update kernel,
// see https://www.drupal.org/project/drupal/issues/2956953.
':link' => Url::fromRoute('commerce_square.settings', [], ['base_url' => ''])->toString(),
]));
}
/**
* Migrate legacy Square Connect OAuth access token.
*/
function commerce_square_post_update_oauth_token_migration() {
$messenger = \Drupal::messenger();
$state = \Drupal::state();
$connect = \Drupal::getContainer()->get('commerce_square.connect');
$client = $connect->getClient(Environment::PRODUCTION);
try {
$oauth_api = $client->getOAuthApi();
// Obtain token request.
$obtain_token_request = new ObtainTokenRequest(
$connect->getAppId(Environment::PRODUCTION),
$connect->getAppSecret(),
);
$obtain_token_request->setMigrationToken($connect->getAccessToken(Environment::PRODUCTION));
$api_response = $oauth_api->obtainToken($obtain_token_request);
if ($api_response->isSuccess()) {
$token_response = $api_response->getResult();
$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(),
]);
$messenger->addStatus(t('Commerce Square Connect OAuth access token has been migrated'));
}
else {
throw ErrorHelper::convertException(
new ApiException(
$api_response->getBody(),
$api_response->getRequest(),
NULL
)
);
}
}
catch (ApiException $e) {
$response_body = $e->getResponseBody();
if ($response_body->message !== 'Cannot migrate access token generated by or returned with refresh token') {
throw new UpdateException($response_body->message);
}
}
}
