Skip to content

Commit

Permalink
Merge branch 'main' of github.com:craftcms/stripe
Browse files Browse the repository at this point in the history
  • Loading branch information
nfourtythree committed Apr 26, 2024
2 parents 206cb85 + 65e0e93 commit b7bd0b4
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 11 deletions.
35 changes: 29 additions & 6 deletions src/Plugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use craft\helpers\Html;
use craft\helpers\UrlHelper;
use craft\models\FieldLayout;
use craft\records\User as UserRecord;
use craft\services\Elements;
use craft\services\Fields;
use craft\services\Utilities;
Expand Down Expand Up @@ -54,6 +55,7 @@
use craft\web\UrlManager;
use yii\base\Event;
use yii\base\InvalidConfigException;
use yii\base\ModelEvent;

/**
* Stripe plugin
Expand Down Expand Up @@ -143,6 +145,7 @@ public function init()
$this->registerResaveCommands();
$this->registerBehaviors();
$this->registerConditionRules();
$this->handleUserElementChanges();

if (!$request->getIsConsoleRequest()) {
if ($request->getIsCpRequest()) {
Expand All @@ -169,12 +172,6 @@ public function init()
->onUpdate(self::PC_PATH_SUBSCRIPTION_FIELD_LAYOUTS, [$subscriptionService, 'handleChangedFieldLayout'])
->onRemove(self::PC_PATH_SUBSCRIPTION_FIELD_LAYOUTS, [$subscriptionService, 'handleDeletedFieldLayout']);

// // Globally register stripe webhooks registry event handlers
// Registry::addHandler(Topics::PRODUCTS_CREATE, new ProductHandler());
// Registry::addHandler(Topics::PRODUCTS_DELETE, new ProductHandler());
// Registry::addHandler(Topics::PRODUCTS_UPDATE, new ProductHandler());
// Registry::addHandler(Topics::INVENTORY_LEVELS_UPDATE, new ProductHandler());

// get stripe environment from the secret key
$this->stripeMode = $this->getStripeMode();
$this->stripeBaseUrl = "$this->dashboardUrl/$this->stripeMode";
Expand Down Expand Up @@ -515,6 +512,32 @@ function(RegisterConditionRulesEvent $event) {
);
}

/**
* Maybe sync changed user email from Craft to Stripe.
*
* @return void
*/
private function handleUserElementChanges(): void
{
Event::on(UserRecord::class, UserRecord::EVENT_BEFORE_UPDATE, function(ModelEvent $event) {
$userRecord = $event->sender;
$user = Craft::$app->getUsers()->getUserById($userRecord->id);
if ($user->isCredentialed) {
$oldEmail = $userRecord->getOldAttribute('email');
$newEmail = $userRecord->getAttribute('email');
if ($oldEmail != $newEmail) {
$customers = $user->getStripeCustomers();

Check failure on line 529 in src/Plugin.php

View workflow job for this annotation

GitHub Actions / ci / Code Quality / PHPStan / PHPStan

Call to an undefined method craft\elements\User::getStripeCustomers().
if (!empty($customers)) {
$client = $this->getApi()->getClient();
foreach ($customers as $customer) {
$client->customers->update($customer->stripeId, ['email' => $newEmail]);
}
}
}
}
});
}

/**
* @inheritdoc
*/
Expand Down
1 change: 1 addition & 0 deletions src/elements/Product.php
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,7 @@ protected static function defineDefaultTableAttributes(string $source): array
'stripeId',
'stripeStatus',
'stripeEdit',
'link',
];
}

Expand Down
5 changes: 1 addition & 4 deletions src/migrations/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ public function createTables(): void
'dateCreated' => $this->dateTime()->notNull(),
'dateUpdated' => $this->dateTime()->notNull(),
'uid' => $this->string(),
'prices' => $this->text()->defaultValue(null),
]);

$this->archiveTableIfExists(Table::PAYMENTMETHODDATA);
Expand Down Expand Up @@ -194,10 +195,6 @@ private function createGeneratedColumns(): void
$this->execute("ALTER TABLE " . Table::SUBSCRIPTIONDATA . " ADD COLUMN " .
$db->quoteColumnName('trialEnd') . " VARCHAR(255) GENERATED ALWAYS AS (" .
$qb->jsonExtract('data', ['trial_end']) . ") STORED;");
// prices
$this->execute("ALTER TABLE " . Table::SUBSCRIPTIONDATA . " ADD COLUMN " .
$db->quoteColumnName('prices') . " VARCHAR(255) GENERATED ALWAYS AS (" .
$qb->jsonExtract('data', ['items', 'data[*]', 'price', 'id']) . ") STORED;");

// invoice data
// created
Expand Down
5 changes: 5 additions & 0 deletions src/models/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ class Settings extends Model
*/
public string $productTemplate = '';

/**
* @var bool Whether updating credentialed user's email address should update Stripe customer(s)
*/
public bool $syncChangedUserEmailsToStripe = true;

/**
* @var mixed
*/
Expand Down
9 changes: 8 additions & 1 deletion src/services/Checkout.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use Craft;
use craft\elements\User;
use craft\helpers\UrlHelper;
use craft\stripe\elements\Price;
use craft\stripe\events\CheckoutSessionEvent;
use craft\stripe\models\Customer;
Expand Down Expand Up @@ -69,7 +70,13 @@ public function getCheckoutUrl(
}
}

return $this->startCheckoutSession(array_values($lineItems), $customer, $successUrl, $cancelUrl, $params);
return $this->startCheckoutSession(
array_values($lineItems),
$customer,
UrlHelper::siteUrl($successUrl),
UrlHelper::siteUrl($cancelUrl),
$params,
);
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/services/Subscriptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ public function createOrUpdateSubscription(StripeSubscription $subscription): bo
'title' => $subscription->description ?? $subscription->id,
'stripeStatus' => $subscription->status,
'data' => Json::decode($subscription->toJSON()),
'prices' => array_map(fn($item) => $item['price']['id'], $subscription->items->data),
];

// Set attributes on the element to emulate it having been loaded with JOINed data:
Expand Down

0 comments on commit b7bd0b4

Please sign in to comment.