• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

stripe / stripe-mirakl-connector / 46022462439

27 Nov 2026 03:10PM UTC coverage: 91.289% (+0.4%) from 90.9%
46022462439

Pull #164

github

ruoltean
fix repo flush
Pull Request #164: Bugfix/c 3556/capture payments

204 of 220 new or added lines in 22 files covered. (92.73%)

1 existing line in 1 file now uncovered.

2924 of 3203 relevant lines covered (91.29%)

12.72 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

85.71
/src/Handler/ValidateMiraklOrderHandler.php
1
<?php
2

3
namespace App\Handler;
4

5
use App\Entity\PaymentMapping;
6
use App\Exception\InvalidArgumentException;
7
use App\Message\ValidateMiraklOrderMessage;
8
use App\Service\MiraklClient;
9
use App\Service\StripeClient;
10
use App\Service\StripeAmount;
11
use App\Repository\PaymentMappingRepository;
12
use Psr\Log\LoggerAwareInterface;
13
use Psr\Log\LoggerAwareTrait;
14
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
15

16
#[AsMessageHandler]
17
class ValidateMiraklOrderHandler implements LoggerAwareInterface
18
{
19
    use LoggerAwareTrait;
20

21
    /**
22
     * @var MiraklClient
23
     */
24
    private $miraklClient;
25

26
    private $stripeClient;
27

28
    private $paymentMappingRepository;
29

30
    public function __construct(
13 ✔
31
        MiraklClient $miraklClient,
32
        StripeClient $stripeClient,
33
        PaymentMappingRepository $paymentMappingRepository
34
    ) {
35
        $this->miraklClient = $miraklClient;
13 ✔
36
        $this->stripeClient = $stripeClient;
13 ✔
37
        $this->paymentMappingRepository = $paymentMappingRepository;
13 ✔
38
    }
39

40
    public function __invoke(ValidateMiraklOrderMessage $message): void
13 ✔
41
    {
42
        $ordersByCommercialId = $message->getOrders();
13 ✔
43

44
        if (empty($ordersByCommercialId)) {
13 ✔
45
            return;
1 ✔
46
        }
47

48
        // Prepare order for validation
49
        $orders = [];
12 ✔
50
        $paymentMappings = $message->getPaymentMappings();
12 ✔
51
        foreach ($ordersByCommercialId as $commercialId => $ordersById) {
12 ✔
52
            if (!isset($paymentMappings[$commercialId]) || !$this->paymentIsValid($commercialId, $ordersById, $paymentMappings[$commercialId])) {
12 ✔
53
                continue;
11 ✔
54
            }
55

56
            foreach ($ordersById as $order) {
3 ✔
57
                $orders[] = [
3 ✔
58
                    'amount' => $order->getAmountDue(),
3 ✔
59
                    'customer_id' => $order->getCustomerId(),
3 ✔
60
                    'order_id' => $order->getOrderId(),
3 ✔
61
                    'payment_status' => 'OK',
3 ✔
62
                    'transaction_number' => $paymentMappings[$commercialId]->getStripeChargeId(),
3 ✔
63
                ];
3 ✔
64
            }
65
        }
66

67
        $this->logger->info('Validate '.count($orders).' Mirakl order(s)');
12 ✔
68
        if (!empty($orders)) {
12 ✔
69
            $this->miraklClient->validateProductPendingDebits($orders);
3 ✔
70
        }
71
    }
72

73
    private function paymentIsValid(string $commercialId, array $orders, PaymentMapping $paymentMapping): bool
12 ✔
74
    {
75
        try {
76
            $charge = $this->retrieveCurrentCharge($paymentMapping);
12 ✔
77
        } catch (\Throwable $exception) {
×
78
            $this->logger->error('Could not retrieve Stripe Charge before Mirakl validation.', [
×
79
                'commercial_id' => $commercialId,
×
80
                'charge_id' => $paymentMapping->getStripeChargeId(),
×
81
                'error' => $exception->getMessage(),
×
82
            ]);
×
83

84
            return false;
×
85
        }
86

87
        $firstOrder = current($orders);
12 ✔
88
        if (false === $firstOrder) {
12 ✔
89
            $this->logger->error('Rejecting Mirakl validation because the commercial order has no pending debits.', [
×
90
                'commercial_id' => $commercialId,
×
91
                'charge_id' => $paymentMapping->getStripeChargeId(),
×
92
            ]);
×
93

94
            return false;
×
95
        }
96

97
        $stripeCurrency = strtolower((string) ($charge->currency ?? ''));
12 ✔
98
        $miraklCurrency = strtolower((string) $firstOrder->getCurrency());
12 ✔
99
        if ('' === $stripeCurrency || '' === $miraklCurrency || $stripeCurrency !== $miraklCurrency) {
12 ✔
100
            $this->logger->error('Rejecting Mirakl validation because Stripe and Mirakl currencies differ.', [
3 ✔
101
                'commercial_id' => $commercialId,
3 ✔
102
                'charge_id' => $paymentMapping->getStripeChargeId(),
3 ✔
103
                'stripe_currency' => $stripeCurrency,
3 ✔
104
                'mirakl_currency' => $miraklCurrency,
3 ✔
105
            ]);
3 ✔
106

107
            $this->markPaymentRejected(
3 ✔
108
                $paymentMapping,
3 ✔
109
                'Stripe and Mirakl currencies differ.',
3 ✔
110
                (bool) ($charge->captured ?? false)
3 ✔
111
            );
3 ✔
112

113
            return false;
3 ✔
114
        }
115

116
        $expectedAmount = 0;
9 ✔
117
        foreach ($orders as $order) {
9 ✔
118
            $orderCurrency = strtolower((string) $order->getCurrency());
9 ✔
119
            if ($orderCurrency !== $miraklCurrency) {
9 ✔
NEW
120
                $this->markPaymentRejected(
×
NEW
121
                    $paymentMapping,
×
NEW
122
                    'Mirakl pending debits have mixed currencies.',
×
NEW
123
                    (bool) ($charge->captured ?? false)
×
NEW
124
                );
×
UNCOV
125
                return false;
×
126
            }
127
            try {
128
                $orderAmount = StripeAmount::toMinorUnits($order->getAmountDue(), $miraklCurrency);
9 ✔
129
                if ($orderAmount <= 0) {
9 ✔
130
                    throw new InvalidArgumentException('Mirakl pending debit amount must be positive.');
2 ✔
131
                }
132
                $expectedAmount += $orderAmount;
9 ✔
133
            } catch (InvalidArgumentException $e) {
4 ✔
134
                $this->logger->error('Rejecting Mirakl validation because the order amount is invalid.', [
4 ✔
135
                    'commercial_id' => $commercialId,
4 ✔
136
                    'error' => $e->getMessage(),
4 ✔
137
                ]);
4 ✔
138
                $this->markPaymentRejected(
4 ✔
139
                    $paymentMapping,
4 ✔
140
                    $e->getMessage(),
4 ✔
141
                    (bool) ($charge->captured ?? false)
4 ✔
142
                );
4 ✔
143

144
                return false;
4 ✔
145
            }
146
        }
147

148
        $chargeAmount = (int) ($charge->amount ?? 0);
7 ✔
149
        $amountRefunded = (int) ($charge->amount_refunded ?? 0);
7 ✔
150
        $usableAmount = $chargeAmount - $amountRefunded;
7 ✔
151
        $chargeStatus = (string) ($charge->status ?? '');
7 ✔
152
        $disputed = (bool) ($charge->disputed ?? false);
7 ✔
153
        if ('pending' === $chargeStatus && $usableAmount >= $expectedAmount && !$disputed) {
7 ✔
154
            $this->logger->info('Postponing Mirakl validation because Stripe payment is still pending.', [
1 ✔
155
                'commercial_id' => $commercialId,
1 ✔
156
                'charge_id' => $paymentMapping->getStripeChargeId(),
1 ✔
157
            ]);
1 ✔
158

159
            return false;
1 ✔
160
        }
161

162
        if ($usableAmount < $expectedAmount || 'succeeded' !== $chargeStatus || $disputed) {
6 ✔
163
            $this->logger->error('Rejecting Mirakl validation because Stripe payment is not sufficient or usable.', [
3 ✔
164
                'commercial_id' => $commercialId,
3 ✔
165
                'charge_id' => $paymentMapping->getStripeChargeId(),
3 ✔
166
                'expected_amount' => $expectedAmount,
3 ✔
167
                'usable_amount' => $usableAmount,
3 ✔
168
                'charge_status' => $chargeStatus,
3 ✔
169
                'disputed' => $disputed,
3 ✔
170
            ]);
3 ✔
171

172
            $this->markPaymentRejected(
3 ✔
173
                $paymentMapping,
3 ✔
174
                'Stripe payment is not sufficient or usable.',
3 ✔
175
                (bool) ($charge->captured ?? false)
3 ✔
176
            );
3 ✔
177

178
            return false;
3 ✔
179
        }
180

181
        $paymentMapping->setStripeAmount($chargeAmount);
3 ✔
182
        $paymentMapping->setStripeCurrency($stripeCurrency);
3 ✔
183
        $this->persistChanges($paymentMapping);
3 ✔
184

185
        return true;
3 ✔
186
    }
187

188
    private function markPaymentRejected(PaymentMapping $paymentMapping, string $reason, bool $chargeCaptured): void
10 ✔
189
    {
190
        // A captured charge has already moved money. Keep it mapped and visible to
191
        // subsequent Stripe events so refunds and disputes can still be processed.
192
        // The rejection reason is useful for diagnosis, but must not make the
193
        // mapping eligible for replacement or cause the webhook to ignore it.
194
        if ($chargeCaptured || PaymentMapping::CAPTURED === $paymentMapping->getStatus()) {
10 ✔
195
            $paymentMapping->setStatus(PaymentMapping::CAPTURED);
8 ✔
196
            $paymentMapping->setStatusReason(PaymentMapping::INVALID_PAYMENT_REASON_PREFIX.' '.$reason);
8 ✔
197
            $this->persistChanges($paymentMapping);
8 ✔
198

199
            return;
8 ✔
200
        }
201

202
        $paymentMapping->setStatus(PaymentMapping::CANCELED);
2 ✔
203
        $paymentMapping->setStatusReason(PaymentMapping::INVALID_PAYMENT_REASON_PREFIX.' '.$reason);
2 ✔
204
        $this->persistChanges($paymentMapping);
2 ✔
205
    }
206

207
    /**
208
     * The mapping comes from a queued message, so it is detached from the entity manager
209
     * and a plain flush would not write anything. Apply the changes to the managed entity.
210
     */
211
    private function persistChanges(PaymentMapping $paymentMapping): void
11 ✔
212
    {
213
        $managed = $this->paymentMappingRepository->findOneByStripeChargeId($paymentMapping->getStripeChargeId());
11 ✔
214
        if (null !== $managed && $managed !== $paymentMapping) {
11 ✔
215
            $managed->setStatus($paymentMapping->getStatus());
4 ✔
216
            $managed->setStatusReason($paymentMapping->getStatusReason());
4 ✔
217
            if (null !== $paymentMapping->getStripeAmount()) {
4 ✔
218
                $managed->setStripeAmount($paymentMapping->getStripeAmount());
1 ✔
219
            }
220
            if (null !== $paymentMapping->getStripeCurrency()) {
4 ✔
221
                $managed->setStripeCurrency($paymentMapping->getStripeCurrency());
1 ✔
222
            }
223
        }
224

225
        $this->paymentMappingRepository->flush();
11 ✔
226
    }
227

228
    private function retrieveCurrentCharge(PaymentMapping $paymentMapping): \Stripe\Charge
12 ✔
229
    {
230
        $paymentId = $paymentMapping->getStripeChargeId();
12 ✔
231
        if (!str_starts_with($paymentId, 'pi_')) {
12 ✔
232
            return $this->stripeClient->chargeRetrieve($paymentId);
11 ✔
233
        }
234

235
        $paymentIntent = $this->stripeClient->paymentIntentRetrieve($paymentId);
1 ✔
236
        $latestCharge = $paymentIntent->latest_charge ?? null;
1 ✔
237
        if ($latestCharge instanceof \Stripe\Charge) {
1 ✔
238
            return $latestCharge;
×
239
        }
240

241
        if (is_string($latestCharge) && '' !== $latestCharge) {
1 ✔
242
            return $this->stripeClient->chargeRetrieve($latestCharge);
1 ✔
243
        }
244

245
        throw new \RuntimeException(sprintf('PaymentIntent %s has no latest Charge.', $paymentId));
×
246
    }
247

248
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc