Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,26 @@ final class PaymentGatewayProfileFactory
public static function build(string $provider, array $params): ?PaymentGatewayProfile
{
Log::debug("PaymentGatewayProfileFactory::build()", ['provider' => $provider, 'params' => $params]);
$profile = null;
if ($provider == IPaymentConstants::ProviderStripe) {
$profile = static::populate(new StripePaymentProfile, $params);
}
return static::populate(static::create($provider), $params);
}

if ($provider == IPaymentConstants::ProviderLawPay) {
$profile = static::populate(new LawPayPaymentProfile, $params);
}
/**
* Returns an empty profile for the provider. Unlike build(), it never calls the payment
* gateway, so the caller can keep a reference to the profile before populate() creates
* any webhook.
* @param string $provider
* @return PaymentGatewayProfile
* @throws \models\exceptions\ValidationException
*/
public static function create(string $provider): PaymentGatewayProfile
{
if ($provider == IPaymentConstants::ProviderStripe)
return new StripePaymentProfile;

if(is_null($profile))
throw new ValidationException("Profile type does not exists.");
if ($provider == IPaymentConstants::ProviderLawPay)
return new LawPayPaymentProfile;

return $profile;
throw new ValidationException("Profile type does not exists.");
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,16 @@ public function setTestMode(): void

abstract public function buildWebHook(): void;

/**
* Deletes at the payment gateway every webhook that this in-memory instance created itself.
* Called when the transaction meant to persist the profile fails: the DB rollback cannot
* undo a call to the gateway, and a webhook nobody stored would be left behind.
* Providers whose webhooks cannot be told apart per profile keep this no-op.
*/
public function discardCreatedWebHooks(): void
{
}

abstract protected function clearWebHooks():void;

public function setExternalId(string $external_id): void{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,13 @@ class StripePaymentProfile extends PaymentGatewayProfile
#[ORM\Column(name: 'SendEmailReceipt', type: 'boolean')]
protected $send_email_receipt;

/**
* Webhooks this in-memory instance created at Stripe, so that discardCreatedWebHooks() can
* delete them again. Not mapped: it never outlives the request that created them.
* @var array<int, array{id: string, test_mode: bool}>
*/
private array $created_webhooks = [];

/**
* StripePaymentProfile constructor.
*/
Expand Down Expand Up @@ -235,6 +242,7 @@ public function buildWebHook(): void
]));
// and set web hook info
$this->setWebHookInfo($info);
$this->created_webhooks[] = ['id' => $info['id'], 'test_mode' => (bool)$this->test_mode_enabled];
}
} catch (\Exception $ex) {
Log::error($ex);
Expand Down Expand Up @@ -289,6 +297,27 @@ protected function clearLiveWebHook(): void
}
}

/**
* @inheritDoc
*/
public function discardCreatedWebHooks(): void
{
foreach ($this->created_webhooks as $webhook) {
$id = $webhook['id'];
try {
Log::warning(sprintf("StripePaymentProfile::discardCreatedWebHooks deleting webhook %s", $id));
$config = $webhook['test_mode'] ? $this->createTestConfiguration() : $this->createLiveConfiguration();
(new StripeApi($config))->deleteWebHookById($id);
if ($this->live_webhook_id === $id) $this->live_webhook_id = $this->live_webhook_secret_key = '';
if ($this->test_webhook_id === $id) $this->test_webhook_id = $this->test_webhook_secret_key = '';
} catch (\Exception $ex) {
// the profile is not stored, so nothing else will ever delete this webhook
Log::error(sprintf("StripePaymentProfile::discardCreatedWebHooks could not delete webhook %s: %s", $id, $ex->getMessage()));
}
}
$this->created_webhooks = [];
}

protected function clearWebHooks(): void
{
Log::debug("StripePaymentProfile::clearWebHooks");
Expand Down
86 changes: 69 additions & 17 deletions app/Services/Model/Imp/PaymentGatewayProfileService.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
use Illuminate\Support\Facades\Log;
use models\exceptions\EntityNotFoundException;
use models\exceptions\ValidationException;
use models\summit\IPaymentConstants;
use models\summit\PaymentGatewayProfile;
use models\summit\PaymentGatewayProfileFactory;
use models\summit\Summit;
use services\utils\AmbiguousCommitException;

/**
* Class PaymentGatewayProfileService
Expand All @@ -35,24 +37,74 @@ final class PaymentGatewayProfileService
*/
public function addPaymentProfile(Summit $summit, array $payload): ?PaymentGatewayProfile
{
return $this->tx_service->transaction(function () use ($summit, $payload) {
Log::debug("PaymentGatewayProfileService::addPaymentProfilee", ["summit" => $summit->getId(), 'payload' => $payload]);
$payload['summit'] = $summit;
$profile = PaymentGatewayProfileFactory::build($payload['provider'], $payload);
$formerProfile = $summit->getPaymentGateWayProfilePerApp($profile->getApplicationType());
if ($profile->isActive() && !is_null($formerProfile) && $formerProfile->isActive()) {
throw new ValidationException
(
sprintf("There is already an active Payment Profile for application type %s,", $formerProfile->getApplicationType())
);
}
$summit->addPaymentProfile($profile);
if (isset($payload['active']) && boolval($payload['active']) == true) {
// force activation ( rebuild web hook )
$profile->activate();
// Populating a profile can already create its webhook at the payment gateway, and a DB
// rollback cannot undo that. Every profile built here is tracked so that its webhooks can
// be deleted again when it does not end up stored: a failed transaction, an attempt that
// the root transaction re-ran after a transient DB error, or a returned profile that the
// transaction never inserted.
$built_profiles = [];
try {
$profile = $this->tx_service->transaction(function () use ($summit, $payload, &$built_profiles) {
Log::debug("PaymentGatewayProfileService::addPaymentProfilee", ["summit" => $summit->getId(), 'payload' => $payload]);
$is_active = isset($payload['active']) && boolval($payload['active']) == true;
// check before building the profile, so that a rejected one never reaches the gateway
if ($is_active) {
$formerProfile = $summit->getPaymentGateWayProfilePerApp
(
$payload['application_type'] ?? IPaymentConstants::ApplicationTypeRegistration
);
if (!is_null($formerProfile) && $formerProfile->isActive()) {
throw new ValidationException
(
sprintf("There is already an active Payment Profile for application type %s,", $formerProfile->getApplicationType())
);
}
}
$payload['summit'] = $summit;
$profile = PaymentGatewayProfileFactory::create($payload['provider']);
$built_profiles[] = $profile;
PaymentGatewayProfileFactory::populate($profile, $payload);
$summit->addPaymentProfile($profile);
if ($is_active) {
// force activation ( rebuild web hook )
$profile->activate();
}
return $profile;
});
} catch (AmbiguousCommitException $ex) {
// The COMMIT of the last attempt was sent but never acknowledged, so its profile may
// be stored, and its webhook has to stay. The root transaction re-runs the closure
// only before COMMIT, so every earlier attempt was rolled back.
$last_profile = array_pop($built_profiles);
foreach ($built_profiles as $built_profile)
$built_profile->discardCreatedWebHooks();
if (!is_null($last_profile)) {
Log::warning(sprintf(
"PaymentGatewayProfileService::addPaymentProfile summit %s commit outcome unknown, kept the webhooks of the %s profile; reconcile them with the stored payment profiles.",
$summit->getId(),
$last_profile->getApplicationType()
));
}
return $profile;
});
throw $ex;
} catch (\Throwable $ex) {
foreach ($built_profiles as $built_profile)
$built_profile->discardCreatedWebHooks();
throw $ex;
}

if ($profile->isNew()) {
Log::warning(sprintf(
"PaymentGatewayProfileService::addPaymentProfile summit %s the transaction returned a %s profile that was not stored.",
$summit->getId(),
$profile->getApplicationType()
));
}
foreach ($built_profiles as $built_profile) {
// the returned profile keeps its webhooks only when the transaction inserted it
if ($built_profile !== $profile || $profile->isNew())
$built_profile->discardCreatedWebHooks();
}
return $profile;
}

/**
Expand Down
Loading
Loading