Skip to content

Commit

Permalink
Fixed #12
Browse files Browse the repository at this point in the history
  • Loading branch information
andris-sevcenko committed May 23, 2018
1 parent 646750f commit 61090be
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 12 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Changelog
## Unreleased

- Added support for card tokens, not just payment sources. ([#9](https://github.com/craftcms/commerce-stripe/issues/9))
- Allow creating payment source on behalf of users. ([#12](https://github.com/craftcms/commerce-stripe/issues/12))

## 1.0.1

Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"rss": "https://github.com/craftcms/commerce-stripe/commits/master.atom"
},
"require": {
"craftcms/commerce": "^2.0.0-alpha.5",
"craftcms/commerce": "^2.0.0-beta.5",
"stripe/stripe-php": "^6.1"
},
"autoload": {
Expand Down
17 changes: 6 additions & 11 deletions src/gateways/Gateway.php
Original file line number Diff line number Diff line change
Expand Up @@ -272,19 +272,13 @@ public function completePurchase(Transaction $transaction): RequestResponseInter
/**
* @inheritdoc
*/
public function createPaymentSource(BasePaymentForm $sourceData): PaymentSource
public function createPaymentSource(BasePaymentForm $sourceData, int $userId): PaymentSource
{
/** @var Payment $sourceData */
$user = Craft::$app->getUser();

if ($user->getIsGuest()) {
$user->loginRequired();
}

$sourceData->token = $this->_normalizePaymentToken((string) $sourceData->token);

try {
$stripeCustomer = $this->_getStripeCustomer($user->getIdentity());
$stripeCustomer = $this->_getStripeCustomer($userId);
$stripeResponse = $stripeCustomer->sources->create(['source' => $sourceData->token]);

$stripeCustomer->default_source = $stripeResponse->id;
Expand All @@ -299,7 +293,7 @@ public function createPaymentSource(BasePaymentForm $sourceData): PaymentSource
}

$paymentSource = new PaymentSource([
'userId' => $user->getId(),
'userId' => $userId,
'gatewayId' => $this->id,
'token' => $stripeResponse->id,
'response' => $stripeResponse->jsonSerialize(),
Expand Down Expand Up @@ -1277,14 +1271,15 @@ private function _handleSubscriptionUpdated(array $data)
/**
* Get the Stripe customer for a User.
*
* @param User $user
* @param int $userId
*
* @return Customer
* @throws CustomerException if wasn't able to create or retrieve Stripe Customer.
*/
private function _getStripeCustomer(User $user): Customer
private function _getStripeCustomer(int $userId): Customer
{
try {
$user = Craft::$app->getUsers()->getUserById($userId);
$customers = StripePlugin::getInstance()->getCustomers();
$customer = $customers->getCustomer($this->id, $user);
return Customer::retrieve($customer->reference);
Expand Down

0 comments on commit 61090be

Please sign in to comment.