| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Services\Payment; |
| 4 |
|
| 5 |
use IvyForms\Services\Translations\BackendStrings; |
| 6 |
|
| 7 |
/** |
| 8 |
* Re-reads a created Square payment and checks amount/currency/status. |
| 9 |
*/ |
| 10 |
final class SquarePaymentLookup |
| 11 |
{ |
| 12 |
/** |
| 13 |
* @param array<string, mixed> $parsed |
| 14 |
* @return array<string, mixed> |
| 15 |
*/ |
| 16 |
public static function confirmCreated(array $parsed, int $amountCents, string $currency, string $accessToken): array |
| 17 |
{ |
| 18 |
if (empty($parsed['success'])) { |
| 19 |
return $parsed; |
| 20 |
} |
| 21 |
|
| 22 |
$retrieved = self::retrieve((string) ($parsed['transactionId'] ?? ''), $accessToken); |
| 23 |
$payment = is_array($retrieved['payment'] ?? null) |
| 24 |
? $retrieved['payment'] |
| 25 |
: (is_array($parsed['payment'] ?? null) ? $parsed['payment'] : []); |
| 26 |
|
| 27 |
if (!self::matchesExpected($payment, $amountCents, $currency)) { |
| 28 |
return [ |
| 29 |
'success' => false, |
| 30 |
'message' => BackendStrings::getPaymentStrings()['payment_failed'], |
| 31 |
]; |
| 32 |
} |
| 33 |
|
| 34 |
return $parsed; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* @return array<string, mixed> |
| 39 |
*/ |
| 40 |
private static function retrieve(string $paymentId, string $accessToken): array |
| 41 |
{ |
| 42 |
if ($paymentId === '' || $accessToken === '') { |
| 43 |
return []; |
| 44 |
} |
| 45 |
|
| 46 |
$response = wp_remote_get( |
| 47 |
SquareEnvironment::getApiBaseUrl() . '/payments/' . rawurlencode($paymentId), |
| 48 |
[ |
| 49 |
'headers' => [ |
| 50 |
'Authorization' => 'Bearer ' . $accessToken, |
| 51 |
'Square-Version' => '2024-10-17', |
| 52 |
], |
| 53 |
'timeout' => 30, |
| 54 |
] |
| 55 |
); |
| 56 |
|
| 57 |
if (is_wp_error($response)) { |
| 58 |
return []; |
| 59 |
} |
| 60 |
|
| 61 |
$decoded = json_decode((string) wp_remote_retrieve_body($response), true); |
| 62 |
|
| 63 |
return is_array($decoded) ? $decoded : []; |
| 64 |
} |
| 65 |
|
| 66 |
/** |
| 67 |
* @param array<string, mixed> $payment |
| 68 |
*/ |
| 69 |
private static function matchesExpected(array $payment, int $amountCents, string $currency): bool |
| 70 |
{ |
| 71 |
$money = is_array($payment['amount_money'] ?? null) ? $payment['amount_money'] : []; |
| 72 |
|
| 73 |
return (int) ($money['amount'] ?? 0) === $amountCents |
| 74 |
&& strtoupper((string) ($money['currency'] ?? '')) === strtoupper($currency) |
| 75 |
&& strtoupper((string) ($payment['status'] ?? '')) === 'COMPLETED'; |
| 76 |
} |
| 77 |
} |
| 78 |
|