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

Bank transfer payment method not completing orders #324

Merged
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Release Notes for Stripe for Craft Commerce

## Unreleased

- Fixed a bug where choosing bank transfer as a payment method wouldn’t complete an order. ([#315](https://github.com/craftcms/commerce-stripe/issues/315))
- Added `craft\commerce\stripe\SubscriptionGateway::handleCustomerCashBalanceTransaction()`.
- Added `craft\commerce\stripe\SubscriptionGateway::transactionSupportsRefund()`.

## 4.1.5.3 - 2025-02-05

- Fixed a PHP error that could occur when handling a webhook request.
Expand Down
2 changes: 1 addition & 1 deletion src/base/Gateway.php
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ public function getTransactionHashFromWebhook(): ?string

$rawData = Craft::$app->getRequest()->getRawBody();
$data = Json::decodeIfJson($rawData);

if ($data) {
$transactionHash = ArrayHelper::getValue($data, 'data.object.metadata.transaction_reference');
if (!$transactionHash || !is_string($transactionHash)) {
Expand Down
111 changes: 110 additions & 1 deletion src/base/SubscriptionGateway.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,18 @@
use craft\commerce\base\PlanInterface;
use craft\commerce\base\SubscriptionResponseInterface;
use craft\commerce\elements\Subscription;
use craft\commerce\errors\CurrencyException;
use craft\commerce\errors\OrderStatusException;
use craft\commerce\errors\SubscriptionException;
use craft\commerce\errors\TransactionException;
use craft\commerce\helpers\Currency as CurrencyHelper;
use craft\commerce\models\Currency;
use craft\commerce\models\PaymentSource;
use craft\commerce\models\subscriptions\CancelSubscriptionForm as BaseCancelSubscriptionForm;
use craft\commerce\models\subscriptions\SubscriptionForm as BaseSubscriptionForm;
use craft\commerce\models\subscriptions\SubscriptionPayment;
use craft\commerce\models\subscriptions\SwitchPlansForm;
use craft\commerce\models\Transaction;
use craft\commerce\Plugin;
use craft\commerce\Plugin as CommercePlugin;
use craft\commerce\records\Transaction as TransactionRecord;
Expand All @@ -36,10 +41,12 @@
use craft\helpers\StringHelper;
use craft\web\View;
use Stripe\ApiResource;
use Stripe\CustomerCashBalanceTransaction;
use Stripe\Invoice as StripeInvoice;
use Stripe\Refund;
use Stripe\SubscriptionItem;
use Throwable;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use function count;

Expand Down Expand Up @@ -480,6 +487,9 @@ public function handleWebhook(array $data): void
case 'payment_intent.succeeded':
$this->handlePaymentIntentSucceeded($data);
break;
case CustomerCashBalanceTransaction::OBJECT_NAME . '.created':
$this->handleCustomerCashBalanceTransaction($data);
break;
case 'charge.refunded':
$this->handleRefunded($data);
break;
Expand Down Expand Up @@ -528,6 +538,7 @@ public function handlePaymentIntentSucceeded(array $data): void

if ($transaction->parentId === null) {
// Try and retrieve child transactions if this is a saved transaction
/** @var Transaction[] $children */
$children = $transaction->id
? Plugin::getInstance()->getTransactions()->getChildrenByTransactionId($transaction->id)
: [];
Expand All @@ -551,12 +562,110 @@ public function handlePaymentIntentSucceeded(array $data): void
$transactionRecord->message = '';
$transactionRecord->response = $paymentIntent;

$transactionRecord->save(false);
if ($transactionRecord->save(false)) {
// Silently drop successful child transactions as they are now consolidated into the parent transaction
TransactionRecord::deleteAll([
'parentId' => $updateTransaction->id,
'status' => TransactionRecord::STATUS_SUCCESS,
]);
}

$transaction->getOrder()->updateOrderPaidInformation();
}
}
}

/**
* @param array $data
* @return void
* @throws ElementNotFoundException
* @throws InvalidConfigException
* @throws Throwable
* @throws CurrencyException
* @throws OrderStatusException
* @throws TransactionException
* @throws Exception
* @since 4.1.6
*/
protected function handleCustomerCashBalanceTransaction(array $data): void
{
$cashBalance = $data['data']['object'];
if ($cashBalance['object'] === CustomerCashBalanceTransaction::OBJECT_NAME && $cashBalance['type'] === CustomerCashBalanceTransaction::TYPE_APPLIED_TO_PAYMENT) {
if (!array_key_exists('applied_to_payment', $cashBalance) || !array_key_exists('payment_intent', $cashBalance['applied_to_payment'])) {
return;
}

$transaction = Plugin::getInstance()->getTransactions()->getTransactionByReference($cashBalance['applied_to_payment']['payment_intent']);
if (!$transaction || $transaction->parentId !== null) {
return;
}

$children = Plugin::getInstance()->getTransactions()->getChildrenByTransactionId($transaction->id);

if (empty($children)) {
return;
}

// Find processing transaction with the same reference
$childTransaction = null;
foreach ($children as $child) {
if ($child->reference === $transaction->reference && $child->status === TransactionRecord::STATUS_PROCESSING) {
$childTransaction = $child;
break;
}
}

if ($childTransaction === null) {
return;
}

// Inspect the partial payment data to create a new child transaction
$transaction = Plugin::getInstance()->getTransactions()->createTransaction($childTransaction->getOrder(), $childTransaction);

$currency = Plugin::getInstance()->getPaymentCurrencies()->getPaymentCurrencyByIso(strtoupper($cashBalance['currency']));

// Flip `$cash['net_amount']` to a positive value
$paymentAmount = $cashBalance['net_amount'] > 0 ? $cashBalance['net_amount'] : $cashBalance['net_amount'] * -1;
// Convert from minor unit
$paymentAmount = $paymentAmount / (10 ** $currency->minorUnit);

$transaction->amount = $paymentAmount;
if ($transaction->currency != $transaction->paymentCurrency) {
$orderCurrency = Plugin::getInstance()->getPaymentCurrencies()->getPaymentCurrencyByIso($transaction->currency);
$amount = CurrencyHelper::round($paymentAmount / $transaction->paymentRate, $orderCurrency);
$transaction->amount = $amount;
}

$transaction->paymentAmount = $paymentAmount;
$transaction->status = TransactionRecord::STATUS_SUCCESS;
$transaction->response = $cashBalance;


Plugin::getInstance()->getTransactions()->saveTransaction($transaction, false);
}
}

/**
* @inheritdoc
*/
public function transactionSupportsRefund(Transaction $transaction): bool
{
if ($transaction->response && $transaction->status === TransactionRecord::STATUS_SUCCESS) {
$response = Json::decodeIfJson($transaction->response);

// If this is a bank transfer funded payment, we can't refund it.
if (isset($response['object']) && $response['object'] === CustomerCashBalanceTransaction::OBJECT_NAME && isset($response['type']) && $response['type'] === CustomerCashBalanceTransaction::TYPE_APPLIED_TO_PAYMENT) {
return false;
}
}

if (method_exists(parent::class, 'transactionSupportsRefund')) {
return parent::transactionSupportsRefund($transaction);
}

return true;
}

/**
* Handle a failed invoice by updating the subscription data for the subscription it failed.
*
Expand Down
7 changes: 7 additions & 0 deletions src/responses/PaymentIntentResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

use craft\commerce\base\RequestResponseInterface;
use craft\commerce\errors\NotImplementedException;
use Stripe\PaymentIntent;
use Stripe\Refund;

class PaymentIntentResponse implements RequestResponseInterface
Expand Down Expand Up @@ -63,6 +64,12 @@ public function isProcessing(): bool
return true;
}

if (array_key_exists('object', $this->data) && $this->data['object'] == PaymentIntent::OBJECT_NAME
&& array_key_exists('next_action', $this->data) && is_array($this->data['next_action'])
&& array_key_exists('type', $this->data['next_action']) && $this->data['next_action']['type'] == 'display_bank_transfer_instructions') {
return true;
}

return false;
}

Expand Down
Loading