Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subscription billing fixes #3590

Merged
merged 4 commits into from
Jul 18, 2024
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Release Notes for Craft Commerce

## Unreleased

- Fixed PHP error that occurred when saving an estimated billing address. ([#3549](https://github.com/craftcms/commerce/pull/3549))
- Fixed a bug where SCA payment sources prevented a subscription from starting. ([#3590](https://github.com/craftcms/commerce/pull/3590))

## 4.6.3.1 - 2024-06-20

- Fixed a PHP error that could occur on app initialization. ([#3546](https://github.com/craftcms/commerce/issues/3546))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
{% set subscriptionUid = craft.app.request.getParam('subscription') %}
{# @var subscription \craft\commerce\elements\Subscription #}
{% set subscription = craft.subscriptions()
.anyStatus()
.status(null)
.uid(subscriptionUid)
.one() %}

Expand Down Expand Up @@ -41,6 +41,7 @@

<fieldset>
<form>
{{ redirectInput('shop/plans') }}
{{ subscription.getBillingIssueResolveFormHtml()|raw }}
</form>
</fieldset>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
{% set subscriptionUid = craft.app.request.getParam('subscription') %}
{# @var subscription \craft\commerce\elements\Subscription #}
{% set subscription = craft.subscriptions()
.anyStatus()
.status(null)
.uid(subscriptionUid)
.one() %}

Expand Down Expand Up @@ -41,6 +41,7 @@

<fieldset>
<form>
{{ redirectInput('[[folderName]]/plans') }}
{{ subscription.getBillingIssueResolveFormHtml()|raw }}
</form>
</fieldset>
Expand Down
2 changes: 1 addition & 1 deletion src/Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ public static function editions(): array
/**
* @inheritDoc
*/
public string $schemaVersion = '4.5.2';
public string $schemaVersion = '4.5.3';

/**
* @inheritdoc
Expand Down
3 changes: 1 addition & 2 deletions src/base/SubscriptionGatewayInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

namespace craft\commerce\base;

use craft\base\SavableComponentInterface;
use craft\commerce\elements\Subscription;
use craft\commerce\errors\NotImplementedException;
use craft\commerce\errors\SubscriptionException;
Expand All @@ -23,7 +22,7 @@
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 2.0
*/
interface SubscriptionGatewayInterface extends SavableComponentInterface
interface SubscriptionGatewayInterface extends GatewayInterface
{
/**
* Cancels a subscription.
Expand Down
81 changes: 62 additions & 19 deletions src/controllers/SubscriptionsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use craft\commerce\helpers\PaymentForm;
use craft\commerce\Plugin;
use craft\commerce\Plugin as Commerce;
use craft\commerce\records\Subscription as SubscriptionRecord;
use craft\commerce\stripe\gateways\PaymentIntents;
use craft\commerce\web\assets\commercecp\CommerceCpAsset;
use craft\helpers\App;
Expand Down Expand Up @@ -164,6 +165,9 @@ public function actionSubscribe(): ?Response
{
$this->requireLogin();
$this->requirePostRequest();
$user = Craft::$app->getUser()->getIdentity();

$returnUrl = $this->request->getValidatedBodyParam('redirect');

$plugin = Commerce::getInstance();

Expand Down Expand Up @@ -194,34 +198,35 @@ public function actionSubscribe(): ?Response
}

try {
// We provide backward compatibility for stripe plugin 3.0
$paymentFormData = $this->request->getBodyParam(PaymentForm::getPaymentFormParamName($gateway->handle)) ?? [];

$createPaymentSource = function($gateway, $paymentFormData) use ($plugin) {
$paymentForm = $gateway->getPaymentFormModel();
$paymentForm->setAttributes($paymentFormData, false);
if (!empty($paymentFormData)) {
Craft::$app->getDeprecator()->log('SubscriptionController::create-newPaymentMethod', 'The subscription create action now requires that a customer’s default payment source is set up before subscribing, or pass the payment source information to the subscribe form.');

if ($paymentForm->validate()) {
$plugin->getPaymentSources()->createPaymentSource(Craft::$app->getUser()->getId(), $gateway, $paymentForm);
}
};

$exists = class_exists(PaymentIntents::class);
/** @phpstan-ignore-next-line */
if ($exists && $plan->getGateway() instanceof PaymentIntents) {
Craft::$app->getDeprecator()->log('SubscriptionController::create-newPaymentMethod', 'The subscription create action now requires that a customer’s default payment source is set up before subscribing with Stripe.');
// Only be backward compatible with Stripe if they supply the payment method ID.
if (isset($paymentFormData['paymentMethodId'])) {
$createPaymentSource = function($gateway, $paymentFormData) use ($plugin) {
$paymentForm = $gateway->getPaymentFormModel();
$paymentForm->setAttributes($paymentFormData, false);

if ($paymentForm->validate()) {
$plugin->getPaymentSources()->createPaymentSource(Craft::$app->getUser()->getId(), $gateway, $paymentForm);
}
};

$exists = class_exists(PaymentIntents::class);
/** @phpstan-ignore-next-line */
if ($exists && $plan->getGateway() instanceof PaymentIntents) {
if (isset($paymentFormData['paymentMethodId'])) {
$createPaymentSource($gateway, $paymentFormData);
}
} else {
$createPaymentSource($gateway, $paymentFormData);
}
} else {
$createPaymentSource($gateway, $paymentFormData);
}

$fieldsLocation = $this->request->getParam('fieldsLocation', 'fields');
$fieldValues = $this->request->getBodyParam($fieldsLocation, []);

$subscription = $plugin->getSubscriptions()->createSubscription(Craft::$app->getUser()->getIdentity(), $plan, $parameters, $fieldValues);
$subscription = $plugin->getSubscriptions()->createSubscription($user, $plan, $parameters, $fieldValues);
} catch (\Exception $exception) {
Craft::$app->getErrorHandler()->logException($exception);

Expand All @@ -231,6 +236,14 @@ public function actionSubscribe(): ?Response
$error = $exception->getMessage();
}

if ($returnUrl) {
$returnUrl = $this->getView()->renderObjectTemplate($returnUrl, $subscription);
$subscriptionRecord = SubscriptionRecord::findOne($subscription->id);
$subscriptionRecord->returnUrl = $returnUrl;
$subscriptionRecord->save();
$subscription->returnUrl = $returnUrl;
}

if (!$error && $subscription && $subscription->isSuspended && !$subscription->hasStarted) {
$url = Plugin::getInstance()->getSettings()->updateBillingDetailsUrl;

Expand All @@ -249,7 +262,8 @@ public function actionSubscribe(): ?Response
Craft::t('commerce', 'Subscription started.'),
data: [
'subscription' => $subscription ?? null,
]
],
redirect: $returnUrl
);
}

Expand Down Expand Up @@ -424,6 +438,35 @@ public function actionCancel(): ?Response
);
}

public function actionCompleteSubscription(): ?Response
{
$subscriptionUid = $this->request->getRequiredQueryParam('subscription');
$subscription = Subscription::find()->status(null)->uid($subscriptionUid)->one();

if (!$subscription) {
throw new NotFoundHttpException('Subscription not found');
}

$gateway = $subscription->getGateway();
$transactionHash = $gateway->getTransactionHashFromWebhook();
$useMutex = (bool)$transactionHash;
$transactionLockName = 'commerceTransaction:' . $transactionHash;
$mutex = Craft::$app->getMutex();

if ($useMutex && !$mutex->acquire($transactionLockName, 15)) {
throw new Exception('Unable to acquire a lock for transaction: ' . $transactionHash);
}

$gateway->refreshPaymentHistory($subscription);

if ($useMutex) {
$mutex->release($transactionLockName);
}

return $this->asSuccess(redirect: $subscription->returnUrl);
}


/**
* @param Subscription $subscription
* @throws ForbiddenHttpException
Expand Down
6 changes: 6 additions & 0 deletions src/elements/Subscription.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,11 @@ class Subscription extends Element
*/
public ?DateTime $dateSuspended = null;

/**
* @var string|null The URL to return to after a subscription is created
*/
public ?string $returnUrl = null;

/**
* @var SubscriptionGatewayInterface|null
*/
Expand Down Expand Up @@ -594,6 +599,7 @@ public function afterSave(bool $isNew): void
$subscriptionRecord->hasStarted = $this->hasStarted;
$subscriptionRecord->isSuspended = $this->isSuspended;
$subscriptionRecord->dateSuspended = $this->dateSuspended;
$subscriptionRecord->returnUrl = $this->returnUrl;

// We want to always have the same date as the element table, based on the logic for updating these in the element service i.e resaving
$subscriptionRecord->dateUpdated = $this->dateUpdated;
Expand Down
1 change: 1 addition & 0 deletions src/elements/db/SubscriptionQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -733,6 +733,7 @@ protected function beforePrepare(): bool
'commerce_subscriptions.subscriptionData',
'commerce_subscriptions.trialDays',
'commerce_subscriptions.userId',
'commerce_subscriptions.returnUrl',
]);

if (isset($this->userId)) {
Expand Down
1 change: 1 addition & 0 deletions src/migrations/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,7 @@ public function createTables(): void
'isCanceled' => $this->boolean()->notNull()->defaultValue(false),
'dateCanceled' => $this->dateTime(),
'isExpired' => $this->boolean()->notNull()->defaultValue(false),
'returnUrl' => $this->text(),
'dateExpired' => $this->dateTime(),
'dateCreated' => $this->dateTime()->notNull(),
'dateUpdated' => $this->dateTime()->notNull(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace craft\commerce\migrations;

use craft\db\Migration;

/**
* m240717_044256_add_return_url_to_subscription migration.
*/
class m240717_044256_add_return_url_to_subscription extends Migration
{
/**
* @inheritdoc
*/
public function safeUp(): bool
{
// add returnUrl to subscriptions table
$this->addColumn('{{%commerce_subscriptions}}', 'returnUrl', $this->text()->after('isExpired'));

return true;
}

/**
* @inheritdoc
*/
public function safeDown(): bool
{
echo "m240717_044256_add_return_url_to_subscription cannot be reverted.\n";
return false;
}
}
1 change: 1 addition & 0 deletions src/records/Subscription.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
* @property int $trialDays
* @property ActiveQueryInterface $user
* @property int $userId
* @property string $returnUrl
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 2.0
*/
Expand Down
Loading