-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeletePaymentMethod.php
75 lines (63 loc) · 2.53 KB
/
DeletePaymentMethod.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
declare(strict_types=1);
namespace MatchBot\Application\Actions;
use Fig\Http\Message\StatusCodeInterface;
use JetBrains\PhpStorm\Pure;
use MatchBot\Application\Auth\PersonManagementAuthMiddleware;
use MatchBot\Application\Auth\PersonWithPasswordAuthMiddleware;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Log\LoggerInterface;
use Stripe\Exception\ApiErrorException;
use Stripe\Exception\InvalidRequestException;
use Stripe\StripeClient;
class DeletePaymentMethod extends Action
{
#[Pure]
public function __construct(
private StripeClient $stripeClient,
LoggerInterface $logger
) {
parent::__construct($logger);
}
/**
* @throws ApiErrorException
* @see PersonWithPasswordAuthMiddleware
*/
protected function action(Request $request, Response $response, array $args): Response
{
$customerId = $request->getAttribute(PersonManagementAuthMiddleware::PSP_ATTRIBUTE_NAME);
\assert(is_string($customerId));
$paymentMethodId = $args['payment_method_id'];
\assert(is_string($paymentMethodId));
/** @var array<array{id: string}> $allPaymentMethodsOfCustomer */
$allPaymentMethodsOfCustomer = $this->stripeClient->customers->allPaymentMethods(
$customerId,
)->toArray()['data'];
$allCustomersPaymentMethodIds = array_map(
static fn(array $pm): string => $pm['id'],
$allPaymentMethodsOfCustomer
);
if (!in_array($paymentMethodId, $allCustomersPaymentMethodIds, true)) {
$this->logger->warning(
"Refusing to delete stripe payment method as not found for customer",
compact('customerId', 'paymentMethodId')
);
return $this->respondWithData(
$response,
['error' => 'Payment method not found'],
StatusCodeInterface::STATUS_BAD_REQUEST
);
}
try {
$this->stripeClient->paymentMethods->detach($paymentMethodId);
} catch (InvalidRequestException $e) {
$this->logger->error(
"Failed to delete payment method, error: " . $e->getMessage(),
compact('customerId', 'paymentMethodId')
);
return $this->respondWithData($response, ['error' => "Could not delete payment method"], 400);
}
return $this->respondWithData($response, data: [], statusCode: StatusCodeInterface::STATUS_NO_CONTENT);
}
}